diff --git a/.circleci/config.yml b/.circleci/config.yml deleted file mode 100644 index 74940a5a754..00000000000 --- a/.circleci/config.yml +++ /dev/null @@ -1,26 +0,0 @@ -version: 2 -jobs: - build: - branches: - only: - - master - - develop - - addinCircleCI - - docker: - - image: circleci/openjdk:8-jdk-browsers - working_directory: ~/java-tron - steps: - - checkout - - run: - name: multi_os_result - command: echo "curl http://60.205.215.34/multi_os_result" -# -# - run: -# name: Daily Build Report -# command: curl http://47.95.206.44:50080/Daily_Build_Task_Report -# -# - run: -# name: Download Links -# command: sh DownloadLinks.sh - diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md deleted file mode 100644 index 6d82a3ae6a9..00000000000 --- a/.github/ISSUE_TEMPLATE.md +++ /dev/null @@ -1,13 +0,0 @@ - - -### 1. What did you do? - - - -### 2. What did you expect to see? - - - -### 3. What did you see instead? - - diff --git a/.github/ISSUE_TEMPLATE/ask-a-question.md b/.github/ISSUE_TEMPLATE/ask-a-question.md new file mode 100644 index 00000000000..e503998b477 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/ask-a-question.md @@ -0,0 +1,10 @@ +--- +name: Ask a question +about: Something is unclear +title: '' +labels: 'type:docs' +assignees: '' + +--- +This should only be used in very rare cases e.g. if you are not 100% sure if something is a bug or asking a question that leads to improving the documentation. For general questions please use [Discord](https://discord.gg/cGKSsRVCGm) or [Telegram](https://t.me/TronOfficialDevelopersGroupEn). + diff --git a/.github/ISSUE_TEMPLATE/report-a-bug.md b/.github/ISSUE_TEMPLATE/report-a-bug.md new file mode 100644 index 00000000000..a0d68121565 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/report-a-bug.md @@ -0,0 +1,50 @@ +--- +name: Report a bug +about: Create a report to help us improve +title: '' +labels: 'type:bug' +assignees: '' + +--- + + + + + +#### Software Versions + + + + +#### Expected behaviour + + + +#### Actual behaviour + + + +#### Frequency + + +#### Steps to reproduce the behaviour + +1. [Step 1] +2. [Step 2] +3. [Step ...] + +#### Backtrace + +```` +[backtrace] +```` + +When submitting logs: please submit them as text and not screenshots. diff --git a/.github/ISSUE_TEMPLATE/request-a-feature.md b/.github/ISSUE_TEMPLATE/request-a-feature.md new file mode 100644 index 00000000000..261f1088ded --- /dev/null +++ b/.github/ISSUE_TEMPLATE/request-a-feature.md @@ -0,0 +1,28 @@ +--- +name: Request a feature +about: Suggest an idea for this project +title: '' +labels: 'type:feature' +assignees: '' + +--- +# Background + +# Rationale + +Why should this feature exist? + +What are the use-cases? + +# Specification + +# Test Specification + +# Scope Of Impact + + +# Implementation + +Do you have ideas regarding the implementation of this feature? + +Are you willing to implement this feature? diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000000..5a0f120e116 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,64 @@ +name: "CodeQL" + +on: + push: + branches: [ 'develop', 'master', 'release_**' ] + pull_request: + # The branches below must be a subset of the branches above + branches: [ 'develop' ] + schedule: + - cron: '6 10 * * 0' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ 'java' ] + # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] + # Use only 'java' to analyze code written in Java, Kotlin or both + # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both + # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + + # For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs + # queries: security-extended,security-and-quality + + # Autobuild attempts to build any compiled languages (C/C++, C#, Go, Java, or Swift). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun + + # If the Autobuild fails above, remove it and uncomment the following three lines. + # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. + + # - run: | + # echo "Run, Build Application using script" + # ./location_of_script_within_repo/buildscript.sh + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: "/language:${{matrix.language}}" diff --git a/.github/workflows/docker-publish.yml b/.github/workflows/docker-publish.yml deleted file mode 100644 index 051bed60aa5..00000000000 --- a/.github/workflows/docker-publish.yml +++ /dev/null @@ -1,83 +0,0 @@ -name: Docker - -# This workflow uses actions that are not certified by GitHub. -# They are provided by a third-party and are governed by -# separate terms of service, privacy policy, and support -# documentation. - -on: - push: - tags: - - "GreatVoyage-v*" - -env: - # Use docker.io for Docker Hub if empty - REGISTRY: docker.io - # github.repository as / - IMAGE_NAME: ${{ github.repository }} - - -jobs: - build: - - runs-on: ubuntu-latest - permissions: - contents: read - packages: write - # This is used to complete the identity challenge - # with sigstore/fulcio when running outside of PRs. - id-token: write - - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - # Install the cosign tool except on PR - # https://github.com/sigstore/cosign-installer - - name: Install cosign - if: github.event_name != 'pull_request' - uses: sigstore/cosign-installer@1e95c1de343b5b0c23352d6417ee3e48d5bcd422 - with: - cosign-release: 'v1.4.0' - - - # Workaround: https://github.com/docker/build-push-action/issues/461 - - name: Setup Docker buildx - uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf - - # Login against a Docker registry except on PR - # https://github.com/docker/login-action - - name: Log into registry ${{ env.REGISTRY }} - if: github.event_name != 'pull_request' - uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c - with: - registry: ${{ env.REGISTRY }} - username: ${{ secrets.DOCKER_USERNAME }} - password: ${{ secrets.DOCKER_PASSWORD }} - - # Extract metadata (tags, labels) for Docker - # https://github.com/docker/metadata-action - - name: Extract Docker metadata - id: meta - uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38 - with: - images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} - - # Build and push Docker image with Buildx (don't push on PR) - # https://github.com/docker/build-push-action - - name: Build and push Docker image - id: build-and-push - uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc - with: - context: . - push: ${{ github.event_name != 'pull_request' }} - tags: ${{ steps.meta.outputs.tags }} - labels: ${{ steps.meta.outputs.labels }} - - - name: Sign the published Docker image - if: ${{ github.event_name != 'pull_request' }} - env: - COSIGN_EXPERIMENTAL: "true" - # This step uses the identity token to provision an ephemeral certificate - # against the sigstore community Fulcio instance. - run: cosign sign ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ steps.build-and-push.outputs.digest }} diff --git a/.github/workflows/math-check.yml b/.github/workflows/math-check.yml new file mode 100644 index 00000000000..0f0255815d5 --- /dev/null +++ b/.github/workflows/math-check.yml @@ -0,0 +1,93 @@ +name: Check Math Usage + +on: + push: + branches: [ 'master', 'release_**' ] + pull_request: + branches: [ 'develop', 'release_**' ] + workflow_dispatch: + +jobs: + check-math: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Check for java.lang.Math usage + id: check-math + shell: bash + run: | + echo "Checking for java.lang.Math usage..." + + touch math_usage.txt + + while IFS= read -r file; do + filename=$(basename "$file") + if [[ "$filename" == "StrictMathWrapper.java" || "$filename" == "MathWrapper.java" ]]; then + continue + fi + + perl -0777 -ne ' + s/"([^"\\]|\\.)*"//g; + s/'\''([^'\''\\]|\\.)*'\''//g; + s!/\*([^*]|\*[^/])*\*/!!g; + s!//[^\n]*!!g; + $hasMath = 0; + $hasMath = 1 if /^[\s]*import[\s]+java\.lang\.Math\b/m; + $hasMath = 1 if /\bjava\s*\.\s*lang\s*\.\s*Math\s*\./; + $hasMath = 1 if /(?> math_usage.txt + done < <(find . -type f -name "*.java") + + sort -u math_usage.txt -o math_usage.txt + + if [ -s math_usage.txt ]; then + echo "❌ Error: Forbidden Math usage found in the following files:" + cat math_usage.txt + echo "math_found=true" >> $GITHUB_OUTPUT + echo "Please use org.tron.common.math.StrictMathWrapper instead of direct Math usage." + else + echo "✅ No forbidden Math usage found" + echo "math_found=false" >> $GITHUB_OUTPUT + fi + + - name: Upload findings + if: steps.check-math.outputs.math_found == 'true' + uses: actions/upload-artifact@v4 + with: + name: math-usage-report + path: math_usage.txt + + - name: Create comment + if: github.event_name == 'pull_request' && steps.check-math.outputs.math_found == 'true' + uses: actions/github-script@v6 + with: + script: | + const fs = require('fs'); + const findings = fs.readFileSync('math_usage.txt', 'utf8'); + const body = `### ❌ Math Usage Detection Results + + Found forbidden usage of \`java.lang.Math\` in the following files: + + \`\`\` + ${findings} + \`\`\` + + **Please review if this usage is intended.** + > [!CAUTION] + > Note: You should use \`org.tron.common.math.StrictMathWrapper\`. + > If you need to use \`java.lang.Math\`, please provide a justification. + `; + + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body: body + }); + + - name: Fail if Math usage found + if: steps.check-math.outputs.math_found == 'true' + run: exit 1 diff --git a/.gitignore b/.gitignore index b980800f353..3917bb44679 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,6 @@ shareddata.* # protobuf generated classes src/main/gen - src/main/java/org/tron/core/bftconsensus src/test/java/org/tron/consensus2 src/main/java/META-INF/ @@ -55,3 +54,6 @@ Wallet # vm_trace /vm_trace/ + +/framework/propPath +.cache diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 29368a646ab..79bf8567a61 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -103,12 +103,12 @@ If you want to contribute codes to java-tron, please follow the following steps: Submit a pull request (PR) from your repository to `tronprotocol/java-tron`. Please be sure to click on the link in the red box shown below. Select the base branch for tronprotocol and the compare branch for your personal fork repository. - ![](https://codimd.s3.shivering-isles.com/demo/uploads/e24435ab42e4287d9369a2136.png) + ![image](https://raw.githubusercontent.com/tronprotocol/documentation-en/master/images/javatron_pr.png) ## Code Review Guidelines -The only way to get code into java-tron is to send a pull request. Those pull requests need to be reviewed by someone. there a guide that explains our expectations around PRs for both authors and reviewers. +The only way to get code into java-tron is to send a pull request. Those pull requests need to be reviewed by someone. The following guide explains our expectations around PRs for both authors and reviewers. ### Terminology - The author of a pull request is the entity who wrote the diff and submitted it to GitHub. @@ -151,7 +151,7 @@ Please make sure your submission meets the following code style: ### Commit Messages -Commit messages should follow the rule below, we provide a template corresponding instructions. +Commit messages should follow the rule below, we provide a template with corresponding instructions. Template: ``` @@ -182,14 +182,14 @@ The subject contains a succinct description of the change: 4. Do not end the subject line with a period. 5. Avoid meaningless commits. It is recommended to use the git rebase command. -Message body use the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior. +Message body uses the imperative, present tense: "change" not "changed" nor "changes". The body should include the motivation for the change and contrast this with previous behavior. Here is an example: ``` -feat(block): optimize product block +feat(block): optimize the block-producing logic -1. optimize the block production threads -2. improve transaction entry speed +1. increase the priority that block producing thread acquires synchronization lock +2. add the interruption exception handling in block-producing thread Closes #1234 ``` @@ -217,7 +217,7 @@ If the purpose of this submission is to modify one issue, you need to refer to t ### Special Situations And How To Deal With Them -As a reviewer, you may find yourself in one of the sitations below. Here’s how to deal with those: +As a reviewer, you may find yourself in one of the situations below. Here’s how to deal with those: The author doesn’t follow up: ping them after a while (i.e. after a few days). If there is no further response, close the PR or complete the work yourself. diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 1a6702c305e..00000000000 --- a/Dockerfile +++ /dev/null @@ -1,43 +0,0 @@ -FROM tronprotocol/centos7 - -ENV TMP_DIR="/tron-build" -ENV JDK_TAR="jdk-8u202-linux-x64.tar.gz" -ENV JDK_DIR="jdk1.8.0_202" -ENV JDK_MD5="0029351f7a946f6c05b582100c7d45b7" -ENV BASE_DIR="/java-tron" - - -RUN set -o errexit -o nounset \ - && yum -y install git wget \ - && wget -P /usr/local https://github.com/frekele/oracle-java/releases/download/8u202-b08/$JDK_TAR \ - && echo "$JDK_MD5 /usr/local/$JDK_TAR" | md5sum -c \ - && tar -zxf /usr/local/$JDK_TAR -C /usr/local\ - && rm /usr/local/$JDK_TAR \ - && export JAVA_HOME=/usr/local/$JDK_DIR \ - && export CLASSPATH=$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar \ - && export PATH=$PATH:$JAVA_HOME/bin \ - && echo "git clone" \ - && mkdir -p $TMP_DIR \ - && cd $TMP_DIR \ - && git clone https://github.com/tronprotocol/java-tron.git \ - && cd java-tron \ - && git checkout master \ - && ./gradlew build -x test \ - && cd build/distributions \ - && unzip -o java-tron-1.0.0.zip \ - && mv java-tron-1.0.0 $BASE_DIR \ - && wget -P $BASE_DIR/config https://raw.githubusercontent.com/tronprotocol/tron-deployment/master/main_net_config.conf \ - && rm -rf $TMP_DIR \ - && rm -rf ~/.gradle \ - && mv $JAVA_HOME/jre /usr/local \ - && rm -rf $JAVA_HOME \ - && yum clean all - -ENV JAVA_HOME="/usr/local/jre" -ENV PATH=$PATH:$JAVA_HOME/bin - -COPY docker-entrypoint.sh $BASE_DIR/bin - -WORKDIR $BASE_DIR - -ENTRYPOINT ["./bin/docker-entrypoint.sh"] diff --git a/DownloadLinks.sh b/DownloadLinks.sh deleted file mode 100644 index babc5a266f6..00000000000 --- a/DownloadLinks.sh +++ /dev/null @@ -1,21 +0,0 @@ -PassFlag=`curl -s http://47.95.206.44:50080/Daily_Build_Task_Report | grep "Failed: 0" | wc -c` - -if [ $PassFlag -eq 0 ]; then - echo "Daily Build Stest Fail" - echo "To view Daily Replay and Stress Test logs please visit website below on browsers" - echo "--- http://47.95.206.44:50080/latestReplayLog" - echo "--- http://47.95.206.44:50080/latestStressLog" - -else - echo "Daily Build Stest Pass" - echo "Build on `date +"%Y-%m-%d"` 3:00:00 (CST), UTC +8" - echo "Please visit following website to download java-tron.jar on browsers" - echo "--- http://47.95.206.44:50080/Daily_Build/jFava-tron.jar" - echo "To view Daily Replay and Stress Test logs please visit website below on browsers" - echo "--- http://47.95.206.44:50080/latestReplayLog" - echo "--- http://47.95.206.44:50080/latestStressLog" - echo "The following compressed package is provided for user to set up Fullnode. Please use Linux OS to Download" - echo "--- curl -# -O http://47.95.206.44:50080/Daily_Build/java-tron.tar.gz" - echo "To unzip file use the command below" - echo "--- tar -xzvf java-tron.tar.gz" -fi \ No newline at end of file diff --git a/README.md b/README.md index 477b271a17f..0d0eeb6ef71 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,6 @@ Java implementation of the Tron Protocol -

@@ -42,82 +41,136 @@

## Table of Contents -- [What’s TRON?](#What’s-TRON) -- [Building the Source Code](#Building-the-source) - - [Getting the Source Code](#Getting-the-Source-Code) - - [Build](#Build) -- [Running java-tron](#Running-java-tron) -- [Community](#Community) -- [Contribution](#Contribution) -- [Resources](#Resources) -- [License](#License) - -## What's TRON? + +- [What’s TRON?](#whats-tron) +- [Building the Source Code](#building-the-source-code) +- [Running java-tron](#running-java-tron) +- [Community](#community) +- [Contribution](#contribution) +- [Resources](#resources) +- [Integrity Check](#integrity-check) +- [License](#license) + +# What's TRON? TRON is a project dedicated to building the infrastructure for a truly decentralized Internet. -* Tron Protocol, one of the largest blockchain-based operating systems in the world, offers scalable, high-availability and high-throughput support that underlies all the decentralized applications in the TRON ecosystem. +- Tron Protocol, one of the largest blockchain-based operating systems in the world, offers scalable, high-availability and high-throughput support that underlies all the decentralized applications in the TRON ecosystem. -* Tron Virtual Machine (TVM) allows anyone to develop decentralized applications (DAPPs) for themselves or their communities with smart contracts thereby making decentralized crowdfunding and token issuance easier than ever. +- Tron Virtual Machine (TVM) allows anyone to develop decentralized applications (DAPPs) for themselves or their communities with smart contracts thereby making decentralized crowdfunding and token issuance easier than ever. TRON enables large-scale development and engagement. With over 2000 transactions per second (TPS), high concurrency, low latency, and massive data transmission. It is ideal for building decentralized entertainment applications. Free features and incentive systems allow developers to create premium app experiences for users. -# Building the source -Building java-tron requires `git` and `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. It is recommended to operate on `Linux` and `OSX` operating systems. +# Building the Source Code -## Getting the Source Code - - ```bash - $ git clone https://github.com/tronprotocol/java-tron.git - $ git checkout -t origin/master - ``` +Building java-tron requires `git` package and 64-bit version of `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. Make sure you operate on `Linux` and `MacOS` operating systems. -## Build +Clone the repo and switch to the `master` branch ```bash +$ git clone https://github.com/tronprotocol/java-tron.git $ cd java-tron -$ ./gradlew clean build -x test +$ git checkout -t origin/master ``` -The `FullNode.jar` file can be found in `java-tron/build/libs/FullNode.jar` after build successful. +then run the following command to build java-tron, the `FullNode.jar` file can be found in `java-tron/build/libs/` after build successfully. + +```bash +$ ./gradlew clean build -x test +``` # Running java-tron -Get the mainnet configurate file: [main_net_config.conf](https://github.com/tronprotocol/tron-deployment/blob/master/main_net_config.conf), other network configuration files can be find [here](https://github.com/tronprotocol/tron-deployment). +Running java-tron requires 64-bit version of `Oracle JDK 1.8` to be installed, other JDK versions are not supported yet. Make sure you operate on `Linux` and `MacOS` operating systems. + +Get the mainnet configuration file: [main_net_config.conf](https://github.com/tronprotocol/tron-deployment/blob/master/main_net_config.conf), other network configuration files can be found [here](https://github.com/tronprotocol/tron-deployment). + +## Hardware Requirements + +Minimum: + +- CPU with 8 cores +- 16GB RAM +- 3TB free storage space to sync the Mainnet + +Recommended: + +- CPU with 16+ cores(32+ cores for a super representative) +- 32GB+ RAM(64GB+ for a super representative) +- High Performance SSD with at least 4TB free space +- 100+ MB/s download Internet service + +## Running a full node for mainnet + +Full node has full historical data, it is the entry point into the TRON network, it can be used by other processes as a gateway into the TRON network via HTTP and GRPC endpoints. You can interact with the TRON network through full node:transfer assets, deploy contracts, interact with contracts and so on. `-c` parameter specifies a configuration file to run a full node: + +```bash +$ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ + -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ + -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ + -XX:+PrintGCDateStamps -Xloggc:gc.log \ + -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ + -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ + -jar FullNode.jar -c main_net_config.conf >> start.log 2>&1 & +``` + +## Running a super representative node for mainnet + +Adding the `--witness` parameter to the startup command, full node will run as a super representative node. The super representative node supports all the functions of the full node and also supports block production. Before running, make sure you have a super representative account and get votes from others. Once the number of obtained votes ranks in the top 27, your super representative node will participate in block production. +Fill in the private key of a super representative address into the `localwitness` list in the `main_net_config.conf`. Here is an example: -* **Running a full node for mainnet** - Full node has full historical data, it is the entry point into the TRON network , it can be used by other processes as a gateway into the TRON network via HTTP and GRPC endpoints. You can interact with the TRON network through full node:transfer assets, deploy contracts, interact with contracts and so on. `-c ` parameter specifies a configuration file to run a full node: - ```bash - $ java -jar FullNode.jar -c main_net_config.conf - ``` -* **Running a super representative node for mainnet** - Adding the `--witness` parameter to the startup command, full node will run as a super representative node. The super representative node supports all the functions of the full node and also supports block production. Before running, make sure you have a super representative account and get votes from others,once the number of obtained votes ranks in the top 27, your super representative node will participate in block production. +``` + localwitness = [ + + ] +``` - Fill in the private key of super representative address into the `localwitness` list in the `main_net_config.conf`, here is an example: - ``` - localwitness = [ - 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 - ] - ``` +then run the following command to start the node: - then run the following command to start the node: - ```bash - $ java -jar FullNode.jar --witness -c main_net_config.conf - ``` +```bash +$ nohup java -Xms9G -Xmx9G -XX:ReservedCodeCacheSize=256m \ + -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m \ + -XX:MaxDirectMemorySize=1G -XX:+PrintGCDetails \ + -XX:+PrintGCDateStamps -Xloggc:gc.log \ + -XX:+UseConcMarkSweepGC -XX:NewRatio=2 \ + -XX:+CMSScavengeBeforeRemark -XX:+ParallelRefProcEnabled \ + -XX:+HeapDumpOnOutOfMemoryError \ + -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 \ + -jar FullNode.jar --witness -c main_net_config.conf >> start.log 2>&1 & +``` ## Quick Start Tool -An easier way to build and run java-tron is to use `start.sh`, `start.sh` is a quick start script written in shell language, you can use it to build and run java-tron quickly and easily. + +An easier way to build and run java-tron is to use `start.sh`. `start.sh` is a quick start script written in the Shell language. You can use it to build and run java-tron quickly and easily. Here are some common use cases of the scripting tool -* Use `start.sh` to start a full node with the downloaded `FullNode.jar` -* Use `start.sh` to download the latest `FullNode.jar` and start a full node. -* Use `start.sh` to download the latest source code and compile a `FullNode.jar` and then start a full node. + +- Use `start.sh` to start a full node with the downloaded `FullNode.jar` +- Use `start.sh` to download the latest `FullNode.jar` and start a full node. +- Use `start.sh` to download the latest source code and compile a `FullNode.jar` and then start a full node. For more details, please refer to the tool [guide](./shell.md). +## Run inside Docker container + +One of the quickest ways to get `java-tron` up and running on your machine is by using Docker: + +```shell +$ docker run -d --name="java-tron" \ + -v /your_path/output-directory:/java-tron/output-directory \ + -v /your_path/logs:/java-tron/logs \ + -p 8090:8090 -p 18888:18888 -p 50051:50051 \ + tronprotocol/java-tron \ + -c /java-tron/config/main_net_config.conf +``` + +This will mount the `output-directory` and `logs` directories on the host, the docker.sh tool can also be used to simplify the use of docker, see more [here](docker/docker.md). # Community + [Tron Developers & SRs](https://discord.gg/hqKvyAM) is Tron's official Discord channel. Feel free to join this channel if you have any questions. [Core Devs Community](https://t.me/troncoredevscommunity) is the Telegram channel for java-tron community developers. If you want to contribute to java-tron, please join this channel. @@ -125,18 +178,27 @@ For more details, please refer to the tool [guide](./shell.md). [tronprotocol/allcoredev](https://gitter.im/tronprotocol/allcoredev) is the official Gitter channel for developers. # Contribution -If you'd like to contribute to java-tron, please read the following instructions. -- [Contribution](./CONTRIBUTING.md) +Thank you for considering to help out with the source code! If you'd like to contribute to java-tron, please see the [Contribution Guide](./CONTRIBUTING.md) for more details. # Resources -* [Medium](https://medium.com/@coredevs) java-tron's official technical articles are published there. -* [Documentation](https://tronprotocol.github.io/documentation-en/introduction/) java-tron's official technical documentation website. -* [Test network](http://nileex.io/) A stable test network of TRON contributed by TRON community. -* [Tronscan](https://tronscan.org/#/) TRON network blockchain browser. -* [Wallet-cli](https://github.com/tronprotocol/wallet-cli) TRON network wallet using command line. -* [TIP](https://github.com/tronprotocol/tips) TRON Improvement Proposal (TIP) describes standards for the TRON network. -* [TP](https://github.com/tronprotocol/tips/tree/master/tp) TRON Protocol (TP) describes standards already implemented in TRON network but not published as a TIP. + +- [Medium](https://medium.com/@coredevs) java-tron's official technical articles are published there. +- [Documentation](https://tronprotocol.github.io/documentation-en/introduction/) java-tron's official technical documentation website. +- [Test network](http://nileex.io/) A stable test network of TRON contributed by TRON community. +- [Tronscan](https://tronscan.org/#/) TRON network blockchain browser. +- [Wallet-cli](https://github.com/tronprotocol/wallet-cli) TRON network wallet using command line. +- [TIP](https://github.com/tronprotocol/tips) TRON Improvement Proposal (TIP) describes standards for the TRON network. +- [TP](https://github.com/tronprotocol/tips/tree/master/tp) TRON Protocol (TP) describes standards already implemented in TRON network but not published as a TIP. + +# Integrity Check + +- After January 3, 2023, the release files will be signed using a GPG key pair, and the correctness of the signature will be verified using the following public key: + ``` + pub: 1254 F859 D2B1 BD9F 66E7 107D F859 BCB4 4A28 290B + uid: build@tron.network + ``` # License + java-tron is released under the [LGPLv3 license](https://github.com/tronprotocol/java-tron/blob/master/LICENSE). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000000..b3125ce6af1 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,7 @@ +## Supported Versions +Please see [Releases](https://github.com/tronprotocol/java-tron/releases). We recommend using the [most recently released version](https://github.com/tronprotocol/java-tron/releases/latest). + +## Reporting a Vulnerability +**Please do not file a public ticket** mentioning the vulnerability. +To find out how to report a vulnerability in TRON, visit [https://hackerone.com/tron_dao](https://hackerone.com/tron_dao?type=team) or email [bounty@tron.network](mailto:bounty@tron.network). +Please read the [disclosure policy](https://www.hackerone.com/disclosure-guidelines) for more information about publicly disclosed security vulnerabilities. diff --git a/Tron protobuf protocol document.md b/Tron protobuf protocol document.md index 115b897c020..d8e621ed69a 100644 --- a/Tron protobuf protocol document.md +++ b/Tron protobuf protocol document.md @@ -90,7 +90,7 @@ enum AccountType { `allowance`: the allowance of this account. - `latest_withdrew_time`: the latest operation time of this account. + `latest_withdraw_time`: the latest operation time of this account. `code`: reserved @@ -546,11 +546,11 @@ Transaction and transaction-related messages. message `raw` - `ref_block_bytes`: Deprecated. + `ref_block_bytes`: intercepted part of the now block bytes in transaction head. - `ref_block_num`: now block number in transaction head. + `ref_block_num`: Deprecated. - `ref_block_hash`: now block hash in transaction head. + `ref_block_hash`:intercepted part of the now block hash in transaction head.. `expiration`: the expiration time in transaction head. @@ -565,15 +565,15 @@ Transaction and transaction-related messages. ```java message raw { bytes ref_block_bytes = 1; - int64 ref_block_num = 3; + int64 ref_block_num = 3; bytes ref_block_hash = 4; - int64 expiration = 8; + int64 expiration = 8; repeated authority auths = 9; - bytes data = 10; + bytes data = 10; repeated Contract contract = 11; - bytes scripts = 12; + bytes scripts = 12; int64 timestamp = 14; - int64 fee_limit = 18; + int64 fee_limit = 18; } ``` @@ -620,6 +620,14 @@ Transaction and transaction-related messages. ClearABIContract = 48; UpdateBrokerageContract = 49; ShieldedTransferContract = 51; + MarketSellAssetContract = 52; + MarketCancelOrderContract = 53; + FreezeBalanceV2Contract = 54; + UnfreezeBalanceV2Contract = 55; + WithdrawExpireUnfreezeContract = 56; + DelegateResourceContract = 57; + UnDelegateResourceContract = 58; + CancelAllUnfreezeV2Contract = 59; } ContractType type = 1; google.protobuf.Any parameter = 2; @@ -873,6 +881,14 @@ Contract and contract-related messages. ClearABIContract = 48; UpdateBrokerageContract = 49; ShieldedTransferContract = 51; + MarketSellAssetContract = 52; + MarketCancelOrderContract = 53; + FreezeBalanceV2Contract = 54; + UnfreezeBalanceV2Contract = 55; + WithdrawExpireUnfreezeContract = 56; + DelegateResourceContract = 57; + UnDelegateResourceContract = 58; + CancelAllUnfreezeV2Contract = 59; } ContractType type = 1; google.protobuf.Any parameter = 2; @@ -959,7 +975,7 @@ Contract and contract-related messages. - message `VoteAssetContract` - `owner_address`: assress of contract owner. + `owner_address`: address of contract owner. `vote_address`: voted address of asset. @@ -1043,7 +1059,7 @@ Contract and contract-related messages. `total_supply`: maximum of asset. - `frozen_supply`: frozen supplt of asset. + `frozen_supply`: frozen supply of asset. `trx_num`: trx num defines token price. @@ -1063,11 +1079,11 @@ Contract and contract-related messages. `free_asset_net_limit`: free bandwidth limit each account owns when transfers asset. - `public_free_asset_net_limit`: free bandwidth limit for all acoounts. + `public_free_asset_net_limit`: free bandwidth limit for all accounts. `public_free_asset_net_usage`: free bandwidth usage of all accounts. - `public_latest_free_net_time`: the latest bandwidth consumption time fo token transfer. + `public_latest_free_net_time`: the latest bandwidth consumption time for token transfer. ```java message AssetIssueContract { @@ -1115,7 +1131,7 @@ Contract and contract-related messages. `owner_address`: owner address. - `to_address`: reveiver address. + `to_address`: receiver address. `asset_name`: target asset name. @@ -1445,7 +1461,7 @@ Contract and contract-related messages. `owner_address`: address of owner. - `owner`: autuority to execute all contracts. + `owner`: authority to execute all contracts. `witness`: used by SR for generating blocks. @@ -1498,7 +1514,7 @@ Contract and contract-related messages. `binding_signature`: signature to verify transaction. - `transparent_to_address`: transparent address of reveiver. + `transparent_to_address`: transparent address of receiver. `to_amount`: amount to transparent to_address @@ -1520,7 +1536,7 @@ Contract and contract-related messages. ### Smart Contract -message `SmartContract` has mutiple attributes and nested message `ABI` +message `SmartContract` has multiple attributes and nested message `ABI` - message `SmartContract` @@ -1543,7 +1559,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` - message `Param` - `indexed`: `true` if the field is part of the log’s topics, `false` if it one of the log’s data segment. + `indexed`: `true` if the field is part of the log’s topics, `false` if it is one of the log’s data segment. `name`: name of the parameter. @@ -1741,7 +1757,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` `tree`: incremental merkle tree. - `filled`: this is a array, it contains the root of the subtree which can be combined with the param tree to be a new merkle tree. + `filled`: this is an array, it contains the root of the subtree which can be combined with the param tree to be a new merkle tree. `cursor`: the node that can be combined to a subtree, when they are combined to a subtree, compute its root and put it into the filled. @@ -1766,7 +1782,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` `vouchers`: this is an array, each items represents the merklevoucher of the outputpoint. - `paths`: his is an array each items represents the path of the outputpoint. + `paths`: this is an array each items represents the path of the outputpoint. ```java message IncrementalMerkleVoucherInfo { @@ -2019,7 +2035,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` TOO_MANY_PEERS = 0x04; DUPLICATE_PEER = 0x05; INCOMPATIBLE_PROTOCOL = 0x06; - NULL_IDENTITY = 0x07; + RANDOM_ELIMINATION = 0x07; PEER_QUITING = 0x08; UNEXPECTED_IDENTITY = 0x09; LOCAL_IDENTITY = 0x0A; @@ -2108,13 +2124,13 @@ message `SmartContract` has mutiple attributes and nested message `ABI` - #### Node Information - Node information is separaed into several parts and implemented by nested messages. + Node information is separated into several parts and implemented by nested messages. - message `NodeInfo` - `beginSyncNum`: beginning block height for synchornize. + `beginSyncNum`: beginning block height for synchronize. `block`: head block id. @@ -2138,13 +2154,13 @@ message `SmartContract` has mutiple attributes and nested message `ABI` - message `PeerInfo`: - `lastSyncBlock`: last block id for synchornize. + `lastSyncBlock`: last block id for synchronize. `remainNum`: number of remaining blocks. `lastBlockUpdateTime`: latest block update time . - `syncFlag`: is synchroniing or not. + `syncFlag`: is synchronizing or not. `headBlockTimeWeBothHave`: timestamp of common head block. @@ -2156,7 +2172,7 @@ message `SmartContract` has mutiple attributes and nested message `ABI` `port`: listening port. - `nodeId`: ramdomly generated node ID + `nodeId`: randomly generated node ID `connectTime`: connection time period from established. diff --git a/actuator/build.gradle b/actuator/build.gradle index 34bfc018500..1143dc83618 100644 --- a/actuator/build.gradle +++ b/actuator/build.gradle @@ -1,28 +1,9 @@ description = "actuator – a series of transactions for blockchain." -// Dependency versions -// --------------------------------------- - -def junitVersion = "4.12" -def mockitoVersion = "2.1.0" -def testNgVersion = "6.11" -def slf4jVersion = "1.7.25" -// -------------------------------------- - dependencies { - compile project(":chainbase") - compile project(":protocol") - compile project(":crypto") - testImplementation "junit:junit:$junitVersion" - testImplementation "org.mockito:mockito-core:$mockitoVersion" - - testImplementation "org.testng:testng:$testNgVersion" - - compile "org.slf4j:jcl-over-slf4j:$slf4jVersion" - compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' - compile 'com.github.tronprotocol:zksnark-java-sdk:master-SNAPSHOT' - compile group: 'commons-codec', name: 'commons-codec', version: '1.11' - compile 'org.reflections:reflections:0.9.11' + api project(":chainbase") + api project(":protocol") + api project(":crypto") } test { @@ -50,34 +31,15 @@ test { } } -task testng(type: Test) { - useTestNG() - testLogging { - events = ["skipped", "failed"] - exceptionFormat = "full" - - debug.events = ["skipped", "failed"] - debug.exceptionFormat = "full" - - info.events = ["failed", "skipped"] - info.exceptionFormat = "full" - - warn.events = ["failed", "skipped"] - warn.exceptionFormat = "full" - } -} - jacocoTestReport { reports { xml.enabled = true html.enabled = true } - executionData.from = '../framework/build/jacoco/jacocoTest.exec' + getExecutionData().setFrom(fileTree('../framework/build/jacoco').include("**.exec")) afterEvaluate { classDirectories.from = classDirectories.files.collect { fileTree(dir: it,) } } } - -check.dependsOn testng diff --git a/actuator/src/main/java/org/tron/core/actuator/AbstractActuator.java b/actuator/src/main/java/org/tron/core/actuator/AbstractActuator.java index c88baf9b3ca..c9f83c520bd 100644 --- a/actuator/src/main/java/org/tron/core/actuator/AbstractActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/AbstractActuator.java @@ -2,9 +2,14 @@ import com.google.protobuf.Any; import com.google.protobuf.GeneratedMessageV3; +import org.tron.common.math.Maths; +import org.tron.common.utils.Commons; import org.tron.common.utils.ForkController; import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.exception.BalanceInsufficientException; +import org.tron.core.store.AccountStore; import org.tron.protos.Protocol.Transaction.Contract; import org.tron.protos.Protocol.Transaction.Contract.ContractType; @@ -63,4 +68,61 @@ public AbstractActuator setForkUtils(ForkController forkController) { return this; } + public long addExact(long x, long y) { + return Maths.addExact(x, y, this.disableJavaLangMath()); + } + + public long addExact(int x, int y) { + return Maths.addExact(x, y, this.disableJavaLangMath()); + } + + public long floorDiv(long x, long y) { + return Maths.floorDiv(x, y, this.disableJavaLangMath()); + } + + public long floorDiv(long x, int y) { + return this.floorDiv(x, (long) y); + } + + public long multiplyExact(long x, long y) { + return Maths.multiplyExact(x, y, this.disableJavaLangMath()); + } + + public long multiplyExact(long x, int y) { + return this.multiplyExact(x, (long) y); + } + + public int multiplyExact(int x, int y) { + return Maths.multiplyExact(x, y, this.disableJavaLangMath()); + } + + public long subtractExact(long x, long y) { + return Maths.subtractExact(x, y, this.disableJavaLangMath()); + } + + public int min(int a, int b) { + return Maths.min(a, b, this.disableJavaLangMath()); + } + + public long min(long a, long b) { + return Maths.min(a, b, this.disableJavaLangMath()); + } + + public void adjustBalance(AccountStore accountStore, byte[] accountAddress, long amount) + throws BalanceInsufficientException { + AccountCapsule account = accountStore.getUnchecked(accountAddress); + this.adjustBalance(accountStore, account, amount); + } + + /** + * judge balance. + */ + public void adjustBalance(AccountStore accountStore, AccountCapsule account, long amount) + throws BalanceInsufficientException { + Commons.adjustBalance(accountStore, account, amount, this.disableJavaLangMath()); + } + + boolean disableJavaLangMath() { + return chainBaseManager.getDynamicPropertiesStore().disableJavaLangMath(); + } } diff --git a/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java b/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java index fcc4d775d43..f2eafb20a5e 100644 --- a/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/AccountPermissionUpdateActuator.java @@ -8,7 +8,6 @@ import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; @@ -52,11 +51,11 @@ public boolean execute(Object object) throws ContractExeException { accountPermissionUpdateContract.getActivesList()); accountStore.put(ownerAddress, account); - Commons.adjustBalance(accountStore, ownerAddress, -fee); + adjustBalance(accountStore, ownerAddress, -fee); if (chainBaseManager.getDynamicPropertiesStore().supportBlackHoleOptimization()) { chainBaseManager.getDynamicPropertiesStore().burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } result.setStatus(fee, code.SUCESS); @@ -111,7 +110,7 @@ private boolean checkPermission(Permission permission) throws ContractValidateEx throw new ContractValidateException("key's weight should be greater than 0"); } try { - weightSum = Math.addExact(weightSum, key.getWeight()); + weightSum = addExact(weightSum, key.getWeight()); } catch (ArithmeticException e) { throw new ContractValidateException(e.getMessage()); } diff --git a/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java b/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java index 55218897c5d..331b45f106a 100644 --- a/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/AssetIssueActuator.java @@ -24,7 +24,6 @@ import java.util.List; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; @@ -84,11 +83,11 @@ public boolean execute(Object result) throws ContractExeException { .put(assetIssueCapsuleV2.createDbV2Key(), assetIssueCapsuleV2); } - Commons.adjustBalance(accountStore, ownerAddress, -fee); + adjustBalance(accountStore, ownerAddress, -fee); if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee);//send to blackhole + adjustBalance(accountStore, accountStore.getBlackhole(), fee);//send to blackhole } AccountCapsule accountCapsule = accountStore.get(ownerAddress); List frozenSupplyList = assetIssueContract.getFrozenSupplyList(); diff --git a/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java new file mode 100755 index 00000000000..048f703e9f7 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/CancelAllUnfreezeV2Actuator.java @@ -0,0 +1,206 @@ +package org.tron.core.actuator; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicLong; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol.Account.UnFreezeV2; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.BalanceContract.CancelAllUnfreezeV2Contract; + +@Slf4j(topic = "actuator") +public class CancelAllUnfreezeV2Actuator extends AbstractActuator { + + public CancelAllUnfreezeV2Actuator() { + super(ContractType.CancelAllUnfreezeV2Contract, CancelAllUnfreezeV2Contract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + long fee = calcFee(); + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + byte[] ownerAddress; + try { + ownerAddress = getOwnerAddress().toByteArray(); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + AccountCapsule ownerCapsule = accountStore.get(ownerAddress); + List unfrozenV2List = ownerCapsule.getUnfrozenV2List(); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + AtomicLong atomicWithdrawExpireBalance = new AtomicLong(0L); + /* The triple object is defined by resource type, with left representing the pair object + corresponding to bandwidth, middle representing the pair object corresponding to energy, and + right representing the pair object corresponding to tron power. The pair object for each + resource type, left represents resource weight, and right represents the number of unfreeze + resources for that resource type. */ + Triple, Pair, Pair> + triple = Triple.of( + Pair.of(new AtomicLong(0L), new AtomicLong(0L)), + Pair.of(new AtomicLong(0L), new AtomicLong(0L)), + Pair.of(new AtomicLong(0L), new AtomicLong(0L))); + for (UnFreezeV2 unFreezeV2 : unfrozenV2List) { + updateAndCalculate(triple, ownerCapsule, now, atomicWithdrawExpireBalance, unFreezeV2); + } + ownerCapsule.clearUnfrozenV2(); + addTotalResourceWeight(dynamicStore, triple); + + long withdrawExpireBalance = atomicWithdrawExpireBalance.get(); + if (withdrawExpireBalance > 0) { + ownerCapsule.setBalance(ownerCapsule.getBalance() + withdrawExpireBalance); + } + + accountStore.put(ownerCapsule.createDbKey(), ownerCapsule); + ret.setWithdrawExpireAmount(withdrawExpireBalance); + Map cancelUnfreezeV2AmountMap = new HashMap<>(); + cancelUnfreezeV2AmountMap.put(BANDWIDTH.name(), triple.getLeft().getRight().get()); + cancelUnfreezeV2AmountMap.put(ENERGY.name(), triple.getMiddle().getRight().get()); + cancelUnfreezeV2AmountMap.put(TRON_POWER.name(), triple.getRight().getRight().get()); + ret.putAllCancelUnfreezeV2AmountMap(cancelUnfreezeV2AmountMap); + ret.setStatus(fee, code.SUCESS); + return true; + } + + private void addTotalResourceWeight(DynamicPropertiesStore dynamicStore, + Triple, + Pair, + Pair> triple) { + dynamicStore.addTotalNetWeight(triple.getLeft().getLeft().get()); + dynamicStore.addTotalEnergyWeight(triple.getMiddle().getLeft().get()); + dynamicStore.addTotalTronPowerWeight(triple.getRight().getLeft().get()); + } + + private void updateAndCalculate(Triple, Pair, + Pair> triple, + AccountCapsule ownerCapsule, long now, AtomicLong atomicLong, UnFreezeV2 unFreezeV2) { + if (unFreezeV2.getUnfreezeExpireTime() > now) { + updateFrozenInfoAndTotalResourceWeight(ownerCapsule, unFreezeV2, triple); + } else { + atomicLong.addAndGet(unFreezeV2.getUnfreezeAmount()); + } + } + + @Override + public boolean validate() throws ContractValidateException { + if (Objects.isNull(this.any)) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + + if (Objects.isNull(chainBaseManager)) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + + if (!this.any.is(CancelAllUnfreezeV2Contract.class)) { + throw new ContractValidateException("contract type error, expected type " + + "[CancelAllUnfreezeV2Contract], real type[" + any.getClass() + "]"); + } + + if (!dynamicStore.supportAllowCancelAllUnfreezeV2()) { + throw new ContractValidateException("Not support CancelAllUnfreezeV2 transaction," + + " need to be opened by the committee"); + } + + byte[] ownerAddress; + try { + ownerAddress = getOwnerAddress().toByteArray(); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = accountStore.get(ownerAddress); + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + if (Objects.isNull(accountCapsule)) { + throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + + readableOwnerAddress + NOT_EXIST_STR); + } + + List unfrozenV2List = accountCapsule.getUnfrozenV2List(); + if (unfrozenV2List.isEmpty()) { + throw new ContractValidateException("No unfreezeV2 list to cancel"); + } + + return true; + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return getCancelAllUnfreezeV2Contract().getOwnerAddress(); + } + + private CancelAllUnfreezeV2Contract getCancelAllUnfreezeV2Contract() + throws InvalidProtocolBufferException { + return any.unpack(CancelAllUnfreezeV2Contract.class); + } + + @Override + public long calcFee() { + return 0; + } + + public void updateFrozenInfoAndTotalResourceWeight( + AccountCapsule accountCapsule, UnFreezeV2 unFreezeV2, + Triple, Pair, + Pair> triple) { + switch (unFreezeV2.getType()) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(unFreezeV2.getUnfreezeAmount()); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + triple.getLeft().getLeft().addAndGet(newNetWeight - oldNetWeight); + triple.getLeft().getRight().addAndGet(unFreezeV2.getUnfreezeAmount()); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(unFreezeV2.getUnfreezeAmount()); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + triple.getMiddle().getLeft().addAndGet(newEnergyWeight - oldEnergyWeight); + triple.getMiddle().getRight().addAndGet(unFreezeV2.getUnfreezeAmount()); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(unFreezeV2.getUnfreezeAmount()); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + triple.getRight().getLeft().addAndGet(newTPWeight - oldTPWeight); + triple.getRight().getRight().addAndGet(unFreezeV2.getUnfreezeAmount()); + break; + default: + break; + } + } +} diff --git a/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java b/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java index 5e0b2367dc5..7ce96d3318c 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ClearABIContractActuator.java @@ -1,5 +1,7 @@ package org.tron.core.actuator; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; + import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Arrays; @@ -16,13 +18,10 @@ import org.tron.core.store.AbiStore; import org.tron.core.store.AccountStore; import org.tron.core.store.ContractStore; -import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.code; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; - -import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; @Slf4j(topic = "actuator") public class ClearABIContractActuator extends AbstractActuator { @@ -57,17 +56,16 @@ public boolean execute(Object result) throws ContractExeException { @Override public boolean validate() throws ContractValidateException { - if (!VMConfig.allowTvmConstantinople()) { - throw new ContractValidateException( - "contract type error,unexpected type [ClearABIContract]"); - } - if (this.any == null) { throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); } if (chainBaseManager == null) { throw new ContractValidateException("No account store or contract store!"); } + if (chainBaseManager.getDynamicPropertiesStore().getAllowTvmConstantinople() == 0) { + throw new ContractValidateException( + "contract type error,unexpected type [ClearABIContract]"); + } AccountStore accountStore = chainBaseManager.getAccountStore(); ContractStore contractStore = chainBaseManager.getContractStore(); if (!this.any.is(ClearABIContract.class)) { diff --git a/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java b/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java index 1c6aca4d7d7..352f394d6cb 100755 --- a/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/CreateAccountActuator.java @@ -6,7 +6,6 @@ import com.google.protobuf.InvalidProtocolBufferException; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; @@ -48,13 +47,12 @@ public boolean execute(Object result) accountStore .put(accountCreateContract.getAccountAddress().toByteArray(), accountCapsule); - Commons - .adjustBalance(accountStore, accountCreateContract.getOwnerAddress().toByteArray(), -fee); + adjustBalance(accountStore, accountCreateContract.getOwnerAddress().toByteArray(), -fee); // Add to blackhole address if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException | InvalidProtocolBufferException e) { diff --git a/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java b/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java new file mode 100755 index 00000000000..9e7b0efa5ce --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/DelegateResourceActuator.java @@ -0,0 +1,327 @@ +package org.tron.core.actuator; + +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.core.vm.utils.FreezeV2Util.getV2EnergyUsage; +import static org.tron.core.vm.utils.FreezeV2Util.getV2NetUsage; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.Arrays; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.EnergyProcessor; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DelegatedResourceAccountIndexStore; +import org.tron.core.store.DelegatedResourceStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.utils.TransactionUtil; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; + +@Slf4j(topic = "actuator") +public class DelegateResourceActuator extends AbstractActuator { + + public DelegateResourceActuator() { + super(ContractType.DelegateResourceContract, DelegateResourceContract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + + long fee = calcFee(); + final DelegateResourceContract delegateResourceContract; + AccountStore accountStore = chainBaseManager.getAccountStore(); + byte[] ownerAddress; + try { + delegateResourceContract = this.any.unpack(DelegateResourceContract.class); + ownerAddress = getOwnerAddress().toByteArray(); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + + AccountCapsule ownerCapsule = accountStore + .get(delegateResourceContract.getOwnerAddress().toByteArray()); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + long delegateBalance = delegateResourceContract.getBalance(); + boolean lock = delegateResourceContract.getLock(); + long lockPeriod = getLockPeriod(dynamicStore.supportMaxDelegateLockPeriod(), + delegateResourceContract); + byte[] receiverAddress = delegateResourceContract.getReceiverAddress().toByteArray(); + + // delegate resource to receiver + switch (delegateResourceContract.getResource()) { + case BANDWIDTH: + delegateResource(ownerAddress, receiverAddress, true, + delegateBalance, lock, lockPeriod); + + ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + ownerCapsule.addFrozenBalanceForBandwidthV2(-delegateBalance); + break; + case ENERGY: + delegateResource(ownerAddress, receiverAddress, false, + delegateBalance, lock, lockPeriod); + + ownerCapsule.addDelegatedFrozenV2BalanceForEnergy(delegateBalance); + ownerCapsule.addFrozenBalanceForEnergyV2(-delegateBalance); + break; + default: + logger.debug("Resource Code Error."); + } + + accountStore.put(ownerCapsule.createDbKey(), ownerCapsule); + + ret.setStatus(fee, code.SUCESS); + + return true; + } + + + @Override + public boolean validate() throws ContractValidateException { + if (this.any == null) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + if (chainBaseManager == null) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); + if (!any.is(DelegateResourceContract.class)) { + throw new ContractValidateException( + "contract type error,expected type [DelegateResourceContract],real type[" + + any.getClass() + "]"); + } + + if (!dynamicStore.supportDR()) { + throw new ContractValidateException("No support for resource delegate"); + } + + if (!dynamicStore.supportUnfreezeDelay()) { + throw new ContractValidateException("Not support Delegate resource transaction," + + " need to be opened by the committee"); + } + + final DelegateResourceContract delegateResourceContract; + byte[] ownerAddress; + try { + delegateResourceContract = this.any.unpack(DelegateResourceContract.class); + ownerAddress = getOwnerAddress().toByteArray(); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + + AccountCapsule ownerCapsule = accountStore.get(ownerAddress); + if (ownerCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ActuatorConstant.ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); + } + + long delegateBalance = delegateResourceContract.getBalance(); + if (delegateBalance < TRX_PRECISION) { + throw new ContractValidateException("delegateBalance must be greater than or equal to 1 TRX"); + } + + switch (delegateResourceContract.getResource()) { + case BANDWIDTH: { + BandwidthProcessor processor = new BandwidthProcessor(chainBaseManager); + processor.updateUsageForDelegated(ownerCapsule); + + long accountNetUsage = ownerCapsule.getNetUsage(); + if (null != this.getTx() && this.getTx().isTransactionCreate()) { + accountNetUsage += TransactionUtil.estimateConsumeBandWidthSize(dynamicStore, + ownerCapsule.getFrozenV2BalanceForBandwidth()); + } + long netUsage = (long) (accountNetUsage * TRX_PRECISION * ((double) + (dynamicStore.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); + long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage, + this.disableJavaLangMath()); + if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) { + throw new ContractValidateException( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance"); + } + } + break; + case ENERGY: { + EnergyProcessor processor = new EnergyProcessor(dynamicStore, accountStore); + processor.updateUsage(ownerCapsule); + + long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double) + (dynamicStore.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit())); + long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage, + this.disableJavaLangMath()); + if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) { + throw new ContractValidateException( + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance"); + } + } + break; + default: + throw new ContractValidateException( + "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + + byte[] receiverAddress = delegateResourceContract.getReceiverAddress().toByteArray(); + + if (!DecodeUtil.addressValid(receiverAddress)) { + throw new ContractValidateException("Invalid receiverAddress"); + } + + + if (Arrays.equals(receiverAddress, ownerAddress)) { + throw new ContractValidateException( + "receiverAddress must not be the same as ownerAddress"); + } + + AccountCapsule receiverCapsule = accountStore.get(receiverAddress); + if (receiverCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(receiverAddress); + throw new ContractValidateException( + ActuatorConstant.ACCOUNT_EXCEPTION_STR + + readableOwnerAddress + NOT_EXIST_STR); + } + + boolean lock = delegateResourceContract.getLock(); + if (lock && dynamicStore.supportMaxDelegateLockPeriod()) { + long lockPeriod = getLockPeriod(true, delegateResourceContract); + long maxDelegateLockPeriod = dynamicStore.getMaxDelegateLockPeriod(); + if (lockPeriod < 0 || lockPeriod > maxDelegateLockPeriod) { + throw new ContractValidateException( + "The lock period of delegate resource cannot be less than 0 and cannot exceed " + + maxDelegateLockPeriod + "!"); + } + + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, true); + DelegatedResourceCapsule delegatedResourceCapsule = delegatedResourceStore.get(key); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + if (delegatedResourceCapsule != null) { + switch (delegateResourceContract.getResource()) { + case BANDWIDTH: { + validRemainTime(BANDWIDTH, lockPeriod, + delegatedResourceCapsule.getExpireTimeForBandwidth(), now); + } + break; + case ENERGY: { + validRemainTime(ENERGY, lockPeriod, + delegatedResourceCapsule.getExpireTimeForEnergy(), now); + } + break; + default: + throw new ContractValidateException( + "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + } + } + + if (receiverCapsule.getType() == AccountType.Contract) { + throw new ContractValidateException( + "Do not allow delegate resources to contract addresses"); + } + + return true; + } + + private long getLockPeriod(boolean supportMaxDelegateLockPeriod, + DelegateResourceContract delegateResourceContract) { + long lockPeriod = delegateResourceContract.getLockPeriod(); + if (supportMaxDelegateLockPeriod) { + return lockPeriod == 0 ? DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL : lockPeriod; + } else { + return DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL; + } + } + + private void validRemainTime(ResourceCode resourceCode, long lockPeriod, long expireTime, + long now) throws ContractValidateException { + long remainTime = expireTime - now; + if (lockPeriod * BLOCK_PRODUCED_INTERVAL < remainTime) { + throw new ContractValidateException( + "The lock period for " + resourceCode.name() + " this time cannot be less than the " + + "remaining time[" + remainTime + "ms] of the last lock period for " + + resourceCode.name() + "!"); + } + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return any.unpack(DelegateResourceContract.class).getOwnerAddress(); + } + + @Override + public long calcFee() { + return 0; + } + + private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boolean isBandwidth, + long balance, boolean lock, long lockPeriod) { + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicPropertiesStore = chainBaseManager.getDynamicPropertiesStore(); + DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); + DelegatedResourceAccountIndexStore delegatedResourceAccountIndexStore = chainBaseManager + .getDelegatedResourceAccountIndexStore(); + + // 1. unlock the expired delegate resource + long now = chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + delegatedResourceStore.unLockExpireResource(ownerAddress, receiverAddress, now); + + //modify DelegatedResourceStore + long expireTime = 0; + if (lock) { + expireTime = now + lockPeriod * BLOCK_PRODUCED_INTERVAL; + } + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, lock); + DelegatedResourceCapsule delegatedResourceCapsule = delegatedResourceStore.get(key); + if (delegatedResourceCapsule == null) { + delegatedResourceCapsule = new DelegatedResourceCapsule(ByteString.copyFrom(ownerAddress), + ByteString.copyFrom(receiverAddress)); + } + + if (isBandwidth) { + delegatedResourceCapsule.addFrozenBalanceForBandwidth(balance, expireTime); + } else { + delegatedResourceCapsule.addFrozenBalanceForEnergy(balance, expireTime); + } + delegatedResourceStore.put(key, delegatedResourceCapsule); + + //modify DelegatedResourceAccountIndexStore + delegatedResourceAccountIndexStore.delegateV2(ownerAddress, receiverAddress, + dynamicPropertiesStore.getLatestBlockHeaderTimestamp()); + + //modify AccountStore for receiver + AccountCapsule receiverCapsule = accountStore.get(receiverAddress); + if (isBandwidth) { + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(balance); + } else { + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(balance); + } + accountStore.put(receiverCapsule.createDbKey(), receiverCapsule); + } + +} diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java index b7f5b90da45..27d3da509b4 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeCreateActuator.java @@ -9,7 +9,6 @@ import java.util.Arrays; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; @@ -121,7 +120,7 @@ public boolean execute(Object object) throws ContractExeException { if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } ret.setExchangeId(id); ret.setStatus(fee, code.SUCESS); diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java index 7848f898ced..482f5bdf081 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeInjectActuator.java @@ -71,14 +71,14 @@ public boolean execute(Object object) throws ContractExeException { if (Arrays.equals(tokenID, firstTokenID)) { anotherTokenID = secondTokenID; - anotherTokenQuant = Math - .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance); + anotherTokenQuant = floorDiv(multiplyExact( + secondTokenBalance, tokenQuant), firstTokenBalance); exchangeCapsule.setBalance(firstTokenBalance + tokenQuant, secondTokenBalance + anotherTokenQuant); } else { anotherTokenID = firstTokenID; - anotherTokenQuant = Math - .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance); + anotherTokenQuant = floorDiv(multiplyExact( + firstTokenBalance, tokenQuant), secondTokenBalance); exchangeCapsule.setBalance(firstTokenBalance + anotherTokenQuant, secondTokenBalance + tokenQuant); } diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java index 612f673832e..6f50d61c235 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeTransactionActuator.java @@ -66,7 +66,8 @@ public boolean execute(Object object) throws ContractExeException { long tokenQuant = exchangeTransactionContract.getQuant(); byte[] anotherTokenID; - long anotherTokenQuant = exchangeCapsule.transaction(tokenID, tokenQuant); + long anotherTokenQuant = exchangeCapsule.transaction(tokenID, tokenQuant, + dynamicStore.allowStrictMath()); if (Arrays.equals(tokenID, firstTokenID)) { anotherTokenID = secondTokenID; @@ -205,7 +206,8 @@ public boolean validate() throws ContractValidateException { } } - long anotherTokenQuant = exchangeCapsule.transaction(tokenID, tokenQuant); + long anotherTokenQuant = exchangeCapsule.transaction(tokenID, tokenQuant, + dynamicStore.allowStrictMath()); if (anotherTokenQuant < tokenExpected) { throw new ContractValidateException("token required must greater than expected"); } diff --git a/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java b/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java index 8929305d68c..fb8fe9384d3 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ExchangeWithdrawActuator.java @@ -76,16 +76,12 @@ public boolean execute(Object object) throws ContractExeException { BigInteger bigTokenQuant = new BigInteger(String.valueOf(tokenQuant)); if (Arrays.equals(tokenID, firstTokenID)) { anotherTokenID = secondTokenID; -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance); anotherTokenQuant = bigSecondTokenBalance.multiply(bigTokenQuant) .divide(bigFirstTokenBalance).longValueExact(); exchangeCapsule.setBalance(firstTokenBalance - tokenQuant, secondTokenBalance - anotherTokenQuant); } else { anotherTokenID = firstTokenID; -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance); anotherTokenQuant = bigFirstTokenBalance.multiply(bigTokenQuant) .divide(bigSecondTokenBalance).longValueExact(); exchangeCapsule.setBalance(firstTokenBalance - anotherTokenQuant, @@ -210,8 +206,6 @@ public boolean validate() throws ContractValidateException { BigDecimal bigSecondTokenBalance = new BigDecimal(String.valueOf(secondTokenBalance)); BigDecimal bigTokenQuant = new BigDecimal(String.valueOf(tokenQuant)); if (Arrays.equals(tokenID, firstTokenID)) { -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(secondTokenBalance, tokenQuant), firstTokenBalance); anotherTokenQuant = bigSecondTokenBalance.multiply(bigTokenQuant) .divideToIntegralValue(bigFirstTokenBalance).longValueExact(); if (firstTokenBalance < tokenQuant || secondTokenBalance < anotherTokenQuant) { @@ -230,8 +224,6 @@ public boolean validate() throws ContractValidateException { } } else { -// anotherTokenQuant = Math -// .floorDiv(Math.multiplyExact(firstTokenBalance, tokenQuant), secondTokenBalance); anotherTokenQuant = bigFirstTokenBalance.multiply(bigTokenQuant) .divideToIntegralValue(bigSecondTokenBalance).longValueExact(); if (secondTokenBalance < tokenQuant || firstTokenBalance < anotherTokenQuant) { diff --git a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java index f026a8769e6..421b4e3013a 100755 --- a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceActuator.java @@ -3,6 +3,10 @@ import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; @@ -72,44 +76,48 @@ public boolean execute(Object result) throws ContractExeException { byte[] ownerAddress = freezeBalanceContract.getOwnerAddress().toByteArray(); byte[] receiverAddress = freezeBalanceContract.getReceiverAddress().toByteArray(); + long increment; switch (freezeBalanceContract.getResource()) { case BANDWIDTH: if (!ArrayUtils.isEmpty(receiverAddress) && dynamicStore.supportDR()) { - delegateResource(ownerAddress, receiverAddress, true, - frozenBalance, expireTime); + increment = delegateResource(ownerAddress, receiverAddress, true, + frozenBalance, expireTime); accountCapsule.addDelegatedFrozenBalanceForBandwidth(frozenBalance); } else { + long oldNetWeight = accountCapsule.getFrozenBalance() / TRX_PRECISION; long newFrozenBalanceForBandwidth = frozenBalance + accountCapsule.getFrozenBalance(); accountCapsule.setFrozenForBandwidth(newFrozenBalanceForBandwidth, expireTime); + long newNetWeight = accountCapsule.getFrozenBalance() / TRX_PRECISION; + increment = newNetWeight - oldNetWeight; } - dynamicStore - .addTotalNetWeight(frozenBalance / TRX_PRECISION); + addTotalWeight(BANDWIDTH, dynamicStore, frozenBalance, increment); break; case ENERGY: if (!ArrayUtils.isEmpty(receiverAddress) && dynamicStore.supportDR()) { - delegateResource(ownerAddress, receiverAddress, false, - frozenBalance, expireTime); + increment = delegateResource(ownerAddress, receiverAddress, false, + frozenBalance, expireTime); accountCapsule.addDelegatedFrozenBalanceForEnergy(frozenBalance); } else { + long oldEnergyWeight = accountCapsule.getEnergyFrozenBalance() / TRX_PRECISION; long newFrozenBalanceForEnergy = - frozenBalance + accountCapsule.getAccountResource() - .getFrozenBalanceForEnergy() - .getFrozenBalance(); + frozenBalance + accountCapsule.getEnergyFrozenBalance(); accountCapsule.setFrozenForEnergy(newFrozenBalanceForEnergy, expireTime); + long newEnergyWeight = accountCapsule.getEnergyFrozenBalance() / TRX_PRECISION; + increment = newEnergyWeight - oldEnergyWeight; } - dynamicStore - .addTotalEnergyWeight(frozenBalance / TRX_PRECISION); + addTotalWeight(ENERGY, dynamicStore, frozenBalance, increment); break; case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenBalance() / TRX_PRECISION; long newFrozenBalanceForTronPower = frozenBalance + accountCapsule.getTronPowerFrozenBalance(); accountCapsule.setFrozenForTronPower(newFrozenBalanceForTronPower, expireTime); - - dynamicStore - .addTotalTronPowerWeight(frozenBalance / TRX_PRECISION); + long newTPWeight = accountCapsule.getTronPowerFrozenBalance() / TRX_PRECISION; + increment = newTPWeight - oldTPWeight; + addTotalWeight(TRON_POWER, dynamicStore, frozenBalance, increment); break; default: logger.debug("Resource Code Error."); @@ -123,6 +131,23 @@ public boolean execute(Object result) throws ContractExeException { return true; } + private void addTotalWeight(ResourceCode resourceCode, DynamicPropertiesStore dynamicStore, + long frozenBalance, long increment) { + long weight = dynamicStore.allowNewReward() ? increment : frozenBalance / TRX_PRECISION; + switch (resourceCode) { + case BANDWIDTH: + dynamicStore.addTotalNetWeight(weight); + break; + case ENERGY: + dynamicStore.addTotalEnergyWeight(weight); + break; + case TRON_POWER: + dynamicStore.addTotalTronPowerWeight(weight); + break; + default: + logger.debug("Resource Code Error."); + } + } @Override public boolean validate() throws ContractValidateException { @@ -164,7 +189,7 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("frozenBalance must be positive"); } if (frozenBalance < TRX_PRECISION) { - throw new ContractValidateException("frozenBalance must be more than 1TRX"); + throw new ContractValidateException("frozenBalance must be greater than or equal to 1 TRX"); } int frozenCount = accountCapsule.getFrozenCount(); @@ -172,14 +197,9 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("frozenCount must be 0 or 1"); } if (frozenBalance > accountCapsule.getBalance()) { - throw new ContractValidateException("frozenBalance must be less than accountBalance"); + throw new ContractValidateException("frozenBalance must be less than or equal to accountBalance"); } -// long maxFrozenNumber = dbManager.getDynamicPropertiesStore().getMaxFrozenNumber(); -// if (accountCapsule.getFrozenCount() >= maxFrozenNumber) { -// throw new ContractValidateException("max frozen number is: " + maxFrozenNumber); -// } - long frozenDuration = freezeBalanceContract.getFrozenDuration(); long minFrozenTime = dynamicStore.getMinFrozenTime(); long maxFrozenTime = dynamicStore.getMaxFrozenTime(); @@ -224,8 +244,7 @@ public boolean validate() throws ContractValidateException { //If the receiver is included in the contract, the receiver will receive the resource. if (!ArrayUtils.isEmpty(receiverAddress) && dynamicStore.supportDR()) { if (Arrays.equals(receiverAddress, ownerAddress)) { - throw new ContractValidateException( - "receiverAddress must not be the same as ownerAddress"); + throw new ContractValidateException("receiverAddress must not be the same as ownerAddress"); } if (!DecodeUtil.addressValid(receiverAddress)) { @@ -249,6 +268,11 @@ public boolean validate() throws ContractValidateException { } + if (dynamicStore.supportUnfreezeDelay()) { + throw new ContractValidateException( + "freeze v2 is open, old freeze is closed"); + } + return true; } @@ -262,9 +286,10 @@ public long calcFee() { return 0; } - private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boolean isBandwidth, + private long delegateResource(byte[] ownerAddress, byte[] receiverAddress, boolean isBandwidth, long balance, long expireTime) { AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicPropertiesStore = chainBaseManager.getDynamicPropertiesStore(); DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); DelegatedResourceAccountIndexStore delegatedResourceAccountIndexStore = chainBaseManager .getDelegatedResourceAccountIndexStore(); @@ -292,46 +317,56 @@ private void delegateResource(byte[] ownerAddress, byte[] receiverAddress, boole delegatedResourceStore.put(key, delegatedResourceCapsule); //modify DelegatedResourceAccountIndexStore - { - DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = delegatedResourceAccountIndexStore - .get(ownerAddress); - if (delegatedResourceAccountIndexCapsule == null) { - delegatedResourceAccountIndexCapsule = new DelegatedResourceAccountIndexCapsule( + if (!dynamicPropertiesStore.supportAllowDelegateOptimization()) { + + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = + delegatedResourceAccountIndexStore.get(ownerAddress); + if (ownerIndexCapsule == null) { + ownerIndexCapsule = new DelegatedResourceAccountIndexCapsule( ByteString.copyFrom(ownerAddress)); } - List toAccountsList = delegatedResourceAccountIndexCapsule.getToAccountsList(); + List toAccountsList = ownerIndexCapsule.getToAccountsList(); if (!toAccountsList.contains(ByteString.copyFrom(receiverAddress))) { - delegatedResourceAccountIndexCapsule.addToAccount(ByteString.copyFrom(receiverAddress)); + ownerIndexCapsule.addToAccount(ByteString.copyFrom(receiverAddress)); } - delegatedResourceAccountIndexStore - .put(ownerAddress, delegatedResourceAccountIndexCapsule); - } + delegatedResourceAccountIndexStore.put(ownerAddress, ownerIndexCapsule); - { - DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = delegatedResourceAccountIndexStore - .get(receiverAddress); - if (delegatedResourceAccountIndexCapsule == null) { - delegatedResourceAccountIndexCapsule = new DelegatedResourceAccountIndexCapsule( + DelegatedResourceAccountIndexCapsule receiverIndexCapsule + = delegatedResourceAccountIndexStore.get(receiverAddress); + if (receiverIndexCapsule == null) { + receiverIndexCapsule = new DelegatedResourceAccountIndexCapsule( ByteString.copyFrom(receiverAddress)); } - List fromAccountsList = delegatedResourceAccountIndexCapsule + List fromAccountsList = receiverIndexCapsule .getFromAccountsList(); if (!fromAccountsList.contains(ByteString.copyFrom(ownerAddress))) { - delegatedResourceAccountIndexCapsule.addFromAccount(ByteString.copyFrom(ownerAddress)); + receiverIndexCapsule.addFromAccount(ByteString.copyFrom(ownerAddress)); } - delegatedResourceAccountIndexStore - .put(receiverAddress, delegatedResourceAccountIndexCapsule); + delegatedResourceAccountIndexStore.put(receiverAddress, receiverIndexCapsule); + + } else { + // modify DelegatedResourceAccountIndexStore new + delegatedResourceAccountIndexStore.convert(ownerAddress); + delegatedResourceAccountIndexStore.convert(receiverAddress); + delegatedResourceAccountIndexStore.delegate(ownerAddress, receiverAddress, + dynamicPropertiesStore.getLatestBlockHeaderTimestamp()); } //modify AccountStore AccountCapsule receiverCapsule = accountStore.get(receiverAddress); + long oldWeight; + long newWeight; if (isBandwidth) { + oldWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() / TRX_PRECISION; receiverCapsule.addAcquiredDelegatedFrozenBalanceForBandwidth(balance); + newWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() / TRX_PRECISION; } else { + oldWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() / TRX_PRECISION; receiverCapsule.addAcquiredDelegatedFrozenBalanceForEnergy(balance); + newWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() / TRX_PRECISION; } - accountStore.put(receiverCapsule.createDbKey(), receiverCapsule); + return newWeight - oldWeight; } } diff --git a/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java new file mode 100755 index 00000000000..f0e5505be9c --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/FreezeBalanceV2Actuator.java @@ -0,0 +1,176 @@ +package org.tron.core.actuator; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.BalanceContract.FreezeBalanceV2Contract; + +import java.util.Objects; + +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +@Slf4j(topic = "actuator") +public class FreezeBalanceV2Actuator extends AbstractActuator { + + public FreezeBalanceV2Actuator() { + super(ContractType.FreezeBalanceV2Contract, FreezeBalanceV2Contract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + + long fee = calcFee(); + final FreezeBalanceV2Contract freezeBalanceV2Contract; + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + try { + freezeBalanceV2Contract = any.unpack(FreezeBalanceV2Contract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + AccountCapsule accountCapsule = accountStore.get(freezeBalanceV2Contract.getOwnerAddress().toByteArray()); + + if (dynamicStore.supportAllowNewResourceModel() + && accountCapsule.oldTronPowerIsNotInitialized()) { + accountCapsule.initializeOldTronPower(); + } + + long frozenBalance = freezeBalanceV2Contract.getFrozenBalance(); + long newBalance = accountCapsule.getBalance() - frozenBalance; + + switch (freezeBalanceV2Contract.getResource()) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + dynamicStore.addTotalNetWeight(newNetWeight - oldNetWeight); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + dynamicStore.addTotalEnergyWeight(newEnergyWeight - oldEnergyWeight); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(frozenBalance); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + dynamicStore.addTotalTronPowerWeight(newTPWeight - oldTPWeight); + break; + default: + logger.debug("Resource Code Error."); + } + + accountCapsule.setBalance(newBalance); + accountStore.put(accountCapsule.createDbKey(), accountCapsule); + + ret.setStatus(fee, code.SUCESS); + + return true; + } + + @Override + public boolean validate() throws ContractValidateException { + if (this.any == null) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + if (chainBaseManager == null) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + if (!any.is(FreezeBalanceV2Contract.class)) { + throw new ContractValidateException( + "contract type error,expected type [FreezeBalanceV2Contract],real type[" + any + .getClass() + "]"); + } + + if (!dynamicStore.supportUnfreezeDelay()) { + throw new ContractValidateException("Not support FreezeV2 transaction," + + " need to be opened by the committee"); + } + + final FreezeBalanceV2Contract freezeBalanceV2Contract; + try { + freezeBalanceV2Contract = this.any.unpack(FreezeBalanceV2Contract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + byte[] ownerAddress = freezeBalanceV2Contract.getOwnerAddress().toByteArray(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + + AccountCapsule accountCapsule = accountStore.get(ownerAddress); + if (accountCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ActuatorConstant.ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); + } + + long frozenBalance = freezeBalanceV2Contract.getFrozenBalance(); + if (frozenBalance <= 0) { + throw new ContractValidateException("frozenBalance must be positive"); + } + if (frozenBalance < TRX_PRECISION) { + throw new ContractValidateException("frozenBalance must be greater than or equal to 1 TRX"); + } + + if (frozenBalance > accountCapsule.getBalance()) { + throw new ContractValidateException("frozenBalance must be less than or equal to accountBalance"); + } + + switch (freezeBalanceV2Contract.getResource()) { + case BANDWIDTH: + case ENERGY: + break; + case TRON_POWER: + if (!dynamicStore.supportAllowNewResourceModel()) { + throw new ContractValidateException( + "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + break; + default: + if (dynamicStore.supportAllowNewResourceModel()) { + throw new ContractValidateException( + "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); + } else { + throw new ContractValidateException( + "ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + } + + return true; + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return any.unpack(FreezeBalanceV2Contract.class).getOwnerAddress(); + } + + @Override + public long calcFee() { + return 0; + } + +} \ No newline at end of file diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java index f859e580253..31b5e87e12d 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketCancelOrderActuator.java @@ -23,7 +23,6 @@ import com.google.protobuf.InvalidProtocolBufferException; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.MarketOrderCapsule; @@ -100,7 +99,7 @@ public boolean execute(Object object) throws ContractExeException { if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } // 1. return balance and token MarketUtils diff --git a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java index 15e5a98f86a..d196cdef06f 100644 --- a/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/MarketSellAssetActuator.java @@ -129,7 +129,7 @@ public boolean execute(Object object) throws ContractExeException { if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } // 1. transfer of balance transferBalanceOrToken(accountCapsule); @@ -244,7 +244,7 @@ public boolean validate() throws ContractValidateException { long fee = calcFee(); if (Arrays.equals(sellTokenID, "_".getBytes())) { - if (ownerAccount.getBalance() < Math.addExact(sellTokenQuantity, fee)) { + if (ownerAccount.getBalance() < addExact(sellTokenQuantity, fee)) { throw new ContractValidateException("No enough balance !"); } } else { @@ -401,7 +401,8 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, // makerSellTokenQuantity_A/makerBuyTokenQuantity_TRX long takerBuyTokenQuantityRemain = MarketUtils - .multiplyAndDivide(takerSellRemainQuantity, makerSellQuantity, makerBuyQuantity); + .multiplyAndDivide(takerSellRemainQuantity, makerSellQuantity, makerBuyQuantity, + this.disableJavaLangMath()); if (takerBuyTokenQuantityRemain == 0) { // quantity too small, return sellToken to user @@ -424,7 +425,8 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, // makerBuyTokenQuantity_TRX / makerSellTokenQuantity_A makerBuyTokenQuantityReceive = MarketUtils - .multiplyAndDivide(makerSellRemainQuantity, makerBuyQuantity, makerSellQuantity); + .multiplyAndDivide(makerSellRemainQuantity, makerBuyQuantity, makerSellQuantity, + this.disableJavaLangMath()); takerBuyTokenQuantityReceive = makerOrderCapsule.getSellTokenQuantityRemain(); long takerSellTokenLeft = @@ -447,7 +449,7 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, takerOrderCapsule.setSellTokenQuantityRemain(0); MarketUtils.updateOrderState(takerOrderCapsule, State.INACTIVE, marketAccountStore); - makerOrderCapsule.setSellTokenQuantityRemain(Math.subtractExact( + makerOrderCapsule.setSellTokenQuantityRemain(subtractExact( makerOrderCapsule.getSellTokenQuantityRemain(), takerBuyTokenQuantityRemain)); } else { // taker > maker @@ -458,7 +460,8 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, // makerSellTokenQuantityRemain_A/makerBuyTokenQuantityCurrent_TRX = // makerSellTokenQuantity_A/makerBuyTokenQuantity_TRX makerBuyTokenQuantityReceive = MarketUtils - .multiplyAndDivide(makerSellRemainQuantity, makerBuyQuantity, makerSellQuantity); + .multiplyAndDivide(makerSellRemainQuantity, makerBuyQuantity, makerSellQuantity, + this.disableJavaLangMath()); MarketUtils.updateOrderState(makerOrderCapsule, State.INACTIVE, marketAccountStore); if (makerBuyTokenQuantityReceive == 0) { @@ -475,7 +478,7 @@ private void matchSingleOrder(MarketOrderCapsule takerOrderCapsule, return; } else { makerOrderCapsule.setSellTokenQuantityRemain(0); - takerOrderCapsule.setSellTokenQuantityRemain(Math.subtractExact( + takerOrderCapsule.setSellTokenQuantityRemain(subtractExact( takerOrderCapsule.getSellTokenQuantityRemain(), makerBuyTokenQuantityReceive)); } } @@ -524,7 +527,8 @@ private MarketOrderCapsule createAndSaveOrder(AccountCapsule accountCapsule, private void transferBalanceOrToken(AccountCapsule accountCapsule) { if (Arrays.equals(sellTokenID, "_".getBytes())) { - accountCapsule.setBalance(Math.subtractExact(accountCapsule.getBalance(), sellTokenQuantity)); + accountCapsule.setBalance(subtractExact( + accountCapsule.getBalance(), sellTokenQuantity)); } else { accountCapsule .reduceAssetAmountV2(sellTokenID, sellTokenQuantity, dynamicStore, assetIssueStore); @@ -537,7 +541,7 @@ private void addTrxOrToken(MarketOrderCapsule orderCapsule, long num, byte[] buyTokenId = orderCapsule.getBuyTokenId(); if (Arrays.equals(buyTokenId, "_".getBytes())) { - accountCapsule.setBalance(Math.addExact(accountCapsule.getBalance(), num)); + accountCapsule.setBalance(addExact(accountCapsule.getBalance(), num)); } else { accountCapsule .addAssetAmountV2(buyTokenId, num, dynamicStore, assetIssueStore); @@ -550,7 +554,7 @@ private void addTrxOrToken(MarketOrderCapsule orderCapsule, long num) { byte[] buyTokenId = orderCapsule.getBuyTokenId(); if (Arrays.equals(buyTokenId, "_".getBytes())) { - accountCapsule.setBalance(Math.addExact(accountCapsule.getBalance(), num)); + accountCapsule.setBalance(addExact(accountCapsule.getBalance(), num)); } else { accountCapsule .addAssetAmountV2(buyTokenId, num, dynamicStore, assetIssueStore); diff --git a/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java b/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java index 77e345b2a92..7fdf15acd18 100755 --- a/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ParticipateAssetIssueActuator.java @@ -64,8 +64,8 @@ public boolean execute(Object object) throws ContractExeException { //subtract from owner address byte[] ownerAddress = participateAssetIssueContract.getOwnerAddress().toByteArray(); AccountCapsule ownerAccount = accountStore.get(ownerAddress); - long balance = Math.subtractExact(ownerAccount.getBalance(), cost); - balance = Math.subtractExact(balance, fee); + long balance = subtractExact(ownerAccount.getBalance(), cost); + balance = subtractExact(balance, fee); ownerAccount.setBalance(balance); byte[] key = participateAssetIssueContract.getAssetName().toByteArray(); @@ -74,14 +74,14 @@ public boolean execute(Object object) throws ContractExeException { assetIssueCapsule = Commons .getAssetIssueStoreFinal(dynamicStore, assetIssueStore, assetIssueV2Store).get(key); - long exchangeAmount = Math.multiplyExact(cost, assetIssueCapsule.getNum()); - exchangeAmount = Math.floorDiv(exchangeAmount, assetIssueCapsule.getTrxNum()); + long exchangeAmount = multiplyExact(cost, assetIssueCapsule.getNum()); + exchangeAmount = floorDiv(exchangeAmount, assetIssueCapsule.getTrxNum()); ownerAccount.addAssetAmountV2(key, exchangeAmount, dynamicStore, assetIssueStore); //add to to_address byte[] toAddress = participateAssetIssueContract.getToAddress().toByteArray(); AccountCapsule toAccount = accountStore.get(toAddress); - toAccount.setBalance(Math.addExact(toAccount.getBalance(), cost)); + toAccount.setBalance(addExact(toAccount.getBalance(), cost)); if (!toAccount.reduceAssetAmountV2(key, exchangeAmount, dynamicStore, assetIssueStore)) { throw new ContractExeException("reduceAssetAmount failed !"); } @@ -156,7 +156,7 @@ public boolean validate() throws ContractValidateException { try { //Whether the balance is enough long fee = calcFee(); - if (ownerAccount.getBalance() < Math.addExact(amount, fee)) { + if (ownerAccount.getBalance() < addExact(amount, fee)) { throw new ContractValidateException("No enough balance !"); } @@ -181,8 +181,8 @@ public boolean validate() throws ContractValidateException { int trxNum = assetIssueCapsule.getTrxNum(); int num = assetIssueCapsule.getNum(); - long exchangeAmount = Math.multiplyExact(amount, num); - exchangeAmount = Math.floorDiv(exchangeAmount, trxNum); + long exchangeAmount = multiplyExact(amount, num); + exchangeAmount = floorDiv(exchangeAmount, trxNum); if (exchangeAmount <= 0) { throw new ContractValidateException("Can not process the exchange!"); } diff --git a/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java b/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java index 8b00126c684..2773dc07d26 100644 --- a/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/ShieldedTransferActuator.java @@ -96,9 +96,9 @@ public boolean execute(Object result) //adjust and verify total shielded pool value try { - Commons.adjustTotalShieldedPoolValue( - Math.addExact(Math.subtractExact(shieldedTransferContract.getToAmount(), - shieldedTransferContract.getFromAmount()), fee), dynamicStore); + Commons.adjustTotalShieldedPoolValue(addExact(subtractExact( + shieldedTransferContract.getToAmount(), + shieldedTransferContract.getFromAmount()), fee), dynamicStore); } catch (ArithmeticException | BalanceInsufficientException e) { logger.debug(e.getMessage(), e); ret.setStatus(0, code.FAILED); @@ -327,9 +327,11 @@ private void checkProof(List spendDescriptions, long totalShieldedPoolValue = dynamicStore .getTotalShieldedPoolValue(); try { - valueBalance = Math.addExact(Math.subtractExact(shieldedTransferContract.getToAmount(), + valueBalance = addExact(subtractExact( + shieldedTransferContract.getToAmount(), shieldedTransferContract.getFromAmount()), fee); - totalShieldedPoolValue = Math.subtractExact(totalShieldedPoolValue, valueBalance); + totalShieldedPoolValue = subtractExact( + totalShieldedPoolValue, valueBalance); } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); throw new ZkProofValidateException(e.getMessage(), true); @@ -452,7 +454,7 @@ private void validateTransparent(ShieldedTransferContract shieldedTransferContra AccountCapsule toAccount = accountStore.get(toAddress); if (toAccount != null) { try { - Math.addExact(getZenBalance(toAccount), toAmount); + addExact(getZenBalance(toAccount), toAmount); } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); @@ -462,13 +464,7 @@ private void validateTransparent(ShieldedTransferContract shieldedTransferContra } private long getZenBalance(AccountCapsule account) { - if (account.getAssetMapV2().get(CommonParameter - .getInstance().getZenTokenId()) == null) { - return 0L; - } else { - return account.getAssetMapV2().get(CommonParameter - .getInstance().getZenTokenId()); - } + return account.getAssetV2(CommonParameter.getInstance().getZenTokenId()); } @Override diff --git a/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java b/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java index 94fef0b5c12..a0deabf8f00 100755 --- a/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/TransferActuator.java @@ -7,8 +7,8 @@ import java.util.Arrays; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; @@ -57,13 +57,13 @@ public boolean execute(Object object) throws ContractExeException { fee = fee + dynamicStore.getCreateNewAccountFeeInSystemContract(); } - Commons.adjustBalance(accountStore, ownerAddress, -(Math.addExact(fee, amount))); + adjustBalance(accountStore, ownerAddress, -(addExact(fee, amount))); if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } - Commons.adjustBalance(accountStore, toAddress, amount); + adjustBalance(accountStore, toAddress, amount); ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException | ArithmeticException | InvalidProtocolBufferException e) { logger.debug(e.getMessage(), e); @@ -155,13 +155,15 @@ public boolean validate() throws ContractValidateException { } } - if (balance < Math.addExact(amount, fee)) { + if (balance < addExact(amount, fee)) { + logger.warn("Balance is not sufficient. Account: {}, balance: {}, amount: {}, fee: {}.", + StringUtil.encode58Check(ownerAddress), balance, amount, fee); throw new ContractValidateException( "Validate TransferContract error, balance is not sufficient."); } if (toAccount != null) { - Math.addExact(toAccount.getBalance(), amount); + addExact(toAccount.getBalance(), amount); } } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); diff --git a/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java b/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java index cdc626d5a35..d93263055eb 100644 --- a/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/TransferAssetActuator.java @@ -18,7 +18,6 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.Arrays; -import java.util.Map; import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.ByteArray; @@ -84,11 +83,11 @@ public boolean execute(Object result) throws ContractExeException { .addAssetAmountV2(assetName.toByteArray(), amount, dynamicStore, assetIssueStore); accountStore.put(toAddress, toAccountCapsule); - Commons.adjustBalance(accountStore, ownerAccountCapsule, -fee); + adjustBalance(accountStore, ownerAccountCapsule, -fee); if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), fee); + adjustBalance(accountStore, accountStore.getBlackhole(), fee); } ret.setStatus(fee, code.SUCESS); } catch (BalanceInsufficientException e) { @@ -159,17 +158,7 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("No asset!"); } - Map asset; - if (dynamicStore.getAllowSameTokenName() == 0) { - asset = ownerAccount.getAssetMap(); - } else { - asset = ownerAccount.getAssetMapV2(); - } - if (asset.isEmpty()) { - throw new ContractValidateException("Owner has no asset!"); - } - - Long assetBalance = asset.get(ByteArray.toStr(assetName)); + Long assetBalance = ownerAccount.getAsset(dynamicStore, ByteArray.toStr(assetName)); if (null == assetBalance || assetBalance <= 0) { throw new ContractValidateException("assetBalance must be greater than 0."); } @@ -185,14 +174,10 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("Cannot transfer asset to smartContract."); } - if (dynamicStore.getAllowSameTokenName() == 0) { - assetBalance = toAccount.getAssetMap().get(ByteArray.toStr(assetName)); - } else { - assetBalance = toAccount.getAssetMapV2().get(ByteArray.toStr(assetName)); - } + assetBalance = toAccount.getAsset(dynamicStore, ByteArray.toStr(assetName)); if (assetBalance != null) { try { - assetBalance = Math.addExact(assetBalance, amount); //check if overflow + assetBalance = addExact(assetBalance, amount); //check if overflow } catch (Exception e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); diff --git a/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java b/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java new file mode 100755 index 00000000000..2f2eed7fded --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/UnDelegateResourceActuator.java @@ -0,0 +1,319 @@ +package org.tron.core.actuator; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.Arrays; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.EnergyProcessor; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DelegatedResourceAccountIndexStore; +import org.tron.core.store.DelegatedResourceStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.BalanceContract.UnDelegateResourceContract; + +@Slf4j(topic = "actuator") +public class UnDelegateResourceActuator extends AbstractActuator { + + public UnDelegateResourceActuator() { + super(ContractType.UnDelegateResourceContract, UnDelegateResourceContract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + + long fee = calcFee(); + final UnDelegateResourceContract unDelegateResourceContract; + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); + DelegatedResourceAccountIndexStore delegatedResourceAccountIndexStore = chainBaseManager + .getDelegatedResourceAccountIndexStore(); + try { + unDelegateResourceContract = any.unpack(UnDelegateResourceContract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + + + final long unDelegateBalance = unDelegateResourceContract.getBalance(); + byte[] ownerAddress = unDelegateResourceContract.getOwnerAddress().toByteArray(); + byte[] receiverAddress = unDelegateResourceContract.getReceiverAddress().toByteArray(); + + AccountCapsule receiverCapsule = accountStore.get(receiverAddress); + + long transferUsage = 0; + // modify receiver Account + if (receiverCapsule != null) { + long now = chainBaseManager.getHeadSlot(); + switch (unDelegateResourceContract.getResource()) { + case BANDWIDTH: + BandwidthProcessor bandwidthProcessor = new BandwidthProcessor(chainBaseManager); + bandwidthProcessor.updateUsageForDelegated(receiverCapsule); + + if (receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + < unDelegateBalance) { + // A TVM contract suicide, re-create will produce this situation + receiverCapsule.setAcquiredDelegatedFrozenV2BalanceForBandwidth(0); + } else { + // calculate usage + long unDelegateMaxUsage = (long) ((double) unDelegateBalance / TRX_PRECISION + * ((double) (dynamicStore.getTotalNetLimit()) / dynamicStore.getTotalNetWeight())); + transferUsage = (long) (receiverCapsule.getNetUsage() + * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForBandwidth())); + transferUsage = min(unDelegateMaxUsage, transferUsage); + + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(-unDelegateBalance); + } + + long newNetUsage = receiverCapsule.getNetUsage() - transferUsage; + receiverCapsule.setNetUsage(newNetUsage); + receiverCapsule.setLatestConsumeTime(now); + break; + case ENERGY: + EnergyProcessor energyProcessor = new EnergyProcessor(dynamicStore, accountStore); + energyProcessor.updateUsage(receiverCapsule); + + if (receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy() + < unDelegateBalance) { + // A TVM contract receiver, re-create will produce this situation + receiverCapsule.setAcquiredDelegatedFrozenV2BalanceForEnergy(0); + } else { + // calculate usage + long unDelegateMaxUsage = (long) ((double) unDelegateBalance / TRX_PRECISION + * ((double) (dynamicStore.getTotalEnergyCurrentLimit()) / dynamicStore.getTotalEnergyWeight())); + transferUsage = (long) (receiverCapsule.getEnergyUsage() + * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForEnergy())); + transferUsage = min(unDelegateMaxUsage, transferUsage); + + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(-unDelegateBalance); + } + + long newEnergyUsage = receiverCapsule.getEnergyUsage() - transferUsage; + receiverCapsule.setEnergyUsage(newEnergyUsage); + receiverCapsule.setLatestConsumeTimeForEnergy(now); + break; + default: + //this should never happen + break; + } + accountStore.put(receiverCapsule.createDbKey(), receiverCapsule); + } + + // transfer lock delegate to unlock + delegatedResourceStore.unLockExpireResource(ownerAddress, receiverAddress, + dynamicStore.getLatestBlockHeaderTimestamp()); + + byte[] unlockKey = DelegatedResourceCapsule + .createDbKeyV2(ownerAddress, receiverAddress, false); + DelegatedResourceCapsule unlockResource = delegatedResourceStore + .get(unlockKey); + + // modify owner Account + AccountCapsule ownerCapsule = accountStore.get(ownerAddress); + switch (unDelegateResourceContract.getResource()) { + case BANDWIDTH: { + unlockResource.addFrozenBalanceForBandwidth(-unDelegateBalance, 0); + + ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(-unDelegateBalance); + ownerCapsule.addFrozenBalanceForBandwidthV2(unDelegateBalance); + + BandwidthProcessor processor = new BandwidthProcessor(chainBaseManager); + + long now = chainBaseManager.getHeadSlot(); + if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, + transferUsage, BANDWIDTH, now); + } + } + break; + case ENERGY: { + unlockResource.addFrozenBalanceForEnergy(-unDelegateBalance, 0); + + ownerCapsule.addDelegatedFrozenV2BalanceForEnergy(-unDelegateBalance); + ownerCapsule.addFrozenBalanceForEnergyV2(unDelegateBalance); + + EnergyProcessor processor = new EnergyProcessor(dynamicStore, accountStore); + + long now = chainBaseManager.getHeadSlot(); + if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, transferUsage, ENERGY, now); + } + } + break; + default: + //this should never happen + break; + } + + if (unlockResource.getFrozenBalanceForBandwidth() == 0 + && unlockResource.getFrozenBalanceForEnergy() == 0) { + delegatedResourceStore.delete(unlockKey); + unlockResource = null; + } else { + delegatedResourceStore.put(unlockKey, unlockResource); + } + + byte[] lockKey = DelegatedResourceCapsule + .createDbKeyV2(ownerAddress, receiverAddress, true); + DelegatedResourceCapsule lockResource = delegatedResourceStore + .get(lockKey); + if (lockResource == null && unlockResource == null) { + //modify DelegatedResourceAccountIndexStore + delegatedResourceAccountIndexStore.unDelegateV2(ownerAddress, receiverAddress); + } + + accountStore.put(ownerAddress, ownerCapsule); + + ret.setStatus(fee, code.SUCESS); + + return true; + } + + @Override + public boolean validate() throws ContractValidateException { + if (this.any == null) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + if (chainBaseManager == null) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + DelegatedResourceStore delegatedResourceStore = chainBaseManager.getDelegatedResourceStore(); + if (!dynamicStore.supportDR()) { + throw new ContractValidateException("No support for resource delegate"); + } + + if (!dynamicStore.supportUnfreezeDelay()) { + throw new ContractValidateException("Not support unDelegate resource transaction," + + " need to be opened by the committee"); + } + + if (!this.any.is(UnDelegateResourceContract.class)) { + throw new ContractValidateException( + "contract type error, expected type [UnDelegateResourceContract], real type[" + any + .getClass() + "]"); + } + final UnDelegateResourceContract unDelegateResourceContract; + try { + unDelegateResourceContract = this.any.unpack(UnDelegateResourceContract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + + byte[] ownerAddress = unDelegateResourceContract.getOwnerAddress().toByteArray(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule ownerCapsule = accountStore.get(ownerAddress); + if (ownerCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); + } + + byte[] receiverAddress = unDelegateResourceContract.getReceiverAddress().toByteArray(); + if (!DecodeUtil.addressValid(receiverAddress)) { + throw new ContractValidateException("Invalid receiverAddress"); + } + if (Arrays.equals(receiverAddress, ownerAddress)) { + throw new ContractValidateException( + "receiverAddress must not be the same as ownerAddress"); + } + + // TVM contract suicide can result in no receiving account + // AccountCapsule receiverCapsule = accountStore.get(receiverAddress); + // if (receiverCapsule == null) { + // String readableReceiverAddress = StringUtil.createReadableString(receiverAddress); + // throw new ContractValidateException( + // "Receiver Account[" + readableReceiverAddress + "] does not exist"); + // } + + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, false); + DelegatedResourceCapsule unlockResourceCapsule = delegatedResourceStore.get(key); + byte[] lockKey = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, true); + DelegatedResourceCapsule lockResourceCapsule = delegatedResourceStore.get(lockKey); + if (unlockResourceCapsule == null && lockResourceCapsule == null) { + throw new ContractValidateException( + "delegated Resource does not exist"); + } + + long unDelegateBalance = unDelegateResourceContract.getBalance(); + if (unDelegateBalance <= 0) { + throw new ContractValidateException("unDelegateBalance must be more than 0 TRX"); + } + switch (unDelegateResourceContract.getResource()) { + case BANDWIDTH: { + long delegateBalance = 0; + if (unlockResourceCapsule != null) { + delegateBalance += unlockResourceCapsule.getFrozenBalanceForBandwidth(); + } + if (lockResourceCapsule != null + && lockResourceCapsule.getExpireTimeForBandwidth() < now) { + delegateBalance += lockResourceCapsule.getFrozenBalanceForBandwidth(); + } + if (delegateBalance < unDelegateBalance) { + throw new ContractValidateException( + "insufficient delegatedFrozenBalance(BANDWIDTH), request=" + + unDelegateBalance + ", unlock_balance=" + delegateBalance); + } + } + break; + case ENERGY: { + long delegateBalance = 0; + if (unlockResourceCapsule != null) { + delegateBalance += unlockResourceCapsule.getFrozenBalanceForEnergy(); + } + if (lockResourceCapsule != null + && lockResourceCapsule.getExpireTimeForEnergy() < now) { + delegateBalance += lockResourceCapsule.getFrozenBalanceForEnergy(); + } + if (delegateBalance < unDelegateBalance) { + throw new ContractValidateException("insufficient delegateFrozenBalance(Energy), request=" + + unDelegateBalance + ", unlock_balance=" + delegateBalance); + } + } + break; + default: + throw new ContractValidateException( + "ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"); + } + + return true; + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return any.unpack(UnDelegateResourceContract.class).getOwnerAddress(); + } + + @Override + public long calcFee() { + return 0; + } + +} diff --git a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java index 93dcd61e044..80334f1fc49 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceActuator.java @@ -38,6 +38,9 @@ @Slf4j(topic = "actuator") public class UnfreezeBalanceActuator extends AbstractActuator { + private static final String INVALID_RESOURCE_CODE = + "ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"; + public UnfreezeBalanceActuator() { super(ContractType.UnfreezeBalanceContract, UnfreezeBalanceContract.class); } @@ -83,6 +86,7 @@ public boolean execute(Object result) throws ContractExeException { byte[] receiverAddress = unfreezeBalanceContract.getReceiverAddress().toByteArray(); //If the receiver is not included in the contract, unfreeze frozen balance for this account. //otherwise,unfreeze delegated frozen balance provided this account. + long decrease = 0; if (!ArrayUtils.isEmpty(receiverAddress) && dynamicStore.supportDR()) { byte[] key = DelegatedResourceCapsule .createDbKey(unfreezeBalanceContract.getOwnerAddress().toByteArray(), @@ -107,31 +111,46 @@ public boolean execute(Object result) throws ContractExeException { } AccountCapsule receiverCapsule = accountStore.get(receiverAddress); + if (dynamicStore.getAllowTvmConstantinople() == 0 || (receiverCapsule != null && receiverCapsule.getType() != AccountType.Contract)) { switch (unfreezeBalanceContract.getResource()) { case BANDWIDTH: + long oldNetWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() / + TRX_PRECISION; if (dynamicStore.getAllowTvmSolidity059() == 1 && receiverCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() < unfreezeBalance) { + oldNetWeight = unfreezeBalance / TRX_PRECISION; receiverCapsule.setAcquiredDelegatedFrozenBalanceForBandwidth(0); } else { receiverCapsule.addAcquiredDelegatedFrozenBalanceForBandwidth(-unfreezeBalance); } + long newNetWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() / + TRX_PRECISION; + decrease = newNetWeight - oldNetWeight; break; case ENERGY: + long oldEnergyWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() / + TRX_PRECISION; if (dynamicStore.getAllowTvmSolidity059() == 1 && receiverCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() < unfreezeBalance) { + oldEnergyWeight = unfreezeBalance / TRX_PRECISION; receiverCapsule.setAcquiredDelegatedFrozenBalanceForEnergy(0); } else { receiverCapsule.addAcquiredDelegatedFrozenBalanceForEnergy(-unfreezeBalance); } + long newEnergyWeight = receiverCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() / + TRX_PRECISION; + decrease = newEnergyWeight - oldEnergyWeight; break; default: //this should never happen break; } accountStore.put(receiverCapsule.createDbKey(), receiverCapsule); + } else { + decrease = -unfreezeBalance / TRX_PRECISION; } accountCapsule.setBalance(oldBalance + unfreezeBalance); @@ -141,39 +160,39 @@ public boolean execute(Object result) throws ContractExeException { delegatedResourceStore.delete(key); //modify DelegatedResourceAccountIndexStore - { - DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = delegatedResourceAccountIndexStore - .get(ownerAddress); - if (delegatedResourceAccountIndexCapsule != null) { - List toAccountsList = new ArrayList<>(delegatedResourceAccountIndexCapsule + if (!dynamicStore.supportAllowDelegateOptimization()) { + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = + delegatedResourceAccountIndexStore.get(ownerAddress); + if (ownerIndexCapsule != null) { + List toAccountsList = new ArrayList<>(ownerIndexCapsule .getToAccountsList()); toAccountsList.remove(ByteString.copyFrom(receiverAddress)); - delegatedResourceAccountIndexCapsule.setAllToAccounts(toAccountsList); - delegatedResourceAccountIndexStore - .put(ownerAddress, delegatedResourceAccountIndexCapsule); + ownerIndexCapsule.setAllToAccounts(toAccountsList); + delegatedResourceAccountIndexStore.put(ownerAddress, ownerIndexCapsule); } - } - { - DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = delegatedResourceAccountIndexStore - .get(receiverAddress); - if (delegatedResourceAccountIndexCapsule != null) { - List fromAccountsList = new ArrayList<>(delegatedResourceAccountIndexCapsule + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = + delegatedResourceAccountIndexStore.get(receiverAddress); + if (receiverIndexCapsule != null) { + List fromAccountsList = new ArrayList<>(receiverIndexCapsule .getFromAccountsList()); fromAccountsList.remove(ByteString.copyFrom(ownerAddress)); - delegatedResourceAccountIndexCapsule.setAllFromAccounts(fromAccountsList); - delegatedResourceAccountIndexStore - .put(receiverAddress, delegatedResourceAccountIndexCapsule); + receiverIndexCapsule.setAllFromAccounts(fromAccountsList); + delegatedResourceAccountIndexStore.put(receiverAddress, receiverIndexCapsule); } + } else { + //modify DelegatedResourceAccountIndexStore new + delegatedResourceAccountIndexStore.convert(ownerAddress); + delegatedResourceAccountIndexStore.convert(receiverAddress); + delegatedResourceAccountIndexStore.unDelegate(ownerAddress, receiverAddress); } - } else { delegatedResourceStore.put(key, delegatedResourceCapsule); } } else { switch (unfreezeBalanceContract.getResource()) { case BANDWIDTH: - + long oldNetWeight = accountCapsule.getFrozenBalance() / TRX_PRECISION; List frozenList = Lists.newArrayList(); frozenList.addAll(accountCapsule.getFrozenList()); Iterator iterator = frozenList.iterator(); @@ -189,9 +208,11 @@ public boolean execute(Object result) throws ContractExeException { accountCapsule.setInstance(accountCapsule.getInstance().toBuilder() .setBalance(oldBalance + unfreezeBalance) .clearFrozen().addAllFrozen(frozenList).build()); - + long newNetWeight = accountCapsule.getFrozenBalance() / TRX_PRECISION; + decrease = newNetWeight - oldNetWeight; break; case ENERGY: + long oldEnergyWeight = accountCapsule.getEnergyFrozenBalance() / TRX_PRECISION; unfreezeBalance = accountCapsule.getAccountResource().getFrozenBalanceForEnergy() .getFrozenBalance(); @@ -200,12 +221,17 @@ public boolean execute(Object result) throws ContractExeException { accountCapsule.setInstance(accountCapsule.getInstance().toBuilder() .setBalance(oldBalance + unfreezeBalance) .setAccountResource(newAccountResource).build()); + long newEnergyWeight = accountCapsule.getEnergyFrozenBalance() / TRX_PRECISION; + decrease = newEnergyWeight - oldEnergyWeight; break; case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenBalance() / TRX_PRECISION; unfreezeBalance = accountCapsule.getTronPowerFrozenBalance(); accountCapsule.setInstance(accountCapsule.getInstance().toBuilder() .setBalance(oldBalance + unfreezeBalance) .clearTronPower().build()); + long newTPWeight = accountCapsule.getTronPowerFrozenBalance() / TRX_PRECISION; + decrease = newTPWeight - oldTPWeight; break; default: //this should never happen @@ -213,19 +239,20 @@ public boolean execute(Object result) throws ContractExeException { } } - + + long weight = dynamicStore.allowNewReward() ? decrease : -unfreezeBalance / TRX_PRECISION; switch (unfreezeBalanceContract.getResource()) { case BANDWIDTH: dynamicStore - .addTotalNetWeight(-unfreezeBalance / TRX_PRECISION); + .addTotalNetWeight(weight); break; case ENERGY: dynamicStore - .addTotalEnergyWeight(-unfreezeBalance / TRX_PRECISION); + .addTotalEnergyWeight(weight); break; case TRON_POWER: dynamicStore - .addTotalTronPowerWeight(-unfreezeBalance / TRX_PRECISION); + .addTotalTronPowerWeight(weight); break; default: //this should never happen @@ -402,8 +429,7 @@ public boolean validate() throws ContractValidateException { } break; default: - throw new ContractValidateException( - "ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException(INVALID_RESOURCE_CODE); } } else { @@ -440,8 +466,7 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException("It's not time to unfreeze(TronPower)."); } } else { - throw new ContractValidateException( - "ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException(INVALID_RESOURCE_CODE); } break; default: @@ -449,8 +474,7 @@ public boolean validate() throws ContractValidateException { throw new ContractValidateException( "ResourceCode error.valid ResourceCode[BANDWIDTH、Energy、TRON_POWER]"); } else { - throw new ContractValidateException( - "ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException(INVALID_RESOURCE_CODE); } } diff --git a/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java new file mode 100755 index 00000000000..fb41c97f7ed --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/UnfreezeBalanceV2Actuator.java @@ -0,0 +1,389 @@ +package org.tron.core.actuator; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; + +import com.google.common.collect.Lists; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import lombok.Getter; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.capsule.VotesCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.service.MortgageService; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.VotesStore; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Account.FreezeV2; +import org.tron.protos.Protocol.Account.UnFreezeV2; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.Protocol.Vote; +import org.tron.protos.contract.BalanceContract.UnfreezeBalanceV2Contract; + +@Slf4j(topic = "actuator") +public class UnfreezeBalanceV2Actuator extends AbstractActuator { + + @Getter + private static final int UNFREEZE_MAX_TIMES = 32; + + public UnfreezeBalanceV2Actuator() { + super(ContractType.UnfreezeBalanceV2Contract, UnfreezeBalanceV2Contract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + + long fee = calcFee(); + final UnfreezeBalanceV2Contract unfreezeBalanceV2Contract; + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + MortgageService mortgageService = chainBaseManager.getMortgageService(); + try { + unfreezeBalanceV2Contract = any.unpack(UnfreezeBalanceV2Contract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + byte[] ownerAddress = unfreezeBalanceV2Contract.getOwnerAddress().toByteArray(); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + + mortgageService.withdrawReward(ownerAddress); + + AccountCapsule accountCapsule = accountStore.get(ownerAddress); + long unfreezeAmount = this.unfreezeExpire(accountCapsule, now); + long unfreezeBalance = unfreezeBalanceV2Contract.getUnfreezeBalance(); + + if (dynamicStore.supportAllowNewResourceModel() + && accountCapsule.oldTronPowerIsNotInitialized()) { + accountCapsule.initializeOldTronPower(); + } + + ResourceCode freezeType = unfreezeBalanceV2Contract.getResource(); + + long expireTime = this.calcUnfreezeExpireTime(now); + accountCapsule.addUnfrozenV2List(freezeType, unfreezeBalance, expireTime); + + this.updateTotalResourceWeight(accountCapsule, unfreezeBalanceV2Contract, unfreezeBalance); + this.updateVote(accountCapsule, unfreezeBalanceV2Contract, ownerAddress); + + if (dynamicStore.supportAllowNewResourceModel() + && !accountCapsule.oldTronPowerIsInvalid()) { + accountCapsule.invalidateOldTronPower(); + } + + accountStore.put(ownerAddress, accountCapsule); + + ret.setWithdrawExpireAmount(unfreezeAmount); + ret.setStatus(fee, code.SUCESS); + return true; + } + + @Override + public boolean validate() throws ContractValidateException { + if (this.any == null) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + if (chainBaseManager == null) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + if (!this.any.is(UnfreezeBalanceV2Contract.class)) { + throw new ContractValidateException( + "contract type error, expected type [UnfreezeBalanceContract], real type[" + any + .getClass() + "]"); + } + + if (!dynamicStore.supportUnfreezeDelay()) { + throw new ContractValidateException("Not support UnfreezeV2 transaction," + + " need to be opened by the committee"); + } + + final UnfreezeBalanceV2Contract unfreezeBalanceV2Contract; + try { + unfreezeBalanceV2Contract = this.any.unpack(UnfreezeBalanceV2Contract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + + byte[] ownerAddress = unfreezeBalanceV2Contract.getOwnerAddress().toByteArray(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + + AccountCapsule accountCapsule = accountStore.get(ownerAddress); + if (accountCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); + } + + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + switch (unfreezeBalanceV2Contract.getResource()) { + case BANDWIDTH: + if (!checkExistFrozenBalance(accountCapsule, BANDWIDTH)) { + throw new ContractValidateException("no frozenBalance(BANDWIDTH)"); + } + break; + case ENERGY: + if (!checkExistFrozenBalance(accountCapsule, ENERGY)) { + throw new ContractValidateException("no frozenBalance(Energy)"); + } + break; + case TRON_POWER: + if (dynamicStore.supportAllowNewResourceModel()) { + if (!checkExistFrozenBalance(accountCapsule, TRON_POWER)) { + throw new ContractValidateException("no frozenBalance(TronPower)"); + } + } else { + throw new ContractValidateException("ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"); + } + break; + default: + if (dynamicStore.supportAllowNewResourceModel()) { + throw new ContractValidateException("ResourceCode error.valid ResourceCode[BANDWIDTH、Energy、TRON_POWER]"); + } else { + throw new ContractValidateException("ResourceCode error.valid ResourceCode[BANDWIDTH、Energy]"); + } + } + + if (!checkUnfreezeBalance(accountCapsule, unfreezeBalanceV2Contract, unfreezeBalanceV2Contract.getResource())) { + throw new ContractValidateException( + "Invalid unfreeze_balance, [" + unfreezeBalanceV2Contract.getUnfreezeBalance() + "] is error" + ); + } + + int unfreezingCount = accountCapsule.getUnfreezingV2Count(now); + if (UNFREEZE_MAX_TIMES <= unfreezingCount) { + throw new ContractValidateException("Invalid unfreeze operation, unfreezing times is over limit"); + } + + return true; + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return any.unpack(UnfreezeBalanceV2Contract.class).getOwnerAddress(); + } + + @Override + public long calcFee() { + return 0; + } + + public boolean checkExistFrozenBalance(AccountCapsule accountCapsule, ResourceCode freezeType) { + List frozenV2List = accountCapsule.getFrozenV2List(); + for (FreezeV2 frozenV2 : frozenV2List) { + if (frozenV2.getType().equals(freezeType) && frozenV2.getAmount() > 0) { + return true; + } + } + return false; + } + + public boolean checkUnfreezeBalance(AccountCapsule accountCapsule, + final UnfreezeBalanceV2Contract unfreezeBalanceV2Contract, + ResourceCode freezeType) { + boolean checkOk = false; + + long frozenAmount = 0L; + List freezeV2List = accountCapsule.getFrozenV2List(); + for (FreezeV2 freezeV2 : freezeV2List) { + if (freezeV2.getType().equals(freezeType)) { + frozenAmount = freezeV2.getAmount(); + break; + } + } + + if (unfreezeBalanceV2Contract.getUnfreezeBalance() > 0 + && unfreezeBalanceV2Contract.getUnfreezeBalance() <= frozenAmount) { + checkOk = true; + } + + return checkOk; + } + + public long calcUnfreezeExpireTime(long now) { + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + long unfreezeDelayDays = dynamicStore.getUnfreezeDelayDays(); + + return now + unfreezeDelayDays * FROZEN_PERIOD; + } + + public void updateAccountFrozenInfo(ResourceCode freezeType, AccountCapsule accountCapsule, long unfreezeBalance) { + List freezeV2List = accountCapsule.getFrozenV2List(); + for (int i = 0; i < freezeV2List.size(); i++) { + if (freezeV2List.get(i).getType().equals(freezeType)) { + FreezeV2 freezeV2 = FreezeV2.newBuilder() + .setAmount(freezeV2List.get(i).getAmount() - unfreezeBalance) + .setType(freezeV2List.get(i).getType()) + .build(); + accountCapsule.updateFrozenV2List(i, freezeV2); + break; + } + } + } + + public long unfreezeExpire(AccountCapsule accountCapsule, long now) { + long unfreezeBalance = 0L; + + List unFrozenV2List = Lists.newArrayList(); + unFrozenV2List.addAll(accountCapsule.getUnfrozenV2List()); + Iterator iterator = unFrozenV2List.iterator(); + + while (iterator.hasNext()) { + UnFreezeV2 next = iterator.next(); + if (next.getUnfreezeExpireTime() <= now) { + unfreezeBalance += next.getUnfreezeAmount(); + iterator.remove(); + } + } + + accountCapsule.setInstance( + accountCapsule.getInstance().toBuilder() + .setBalance(accountCapsule.getBalance() + unfreezeBalance) + .clearUnfrozenV2() + .addAllUnfrozenV2(unFrozenV2List).build() + ); + return unfreezeBalance; + } + + public void updateTotalResourceWeight(AccountCapsule accountCapsule, + final UnfreezeBalanceV2Contract unfreezeBalanceV2Contract, + long unfreezeBalance) { + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + switch (unfreezeBalanceV2Contract.getResource()) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(-unfreezeBalance); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + dynamicStore.addTotalNetWeight(newNetWeight - oldNetWeight); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(-unfreezeBalance); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + dynamicStore.addTotalEnergyWeight(newEnergyWeight - oldEnergyWeight); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(-unfreezeBalance); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + dynamicStore.addTotalTronPowerWeight(newTPWeight - oldTPWeight); + break; + default: + //this should never happen + break; + } + } + + private void updateVote(AccountCapsule accountCapsule, + final UnfreezeBalanceV2Contract unfreezeBalanceV2Contract, + byte[] ownerAddress) { + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + VotesStore votesStore = chainBaseManager.getVotesStore(); + + if (accountCapsule.getVotesList().isEmpty()) { + return; + } + if (dynamicStore.supportAllowNewResourceModel()) { + if (accountCapsule.oldTronPowerIsInvalid()) { + switch (unfreezeBalanceV2Contract.getResource()) { + case BANDWIDTH: + case ENERGY: + // there is no need to change votes + return; + default: + break; + } + } else { + // clear all votes at once when new resource model start + VotesCapsule votesCapsule; + if (!votesStore.has(ownerAddress)) { + votesCapsule = new VotesCapsule( + unfreezeBalanceV2Contract.getOwnerAddress(), + accountCapsule.getVotesList() + ); + } else { + votesCapsule = votesStore.get(ownerAddress); + } + accountCapsule.clearVotes(); + votesCapsule.clearNewVotes(); + votesStore.put(ownerAddress, votesCapsule); + return; + } + } + + long totalVote = 0; + for (Protocol.Vote vote : accountCapsule.getVotesList()) { + totalVote += vote.getVoteCount(); + } + long ownedTronPower; + if (dynamicStore.supportAllowNewResourceModel()) { + ownedTronPower = accountCapsule.getAllTronPower(); + } else { + ownedTronPower = accountCapsule.getTronPower(); + } + + // tron power is enough to total votes + if (ownedTronPower >= totalVote * TRX_PRECISION) { + return; + } + if (totalVote == 0) { + return; + } + + VotesCapsule votesCapsule; + if (!votesStore.has(ownerAddress)) { + votesCapsule = new VotesCapsule( + unfreezeBalanceV2Contract.getOwnerAddress(), + accountCapsule.getVotesList() + ); + } else { + votesCapsule = votesStore.get(ownerAddress); + } + + // Update Owner Voting + List addVotes = new ArrayList<>(); + for (Vote vote : accountCapsule.getVotesList()) { + long newVoteCount = (long) + ((double) vote.getVoteCount() / totalVote * ownedTronPower / TRX_PRECISION); + if (newVoteCount > 0) { + Vote newVote = Vote.newBuilder() + .setVoteAddress(vote.getVoteAddress()) + .setVoteCount(newVoteCount) + .build(); + addVotes.add(newVote); + } + } + votesCapsule.clearNewVotes(); + votesCapsule.addAllNewVotes(addVotes); + votesStore.put(ownerAddress, votesCapsule); + + accountCapsule.clearVotes(); + accountCapsule.addAllVotes(addVotes); + } +} \ No newline at end of file diff --git a/actuator/src/main/java/org/tron/core/actuator/UpdateEnergyLimitContractActuator.java b/actuator/src/main/java/org/tron/core/actuator/UpdateEnergyLimitContractActuator.java index 8de083f3fce..f6b67e02891 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UpdateEnergyLimitContractActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UpdateEnergyLimitContractActuator.java @@ -6,15 +6,16 @@ import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.DecodeUtil; -import org.tron.common.utils.StorageUtils; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.AccountStore; import org.tron.core.store.ContractStore; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract; @@ -44,6 +45,7 @@ public boolean execute(Object object) throws ContractExeException { contractStore.put(contractAddress, new ContractCapsule( deployedContract.getInstance().toBuilder().setOriginEnergyLimit(newOriginEnergyLimit) .build())); + RepositoryImpl.removeLruCache(contractAddress); ret.setStatus(fee, code.SUCESS); } catch (InvalidProtocolBufferException e) { @@ -56,16 +58,16 @@ public boolean execute(Object object) throws ContractExeException { @Override public boolean validate() throws ContractValidateException { - if (!StorageUtils.getEnergyLimitHardFork()) { - throw new ContractValidateException( - "contract type error, unexpected type [UpdateEnergyLimitContract]"); - } if (this.any == null) { throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); } if (chainBaseManager == null) { throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); } + if (!ReceiptCapsule.checkForEnergyLimit(chainBaseManager.getDynamicPropertiesStore())) { + throw new ContractValidateException( + "contract type error, unexpected type [UpdateEnergyLimitContract]"); + } AccountStore accountStore = chainBaseManager.getAccountStore(); ContractStore contractStore = chainBaseManager.getContractStore(); if (!this.any.is(UpdateEnergyLimitContract.class)) { diff --git a/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java b/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java index f3d2e6f533d..d0025f14ef6 100755 --- a/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/UpdateSettingContractActuator.java @@ -16,6 +16,7 @@ import org.tron.core.exception.ContractValidateException; import org.tron.core.store.AccountStore; import org.tron.core.store.ContractStore; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract; @@ -45,6 +46,7 @@ public boolean execute(Object object) throws ContractExeException { contractStore.put(contractAddress, new ContractCapsule( deployedContract.getInstance().toBuilder().setConsumeUserResourcePercent(newPercent) .build())); + RepositoryImpl.removeLruCache(contractAddress); ret.setStatus(fee, code.SUCESS); } catch (InvalidProtocolBufferException e) { 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 ff7d6f7e309..9da41574ff0 100644 --- a/actuator/src/main/java/org/tron/core/actuator/VMActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/VMActuator.java @@ -1,9 +1,12 @@ package org.tron.core.actuator; -import static java.lang.Math.max; -import static java.lang.Math.min; import static org.apache.commons.lang3.ArrayUtils.getLength; import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.floorDiv; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.ByteString; import java.math.BigInteger; @@ -21,19 +24,23 @@ import org.tron.common.runtime.InternalTransaction.ExecutorType; 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.StorageUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.core.ChainBaseManager; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.ReceiptCapsule; +import org.tron.core.db.EnergyProcessor; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.utils.TransactionUtil; import org.tron.core.vm.EnergyCost; import org.tron.core.vm.LogInfoTriggerParser; +import org.tron.core.vm.Op; import org.tron.core.vm.OperationRegistry; import org.tron.core.vm.VM; import org.tron.core.vm.VMConstant; @@ -83,6 +90,8 @@ public class VMActuator implements Actuator2 { @Setter private boolean isConstantCall; + private long maxEnergyLimit; + @Setter private boolean enableEventListener; @@ -90,6 +99,7 @@ public class VMActuator implements Actuator2 { public VMActuator(boolean isConstantCall) { this.isConstantCall = isConstantCall; + this.maxEnergyLimit = CommonParameter.getInstance().maxEnergyLimitForConstant; } private static long getEnergyFee(long callerEnergyUsage, long callerEnergyFrozen, @@ -114,8 +124,15 @@ public void validate(Object object) throws ContractValidateException { // Warm up registry class OperationRegistry.init(); trx = context.getTrxCap().getInstance(); + // If tx`s fee limit is set, use it to calc max energy limit for constant call + if (isConstantCall && trx.getRawData().getFeeLimit() > 0) { + maxEnergyLimit = min(maxEnergyLimit, trx.getRawData().getFeeLimit() + / context.getStoreFactory().getChainBaseManager() + .getDynamicPropertiesStore().getEnergyFee(), VMConfig.disableJavaLangMath()); + } blockCap = context.getBlockCap(); - if (VMConfig.allowTvmFreeze() && context.getTrxCap().getTrxTrace() != null) { + if ((VMConfig.allowTvmFreeze() || VMConfig.allowTvmFreezeV2()) + && context.getTrxCap().getTrxTrace() != null) { receipt = context.getTrxCap().getTrxTrace().getReceipt(); } //Route Type @@ -172,9 +189,16 @@ public void execute(Object object) throws ContractExeException { throw e; } - VM.play(program, OperationRegistry.getTable(OperationRegistry.Version.TRON_V1)); + VM.play(program, OperationRegistry.getTable()); result = program.getResult(); + if (VMConfig.allowEnergyAdjustment()) { + // If the last op consumed too much execution time, the CPU time limit for the whole tx can be exceeded. + // This is not fair for other txs in the same block. + // So when allowFairEnergyAdjustment is on, the CPU time limit will be checked at the end of tx execution. + program.checkCPUTimeLimit(Op.getNameOf(program.getLastOp()) + "(TX_LAST_OP)"); + } + if (TrxType.TRX_CONTRACT_CREATION_TYPE == trxType && !result.isRevert()) { byte[] code = program.getResult().getHReturn(); if (code.length != 0 && VMConfig.allowTvmLondon() && code[0] == (byte) 0xEF) { @@ -235,6 +259,9 @@ public void execute(Object object) throws ContractExeException { } else { rootRepository.commit(); } + for (DataWord account : result.getDeleteAccounts()) { + RepositoryImpl.removeLruCache(account.toTronAddress()); + } } catch (JVMStackOverFlowException e) { program.spendAllEnergy(); result = program.getResult(); @@ -348,7 +375,7 @@ private void create() // according to version if (isConstantCall) { - energyLimit = CommonParameter.getInstance().maxEnergyLimitForConstant; + energyLimit = maxEnergyLimit; } else { if (StorageUtils.getEnergyLimitHardFork()) { if (callValue < 0) { @@ -380,7 +407,10 @@ private void create() .createProgramInvoke(TrxType.TRX_CONTRACT_CREATION_TYPE, executorType, trx, tokenValue, tokenId, blockCap.getInstance(), rootRepository, vmStartInUs, vmShouldEndInUs, energyLimit); - this.program = new Program(ops, programInvoke, rootInternalTx); + if (isConstantCall) { + programInvoke.setConstantCall(); + } + this.program = new Program(ops, contractAddress, programInvoke, rootInternalTx); if (VMConfig.allowTvmCompatibleEvm()) { this.program.setContractVersion(1); } @@ -475,7 +505,7 @@ private void call() AccountCapsule caller = rootRepository.getAccount(callerAddress); long energyLimit; if (isConstantCall) { - energyLimit = CommonParameter.getInstance().maxEnergyLimitForConstant; + energyLimit = maxEnergyLimit; } else { AccountCapsule creator = rootRepository .getAccount(deployedContract.getInstance().getOriginAddress().toByteArray()); @@ -496,7 +526,7 @@ private void call() programInvoke.setConstantCall(); } rootInternalTx = new InternalTransaction(trx, trxType); - this.program = new Program(code, programInvoke, rootInternalTx); + this.program = new Program(code, contractAddress, programInvoke, rootInternalTx); if (VMConfig.allowTvmCompatibleEvm()) { this.program.setContractVersion(deployedContract.getContractVersion()); } @@ -531,15 +561,36 @@ public long getAccountEnergyLimitWithFixRatio(AccountCapsule account, long feeLi } long leftFrozenEnergy = rootRepository.getAccountLeftEnergyFromFreeze(account); - if (VMConfig.allowTvmFreeze()) { + if (VMConfig.allowTvmFreeze() || VMConfig.allowTvmFreezeV2()) { receipt.setCallerEnergyLeft(leftFrozenEnergy); } - long energyFromBalance = max(account.getBalance() - callValue, 0) / sunPerEnergy; - long availableEnergy = Math.addExact(leftFrozenEnergy, energyFromBalance); + long energyFromBalance = max(account.getBalance() - callValue, 0, + VMConfig.disableJavaLangMath()) / sunPerEnergy; + long availableEnergy = addExact(leftFrozenEnergy, energyFromBalance, + VMConfig.disableJavaLangMath()); long energyFromFeeLimit = feeLimit / sunPerEnergy; - return min(availableEnergy, energyFromFeeLimit); + if (VMConfig.allowTvmFreezeV2()) { + long now = rootRepository.getHeadSlot(); + EnergyProcessor energyProcessor = + new EnergyProcessor( + rootRepository.getDynamicPropertiesStore(), + ChainBaseManager.getInstance().getAccountStore()); + energyProcessor.updateUsage(account); + account.setLatestConsumeTimeForEnergy(now); + receipt.setCallerEnergyUsage(account.getEnergyUsage()); + receipt.setCallerEnergyWindowSize(account.getWindowSize(ENERGY)); + receipt.setCallerEnergyWindowSizeV2(account.getWindowSizeV2(ENERGY)); + account.setEnergyUsage( + energyProcessor.increase(account, ENERGY, + account.getEnergyUsage(), min(leftFrozenEnergy, energyFromFeeLimit, + VMConfig.disableJavaLangMath()), now, now)); + receipt.setCallerEnergyMergedUsage(account.getEnergyUsage()); + receipt.setCallerEnergyMergedWindowSize(account.getWindowSize(ENERGY)); + rootRepository.updateAccount(account.createDbKey(), account); + } + return min(availableEnergy, energyFromFeeLimit, VMConfig.disableJavaLangMath()); } @@ -552,9 +603,10 @@ private long getAccountEnergyLimitWithFloatRatio(AccountCapsule account, long fe } // can change the calc way long leftEnergyFromFreeze = rootRepository.getAccountLeftEnergyFromFreeze(account); - callValue = max(callValue, 0); - long energyFromBalance = Math - .floorDiv(max(account.getBalance() - callValue, 0), sunPerEnergy); + callValue = max(callValue, 0, VMConfig.disableJavaLangMath()); + long energyFromBalance = floorDiv(max( + account.getBalance() - callValue, 0, VMConfig.disableJavaLangMath()), sunPerEnergy, + VMConfig.disableJavaLangMath()); long energyFromFeeLimit; long totalBalanceForEnergyFreeze = account.getAllFrozenBalanceForEnergy(); @@ -573,13 +625,14 @@ private long getAccountEnergyLimitWithFloatRatio(AccountCapsule account, long fe .multiply(BigInteger.valueOf(feeLimit)) .divide(BigInteger.valueOf(totalBalanceForEnergyFreeze)).longValueExact(); } else { - energyFromFeeLimit = Math - .addExact(leftEnergyFromFreeze, - (feeLimit - leftBalanceForEnergyFreeze) / sunPerEnergy); + energyFromFeeLimit = addExact( + leftEnergyFromFreeze, (feeLimit - leftBalanceForEnergyFreeze) / sunPerEnergy, + VMConfig.disableJavaLangMath()); } } - return min(Math.addExact(leftEnergyFromFreeze, energyFromBalance), energyFromFeeLimit); + return min(addExact(leftEnergyFromFreeze, energyFromBalance, + VMConfig.disableJavaLangMath()), energyFromFeeLimit, VMConfig.disableJavaLangMath()); } public long getTotalEnergyLimit(AccountCapsule creator, AccountCapsule caller, @@ -654,7 +707,8 @@ public long getTotalEnergyLimitWithFixRatio(AccountCapsule creator, AccountCapsu long creatorEnergyLimit = 0; ContractCapsule contractCapsule = rootRepository .getContract(contract.getContractAddress().toByteArray()); - long consumeUserResourcePercent = contractCapsule.getConsumeUserResourcePercent(); + long consumeUserResourcePercent = contractCapsule.getConsumeUserResourcePercent( + VMConfig.disableJavaLangMath()); long originEnergyLimit = contractCapsule.getOriginEnergyLimit(); if (originEnergyLimit < 0) { @@ -664,12 +718,13 @@ public long getTotalEnergyLimitWithFixRatio(AccountCapsule creator, AccountCapsu long originEnergyLeft = 0; if (consumeUserResourcePercent < VMConstant.ONE_HUNDRED) { originEnergyLeft = rootRepository.getAccountLeftEnergyFromFreeze(creator); - if (VMConfig.allowTvmFreeze()) { + if (VMConfig.allowTvmFreeze() || VMConfig.allowTvmFreezeV2()) { receipt.setOriginEnergyLeft(originEnergyLeft); } } if (consumeUserResourcePercent <= 0) { - creatorEnergyLimit = min(originEnergyLeft, originEnergyLimit); + creatorEnergyLimit = min(originEnergyLeft, originEnergyLimit, + VMConfig.disableJavaLangMath()); } else { if (consumeUserResourcePercent < VMConstant.ONE_HUNDRED) { // creatorEnergyLimit = @@ -680,11 +735,30 @@ public long getTotalEnergyLimitWithFixRatio(AccountCapsule creator, AccountCapsu BigInteger.valueOf(callerEnergyLimit) .multiply(BigInteger.valueOf(VMConstant.ONE_HUNDRED - consumeUserResourcePercent)) .divide(BigInteger.valueOf(consumeUserResourcePercent)).longValueExact(), - min(originEnergyLeft, originEnergyLimit) - ); + min(originEnergyLeft, originEnergyLimit, VMConfig.disableJavaLangMath()), + VMConfig.disableJavaLangMath()); } } - return Math.addExact(callerEnergyLimit, creatorEnergyLimit); + if (VMConfig.allowTvmFreezeV2()) { + long now = rootRepository.getHeadSlot(); + EnergyProcessor energyProcessor = + new EnergyProcessor( + rootRepository.getDynamicPropertiesStore(), + ChainBaseManager.getInstance().getAccountStore()); + energyProcessor.updateUsage(creator); + creator.setLatestConsumeTimeForEnergy(now); + receipt.setOriginEnergyUsage(creator.getEnergyUsage()); + receipt.setOriginEnergyWindowSize(creator.getWindowSize(ENERGY)); + receipt.setOriginEnergyWindowSizeV2(creator.getWindowSizeV2(ENERGY)); + creator.setEnergyUsage( + energyProcessor.increase(creator, ENERGY, + creator.getEnergyUsage(), creatorEnergyLimit, now, now)); + receipt.setOriginEnergyMergedUsage(creator.getEnergyUsage()); + receipt.setOriginEnergyMergedWindowSize(creator.getWindowSize(ENERGY)); + rootRepository.updateAccount(creator.createDbKey(), creator); + } + return addExact(callerEnergyLimit, creatorEnergyLimit, + VMConfig.disableJavaLangMath()); } private long getTotalEnergyLimitWithFloatRatio(AccountCapsule creator, AccountCapsule caller, @@ -700,13 +774,17 @@ private long getTotalEnergyLimitWithFloatRatio(AccountCapsule creator, AccountCa ContractCapsule contractCapsule = rootRepository .getContract(contract.getContractAddress().toByteArray()); - long consumeUserResourcePercent = contractCapsule.getConsumeUserResourcePercent(); + long consumeUserResourcePercent = contractCapsule.getConsumeUserResourcePercent( + VMConfig.disableJavaLangMath()); if (creatorEnergyLimit * consumeUserResourcePercent > (VMConstant.ONE_HUNDRED - consumeUserResourcePercent) * callerEnergyLimit) { - return Math.floorDiv(callerEnergyLimit * VMConstant.ONE_HUNDRED, consumeUserResourcePercent); + return floorDiv( + callerEnergyLimit * VMConstant.ONE_HUNDRED, consumeUserResourcePercent, + VMConfig.disableJavaLangMath()); } else { - return Math.addExact(callerEnergyLimit, creatorEnergyLimit); + return addExact(callerEnergyLimit, creatorEnergyLimit, + VMConfig.disableJavaLangMath()); } } @@ -715,5 +793,4 @@ private boolean isCheckTransaction() { .getWitnessSignature().isEmpty(); } - } diff --git a/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java b/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java new file mode 100755 index 00000000000..fd71ebf1404 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuator.java @@ -0,0 +1,148 @@ +package org.tron.core.actuator; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; + +import com.google.common.math.LongMath; +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol.Account.UnFreezeV2; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.BalanceContract.WithdrawExpireUnfreezeContract; + + +@Slf4j(topic = "actuator") +public class WithdrawExpireUnfreezeActuator extends AbstractActuator { + + public WithdrawExpireUnfreezeActuator() { + super(ContractType.WithdrawExpireUnfreezeContract, WithdrawExpireUnfreezeContract.class); + } + + @Override + public boolean execute(Object result) throws ContractExeException { + TransactionResultCapsule ret = (TransactionResultCapsule) result; + if (Objects.isNull(ret)) { + throw new RuntimeException(ActuatorConstant.TX_RESULT_NULL); + } + long fee = calcFee(); + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + final WithdrawExpireUnfreezeContract withdrawExpireUnfreezeContract; + try { + withdrawExpireUnfreezeContract = any.unpack(WithdrawExpireUnfreezeContract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + ret.setStatus(fee, code.FAILED); + throw new ContractExeException(e.getMessage()); + } + AccountCapsule accountCapsule = accountStore.get( + withdrawExpireUnfreezeContract.getOwnerAddress().toByteArray()); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + List unfrozenV2List = accountCapsule.getInstance().getUnfrozenV2List(); + long totalWithdrawUnfreeze = getTotalWithdrawUnfreeze(unfrozenV2List, now); + accountCapsule.setInstance(accountCapsule.getInstance().toBuilder() + .setBalance(accountCapsule.getBalance() + totalWithdrawUnfreeze) + .build()); + List newUnFreezeList = getRemainWithdrawList(unfrozenV2List, now); + accountCapsule.clearUnfrozenV2(); + accountCapsule.addAllUnfrozenV2(newUnFreezeList); + accountStore.put(accountCapsule.createDbKey(), accountCapsule); + ret.setWithdrawExpireAmount(totalWithdrawUnfreeze); + ret.setStatus(fee, code.SUCESS); + return true; + } + + @Override + public boolean validate() throws ContractValidateException { + if (Objects.isNull(this.any)) { + throw new ContractValidateException(ActuatorConstant.CONTRACT_NOT_EXIST); + } + if (Objects.isNull(chainBaseManager)) { + throw new ContractValidateException(ActuatorConstant.STORE_NOT_EXIST); + } + AccountStore accountStore = chainBaseManager.getAccountStore(); + DynamicPropertiesStore dynamicStore = chainBaseManager.getDynamicPropertiesStore(); + if (!this.any.is(WithdrawExpireUnfreezeContract.class)) { + throw new ContractValidateException( + "contract type error, expected type [WithdrawExpireUnfreezeContract], real type[" + any + .getClass() + "]"); + } + + if (!dynamicStore.supportUnfreezeDelay()) { + throw new ContractValidateException("Not support WithdrawExpireUnfreeze transaction," + + " need to be opened by the committee"); + } + + final WithdrawExpireUnfreezeContract withdrawExpireUnfreezeContract; + try { + withdrawExpireUnfreezeContract = this.any.unpack(WithdrawExpireUnfreezeContract.class); + } catch (InvalidProtocolBufferException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + byte[] ownerAddress = withdrawExpireUnfreezeContract.getOwnerAddress().toByteArray(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = accountStore.get(ownerAddress); + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + if (Objects.isNull(accountCapsule)) { + throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + + readableOwnerAddress + NOT_EXIST_STR); + } + + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + List unfrozenV2List = accountCapsule.getInstance().getUnfrozenV2List(); + long totalWithdrawUnfreeze = getTotalWithdrawUnfreeze(unfrozenV2List, now); + if (totalWithdrawUnfreeze <= 0) { + throw new ContractValidateException("no unFreeze balance to withdraw "); + } + try { + LongMath.checkedAdd(accountCapsule.getBalance(), totalWithdrawUnfreeze); + } catch (ArithmeticException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + return true; + } + + private long getTotalWithdrawUnfreeze(List unfrozenV2List, long now) { + return getTotalWithdrawList(unfrozenV2List, now).stream() + .mapToLong(UnFreezeV2::getUnfreezeAmount).sum(); + } + + private List getTotalWithdrawList(List unfrozenV2List, long now) { + return unfrozenV2List.stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= now) + .collect(Collectors.toList()); + } + + private List getRemainWithdrawList(List unfrozenV2List, long now) { + return unfrozenV2List.stream() + .filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() > now) + .collect(Collectors.toList()); + } + + @Override + public ByteString getOwnerAddress() throws InvalidProtocolBufferException { + return any.unpack(WithdrawExpireUnfreezeContract.class).getOwnerAddress(); + } + + @Override + public long calcFee() { + return 0; + } + +} diff --git a/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java b/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java index ee223a32ffa..fc908a1713f 100755 --- a/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java +++ b/actuator/src/main/java/org/tron/core/actuator/WitnessCreateActuator.java @@ -6,7 +6,6 @@ import com.google.protobuf.InvalidProtocolBufferException; import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; @@ -140,12 +139,11 @@ private void createWitness(final WitnessCreateContract witnessCreateContract) } accountStore.put(accountCapsule.createDbKey(), accountCapsule); long cost = dynamicStore.getAccountUpgradeCost(); - Commons - .adjustBalance(accountStore, witnessCreateContract.getOwnerAddress().toByteArray(), -cost); + adjustBalance(accountStore, witnessCreateContract.getOwnerAddress().toByteArray(), -cost); if (dynamicStore.supportBlackHoleOptimization()) { dynamicStore.burnTrx(cost); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole(), +cost); + adjustBalance(accountStore, accountStore.getBlackhole(), +cost); } dynamicStore.addTotalCreateWitnessCost(cost); } 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 8ce040702c5..0bad940da7e 100644 --- a/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/ProposalUtil.java @@ -1,5 +1,11 @@ package org.tron.core.utils; +import static org.tron.core.Constant.CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE; +import static org.tron.core.Constant.CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE; +import static org.tron.core.Constant.DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE; +import static org.tron.core.Constant.DYNAMIC_ENERGY_MAX_FACTOR_RANGE; +import static org.tron.core.config.Parameter.ChainConstant.ONE_YEAR_BLOCK_NUMBERS; + import org.tron.common.utils.ForkController; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.Parameter.ForkBlockVersionEnum; @@ -67,9 +73,16 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, case EXCHANGE_CREATE_FEE: break; case MAX_CPU_TIME_OF_ONE_TX: - if (value < 10 || value > 100) { - throw new ContractValidateException( - "Bad chain parameter value, valid range is [10,100]"); + if (dynamicPropertiesStore.getAllowHigherLimitForMaxCpuTimeOfOneTx() == 1) { + if (value < 10 || value > 400) { + throw new ContractValidateException( + "Bad chain parameter value, valid range is [10,400]"); + } + } else { + if (value < 10 || value > 100) { + throw new ContractValidateException( + "Bad chain parameter value, valid range is [10,100]"); + } } break; case ALLOW_UPDATE_ACCOUNT_NAME: { @@ -501,11 +514,11 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, case ALLOW_ACCOUNT_ASSET_OPTIMIZATION: { if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_3)) { throw new ContractValidateException( - "Bad chain parameter id [ALLOW_ACCOUNT_ASSET_OPTIMIZATION]"); + "Bad chain parameter id [ALLOW_ACCOUNT_ASSET_OPTIMIZATION]"); } if (value != 1) { throw new ContractValidateException( - "This value[ALLOW_ACCOUNT_ASSET_OPTIMIZATION] is only allowed to be 1"); + "This value[ALLOW_ACCOUNT_ASSET_OPTIMIZATION] is only allowed to be 1"); } break; } @@ -531,6 +544,301 @@ public static void validator(DynamicPropertiesStore dynamicPropertiesStore, } break; } + case ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_5)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX] is only allowed to be 1"); + } + break; + } + case ALLOW_ASSET_OPTIMIZATION: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_5)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_ASSET_OPTIMIZATION]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_ASSET_OPTIMIZATION] is only allowed to be 1"); + } + break; + } + case ALLOW_NEW_REWARD: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_6)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_NEW_REWARD]"); + } + if (dynamicPropertiesStore.allowNewReward()) { + throw new ContractValidateException( + "New reward has been valid."); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_NEW_REWARD] is only allowed to be 1"); + } + break; + } + case MEMO_FEE: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_6)) { + throw new ContractValidateException( + "Bad chain parameter id [MEMO_FEE]"); + } + if (value < 0 || value > 1_000_000_000) { + throw new ContractValidateException( + "This value[MEMO_FEE] is only allowed to be in the range 0-1000_000_000"); + } + break; + } + case ALLOW_DELEGATE_OPTIMIZATION: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_6)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_DELEGATE_OPTIMIZATION]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_DELEGATE_OPTIMIZATION] is only allowed to be 1"); + } + break; + } + case UNFREEZE_DELAY_DAYS: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7)) { + throw new ContractValidateException( + "Bad chain parameter id [UNFREEZE_DELAY_DAYS]"); + } + if (value < 1 || value > 365) { + throw new ContractValidateException( + "This value[UNFREEZE_DELAY_DAYS] is only allowed to be in the range 1-365"); + } + break; + } + case ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID] is only allowed to be 1"); + } + break; + } + + case ALLOW_DYNAMIC_ENERGY: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_DYNAMIC_ENERGY]"); + } + if (value < 0 || value > 1) { + throw new ContractValidateException( + "This value[ALLOW_DYNAMIC_ENERGY] is only allowed to be in the range 0-1" + ); + } + if (value == 1 && dynamicPropertiesStore.getChangeDelegation() == 0) { + throw new ContractValidateException( + "[ALLOW_CHANGE_DELEGATION] proposal must be approved " + + "before [ALLOW_DYNAMIC_ENERGY] can be opened"); + } + break; + } + case DYNAMIC_ENERGY_THRESHOLD: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7)) { + throw new ContractValidateException( + "Bad chain parameter id [DYNAMIC_ENERGY_THRESHOLD]"); + } + + if (value < 0 || value > LONG_VALUE) { + throw new ContractValidateException(LONG_VALUE_ERROR); + } + break; + } + case DYNAMIC_ENERGY_INCREASE_FACTOR: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7)) { + throw new ContractValidateException( + "Bad chain parameter id [DYNAMIC_ENERGY_INCREASE_FACTOR]"); + } + + if (value < 0 || value > DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE) { + throw new ContractValidateException( + "This value[DYNAMIC_ENERGY_INCREASE_FACTOR] " + + "is only allowed to be in the range 0-" + + DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE + ); + } + break; + } + case DYNAMIC_ENERGY_MAX_FACTOR: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7)) { + throw new ContractValidateException( + "Bad chain parameter id [DYNAMIC_ENERGY_MAX_FACTOR]"); + } + + if (value < 0 || value > DYNAMIC_ENERGY_MAX_FACTOR_RANGE) { + throw new ContractValidateException( + "This value[DYNAMIC_ENERGY_MAX_FACTOR] " + + "is only allowed to be in the range 0-" + + DYNAMIC_ENERGY_MAX_FACTOR_RANGE + ); + } + break; + } + case ALLOW_TVM_SHANGHAI: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_2)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_TVM_SHANGHAI]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_TVM_SHANGHAI] is only allowed to be 1"); + } + break; + } + case ALLOW_CANCEL_ALL_UNFREEZE_V2: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_2)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_CANCEL_ALL_UNFREEZE_V2]"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_CANCEL_ALL_UNFREEZE_V2] is only allowed to be 1"); + } + if (dynamicPropertiesStore.getUnfreezeDelayDays() == 0) { + throw new ContractValidateException( + "[UNFREEZE_DELAY_DAYS] proposal must be approved " + + "before [ALLOW_CANCEL_ALL_UNFREEZE_V2] can be proposed"); + } + break; + } + case MAX_DELEGATE_LOCK_PERIOD: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_2)) { + throw new ContractValidateException( + "Bad chain parameter id [MAX_DELEGATE_LOCK_PERIOD]"); + } + long maxDelegateLockPeriod = dynamicPropertiesStore.getMaxDelegateLockPeriod(); + if (value <= maxDelegateLockPeriod || value > ONE_YEAR_BLOCK_NUMBERS) { + throw new ContractValidateException( + "This value[MAX_DELEGATE_LOCK_PERIOD] is only allowed to be greater than " + + maxDelegateLockPeriod + " and less than or equal to " + ONE_YEAR_BLOCK_NUMBERS + + " !"); + } + if (dynamicPropertiesStore.getUnfreezeDelayDays() == 0) { + throw new ContractValidateException( + "[UNFREEZE_DELAY_DAYS] proposal must be approved " + + "before [MAX_DELEGATE_LOCK_PERIOD] can be proposed"); + } + break; + } + case ALLOW_OLD_REWARD_OPT: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_4)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_OLD_REWARD_OPT]"); + } + if (dynamicPropertiesStore.allowOldRewardOpt()) { + throw new ContractValidateException( + "[ALLOW_OLD_REWARD_OPT] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_OLD_REWARD_OPT] is only allowed to be 1"); + } + if (!dynamicPropertiesStore.useNewRewardAlgorithm()) { + throw new ContractValidateException( + "[ALLOW_NEW_REWARD] or [ALLOW_TVM_VOTE] proposal must be approved " + + "before [ALLOW_OLD_REWARD_OPT] can be proposed"); + } + break; + } + case ALLOW_ENERGY_ADJUSTMENT: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_5)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_ENERGY_ADJUSTMENT]"); + } + if (dynamicPropertiesStore.getAllowEnergyAdjustment() == 1) { + throw new ContractValidateException( + "[ALLOW_ENERGY_ADJUSTMENT] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_ENERGY_ADJUSTMENT] is only allowed to be 1"); + } + break; + } + case MAX_CREATE_ACCOUNT_TX_SIZE: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_5)) { + throw new ContractValidateException( + "Bad chain parameter id [MAX_CREATE_ACCOUNT_TX_SIZE]"); + } + if (value < CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE + || value > CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE) { + throw new ContractValidateException( + "This value[MAX_CREATE_ACCOUNT_TX_SIZE] is only allowed to be greater than or equal " + + "to " + CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE + " and less than or equal to " + + CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE + "!"); + } + break; + } + case ALLOW_STRICT_MATH: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_7_7)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_STRICT_MATH]"); + } + if (dynamicPropertiesStore.allowStrictMath()) { + throw new ContractValidateException( + "[ALLOW_STRICT_MATH] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_STRICT_MATH] is only allowed to be 1"); + } + break; + } + case CONSENSUS_LOGIC_OPTIMIZATION: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_8_0)) { + throw new ContractValidateException( + "Bad chain parameter id [CONSENSUS_LOGIC_OPTIMIZATION]"); + } + if (dynamicPropertiesStore.getConsensusLogicOptimization() == 1) { + throw new ContractValidateException( + "[CONSENSUS_LOGIC_OPTIMIZATION] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[CONSENSUS_LOGIC_OPTIMIZATION] is only allowed to be 1"); + } + break; + } + case ALLOW_TVM_CANCUN: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_8_0)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_TVM_CANCUN]"); + } + if (dynamicPropertiesStore.getAllowTvmCancun() == 1) { + throw new ContractValidateException( + "[ALLOW_TVM_CANCUN] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_TVM_CANCUN] is only allowed to be 1"); + } + break; + } + case ALLOW_TVM_BLOB: { + if (!forkController.pass(ForkBlockVersionEnum.VERSION_4_8_0)) { + throw new ContractValidateException( + "Bad chain parameter id [ALLOW_TVM_BLOB]"); + } + if (dynamicPropertiesStore.getAllowTvmBlob() == 1) { + throw new ContractValidateException( + "[ALLOW_TVM_BLOB] has been valid, no need to propose again"); + } + if (value != 1) { + throw new ContractValidateException( + "This value[ALLOW_TVM_BLOB] is only allowed to be 1"); + } + break; + } default: break; } @@ -592,7 +900,28 @@ public enum ProposalType { // current value, value range ALLOW_TVM_COMPATIBLE_EVM(60), // 0, 1 FREE_NET_LIMIT(61), // 5000, [0, 100_000] TOTAL_NET_LIMIT(62), // 43_200_000_000L, [0, 1000_000_000_000L] - ALLOW_TVM_LONDON(63); // 0, 1 + ALLOW_TVM_LONDON(63), // 0, 1 + ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX(65), // 0, 1 + ALLOW_ASSET_OPTIMIZATION(66), // 0, 1 + ALLOW_NEW_REWARD(67), // 0, 1 + MEMO_FEE(68), // 0, [0, 1000_000_000] + ALLOW_DELEGATE_OPTIMIZATION(69), + UNFREEZE_DELAY_DAYS(70), // 0, [1, 365] + ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID(71), // 0, 1 + ALLOW_DYNAMIC_ENERGY(72), // 0, 1 + DYNAMIC_ENERGY_THRESHOLD(73), // 0, [0, LONG] + DYNAMIC_ENERGY_INCREASE_FACTOR(74), // 0, [0, 10_000] + DYNAMIC_ENERGY_MAX_FACTOR(75), // 0, [0, 100_000] + ALLOW_TVM_SHANGHAI(76), // 0, 1 + ALLOW_CANCEL_ALL_UNFREEZE_V2(77), // 0, 1 + MAX_DELEGATE_LOCK_PERIOD(78), // (86400, 10512000] + ALLOW_OLD_REWARD_OPT(79), // 0, 1 + ALLOW_ENERGY_ADJUSTMENT(81), // 0, 1 + MAX_CREATE_ACCOUNT_TX_SIZE(82), // [500, 10000] + ALLOW_TVM_CANCUN(83), // 0, 1 + ALLOW_STRICT_MATH(87), // 0, 1 + CONSENSUS_LOGIC_OPTIMIZATION(88), // 0, 1 + ALLOW_TVM_BLOB(89); // 0, 1 private long code; diff --git a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java index cb7c10a1fff..53d6caf5691 100644 --- a/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java +++ b/actuator/src/main/java/org/tron/core/utils/TransactionUtil.java @@ -16,6 +16,9 @@ package org.tron.core.utils; import static org.tron.common.crypto.Hash.sha3omit12; +import static org.tron.common.math.Maths.max; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_COST_BASE_SIZE; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import com.google.common.base.CaseFormat; import com.google.common.primitives.Longs; @@ -41,14 +44,15 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.exception.PermissionException; import org.tron.core.exception.SignatureFormatException; +import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Permission; import org.tron.protos.Protocol.Permission.PermissionType; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract; import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionSign; import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; @Slf4j(topic = "capsule") @Component @@ -179,21 +183,6 @@ public static String makeUpperCamelMethod(String originName) { .replace("_", ""); } - public static TransactionCapsule getTransactionSign(TransactionSign transactionSign) { - byte[] privateKey = transactionSign.getPrivateKey().toByteArray(); - TransactionCapsule trx = new TransactionCapsule(transactionSign.getTransaction()); - trx.sign(privateKey); - return trx; - } - - public TransactionCapsule addSign(TransactionSign transactionSign) - throws PermissionException, SignatureException, SignatureFormatException { - byte[] privateKey = transactionSign.getPrivateKey().toByteArray(); - TransactionCapsule trx = new TransactionCapsule(transactionSign.getTransaction()); - trx.addSign(privateKey, chainBaseManager.getAccountStore()); - return trx; - } - public TransactionSignWeight getTransactionSignWeight(Transaction trx) { TransactionSignWeight.Builder tswBuilder = TransactionSignWeight.newBuilder(); TransactionExtention.Builder trxExBuilder = TransactionExtention.newBuilder(); @@ -205,56 +194,83 @@ public TransactionSignWeight getTransactionSignWeight(Transaction trx) { trxExBuilder.setResult(retBuilder); tswBuilder.setTransaction(trxExBuilder); Result.Builder resultBuilder = Result.newBuilder(); - try { - Contract contract = trx.getRawData().getContract(0); - byte[] owner = TransactionCapsule.getOwner(contract); - AccountCapsule account = chainBaseManager.getAccountStore().get(owner); - if (Objects.isNull(account)) { - throw new PermissionException("Account does not exist!"); - } - int permissionId = contract.getPermissionId(); - Permission permission = account.getPermissionById(permissionId); - if (permission == null) { - throw new PermissionException("Permission for this, does not exist!"); - } - if (permissionId != 0) { - if (permission.getType() != PermissionType.Active) { - throw new PermissionException("Permission type is wrong!"); + + if (trx.getRawData().getContractCount() == 0) { + resultBuilder.setCode(Result.response_code.OTHER_ERROR); + resultBuilder.setMessage("Invalid transaction: no valid contract"); + } else { + try { + Contract contract = trx.getRawData().getContract(0); + byte[] owner = TransactionCapsule.getOwner(contract); + AccountCapsule account = chainBaseManager.getAccountStore().get(owner); + if (Objects.isNull(account)) { + throw new PermissionException("Account does not exist!"); } - //check operations - if (!checkPermissionOperations(permission, contract)) { - throw new PermissionException("Permission denied!"); + int permissionId = contract.getPermissionId(); + Permission permission = account.getPermissionById(permissionId); + if (permission == null) { + throw new PermissionException("Permission for this, does not exist!"); } + if (permissionId != 0) { + if (permission.getType() != PermissionType.Active) { + throw new PermissionException("Permission type is wrong!"); + } + //check operations + if (!checkPermissionOperations(permission, contract)) { + throw new PermissionException("Permission denied!"); + } + } + tswBuilder.setPermission(permission); + if (trx.getSignatureCount() > 0) { + List approveList = new ArrayList<>(); + long currentWeight = TransactionCapsule.checkWeight(permission, trx.getSignatureList(), + Sha256Hash.hash(CommonParameter.getInstance() + .isECKeyCryptoEngine(), trx.getRawData().toByteArray()), approveList); + tswBuilder.addAllApprovedList(approveList); + tswBuilder.setCurrentWeight(currentWeight); + } + if (tswBuilder.getCurrentWeight() >= permission.getThreshold()) { + resultBuilder.setCode(Result.response_code.ENOUGH_PERMISSION); + } else { + resultBuilder.setCode(Result.response_code.NOT_ENOUGH_PERMISSION); + } + } catch (SignatureFormatException signEx) { + resultBuilder.setCode(Result.response_code.SIGNATURE_FORMAT_ERROR); + resultBuilder.setMessage(signEx.getMessage()); + } catch (SignatureException signEx) { + resultBuilder.setCode(Result.response_code.COMPUTE_ADDRESS_ERROR); + resultBuilder.setMessage(signEx.getMessage()); + } catch (PermissionException permEx) { + resultBuilder.setCode(Result.response_code.PERMISSION_ERROR); + resultBuilder.setMessage(permEx.getMessage()); + } catch (Exception ex) { + resultBuilder.setCode(Result.response_code.OTHER_ERROR); + resultBuilder.setMessage(ex.getClass() + " : " + ex.getMessage()); } - tswBuilder.setPermission(permission); - if (trx.getSignatureCount() > 0) { - List approveList = new ArrayList(); - long currentWeight = TransactionCapsule.checkWeight(permission, trx.getSignatureList(), - Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), trx.getRawData().toByteArray()), approveList); - tswBuilder.addAllApprovedList(approveList); - tswBuilder.setCurrentWeight(currentWeight); - } - if (tswBuilder.getCurrentWeight() >= permission.getThreshold()) { - resultBuilder.setCode(Result.response_code.ENOUGH_PERMISSION); - } else { - resultBuilder.setCode(Result.response_code.NOT_ENOUGH_PERMISSION); - } - } catch (SignatureFormatException signEx) { - resultBuilder.setCode(Result.response_code.SIGNATURE_FORMAT_ERROR); - resultBuilder.setMessage(signEx.getMessage()); - } catch (SignatureException signEx) { - resultBuilder.setCode(Result.response_code.COMPUTE_ADDRESS_ERROR); - resultBuilder.setMessage(signEx.getMessage()); - } catch (PermissionException permEx) { - resultBuilder.setCode(Result.response_code.PERMISSION_ERROR); - resultBuilder.setMessage(permEx.getMessage()); - } catch (Exception ex) { - resultBuilder.setCode(Result.response_code.OTHER_ERROR); - resultBuilder.setMessage(ex.getClass() + " : " + ex.getMessage()); } + tswBuilder.setResult(resultBuilder); return tswBuilder.build(); } + public static long estimateConsumeBandWidthSize(DynamicPropertiesStore dps, long balance) { + DelegateResourceContract.Builder builder; + if (dps.supportMaxDelegateLockPeriod()) { + builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setLockPeriod(dps.getMaxDelegateLockPeriod()) + .setBalance(balance); + } else { + builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + } + long builderSize = builder.build().getSerializedSize(); + DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + long builder2Size = builder2.build().getSerializedSize(); + long addSize = max(builderSize - builder2Size, 0L, dps.disableJavaLangMath()); + + return DELEGATE_COST_BASE_SIZE + addSize; + } } diff --git a/actuator/src/main/java/org/tron/core/vm/ChainParameterEnum.java b/actuator/src/main/java/org/tron/core/vm/ChainParameterEnum.java new file mode 100644 index 00000000000..0d9df91ef6c --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/ChainParameterEnum.java @@ -0,0 +1,50 @@ +package org.tron.core.vm; + +import java.util.function.Function; +import org.tron.core.vm.repository.Repository; + +public enum ChainParameterEnum { + + INVALID_PARAMETER_KEY(0, ignored -> 0L), + + TOTAL_NET_LIMIT(1, repository -> repository.getDynamicPropertiesStore().getTotalNetLimit()), + + TOTAL_NET_WEIGHT(2, Repository::getTotalNetWeight), + + TOTAL_ENERGY_CURRENT_LIMIT(3, + repository -> repository.getDynamicPropertiesStore().getTotalEnergyCurrentLimit()), + + TOTAL_ENERGY_WEIGHT(4, Repository::getTotalEnergyWeight), + + UNFREEZE_DELAY_DAYS(5, + repository -> repository.getDynamicPropertiesStore().getUnfreezeDelayDays()), + + ; + + private final long code; + + private final Function action; + + ChainParameterEnum(long code, Function action) { + this.code = code; + this.action = action; + } + + public static ChainParameterEnum fromCode(long code) { + for (ChainParameterEnum each : values()) { + if (each.code == code) { + return each; + } + } + + return INVALID_PARAMETER_KEY; + } + + public long getCode() { + return code; + } + + public Function getAction() { + return action; + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/EnergyCost.java b/actuator/src/main/java/org/tron/core/vm/EnergyCost.java index 8962f5f1c64..b758438c940 100644 --- a/actuator/src/main/java/org/tron/core/vm/EnergyCost.java +++ b/actuator/src/main/java/org/tron/core/vm/EnergyCost.java @@ -2,9 +2,12 @@ import java.math.BigInteger; import org.tron.common.runtime.vm.DataWord; +import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.Program; import org.tron.core.vm.program.Stack; +import static org.tron.core.Constant.DYNAMIC_ENERGY_FACTOR_DECIMAL; + public class EnergyCost { private static final long ZERO_TIER = 0; @@ -36,6 +39,12 @@ public class EnergyCost { private static final long NEW_ACCT_CALL = 25000; private static final long UNFREEZE = 20000; private static final long FREEZE_EXPIRE_TIME = 50; + private static final long FREEZE_V2 = 10000; + private static final long UNFREEZE_V2 = 10000; + private static final long WITHDRAW_EXPIRE_UNFREEZE = 10000; + private static final long CANCEL_ALL_UNFREEZE_V2 = 10000; + private static final long DELEGATE_RESOURCE = 10000; + private static final long UN_DELEGATE_RESOURCE = 10000; private static final long VOTE_WITNESS = 30000; private static final long WITHDRAW_REWARD = 20000; private static final long CREATE = 32000; @@ -48,6 +57,8 @@ public class EnergyCost { private static final long SUICIDE = 0; private static final long STOP = 0; private static final long CREATE_DATA = 200; + private static final long TLOAD = 100; + private static final long TSTORE = 100; public static long getZeroTierCost(Program ignored) { return ZERO_TIER; @@ -150,28 +161,37 @@ public static long getExtCodeHashCost(Program ignored) { public static long getMloadCost(Program program) { Stack stack = program.getStack(); long oldMemSize = program.getMemSize(); - long energyCost = calcMemEnergy(oldMemSize, + return calcMemEnergy(oldMemSize, memNeeded(stack.peek(), new DataWord(32)), 0, Op.MLOAD); - return energyCost; + } + + public static long getMloadCost2(Program program) { + return SPECIAL_TIER + getMloadCost(program); } public static long getMStoreCost(Program program) { Stack stack = program.getStack(); long oldMemSize = program.getMemSize(); - long energyCost = calcMemEnergy(oldMemSize, + return calcMemEnergy(oldMemSize, memNeeded(stack.peek(), new DataWord(32)), 0, Op.MSTORE); - return energyCost; + } + + public static long getMStoreCost2(Program program) { + return SPECIAL_TIER + getMStoreCost(program); } public static long getMStore8Cost(Program program) { Stack stack = program.getStack(); long oldMemSize = program.getMemSize(); - long energyCost = calcMemEnergy(oldMemSize, + return calcMemEnergy(oldMemSize, memNeeded(stack.peek(), DataWord.ONE()), 0, Op.MSTORE8); - return energyCost; + } + + public static long getMStore8Cost2(Program program) { + return SPECIAL_TIER + getMStore8Cost(program); } public static long getSloadCost(Program ignored) { @@ -214,6 +234,26 @@ public static long getSstoreCost(Program program) { } + public static long getTLoadCost(Program ignored) { + return TLOAD; + } + + public static long getTStoreCost(Program ignored) { + return TSTORE; + } + + public static long getMCopyCost(Program program) { + Stack stack = program.getStack(); + long oldMemSize = program.getMemSize(); + + DataWord dstOffset = stack.peek(); + DataWord srcOffset = stack.get(stack.size() - 2); + DataWord maxOffset = dstOffset.compareTo(srcOffset) > 0 ? dstOffset : srcOffset; + return VERY_LOW_TIER + calcMemEnergy(oldMemSize, + memNeeded(maxOffset, stack.get(stack.size() - 3)), + stack.get(stack.size() - 3).longValueSafe(), Op.MCOPY); + } + public static long getLogCost(Program program) { Stack stack = program.getStack(); long oldMemSize = program.getMemSize(); @@ -241,12 +281,19 @@ public static long getSuicideCost(Program ignored) { return SUICIDE; } + public static long getSuicideCost2(Program program) { + DataWord inheritorAddress = program.getStack().peek(); + if (isDeadAccount(program, inheritorAddress)) { + return getSuicideCost(program) + NEW_ACCT_CALL; + } + return getSuicideCost(program); + } + public static long getBalanceCost(Program ignored) { return BALANCE; } public static long getFreezeCost(Program program) { - Stack stack = program.getStack(); DataWord receiverAddressWord = stack.get(stack.size() - 3); if (isDeadAccount(program, receiverAddressWord)) { @@ -263,8 +310,52 @@ public static long getFreezeExpireTimeCost(Program ignored) { return FREEZE_EXPIRE_TIME; } + public static long getFreezeBalanceV2Cost(Program ignored) { + return FREEZE_V2; + } + + public static long getUnfreezeBalanceV2Cost(Program ignored) { + return UNFREEZE_V2; + } + + public static long getWithdrawExpireUnfreezeCost(Program ignored) { + return WITHDRAW_EXPIRE_UNFREEZE; + } + + public static long getCancelAllUnfreezeV2Cost(Program ignored) { + return CANCEL_ALL_UNFREEZE_V2; + } + + public static long getDelegateResourceCost(Program ignored) { + return DELEGATE_RESOURCE; + } + + public static long getUnDelegateResourceCost(Program ignored) { + return UN_DELEGATE_RESOURCE; + } + public static long getVoteWitnessCost(Program program) { + Stack stack = program.getStack(); + long oldMemSize = program.getMemSize(); + DataWord amountArrayLength = stack.get(stack.size() - 1).clone(); + DataWord amountArrayOffset = stack.get(stack.size() - 2); + DataWord witnessArrayLength = stack.get(stack.size() - 3).clone(); + DataWord witnessArrayOffset = stack.get(stack.size() - 4); + + DataWord wordSize = new DataWord(DataWord.WORD_SIZE); + amountArrayLength.mul(wordSize); + BigInteger amountArrayMemoryNeeded = memNeeded(amountArrayOffset, amountArrayLength); + + witnessArrayLength.mul(wordSize); + BigInteger witnessArrayMemoryNeeded = memNeeded(witnessArrayOffset, witnessArrayLength); + + return VOTE_WITNESS + calcMemEnergy(oldMemSize, + (amountArrayMemoryNeeded.compareTo(witnessArrayMemoryNeeded) > 0 + ? amountArrayMemoryNeeded : witnessArrayMemoryNeeded), 0, Op.VOTEWITNESS); + } + + public static long getVoteWitnessCost2(Program program) { Stack stack = program.getStack(); long oldMemSize = program.getMemSize(); DataWord amountArrayLength = stack.get(stack.size() - 1).clone(); @@ -275,9 +366,11 @@ public static long getVoteWitnessCost(Program program) { DataWord wordSize = new DataWord(DataWord.WORD_SIZE); amountArrayLength.mul(wordSize); + amountArrayLength.add(wordSize); // dynamic array length is at least 32 bytes BigInteger amountArrayMemoryNeeded = memNeeded(amountArrayOffset, amountArrayLength); witnessArrayLength.mul(wordSize); + witnessArrayLength.add(wordSize); // dynamic array length is at least 32 bytes BigInteger witnessArrayMemoryNeeded = memNeeded(witnessArrayOffset, witnessArrayLength); return VOTE_WITNESS + calcMemEnergy(oldMemSize, @@ -379,6 +472,18 @@ public static long getCalculateCallCost(Stack stack, Program program, energyCost += calcMemEnergy(oldMemSize, in.max(out), 0, op); + if (VMConfig.allowDynamicEnergy()) { + long factor = program.getContextContractFactor(); + if (factor > DYNAMIC_ENERGY_FACTOR_DECIMAL) { + long penalty = energyCost * factor / DYNAMIC_ENERGY_FACTOR_DECIMAL - energyCost; + if (penalty < 0) { + penalty = 0; + } + program.setCallPenaltyEnergy(penalty); + energyCost += penalty; + } + } + if (energyCost > program.getEnergyLimitLeft().longValueSafe()) { throw new Program.OutOfEnergyException( "Not enough energy for '%s' operation executing: opEnergy[%d], programEnergy[%d]", diff --git a/actuator/src/main/java/org/tron/core/vm/Op.java b/actuator/src/main/java/org/tron/core/vm/Op.java index 6abf6a04632..ed2d8eb2f53 100644 --- a/actuator/src/main/java/org/tron/core/vm/Op.java +++ b/actuator/src/main/java/org/tron/core/vm/Op.java @@ -120,6 +120,10 @@ public class Op { public static final int SELFBALANCE = 0x47; // (0x48) Get block's basefee public static final int BASEFEE = 0x48; + // (0x49) Get blob hash + public static final int BLOBHASH = 0x49; + // (0x4a) Get block's blob basefee + public static final int BLOBBASEFEE = 0x4a; /* Memory, Storage and Flow Operations */ // (0x50) Remove item from stack @@ -145,9 +149,16 @@ public class Op { // (0x5a) Get the amount of available gas public static final int GAS = 0x5a; public static final int JUMPDEST = 0x5b; + // (0x5c) Load word from transient storage + public static final int TLOAD = 0x5c; + // (0x5d) Save word to transient storage + public static final int TSTORE = 0x5d; + // (0x5e) Copy word from memory + public static final int MCOPY = 0x5e; /* Push Operations */ // Place item on stack + public static final int PUSH0 = 0x5f; public static final int PUSH1 = 0x60; public static final int PUSH2 = 0x61; public static final int PUSH3 = 0x62; @@ -236,6 +247,12 @@ public class Op { public static final int FREEZEEXPIRETIME = 0xd7; public static final int VOTEWITNESS = 0xd8; public static final int WITHDRAWREWARD = 0xd9; + public static final int FREEZEBALANCEV2 = 0xda; + public static final int UNFREEZEBALANCEV2 = 0xdb; + public static final int CANCELALLUNFREEZEV2 = 0xdc; + public static final int WITHDRAWEXPIREUNFREEZE = 0xdd; + public static final int DELEGATERESOURCE = 0xde; + public static final int UNDELEGATERESOURCE = 0xdf; // (0xf0) Create a new account with associated code public static final int CREATE = 0xf0; diff --git a/actuator/src/main/java/org/tron/core/vm/OperationActions.java b/actuator/src/main/java/org/tron/core/vm/OperationActions.java index c7a9c2cc2e3..f10fb37dd7e 100644 --- a/actuator/src/main/java/org/tron/core/vm/OperationActions.java +++ b/actuator/src/main/java/org/tron/core/vm/OperationActions.java @@ -6,7 +6,6 @@ import java.math.BigInteger; import java.util.ArrayList; import java.util.List; - import org.tron.common.runtime.vm.DataWord; import org.tron.common.runtime.vm.LogInfo; import org.tron.core.vm.config.VMConfig; @@ -644,6 +643,56 @@ public static void jumpDestAction(Program program) { program.step(); } + public static void tLoadAction(Program program) { + DataWord key = program.stackPop(); + DataWord address = program.getContractAddress(); + + byte[] data = + program.getContractState().getTransientStorageValue(address.getData(), key.getData()); + DataWord value = data != null ? new DataWord(data).clone() : DataWord.ZERO(); + + program.stackPush(value); + program.step(); + } + + public static void tStoreAction(Program program) { + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + DataWord key = program.stackPop(); + DataWord value = program.stackPop(); + DataWord address = program.getContractAddress(); + + program.getContractState() + .updateTransientStorageValue(address.getData(), key.getData(), value.getData()); + program.step(); + } + + public static void mCopyAction(Program program) { + int dstOffset = program.stackPop().intValueSafe(); + int srcOffset = program.stackPop().intValueSafe(); + int length = program.stackPop().intValueSafe(); + + program.memoryCopy(dstOffset, srcOffset, length); + program.step(); + } + + public static void blobHashAction(Program program) { + program.stackPop(); + program.stackPush(DataWord.ZERO()); + program.step(); + } + + public static void blobBaseFeeAction(Program program) { + program.stackPush(DataWord.ZERO()); + program.step(); + } + + public static void push0Action(Program program) { + program.stackPush(DataWord.ZERO()); + program.step(); + } + public static void pushAction(Program program) { int n = program.getCurrentOpIntValue() - Op.PUSH1 + 1; program.step(); @@ -737,8 +786,13 @@ public static void freezeAction(Program program) { DataWord frozenBalance = program.stackPop(); DataWord receiverAddress = program.stackPop(); - boolean result = program.freeze(receiverAddress, frozenBalance, resourceType ); - program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + if (VMConfig.allowTvmFreezeV2()) { + // after v2 activated, we just push zero to stack and do nothing + program.stackPush(DataWord.ZERO()); + } else { + boolean result = program.freeze(receiverAddress, frozenBalance, resourceType ); + program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + } program.step(); } @@ -764,6 +818,78 @@ public static void freezeExpireTimeAction(Program program) { program.step(); } + public static void freezeBalanceV2Action(Program program) { + // after allow vote, check static + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + DataWord resourceType = program.stackPop(); + DataWord frozenBalance = program.stackPop(); + + boolean result = program.freezeBalanceV2(frozenBalance, resourceType); + program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + program.step(); + } + + public static void unfreezeBalanceV2Action(Program program) { + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + + DataWord resourceType = program.stackPop(); + DataWord unfreezeBalance = program.stackPop(); + + boolean result = program.unfreezeBalanceV2(unfreezeBalance, resourceType); + program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + program.step(); + } + + public static void withdrawExpireUnfreezeAction(Program program) { + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + + long expireUnfreezeBalance = program.withdrawExpireUnfreeze(); + program.stackPush(new DataWord(expireUnfreezeBalance)); + program.step(); + } + + public static void cancelAllUnfreezeV2Action(Program program) { + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + + boolean result = program.cancelAllUnfreezeV2Action(); + program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + program.step(); + } + + public static void delegateResourceAction(Program program) { + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + DataWord resourceType = program.stackPop(); + DataWord delegateBalance = program.stackPop(); + DataWord receiverAddress = program.stackPop(); + + boolean result = program.delegateResource(receiverAddress, delegateBalance, resourceType); + program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + program.step(); + } + + public static void unDelegateResourceAction(Program program) { + if (program.isStaticCall()) { + throw new Program.StaticCallModificationException(); + } + DataWord resourceType = program.stackPop(); + DataWord unDelegateBalance = program.stackPop(); + DataWord receiverAddress = program.stackPop(); + + boolean result = program.unDelegateResource(receiverAddress, unDelegateBalance, resourceType); + program.stackPush(result ? DataWord.ONE() : DataWord.ZERO()); + program.step(); + } + public static void voteWitnessAction(Program program) { if (program.isStaticCall()) { throw new Program.StaticCallModificationException(); @@ -891,7 +1017,7 @@ public static void staticCallAction(Program program) { } public static void exeCall(Program program, DataWord adjustedCallEnergy, - DataWord codeAddress, DataWord value, DataWord tokenId, boolean isTokenTransferMsg) { + DataWord codeAddress, DataWord value, DataWord tokenId, boolean isTokenTransferMsg) { DataWord inDataOffs = program.stackPop(); DataWord inDataSize = program.stackPop(); @@ -908,6 +1034,9 @@ public static void exeCall(Program program, DataWord adjustedCallEnergy, PrecompiledContracts.PrecompiledContract contract = PrecompiledContracts.getContractForAddress(codeAddress); if (contract != null) { + if (program.isConstantCall()) { + contract = PrecompiledContracts.getOptimizedContractForConstant(contract); + } program.callToPrecompiledAddress(msg, contract); } else { program.callToAddress(msg); 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 44b00e1a5a3..be29238a775 100644 --- a/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java +++ b/actuator/src/main/java/org/tron/core/vm/OperationRegistry.java @@ -3,13 +3,16 @@ import java.util.HashMap; import java.util.Map; import java.util.function.BooleanSupplier; - import org.tron.core.vm.config.VMConfig; public class OperationRegistry { public enum Version { - TRON_V1, + TRON_V1_0, + TRON_V1_1, + TRON_V1_2, + TRON_V1_3, + TRON_V1_4, // add more // TRON_V2, // ETH @@ -18,10 +21,14 @@ public enum Version { private static final Map tableMap = new HashMap<>(); static { - tableMap.put(Version.TRON_V1, newTronV1OperationSet()); + 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()); } - public static JumpTable newTronV1OperationSet() { + public static JumpTable newTronV10OperationSet() { JumpTable table = newBaseOperationSet(); appendTransferTrc10Operations(table); appendConstantinopleOperations(table); @@ -33,14 +40,46 @@ public static JumpTable newTronV1OperationSet() { return table; } + public static JumpTable newTronV11OperationSet() { + return newTronV10OperationSet(); + } + + public static JumpTable newTronV12OperationSet() { + JumpTable table = newTronV11OperationSet(); + appendFreezeV2Operations(table); + appendDelegateOperations(table); + return table; + } + + public static JumpTable newTronV13OperationSet() { + JumpTable table = newTronV12OperationSet(); + appendShangHaiOperations(table); + return table; + } + + public static JumpTable newTronV14OperationSet() { + JumpTable table = newTronV13OperationSet(); + appendCancunOperations(table); + return table; + } + // Just for warming up class to avoid out_of_time public static void init() {} - public static JumpTable getTable(Version ver) { - // implement as needed - // switch (tx.getType()) { - // } - return tableMap.get(ver); + public static JumpTable getTable() { + // always get the table which has the newest version + JumpTable table = tableMap.get(Version.TRON_V1_4); + + // next make the corresponding changes, exclude activating opcode + if (VMConfig.allowHigherLimitForMaxCpuTimeOfOneTx()) { + adjustMemOperations(table); + } + + if (VMConfig.allowEnergyAdjustment()) { + adjustForFairEnergy(table); + } + + return table; } public static JumpTable newBaseOperationSet() { @@ -538,4 +577,122 @@ 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; + + table.set(new Operation( + Op.FREEZEBALANCEV2, 2, 1, + EnergyCost::getFreezeBalanceV2Cost, + OperationActions::freezeBalanceV2Action, + proposal)); + + table.set(new Operation( + Op.UNFREEZEBALANCEV2, 2, 1, + EnergyCost::getUnfreezeBalanceV2Cost, + OperationActions::unfreezeBalanceV2Action, + proposal)); + + table.set(new Operation( + Op.WITHDRAWEXPIREUNFREEZE, 0, 1, + EnergyCost::getWithdrawExpireUnfreezeCost, + OperationActions::withdrawExpireUnfreezeAction, + proposal)); + + table.set(new Operation( + Op.CANCELALLUNFREEZEV2, 0, 1, + EnergyCost::getCancelAllUnfreezeV2Cost, + OperationActions::cancelAllUnfreezeV2Action, + proposal)); + } + + public static void appendDelegateOperations(JumpTable table) { + BooleanSupplier proposal = VMConfig::allowTvmFreezeV2; + + table.set(new Operation( + Op.DELEGATERESOURCE, 3, 1, + EnergyCost::getDelegateResourceCost, + OperationActions::delegateResourceAction, + proposal)); + + table.set(new Operation( + Op.UNDELEGATERESOURCE, 3, 1, + EnergyCost::getUnDelegateResourceCost, + OperationActions::unDelegateResourceAction, + proposal)); + } + + public static void appendShangHaiOperations(JumpTable table) { + BooleanSupplier proposal = VMConfig::allowTvmShanghai; + + table.set(new Operation( + Op.PUSH0, 0, 1, + EnergyCost::getBaseTierCost, + OperationActions::push0Action, + 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; + + table.set(new Operation( + Op.TLOAD, 1, 1, + EnergyCost::getTLoadCost, + OperationActions::tLoadAction, + proposal)); + + table.set(new Operation( + Op.TSTORE, 2, 0, + EnergyCost::getTStoreCost, + OperationActions::tStoreAction, + proposal)); + + table.set(new Operation( + Op.MCOPY, 3, 0, + EnergyCost::getMCopyCost, + OperationActions::mCopyAction, + proposal)); + + table.set(new Operation( + Op.BLOBHASH, 1, 1, + EnergyCost::getVeryLowTierCost, + OperationActions::blobHashAction, + tvmBlobProposal)); + + table.set(new Operation( + Op.BLOBBASEFEE, 0, 1, + EnergyCost::getBaseTierCost, + OperationActions::blobBaseFeeAction, + tvmBlobProposal)); + } } 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 437ecdd1d8f..7913d7928fa 100644 --- a/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java +++ b/actuator/src/main/java/org/tron/core/vm/PrecompiledContracts.java @@ -1,6 +1,8 @@ package org.tron.core.vm; import static java.util.Arrays.copyOfRange; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; import static org.tron.common.runtime.vm.DataWord.WORD_SIZE; import static org.tron.common.utils.BIUtil.addSafely; import static org.tron.common.utils.BIUtil.isLessThan; @@ -16,6 +18,8 @@ import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import com.google.protobuf.ByteString; + +import java.lang.reflect.Constructor; import java.math.BigInteger; import java.security.MessageDigest; import java.util.ArrayList; @@ -26,7 +30,6 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import lombok.AllArgsConstructor; @@ -35,6 +38,7 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; import org.tron.common.crypto.Blake2bfMessageDigest; import org.tron.common.crypto.Hash; import org.tron.common.crypto.SignUtils; @@ -45,6 +49,7 @@ import org.tron.common.crypto.zksnark.BN128G2; import org.tron.common.crypto.zksnark.Fp; import org.tron.common.crypto.zksnark.PairingCheck; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.ProgramResult; import org.tron.common.runtime.vm.DataWord; @@ -61,9 +66,11 @@ import org.tron.core.exception.ZksnarkException; 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.repository.Repository; +import org.tron.core.vm.utils.FreezeV2Util; +import org.tron.core.vm.utils.MUtil; import org.tron.core.vm.utils.VoteRewardUtil; - import org.tron.protos.Protocol; import org.tron.protos.Protocol.Permission; @@ -98,6 +105,19 @@ public class PrecompiledContracts { private static final EthRipemd160 ethRipemd160 = new EthRipemd160(); private static final Blake2F blake2F = new Blake2F(); + // FreezeV2 PrecompileContracts + private static final GetChainParameter getChainParameter = new GetChainParameter(); + private static final AvailableUnfreezeV2Size availableUnfreezeV2Size = new AvailableUnfreezeV2Size(); + private static final UnfreezableBalanceV2 unfreezableBalanceV2 = new UnfreezableBalanceV2(); + private static final ExpireUnfreezeBalanceV2 expireUnfreezeBalanceV2 = new ExpireUnfreezeBalanceV2(); + private static final DelegatableResource delegatableResource = new DelegatableResource(); + private static final ResourceV2 resourceV2 = new ResourceV2(); + private static final CheckUnDelegateResource checkUnDelegateResource = new CheckUnDelegateResource(); + private static final ResourceUsage resourceUsage = new ResourceUsage(); + private static final TotalResource totalResource = new TotalResource(); + private static final TotalDelegatedResource totalDelegatedResource = new TotalDelegatedResource(); + private static final TotalAcquiredResource totalAcquiredResource = new TotalAcquiredResource(); + private static final DataWord ecRecoverAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000000001"); private static final DataWord sha256Addr = new DataWord( @@ -138,11 +158,54 @@ public class PrecompiledContracts { "0000000000000000000000000000000000000000000000000000000001000009"); private static final DataWord totalVoteCountAddr = new DataWord( "000000000000000000000000000000000000000000000000000000000100000a"); + + // FreezeV2 PrecompileContracts + private static final DataWord getChainParameterAddr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000b"); + + private static final DataWord availableUnfreezeV2SizeAddr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000c"); + + private static final DataWord unfreezableBalanceV2Addr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000d"); + + private static final DataWord expireUnfreezeBalanceV2Addr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000e"); + + private static final DataWord delegatableResourceAddr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000f"); + + private static final DataWord resourceV2Addr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000010"); + + private static final DataWord checkUnDelegateResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000011"); + + private static final DataWord resourceUsageAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000012"); + + private static final DataWord totalResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000013"); + + private static final DataWord totalDelegatedResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000014"); + + private static final DataWord totalAcquiredResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000015"); + private static final DataWord ethRipemd160Addr = new DataWord( "0000000000000000000000000000000000000000000000000000000000020003"); private static final DataWord blake2FAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000020009"); + public static PrecompiledContract getOptimizedContractForConstant(PrecompiledContract contract) { + try { + Constructor constructor = contract.getClass().getDeclaredConstructor(); + return (PrecompiledContracts.PrecompiledContract) constructor.newInstance(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } public static PrecompiledContract getContractForAddress(DataWord address) { @@ -217,6 +280,42 @@ public static PrecompiledContract getContractForAddress(DataWord address) { return blake2F; } + if (VMConfig.allowTvmFreezeV2()) { + if (address.equals(getChainParameterAddr)) { + return getChainParameter; + } + if (address.equals(availableUnfreezeV2SizeAddr)) { + return availableUnfreezeV2Size; + } + if (address.equals(unfreezableBalanceV2Addr)) { + return unfreezableBalanceV2; + } + if (address.equals(expireUnfreezeBalanceV2Addr)) { + return expireUnfreezeBalanceV2; + } + if (address.equals(delegatableResourceAddr)) { + return delegatableResource; + } + if (address.equals(resourceV2Addr)) { + return resourceV2; + } + if (address.equals(checkUnDelegateResourceAddr)) { + return checkUnDelegateResource; + } + if (address.equals(resourceUsageAddr)) { + return resourceUsage; + } + if (address.equals(totalResourceAddr)) { + return totalResource; + } + if (address.equals(totalDelegatedResourceAddr)) { + return totalDelegatedResource; + } + if (address.equals(totalAcquiredResourceAddr)) { + return totalAcquiredResource; + } + } + return null; } @@ -233,6 +332,25 @@ private static byte[] encodeRes(byte[] w1, byte[] w2) { return res; } + private static byte[] encodeMultiRes(byte[]... words) { + if (words == null) { + return null; + } + if (words.length == 1) { + return words[0]; + } + + byte[] res = new byte[words.length * 32]; + + for (int i = 0; i < words.length; i++) { + byte[] word = stripLeadingZeroes(words[i]); + + System.arraycopy(word, 0, res, 32 * (i + 1) - word.length, word.length); + } + + return res; + } + private static byte[] recoverAddrBySign(byte[] sign, byte[] hash) { byte v; byte[] r; @@ -508,14 +626,16 @@ public long getEnergyForData(byte[] data) { int expLen = parseLen(data, 1); int modLen = parseLen(data, 2); - byte[] expHighBytes = parseBytes(data, addSafely(ARGS_OFFSET, baseLen), Math.min(expLen, 32)); - long multComplexity = getMultComplexity(Math.max(baseLen, modLen)); + byte[] expHighBytes = parseBytes(data, addSafely(ARGS_OFFSET, baseLen), min(expLen, 32, + VMConfig.disableJavaLangMath())); + + long multComplexity = getMultComplexity(max(baseLen, modLen, VMConfig.disableJavaLangMath())); long adjExpLen = getAdjustedExponentLength(expHighBytes, expLen); // use big numbers to stay safe in case of overflow BigInteger energy = BigInteger.valueOf(multComplexity) - .multiply(BigInteger.valueOf(Math.max(adjExpLen, 1))) + .multiply(BigInteger.valueOf(max(adjExpLen, 1, VMConfig.disableJavaLangMath()))) .divide(GQUAD_DIVISOR); return isLessThan(energy, BigInteger.valueOf(Long.MAX_VALUE)) ? energy.longValueExact() @@ -840,10 +960,15 @@ public Pair execute(byte[] rawData) { long totalWeight = 0L; List executedSignList = new ArrayList<>(); for (byte[] sign : signatures) { - if (ByteArray.matrixContains(executedSignList, sign)) { - continue; - } byte[] recoveredAddr = recoverAddrBySign(sign, hash); + + sign = merge(recoveredAddr, sign); + if (ByteArray.matrixContains(executedSignList, recoveredAddr)) { + if (ByteArray.matrixContains(executedSignList, sign)) { + continue; + } + MUtil.checkCPUTime(); + } long weight = TransactionCapsule.getWeight(permission, recoveredAddr); if (weight == 0) { //incorrect sign @@ -851,6 +976,7 @@ public Pair execute(byte[] rawData) { } totalWeight += weight; executedSignList.add(sign); + executedSignList.add(recoveredAddr); } if (totalWeight >= permission.getThreshold()) { @@ -858,6 +984,9 @@ public Pair execute(byte[] rawData) { } } } catch (Throwable t) { + if (t instanceof OutOfTimeException) { + throw t; + } logger.info("ValidateMultiSign error:{}", t.getMessage()); } } @@ -868,11 +997,13 @@ public Pair execute(byte[] rawData) { public static class BatchValidateSign extends PrecompiledContract { private static final ExecutorService workers; + private static final String workersName = "validate-sign-contract"; private static final int ENGERYPERSIGN = 1500; private static final int MAX_SIZE = 16; static { - workers = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() / 2 + 1); + workers = ExecutorServiceManager.newFixedThreadPool(workersName, + Runtime.getRuntime().availableProcessors() / 2 + 1); } @Override @@ -1175,10 +1306,12 @@ public static class VerifyTransferProof extends VerifyProof { private static final Integer[] SIZE = {2080, 2368, 2464, 2752}; private static final ExecutorService workersInConstantCall; private static final ExecutorService workersInNonConstantCall; + private static final String constantCallName = "verify-transfer-constant-call"; + private static final String nonConstantCallName = "verify-transfer-non-constant-call"; static { - workersInConstantCall = Executors.newFixedThreadPool(5); - workersInNonConstantCall = Executors.newFixedThreadPool(5); + workersInConstantCall = ExecutorServiceManager.newFixedThreadPool(constantCallName, 5); + workersInNonConstantCall = ExecutorServiceManager.newFixedThreadPool(nonConstantCallName, 5); } @Override @@ -1683,9 +1816,18 @@ public Pair execute(byte[] data) { byte[] address = new DataWord(data).toTronAddress(); AccountCapsule accountCapsule = this.getDeposit().getAccount(address); - long tronPower = accountCapsule != null - ? accountCapsule.getTronPower() / TRX_PRECISION : 0; - return Pair.of(true, longTo32Bytes(tronPower)); + long tronPower; + if (accountCapsule == null) { + tronPower = 0; + } else { + if (getDeposit().getDynamicPropertiesStore().supportUnfreezeDelay() + && getDeposit().getDynamicPropertiesStore().supportAllowNewResourceModel()) { + tronPower = accountCapsule.getAllTronPower(); + } else { + tronPower = accountCapsule.getTronPower(); + } + } + return Pair.of(true, longTo32Bytes(tronPower / TRX_PRECISION)); } } @@ -1744,4 +1886,308 @@ public Pair execute(byte[] data) { return Pair.of(true, result); } } + + public static class GetChainParameter extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + long code = new DataWord(data).longValueSafe(); + + long res = ChainParameterEnum.fromCode(code).getAction().apply( + getDeposit()); + + return Pair.of(true, longTo32Bytes(res)); + } + } + + public static class AvailableUnfreezeV2Size extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + byte[] address = new DataWord(data).toTronAddress(); + + long result = FreezeV2Util.queryAvailableUnfreezeV2Size(address, getDeposit()); + return Pair.of(true, longTo32Bytes(result)); + } + } + + public static class UnfreezableBalanceV2 extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long type = words[1].longValueSafe(); + + long balance = FreezeV2Util.queryUnfreezableBalanceV2(address, type, getDeposit()); + return Pair.of(true, longTo32Bytes(balance)); + } + } + + public static class ExpireUnfreezeBalanceV2 extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long time = words[1].longValueSafe(); + + if (time < 0) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + if (time >= Long.MAX_VALUE / 1_000) { + time = Long.MAX_VALUE; + } else { + time = time * 1_000; + } + + long balance = FreezeV2Util.queryExpireUnfreezeBalanceV2(address, time, getDeposit()); + return Pair.of(true, longTo32Bytes(balance)); + } + } + + public static class DelegatableResource extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long type = words[1].longValueSafe(); + + long result = FreezeV2Util.queryDelegatableResource(address, type, getDeposit()); + return Pair.of(true, longTo32Bytes(result)); + } + } + + public static class ResourceV2 extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 3 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] target = words[0].toTronAddress(); + byte[] from = words[1].toTronAddress(); + long type = words[2].longValueSafe(); + + long balance; + if (Arrays.equals(from, target)) { + balance = FreezeV2Util.queryUnfreezableBalanceV2(from, type, getDeposit()); + } else { + balance = FreezeV2Util.queryResourceV2(from, target, type, getDeposit()); + } + return Pair.of(true, longTo32Bytes(balance)); + } + } + + public static class CheckUnDelegateResource extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 3 * WORD_SIZE) { + return Pair.of(true, encodeMultiRes( + DataWord.ZERO().getData(), DataWord.ZERO().getData(), DataWord.ZERO().getData())); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] target = words[0].toTronAddress(); + long amount = words[1].longValueSafe(); + long type = words[2].longValueSafe(); + + Triple values = + FreezeV2Util.checkUndelegateResource(target, amount, type, getDeposit()); + if (values == null || values.getLeft() == null + || values.getMiddle() == null || values.getRight() == null) { + return Pair.of(true, encodeMultiRes( + DataWord.ZERO().getData(), DataWord.ZERO().getData(), DataWord.ZERO().getData())); + } + + return Pair.of(true, encodeMultiRes(longTo32Bytes(values.getLeft()), + longTo32Bytes(values.getMiddle()), longTo32Bytes(values.getRight()))); + } + } + + public static class ResourceUsage extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, encodeRes(DataWord.ZERO().getData(), DataWord.ZERO().getData())); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long type = words[1].longValueSafe(); + + Pair values = FreezeV2Util.queryFrozenBalanceUsage(address, type, getDeposit()); + if (values == null || values.getLeft() == null || values.getRight() == null) { + return Pair.of(true, encodeRes(DataWord.ZERO().getData(), DataWord.ZERO().getData())); + } + + return Pair.of(true, encodeRes( + longTo32Bytes(values.getLeft()), longTo32Bytes(values.getRight()))); + } + } + + public static class TotalResource extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long type = words[1].longValueSafe(); + + AccountCapsule accountCapsule = getDeposit().getAccount(address); + if (accountCapsule == null) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + long totalResource = 0; + if (type == 0) { + totalResource = accountCapsule.getAllFrozenBalanceForBandwidth(); + } else if (type == 1) { + totalResource = accountCapsule.getAllFrozenBalanceForEnergy(); + } + + return Pair.of(true, longTo32Bytes(totalResource)); + } + } + + public static class TotalDelegatedResource extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long type = words[1].longValueSafe(); + + AccountCapsule accountCapsule = getDeposit().getAccount(address); + if (accountCapsule == null) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + long delegatedResource = 0; + if (type == 0) { + delegatedResource = accountCapsule.getTotalDelegatedFrozenBalanceForBandwidth(); + } else if (type == 1) { + delegatedResource = accountCapsule.getTotalDelegatedFrozenBalanceForEnergy(); + } + + return Pair.of(true, longTo32Bytes(delegatedResource)); + } + } + + public static class TotalAcquiredResource extends PrecompiledContract { + + @Override + public long getEnergyForData(byte[] data) { + return 50; + } + + @Override + public Pair execute(byte[] data) { + if (data == null || data.length != 2 * WORD_SIZE) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + DataWord[] words = DataWord.parseArray(data); + byte[] address = words[0].toTronAddress(); + long type = words[1].longValueSafe(); + + AccountCapsule accountCapsule = getDeposit().getAccount(address); + if (accountCapsule == null) { + return Pair.of(true, DataWord.ZERO().getData()); + } + + long acquiredResource = 0; + if (type == 0) { + acquiredResource = accountCapsule.getTotalAcquiredDelegatedFrozenBalanceForBandwidth(); + } else if (type == 1) { + acquiredResource = accountCapsule.getTotalAcquiredDelegatedFrozenBalanceForEnergy(); + } + + return Pair.of(true, longTo32Bytes(acquiredResource)); + } + } + } diff --git a/actuator/src/main/java/org/tron/core/vm/VM.java b/actuator/src/main/java/org/tron/core/vm/VM.java index 410e7bad311..2150df04c64 100644 --- a/actuator/src/main/java/org/tron/core/vm/VM.java +++ b/actuator/src/main/java/org/tron/core/vm/VM.java @@ -1,5 +1,9 @@ package org.tron.core.vm; +import static org.tron.core.Constant.DYNAMIC_ENERGY_FACTOR_DECIMAL; + +import com.google.common.collect.ImmutableSet; +import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.springframework.util.StringUtils; @@ -12,8 +16,18 @@ @Slf4j(topic = "VM") public class VM { + private static final Set CALL_OPS = ImmutableSet.of(Op.CALL, Op.STATICCALL, + Op.DELEGATECALL, Op.CALLCODE, Op.CALLTOKEN); + public static void play(Program program, JumpTable jumpTable) { try { + long factor = DYNAMIC_ENERGY_FACTOR_DECIMAL; + long energyUsage = 0L; + + if (VMConfig.allowDynamicEnergy()) { + factor = program.updateContextContractFactor(); + } + while (!program.isStopped()) { if (VMConfig.vmTrace()) { program.saveOpTrace(); @@ -32,7 +46,40 @@ public static void play(Program program, JumpTable jumpTable) { String opName = Op.getNameOf(op.getOpcode()); /* spend energy before execution */ - program.spendEnergy(op.getEnergyCost(program), opName); + long energy = op.getEnergyCost(program); + if (VMConfig.allowDynamicEnergy()) { + long actualEnergy = energy; + // CALL Ops have special calculation on energy. + if (CALL_OPS.contains(op.getOpcode())) { + actualEnergy = energy + - program.getAdjustedCallEnergy().longValueSafe() + - program.getCallPenaltyEnergy(); + } + energyUsage += actualEnergy; + + if (factor > DYNAMIC_ENERGY_FACTOR_DECIMAL) { + long penalty; + + // CALL Ops have special calculation on energy. + if (CALL_OPS.contains(op.getOpcode())) { + penalty = program.getCallPenaltyEnergy(); + } else { + penalty = energy * factor / DYNAMIC_ENERGY_FACTOR_DECIMAL - energy; + if (penalty < 0) { + penalty = 0; + } + energy += penalty; + } + + program.spendEnergyWithPenalty(energy, penalty, opName); + } else { + program.spendEnergy(energy, opName); + } + + } else { + program.spendEnergy(energy, opName); + } + /* check if cpu time out */ program.checkCPUTimeLimit(opName); @@ -53,6 +100,11 @@ public static void play(Program program, JumpTable jumpTable) { program.fullTrace(); } } + + if (VMConfig.allowDynamicEnergy()) { + program.addContextContractUsage(energyUsage); + } + } catch (JVMStackOverFlowException | OutOfTimeException e) { throw e; } catch (RuntimeException e) { diff --git a/actuator/src/main/java/org/tron/core/vm/VMConstant.java b/actuator/src/main/java/org/tron/core/vm/VMConstant.java index 4e7f6b29e3f..abbb6ae6d38 100644 --- a/actuator/src/main/java/org/tron/core/vm/VMConstant.java +++ b/actuator/src/main/java/org/tron/core/vm/VMConstant.java @@ -10,6 +10,8 @@ public class VMConstant { public static final int ONE_THOUSAND = 1000; public static final long SUN_PER_ENERGY = 100; + public static final String WITHDRAW_EXPIRE_BALANCE = "WithdrawExpireBalance"; + private VMConstant() { } } 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 7d080b23b37..2f469e0579a 100644 --- a/actuator/src/main/java/org/tron/core/vm/VMUtils.java +++ b/actuator/src/main/java/org/tron/core/vm/VMUtils.java @@ -2,6 +2,7 @@ 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; @@ -12,7 +13,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.util.Arrays; -import java.util.Map; import java.util.zip.Deflater; import java.util.zip.DeflaterOutputStream; import lombok.extern.slf4j.Slf4j; @@ -20,6 +20,7 @@ import org.tron.common.utils.ByteUtil; import org.tron.common.utils.Commons; import org.tron.common.utils.DecodeUtil; +import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.exception.ContractValidateException; import org.tron.core.vm.config.VMConfig; @@ -33,6 +34,11 @@ public final class VMUtils { private VMUtils() { } + public static int getAddressSize() { + return VMConfig.allowEnergyAdjustment() ? + Constant.TRON_ADDRESS_SIZE : Constant.STANDARD_ADDRESS_SIZE; + } + public static void closeQuietly(Closeable closeable) { try { if (closeable != null) { @@ -164,7 +170,7 @@ public static boolean validateForSmartContract(Repository deposit, byte[] ownerA "Validate InternalTransfer error, balance is not sufficient."); } - Math.addExact(toAccount.getBalance(), amount); + addExact(toAccount.getBalance(), amount, VMConfig.disableJavaLangMath()); } catch (ArithmeticException e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); @@ -210,17 +216,8 @@ public static boolean validateForSmartContract(Repository deposit, byte[] ownerA throw new ContractValidateException("No asset !"); } - Map asset; - if (deposit.getDynamicPropertiesStore().getAllowSameTokenName() == 0) { - asset = ownerAccount.getAssetMap(); - } else { - asset = ownerAccount.getAssetMapV2(); - } - if (asset.isEmpty()) { - throw new ContractValidateException("Owner no asset!"); - } - - Long assetBalance = asset.get(ByteArray.toStr(tokenIdWithoutLeadingZero)); + Long assetBalance = ownerAccount.getAsset(deposit.getDynamicPropertiesStore(), + ByteArray.toStr(tokenIdWithoutLeadingZero)); if (null == assetBalance || assetBalance <= 0) { throw new ContractValidateException("assetBalance must greater than 0."); } @@ -230,14 +227,12 @@ public static boolean validateForSmartContract(Repository deposit, byte[] ownerA AccountCapsule toAccount = deposit.getAccount(toAddress); if (toAccount != null) { - if (deposit.getDynamicPropertiesStore().getAllowSameTokenName() == 0) { - assetBalance = toAccount.getAssetMap().get(ByteArray.toStr(tokenIdWithoutLeadingZero)); - } else { - assetBalance = toAccount.getAssetMapV2().get(ByteArray.toStr(tokenIdWithoutLeadingZero)); - } + assetBalance = toAccount.getAsset(deposit.getDynamicPropertiesStore(), + ByteArray.toStr(tokenIdWithoutLeadingZero)); if (assetBalance != null) { try { - assetBalance = Math.addExact(assetBalance, amount); //check if overflow + addExact(assetBalance, amount, + VMConfig.disableJavaLangMath()); //check if overflow } catch (Exception e) { logger.debug(e.getMessage(), e); throw new ContractValidateException(e.getMessage()); 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 2a9cd42cf0a..1ec8a75d669 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 @@ -29,6 +29,21 @@ public static void load(StoreFactory storeFactory) { VMConfig.initAllowTvmVote(ds.getAllowTvmVote()); VMConfig.initAllowTvmLondon(ds.getAllowTvmLondon()); VMConfig.initAllowTvmCompatibleEvm(ds.getAllowTvmCompatibleEvm()); + VMConfig.initAllowHigherLimitForMaxCpuTimeOfOneTx( + ds.getAllowHigherLimitForMaxCpuTimeOfOneTx()); + VMConfig.initAllowTvmFreezeV2(ds.supportUnfreezeDelay() ? 1 : 0); + VMConfig.initAllowOptimizedReturnValueOfChainId( + ds.getAllowOptimizedReturnValueOfChainId()); + VMConfig.initAllowDynamicEnergy(ds.getAllowDynamicEnergy()); + VMConfig.initDynamicEnergyThreshold(ds.getDynamicEnergyThreshold()); + VMConfig.initDynamicEnergyIncreaseFactor(ds.getDynamicEnergyIncreaseFactor()); + VMConfig.initDynamicEnergyMaxFactor(ds.getDynamicEnergyMaxFactor()); + VMConfig.initAllowTvmShangHai(ds.getAllowTvmShangHai()); + VMConfig.initAllowEnergyAdjustment(ds.getAllowEnergyAdjustment()); + VMConfig.initAllowStrictMath(ds.getAllowStrictMath()); + VMConfig.initAllowTvmCancun(ds.getAllowTvmCancun()); + VMConfig.initDisableJavaLangMath(ds.getConsensusLogicOptimization()); + VMConfig.initAllowTvmBlob(ds.getAllowTvmBlob()); } } } diff --git a/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java b/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java deleted file mode 100644 index 76eeb6199ba..00000000000 --- a/actuator/src/main/java/org/tron/core/vm/config/VMConfig.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.tron.core.vm.config; - -import lombok.Setter; -import org.tron.common.parameter.CommonParameter; - -/** - * For developer only - */ -public class VMConfig { - - private static boolean vmTraceCompressed = false; - - @Setter - private static boolean vmTrace = false; - - private static boolean ALLOW_TVM_TRANSFER_TRC10 = false; - - private static boolean ALLOW_TVM_CONSTANTINOPLE = false; - - private static boolean ALLOW_MULTI_SIGN = false; - - private static boolean ALLOW_TVM_SOLIDITY_059 = false; - - private static boolean ALLOW_SHIELDED_TRC20_TRANSACTION = false; - - private static boolean ALLOW_TVM_ISTANBUL = false; - - private static boolean ALLOW_TVM_FREEZE = false; - - private static boolean ALLOW_TVM_VOTE = false; - - private static boolean ALLOW_TVM_LONDON = false; - - private static boolean ALLOW_TVM_COMPATIBLE_EVM = false; - - private VMConfig() {} - - public static boolean vmTrace() { - return vmTrace; - } - - public static boolean vmTraceCompressed() { - return vmTraceCompressed; - } - - public static void initVmHardFork(boolean pass) { - CommonParameter.ENERGY_LIMIT_HARD_FORK = pass; - } - - public static void initAllowMultiSign(long allow) { - ALLOW_MULTI_SIGN = allow == 1; - } - - public static void initAllowTvmTransferTrc10(long allow) { - ALLOW_TVM_TRANSFER_TRC10 = allow == 1; - } - - public static void initAllowTvmConstantinople(long allow) { - ALLOW_TVM_CONSTANTINOPLE = allow == 1; - } - - public static void initAllowTvmSolidity059(long allow) { - ALLOW_TVM_SOLIDITY_059 = allow == 1; - } - - public static void initAllowShieldedTRC20Transaction(long allow) { - ALLOW_SHIELDED_TRC20_TRANSACTION = allow == 1; - } - - public static void initAllowTvmIstanbul(long allow) { - ALLOW_TVM_ISTANBUL = allow == 1; - } - - public static void initAllowTvmFreeze(long allow) { - ALLOW_TVM_FREEZE = allow == 1; - } - - public static void initAllowTvmVote(long allow) { - ALLOW_TVM_VOTE = allow == 1; - } - - public static void initAllowTvmLondon(long allow) { - ALLOW_TVM_LONDON = allow == 1; - } - - public static void initAllowTvmCompatibleEvm(long allow) { - ALLOW_TVM_COMPATIBLE_EVM = allow == 1; - } - - public static boolean getEnergyLimitHardFork() { - return CommonParameter.ENERGY_LIMIT_HARD_FORK; - } - - public static boolean allowTvmTransferTrc10() { - return ALLOW_TVM_TRANSFER_TRC10; - } - - public static boolean allowTvmConstantinople() { - return ALLOW_TVM_CONSTANTINOPLE; - } - - public static boolean allowMultiSign() { - return ALLOW_MULTI_SIGN; - } - - public static boolean allowTvmSolidity059() { - return ALLOW_TVM_SOLIDITY_059; - } - - public static boolean allowShieldedTRC20Transaction() { - return ALLOW_SHIELDED_TRC20_TRANSACTION; - } - - public static boolean allowTvmIstanbul() { - return ALLOW_TVM_ISTANBUL; - } - - public static boolean allowTvmFreeze() { - return ALLOW_TVM_FREEZE; - } - - public static boolean allowTvmVote() { - return ALLOW_TVM_VOTE; - } - - public static boolean allowTvmLondon() { - return ALLOW_TVM_LONDON; - } - - public static boolean allowTvmCompatibleEvm() { - return ALLOW_TVM_COMPATIBLE_EVM; - } -} 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 new file mode 100644 index 00000000000..ec1f4363205 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/CancelAllUnfreezeV2Processor.java @@ -0,0 +1,98 @@ +package org.tron.core.vm.nativecontract; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.vm.VMConstant; +import org.tron.core.vm.nativecontract.param.CancelAllUnfreezeV2Param; +import org.tron.core.vm.repository.Repository; +import org.tron.protos.Protocol; + +@Slf4j(topic = "VMProcessor") +public class CancelAllUnfreezeV2Processor { + + public void validate(CancelAllUnfreezeV2Param param, Repository repo) throws ContractValidateException { + if (repo == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + + byte[] ownerAddress = param.getOwnerAddress(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = repo.getAccount(ownerAddress); + if (Objects.isNull(accountCapsule)) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); + } + } + + public Map execute(CancelAllUnfreezeV2Param param, Repository repo) throws ContractExeException { + Map result = new HashMap<>(); + byte[] ownerAddress = param.getOwnerAddress(); + AccountCapsule ownerCapsule = repo.getAccount(ownerAddress); + long now = repo.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + long withdrawExpireBalance = 0L; + for (Protocol.Account.UnFreezeV2 unFreezeV2: ownerCapsule.getUnfrozenV2List()) { + if (unFreezeV2.getUnfreezeExpireTime() > now) { + String resourceName = unFreezeV2.getType().name(); + result.put(resourceName, result.getOrDefault(resourceName, 0L) + unFreezeV2.getUnfreezeAmount()); + + updateFrozenInfoAndTotalResourceWeight(ownerCapsule, unFreezeV2, repo); + } else { + // withdraw + withdrawExpireBalance += unFreezeV2.getUnfreezeAmount(); + } + } + if (withdrawExpireBalance > 0) { + ownerCapsule.setBalance(ownerCapsule.getBalance() + withdrawExpireBalance); + } + ownerCapsule.clearUnfrozenV2(); + + repo.updateAccount(ownerCapsule.createDbKey(), ownerCapsule); + + result.put(VMConstant.WITHDRAW_EXPIRE_BALANCE, withdrawExpireBalance); + return result; + } + + public void updateFrozenInfoAndTotalResourceWeight( + AccountCapsule accountCapsule, Protocol.Account.UnFreezeV2 unFreezeV2, Repository repo) { + switch (unFreezeV2.getType()) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(unFreezeV2.getUnfreezeAmount()); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + repo.addTotalNetWeight(newNetWeight - oldNetWeight); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(unFreezeV2.getUnfreezeAmount()); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + repo.addTotalEnergyWeight(newEnergyWeight - oldEnergyWeight); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(unFreezeV2.getUnfreezeAmount()); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + repo.addTotalTronPowerWeight(newTPWeight - oldTPWeight); + break; + default: + // this should never happen + break; + } + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java new file mode 100644 index 00000000000..d03af04aaf3 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/DelegateResourceProcessor.java @@ -0,0 +1,192 @@ +package org.tron.core.vm.nativecontract; + +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.core.vm.utils.FreezeV2Util.getV2EnergyUsage; +import static org.tron.core.vm.utils.FreezeV2Util.getV2NetUsage; + +import com.google.common.primitives.Bytes; +import com.google.protobuf.ByteString; +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.ChainBaseManager; +import org.tron.core.actuator.ActuatorConstant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.EnergyProcessor; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.DelegatedResourceAccountIndexStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.nativecontract.param.DelegateResourceParam; +import org.tron.core.vm.repository.Repository; +import org.tron.protos.Protocol; + +@Slf4j(topic = "VMProcessor") +public class DelegateResourceProcessor { + + public void validate(DelegateResourceParam param, Repository repo) throws ContractValidateException { + if (repo == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + + byte[] ownerAddress = param.getOwnerAddress(); + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + if (!dynamicStore.supportDR()) { + throw new ContractValidateException("No support for resource delegate"); + } + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule ownerCapsule = repo.getAccount(ownerAddress); + if (ownerCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ActuatorConstant.ACCOUNT_EXCEPTION_STR + readableOwnerAddress + NOT_EXIST_STR); + } + long delegateBalance = param.getDelegateBalance(); + if (delegateBalance < TRX_PRECISION) { + throw new ContractValidateException("delegateBalance must be greater than or equal to 1 TRX"); + } + + boolean disableJavaLangMath = VMConfig.disableJavaLangMath(); + switch (param.getResourceType()) { + case BANDWIDTH: { + BandwidthProcessor processor = new BandwidthProcessor(ChainBaseManager.getInstance()); + processor.updateUsageForDelegated(ownerCapsule); + + long netUsage = (long) (ownerCapsule.getNetUsage() * TRX_PRECISION * ((double) + (repo.getTotalNetWeight()) / dynamicStore.getTotalNetLimit())); + + long v2NetUsage = getV2NetUsage(ownerCapsule, netUsage, disableJavaLangMath); + + if (ownerCapsule.getFrozenV2BalanceForBandwidth() - v2NetUsage < delegateBalance) { + throw new ContractValidateException( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance"); + } + } + break; + case ENERGY: { + EnergyProcessor processor = + new EnergyProcessor(dynamicStore, ChainBaseManager.getInstance().getAccountStore()); + processor.updateUsage(ownerCapsule); + + long energyUsage = (long) (ownerCapsule.getEnergyUsage() * TRX_PRECISION * ((double) + (repo.getTotalEnergyWeight()) / dynamicStore.getTotalEnergyCurrentLimit())); + + long v2EnergyUsage = getV2EnergyUsage(ownerCapsule, energyUsage, disableJavaLangMath); + + if (ownerCapsule.getFrozenV2BalanceForEnergy() - v2EnergyUsage < delegateBalance) { + throw new ContractValidateException( + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance"); + } + } + break; + default: + throw new ContractValidateException( + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + + byte[] receiverAddress = param.getReceiverAddress(); + + if (!DecodeUtil.addressValid(receiverAddress)) { + throw new ContractValidateException("Invalid receiverAddress"); + } + if (Arrays.equals(receiverAddress, ownerAddress)) { + throw new ContractValidateException( + "receiverAddress must not be the same as ownerAddress"); + } + AccountCapsule receiverCapsule = repo.getAccount(receiverAddress); + if (receiverCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(receiverAddress); + throw new ContractValidateException( + ActuatorConstant.ACCOUNT_EXCEPTION_STR + + readableOwnerAddress + NOT_EXIST_STR); + } + if (receiverCapsule.getType() == Protocol.AccountType.Contract) { + throw new ContractValidateException( + "Do not allow delegate resources to contract addresses"); + } + } + + public void execute(DelegateResourceParam param, Repository repo) { + byte[] ownerAddress = param.getOwnerAddress(); + AccountCapsule ownerCapsule = repo.getAccount(param.getOwnerAddress()); + long delegateBalance = param.getDelegateBalance(); + byte[] receiverAddress = param.getReceiverAddress(); + + // delegate resource to receiver + switch (param.getResourceType()) { + case BANDWIDTH: + delegateResource(ownerAddress, receiverAddress, true, + delegateBalance, repo); + + ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + ownerCapsule.addFrozenBalanceForBandwidthV2(-delegateBalance); + break; + case ENERGY: + delegateResource(ownerAddress, receiverAddress, false, + delegateBalance, repo); + + ownerCapsule.addDelegatedFrozenV2BalanceForEnergy(delegateBalance); + ownerCapsule.addFrozenBalanceForEnergyV2(-delegateBalance); + break; + default: + logger.debug("Resource Code Error."); + } + + repo.updateAccount(ownerCapsule.createDbKey(), ownerCapsule); + } + + private void delegateResource( + byte[] ownerAddress, + byte[] receiverAddress, + boolean isBandwidth, + long delegateBalance, + Repository repo) { + //modify DelegatedResourceStore + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, false); + DelegatedResourceCapsule delegatedResourceCapsule = repo.getDelegatedResource(key); + if (delegatedResourceCapsule == null) { + delegatedResourceCapsule = new DelegatedResourceCapsule( + ByteString.copyFrom(ownerAddress), + ByteString.copyFrom(receiverAddress)); + } + if (isBandwidth) { + delegatedResourceCapsule.addFrozenBalanceForBandwidth(delegateBalance, 0); + } else { + delegatedResourceCapsule.addFrozenBalanceForEnergy(delegateBalance, 0); + } + + //modify DelegatedResourceAccountIndex + long now = repo.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + byte[] fromKey = Bytes.concat( + DelegatedResourceAccountIndexStore.getV2_FROM_PREFIX(), ownerAddress, receiverAddress); + DelegatedResourceAccountIndexCapsule toIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(receiverAddress)); + toIndexCapsule.setTimestamp(now); + repo.updateDelegatedResourceAccountIndex(fromKey, toIndexCapsule); + + byte[] toKey = Bytes.concat( + DelegatedResourceAccountIndexStore.getV2_TO_PREFIX(), receiverAddress, ownerAddress); + DelegatedResourceAccountIndexCapsule fromIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(ownerAddress)); + fromIndexCapsule.setTimestamp(now); + repo.updateDelegatedResourceAccountIndex(toKey, fromIndexCapsule); + + //update Account for receiver + AccountCapsule receiverCapsule = repo.getAccount(receiverAddress); + if (isBandwidth) { + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + } else { + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(delegateBalance); + } + repo.updateDelegatedResource(key, delegatedResourceCapsule); + repo.updateAccount(receiverCapsule.createDbKey(), receiverCapsule); + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java index 9a1af3c9cec..3088527ace6 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceProcessor.java @@ -30,9 +30,9 @@ public void validate(FreezeBalanceParam param, Repository repo) throws ContractV if (frozenBalance <= 0) { throw new ContractValidateException("FrozenBalance must be positive"); } else if (frozenBalance < TRX_PRECISION) { - throw new ContractValidateException("FrozenBalance must be more than 1TRX"); + throw new ContractValidateException("FrozenBalance must be greater than or equal to 1 TRX"); } else if (frozenBalance > ownerCapsule.getBalance()) { - throw new ContractValidateException("FrozenBalance must be less than accountBalance"); + throw new ContractValidateException("FrozenBalance must be less than or equal to accountBalance"); } // validate frozen count of owner account @@ -48,7 +48,7 @@ public void validate(FreezeBalanceParam param, Repository repo) throws ContractV break; default: throw new ContractValidateException( - "ResourceCode error,valid ResourceCode[BANDWIDTH、ENERGY]"); + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); } // validate for delegating resource 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 new file mode 100644 index 00000000000..e7e932194ed --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/FreezeBalanceV2Processor.java @@ -0,0 +1,106 @@ +package org.tron.core.vm.nativecontract; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; +import org.tron.core.vm.repository.Repository; + +@Slf4j(topic = "VMProcessor") +public class FreezeBalanceV2Processor { + + public void validate(FreezeBalanceV2Param param, Repository repo) throws ContractValidateException { + if (repo == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + + byte[] ownerAddress = param.getOwnerAddress(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule ownerCapsule = repo.getAccount(ownerAddress); + if (ownerCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); + } + long frozenBalance = param.getFrozenBalance(); + if (frozenBalance <= 0) { + throw new ContractValidateException("FrozenBalance must be positive"); + } else if (frozenBalance < TRX_PRECISION) { + throw new ContractValidateException("FrozenBalance must be greater than or equal to 1 TRX"); + } else if (frozenBalance > ownerCapsule.getBalance()) { + throw new ContractValidateException( + "FrozenBalance must be less than or equal to accountBalance"); + } + + // validate arg @resourceType + switch (param.getResourceType()) { + case BANDWIDTH: + case ENERGY: + break; + case TRON_POWER: + if (!repo.getDynamicPropertiesStore().supportAllowNewResourceModel()) { + throw new ContractValidateException( + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + break; + default: + if (repo.getDynamicPropertiesStore().supportAllowNewResourceModel()) { + throw new ContractValidateException( + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); + } else { + throw new ContractValidateException( + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + } + } + + public void execute(FreezeBalanceV2Param param, Repository repo) { + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + + byte[] ownerAddress = param.getOwnerAddress(); + long frozenBalance = param.getFrozenBalance(); + AccountCapsule accountCapsule = repo.getAccount(ownerAddress); + if (dynamicStore.supportAllowNewResourceModel() + && accountCapsule.oldTronPowerIsNotInitialized()) { + accountCapsule.initializeOldTronPower(); + } + switch (param.getResourceType()) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + repo.addTotalNetWeight(newNetWeight - oldNetWeight); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + repo.addTotalEnergyWeight(newEnergyWeight - oldEnergyWeight); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(frozenBalance); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + repo.addTotalTronPowerWeight(newTPWeight - oldTPWeight); + break; + default: + logger.debug("Resource Code Error."); + } + + // deduce balance of owner account + long newBalance = accountCapsule.getBalance() - frozenBalance; + accountCapsule.setBalance(newBalance); + repo.updateAccount(accountCapsule.createDbKey(), accountCapsule); + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java new file mode 100644 index 00000000000..99bcecdbd44 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnDelegateResourceProcessor.java @@ -0,0 +1,211 @@ +package org.tron.core.vm.nativecontract; + +import static org.tron.common.math.Maths.min; +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.common.primitives.Bytes; +import java.util.Arrays; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.EnergyProcessor; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.DelegatedResourceAccountIndexStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.nativecontract.param.UnDelegateResourceParam; +import org.tron.core.vm.repository.Repository; + +@Slf4j(topic = "VMProcessor") +public class UnDelegateResourceProcessor { + + public void validate(UnDelegateResourceParam param, Repository repo) throws ContractValidateException { + if (repo == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + + byte[] ownerAddress = param.getOwnerAddress(); + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + if (!dynamicStore.supportDR()) { + throw new ContractValidateException("No support for resource delegate"); + } + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule ownerCapsule = repo.getAccount(ownerAddress); + if (ownerCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); + } + + byte[] receiverAddress = param.getReceiverAddress(); + if (!DecodeUtil.addressValid(receiverAddress)) { + throw new ContractValidateException("Invalid receiverAddress"); + } + if (Arrays.equals(receiverAddress, ownerAddress)) { + throw new ContractValidateException( + "receiverAddress must not be the same as ownerAddress"); + } + + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, false); + DelegatedResourceCapsule delegatedResourceCapsule = repo.getDelegatedResource(key); + if (delegatedResourceCapsule == null) { + throw new ContractValidateException( + "delegated Resource does not exist"); + } + + long unDelegateBalance = param.getUnDelegateBalance(); + if (unDelegateBalance <= 0) { + throw new ContractValidateException("unDelegateBalance must be more than 0 TRX"); + } + switch (param.getResourceType()) { + case BANDWIDTH: + if (delegatedResourceCapsule.getFrozenBalanceForBandwidth() < unDelegateBalance) { + throw new ContractValidateException("insufficient delegatedFrozenBalance(BANDWIDTH), request=" + + unDelegateBalance + ", balance=" + delegatedResourceCapsule.getFrozenBalanceForBandwidth()); + } + break; + case ENERGY: + if (delegatedResourceCapsule.getFrozenBalanceForEnergy() < unDelegateBalance) { + throw new ContractValidateException("insufficient delegateFrozenBalance(ENERGY), request=" + + unDelegateBalance + ", balance=" + delegatedResourceCapsule.getFrozenBalanceForEnergy()); + } + break; + default: + throw new ContractValidateException( + "Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + } + + public void execute(UnDelegateResourceParam param, Repository repo) { + byte[] ownerAddress = param.getOwnerAddress(); + byte[] receiverAddress = param.getReceiverAddress(); + long unDelegateBalance = param.getUnDelegateBalance(); + AccountCapsule ownerCapsule = repo.getAccount(ownerAddress); + AccountCapsule receiverCapsule = repo.getAccount(receiverAddress); + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + long now = repo.getHeadSlot(); + + long transferUsage = 0; + // modify receiver Account + if (receiverCapsule != null) { + switch (param.getResourceType()) { + case BANDWIDTH: + BandwidthProcessor bandwidthProcessor = new BandwidthProcessor(ChainBaseManager.getInstance()); + bandwidthProcessor.updateUsageForDelegated(receiverCapsule); + /* For example, in a scenario where a regular account can be upgraded to a contract + account through an interface, the account information will be cleared after the + contract suicide, and this account will be converted to a regular account in the future */ + if (receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + < unDelegateBalance) { + // A TVM contract suicide, re-create will produce this situation + receiverCapsule.setAcquiredDelegatedFrozenV2BalanceForBandwidth(0); + } else { + // calculate usage + long unDelegateMaxUsage = (long) ((double) unDelegateBalance / TRX_PRECISION + * dynamicStore.getTotalNetLimit() / repo.getTotalNetWeight()); + transferUsage = (long) (receiverCapsule.getNetUsage() + * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForBandwidth())); + transferUsage = min(unDelegateMaxUsage, transferUsage, VMConfig.disableJavaLangMath()); + + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(-unDelegateBalance); + } + + long newNetUsage = receiverCapsule.getNetUsage() - transferUsage; + receiverCapsule.setNetUsage(newNetUsage); + receiverCapsule.setLatestConsumeTime(now); + break; + case ENERGY: + EnergyProcessor energyProcessor = + new EnergyProcessor(dynamicStore, ChainBaseManager.getInstance().getAccountStore()); + energyProcessor.updateUsage(receiverCapsule); + + if (receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy() + < unDelegateBalance) { + // A TVM contract receiver, re-create will produce this situation + receiverCapsule.setAcquiredDelegatedFrozenV2BalanceForEnergy(0); + } else { + // calculate usage + long unDelegateMaxUsage = (long) ((double) unDelegateBalance / TRX_PRECISION + * dynamicStore.getTotalEnergyCurrentLimit() / repo.getTotalEnergyWeight()); + transferUsage = (long) (receiverCapsule.getEnergyUsage() + * ((double) (unDelegateBalance) / receiverCapsule.getAllFrozenBalanceForEnergy())); + transferUsage = min(unDelegateMaxUsage, transferUsage, VMConfig.disableJavaLangMath()); + + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(-unDelegateBalance); + } + + long newEnergyUsage = receiverCapsule.getEnergyUsage() - transferUsage; + receiverCapsule.setEnergyUsage(newEnergyUsage); + receiverCapsule.setLatestConsumeTimeForEnergy(now); + break; + default: + //this should never happen + break; + } + repo.updateAccount(receiverCapsule.createDbKey(), receiverCapsule); + } + + // modify owner Account + byte[] key = DelegatedResourceCapsule.createDbKeyV2(ownerAddress, receiverAddress, false); + DelegatedResourceCapsule delegatedResourceCapsule = repo.getDelegatedResource(key); + switch (param.getResourceType()) { + case BANDWIDTH: { + delegatedResourceCapsule.addFrozenBalanceForBandwidth(-unDelegateBalance, 0); + + ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(-unDelegateBalance); + ownerCapsule.addFrozenBalanceForBandwidthV2(unDelegateBalance); + + BandwidthProcessor processor = new BandwidthProcessor(ChainBaseManager.getInstance()); + if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, + transferUsage, BANDWIDTH, now); + } + } + break; + case ENERGY: { + delegatedResourceCapsule.addFrozenBalanceForEnergy(-unDelegateBalance, 0); + + ownerCapsule.addDelegatedFrozenV2BalanceForEnergy(-unDelegateBalance); + ownerCapsule.addFrozenBalanceForEnergyV2(unDelegateBalance); + + EnergyProcessor processor = + new EnergyProcessor(dynamicStore, ChainBaseManager.getInstance().getAccountStore()); + if (Objects.nonNull(receiverCapsule) && transferUsage > 0) { + processor.unDelegateIncrease(ownerCapsule, receiverCapsule, transferUsage, ENERGY, now); + } + } + break; + default: + //this should never happen + break; + } + + if (delegatedResourceCapsule.getFrozenBalanceForBandwidth() == 0 + && delegatedResourceCapsule.getFrozenBalanceForEnergy() == 0) { + //modify DelegatedResourceAccountIndex + byte[] fromKey = Bytes.concat( + DelegatedResourceAccountIndexStore.getV2_FROM_PREFIX(), ownerAddress, receiverAddress); + repo.updateDelegatedResourceAccountIndex( + fromKey, new DelegatedResourceAccountIndexCapsule(new byte[0])); + byte[] toKey = Bytes.concat( + DelegatedResourceAccountIndexStore.getV2_TO_PREFIX(), receiverAddress, ownerAddress); + repo.updateDelegatedResourceAccountIndex( + toKey, new DelegatedResourceAccountIndexCapsule(new byte[0])); + } + + repo.updateDelegatedResource(key, delegatedResourceCapsule); + repo.updateAccount(ownerCapsule.createDbKey(), ownerCapsule); + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java index 0eda888d3ca..53981a22d34 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceProcessor.java @@ -65,8 +65,8 @@ public void validate(UnfreezeBalanceParam param, Repository repo) } break; default: - throw new ContractValidateException("ResourceCode error." - + "valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException("Unknown ResourceCode, " + + "valid ResourceCode[BANDWIDTH、ENERGY]"); } } else { switch (param.getResourceType()) { @@ -95,8 +95,8 @@ public void validate(UnfreezeBalanceParam param, Repository repo) } break; default: - throw new ContractValidateException("ResourceCode error." - + "valid ResourceCode[BANDWIDTH、Energy]"); + throw new ContractValidateException("Unknown ResourceCode, " + + "valid ResourceCode[BANDWIDTH、ENERGY]"); } } } @@ -136,10 +136,12 @@ public long execute(UnfreezeBalanceParam param, Repository repo) { if (receiverCapsule != null) { switch (param.getResourceType()) { case BANDWIDTH: - receiverCapsule.safeAddAcquiredDelegatedFrozenBalanceForBandwidth(-unfreezeBalance); + receiverCapsule.safeAddAcquiredDelegatedFrozenBalanceForBandwidth(-unfreezeBalance, + VMConfig.disableJavaLangMath()); break; case ENERGY: - receiverCapsule.safeAddAcquiredDelegatedFrozenBalanceForEnergy(-unfreezeBalance); + receiverCapsule.safeAddAcquiredDelegatedFrozenBalanceForEnergy(-unfreezeBalance, + VMConfig.disableJavaLangMath()); break; default: //this should never happen 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 new file mode 100644 index 00000000000..af2cbf63a43 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/UnfreezeBalanceV2Processor.java @@ -0,0 +1,286 @@ +package org.tron.core.vm.nativecontract; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; +import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.common.collect.Lists; +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.actuator.UnfreezeBalanceV2Actuator; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.VotesCapsule; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.DynamicPropertiesStore; +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.VoteRewardUtil; +import org.tron.protos.Protocol; +import org.tron.protos.contract.Common; + +@Slf4j(topic = "VMProcessor") +public class UnfreezeBalanceV2Processor { + + public void validate(UnfreezeBalanceV2Param param, Repository repo) + throws ContractValidateException { + if (repo == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + + byte[] ownerAddress = param.getOwnerAddress(); + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = repo.getAccount(ownerAddress); + if (accountCapsule == null) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException( + ACCOUNT_EXCEPTION_STR + readableOwnerAddress + "] does not exist"); + } + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + int unfreezingCount = accountCapsule.getUnfreezingV2Count(now); + if (UnfreezeBalanceV2Actuator.getUNFREEZE_MAX_TIMES() <= unfreezingCount) { + throw new ContractValidateException("Invalid unfreeze operation, unfreezing times is over limit"); + } + switch (param.getResourceType()) { + case BANDWIDTH: + // validate frozen balance + if (!this.checkExistFrozenBalance(accountCapsule, Common.ResourceCode.BANDWIDTH)) { + throw new ContractValidateException("no frozenBalance(BANDWIDTH)"); + } + break; + case ENERGY: + // validate frozen balance + if (!this.checkExistFrozenBalance(accountCapsule, Common.ResourceCode.ENERGY)) { + throw new ContractValidateException("no frozenBalance(ENERGY)"); + } + break; + case TRON_POWER: + if (dynamicStore.supportAllowNewResourceModel()) { + if (!this.checkExistFrozenBalance(accountCapsule, Common.ResourceCode.TRON_POWER)) { + throw new ContractValidateException("no frozenBalance(TRON_POWER)"); + } + } else { + throw new ContractValidateException("Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + break; + default: + if (dynamicStore.supportAllowNewResourceModel()) { + throw new ContractValidateException("Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY、TRON_POWER]"); + } else { + throw new ContractValidateException("Unknown ResourceCode, valid ResourceCode[BANDWIDTH、ENERGY]"); + } + } + + if (!checkUnfreezeBalance(accountCapsule, param.getUnfreezeBalance(), param.getResourceType())) { + throw new ContractValidateException( + "Invalid unfreeze_balance, [" + param.getUnfreezeBalance() + "] is invalid"); + } + } + + private boolean checkUnfreezeBalance( + AccountCapsule accountCapsule, long unfreezeBalance, Common.ResourceCode freezeType) { + if (unfreezeBalance <= 0) { + return false; + } + long frozenBalance = 0L; + List freezeV2List = accountCapsule.getFrozenV2List(); + for (Protocol.Account.FreezeV2 freezeV2 : freezeV2List) { + if (freezeV2.getType().equals(freezeType)) { + frozenBalance = freezeV2.getAmount(); + break; + } + } + + return unfreezeBalance <= frozenBalance; + } + + private boolean checkExistFrozenBalance(AccountCapsule accountCapsule, Common.ResourceCode freezeType) { + List frozenV2List = accountCapsule.getFrozenV2List(); + for (Protocol.Account.FreezeV2 frozenV2 : frozenV2List) { + if (frozenV2.getType().equals(freezeType) && frozenV2.getAmount() > 0) { + return true; + } + } + return false; + } + + public long execute(UnfreezeBalanceV2Param param, Repository repo) { + byte[] ownerAddress = param.getOwnerAddress(); + long unfreezeBalance = param.getUnfreezeBalance(); + VoteRewardUtil.withdrawReward(ownerAddress, repo); + + AccountCapsule accountCapsule = repo.getAccount(ownerAddress); + long now = repo.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + + long unfreezeExpireBalance = this.unfreezeExpire(accountCapsule, now); + + if (repo.getDynamicPropertiesStore().supportAllowNewResourceModel() + && accountCapsule.oldTronPowerIsNotInitialized()) { + accountCapsule.initializeOldTronPower(); + } + + long expireTime = this.calcUnfreezeExpireTime(now, repo); + accountCapsule.addUnfrozenV2List(param.getResourceType(), unfreezeBalance, expireTime); + + this.updateTotalResourceWeight(accountCapsule, param.getResourceType(), unfreezeBalance, repo); + this.updateVote(accountCapsule, param.getResourceType(), ownerAddress, repo); + + if (repo.getDynamicPropertiesStore().supportAllowNewResourceModel() + && !accountCapsule.oldTronPowerIsInvalid()) { + accountCapsule.invalidateOldTronPower(); + } + + repo.updateAccount(accountCapsule.createDbKey(), accountCapsule); + return unfreezeExpireBalance; + } + + private long unfreezeExpire(AccountCapsule accountCapsule, long now) { + long unfreezeBalance = 0L; + + List unFrozenV2List = Lists.newArrayList(); + unFrozenV2List.addAll(accountCapsule.getUnfrozenV2List()); + Iterator iterator = unFrozenV2List.iterator(); + + while (iterator.hasNext()) { + Protocol.Account.UnFreezeV2 next = iterator.next(); + if (next.getUnfreezeExpireTime() <= now) { + unfreezeBalance += next.getUnfreezeAmount(); + iterator.remove(); + } + } + + accountCapsule.setInstance( + accountCapsule.getInstance().toBuilder() + .setBalance(accountCapsule.getBalance() + unfreezeBalance) + .clearUnfrozenV2() + .addAllUnfrozenV2(unFrozenV2List).build() + ); + return unfreezeBalance; + } + + private long calcUnfreezeExpireTime(long now, Repository repo) { + long unfreezeDelayDays = repo.getDynamicPropertiesStore().getUnfreezeDelayDays(); + + return now + unfreezeDelayDays * FROZEN_PERIOD; + } + + public void updateTotalResourceWeight(AccountCapsule accountCapsule, + Common.ResourceCode freezeType, + long unfreezeBalance, + Repository repo) { + switch (freezeType) { + case BANDWIDTH: + long oldNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForBandwidthV2(-unfreezeBalance); + long newNetWeight = accountCapsule.getFrozenV2BalanceWithDelegated(BANDWIDTH) / TRX_PRECISION; + repo.addTotalNetWeight(newNetWeight - oldNetWeight); + break; + case ENERGY: + long oldEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + accountCapsule.addFrozenBalanceForEnergyV2(-unfreezeBalance); + long newEnergyWeight = accountCapsule.getFrozenV2BalanceWithDelegated(ENERGY) / TRX_PRECISION; + repo.addTotalEnergyWeight(newEnergyWeight - oldEnergyWeight); + break; + case TRON_POWER: + long oldTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + accountCapsule.addFrozenForTronPowerV2(-unfreezeBalance); + long newTPWeight = accountCapsule.getTronPowerFrozenV2Balance() / TRX_PRECISION; + repo.addTotalTronPowerWeight(newTPWeight - oldTPWeight); + break; + default: + //this should never happen + break; + } + } + + private void updateVote( + AccountCapsule accountCapsule, + Common.ResourceCode freezeType, + byte[] ownerAddress, + Repository repo) { + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + + if (!VMConfig.allowTvmVote() || accountCapsule.getVotesList().isEmpty()) { + return; + } + if (dynamicStore.supportAllowNewResourceModel()) { + if (accountCapsule.oldTronPowerIsInvalid()) { + switch (freezeType) { + case BANDWIDTH: + case ENERGY: + // there is no need to change votes + return; + default: + break; + } + } else { + // clear all votes at once when new resource model start + VotesCapsule votesCapsule = repo.getVotes(ownerAddress); + if (votesCapsule == null) { + votesCapsule = + new VotesCapsule(ByteString.copyFrom(ownerAddress), accountCapsule.getVotesList()); + } + accountCapsule.clearVotes(); + votesCapsule.clearNewVotes(); + repo.updateVotes(ownerAddress, votesCapsule); + return; + } + } + + long totalVote = 0; + for (Protocol.Vote vote : accountCapsule.getVotesList()) { + totalVote += vote.getVoteCount(); + } + if (totalVote == 0) { + return; + } + + long ownedTronPower; + if (dynamicStore.supportAllowNewResourceModel()) { + ownedTronPower = accountCapsule.getAllTronPower(); + } else { + ownedTronPower = accountCapsule.getTronPower(); + } + // tron power is enough to total votes + if (ownedTronPower >= totalVote * TRX_PRECISION) { + return; + } + + VotesCapsule votesCapsule = repo.getVotes(ownerAddress); + if (votesCapsule == null) { + votesCapsule = + new VotesCapsule(ByteString.copyFrom(ownerAddress), accountCapsule.getVotesList()); + } + + // Update Owner Voting + List votesToAdd = new ArrayList<>(); + for (Protocol.Vote vote : accountCapsule.getVotesList()) { + long newVoteCount = + (long) ((double) vote.getVoteCount() / totalVote * ownedTronPower / TRX_PRECISION); + if (newVoteCount > 0) { + votesToAdd.add( + Protocol.Vote.newBuilder() + .setVoteAddress(vote.getVoteAddress()) + .setVoteCount(newVoteCount) + .build()); + } + } + votesCapsule.clearNewVotes(); + votesCapsule.addAllNewVotes(votesToAdd); + repo.updateVotes(ownerAddress, votesCapsule); + + accountCapsule.clearVotes(); + accountCapsule.addAllVotes(votesToAdd); + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/VoteWitnessProcessor.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/VoteWitnessProcessor.java index ddc28bc2a41..8e17ffe8b13 100644 --- a/actuator/src/main/java/org/tron/core/vm/nativecontract/VoteWitnessProcessor.java +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/VoteWitnessProcessor.java @@ -8,11 +8,9 @@ import com.google.common.math.LongMath; import com.google.protobuf.ByteString; - import java.util.HashMap; import java.util.Iterator; import java.util.Map; - import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; @@ -87,7 +85,13 @@ public void execute(VoteWitnessParam param, Repository repo) throws ContractExeE } } - long tronPower = accountCapsule.getTronPower(); + long tronPower; + if (repo.getDynamicPropertiesStore().supportUnfreezeDelay() + && repo.getDynamicPropertiesStore().supportAllowNewResourceModel()) { + tronPower = accountCapsule.getAllTronPower(); + } else { + tronPower = accountCapsule.getTronPower(); + } sum = LongMath.checkedMultiply(sum, TRX_PRECISION); if (sum > tronPower) { throw new ContractExeException( 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 new file mode 100644 index 00000000000..0bcdb10d46f --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/WithdrawExpireUnfreezeProcessor.java @@ -0,0 +1,92 @@ +package org.tron.core.vm.nativecontract; + +import static org.tron.core.actuator.ActuatorConstant.ACCOUNT_EXCEPTION_STR; +import static org.tron.core.actuator.ActuatorConstant.NOT_EXIST_STR; +import static org.tron.core.actuator.ActuatorConstant.STORE_NOT_EXIST; + +import com.google.common.math.LongMath; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.nativecontract.param.WithdrawExpireUnfreezeParam; +import org.tron.core.vm.repository.Repository; +import org.tron.protos.Protocol; + +@Slf4j(topic = "VMProcessor") +public class WithdrawExpireUnfreezeProcessor { + + public void validate(WithdrawExpireUnfreezeParam param, Repository repo) throws ContractValidateException { + if (repo == null) { + throw new ContractValidateException(STORE_NOT_EXIST); + } + + byte[] ownerAddress = param.getOwnerAddress(); + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + if (!DecodeUtil.addressValid(ownerAddress)) { + throw new ContractValidateException("Invalid address"); + } + AccountCapsule accountCapsule = repo.getAccount(ownerAddress); + if (Objects.isNull(accountCapsule)) { + String readableOwnerAddress = StringUtil.createReadableString(ownerAddress); + throw new ContractValidateException(ACCOUNT_EXCEPTION_STR + + readableOwnerAddress + NOT_EXIST_STR); + } + + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + List unfrozenV2List = accountCapsule.getInstance() + .getUnfrozenV2List(); + long totalWithdrawUnfreeze = getTotalWithdrawUnfreeze(unfrozenV2List, now); + if (totalWithdrawUnfreeze < 0) { + throw new ContractValidateException("no unFreeze balance to withdraw "); + } + try { + LongMath.checkedAdd(accountCapsule.getBalance(), totalWithdrawUnfreeze); + } catch (ArithmeticException e) { + logger.debug(e.getMessage(), e); + throw new ContractValidateException(e.getMessage()); + } + } + + private long getTotalWithdrawUnfreeze(List unfrozenV2List, long now) { + return getTotalWithdrawList(unfrozenV2List, now).stream() + .mapToLong(Protocol.Account.UnFreezeV2::getUnfreezeAmount).sum(); + } + + private List getTotalWithdrawList(List unfrozenV2List, long now) { + return unfrozenV2List.stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= now) + .collect(Collectors.toList()); + } + + public long execute(WithdrawExpireUnfreezeParam param, Repository repo) throws ContractExeException { + byte[] ownerAddress = param.getOwnerAddress(); + DynamicPropertiesStore dynamicStore = repo.getDynamicPropertiesStore(); + AccountCapsule ownerCapsule = repo.getAccount(ownerAddress); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + List unfrozenV2List = ownerCapsule.getInstance().getUnfrozenV2List(); + long totalWithdrawUnfreeze = getTotalWithdrawUnfreeze(unfrozenV2List, now); + if (totalWithdrawUnfreeze <= 0) { + return 0; + } + ownerCapsule.setInstance(ownerCapsule.getInstance().toBuilder() + .setBalance(ownerCapsule.getBalance() + totalWithdrawUnfreeze) + .build()); + List newUnFreezeList = getRemainWithdrawList(unfrozenV2List, now); + ownerCapsule.clearUnfrozenV2(); + ownerCapsule.addAllUnfrozenV2(newUnFreezeList); + repo.updateAccount(ownerCapsule.createDbKey(), ownerCapsule); + return totalWithdrawUnfreeze; + } + + private List getRemainWithdrawList(List unfrozenV2List, long now) { + return unfrozenV2List.stream() + .filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() > now) + .collect(Collectors.toList()); + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/param/CancelAllUnfreezeV2Param.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/CancelAllUnfreezeV2Param.java new file mode 100644 index 00000000000..f345fa0b344 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/CancelAllUnfreezeV2Param.java @@ -0,0 +1,14 @@ +package org.tron.core.vm.nativecontract.param; + +public class CancelAllUnfreezeV2Param { + + private byte[] ownerAddress; + + public byte[] getOwnerAddress() { + return ownerAddress; + } + + public void setOwnerAddress(byte[] ownerAddress) { + this.ownerAddress = ownerAddress; + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/param/DelegateResourceParam.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/DelegateResourceParam.java new file mode 100644 index 00000000000..f7d897800b5 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/DelegateResourceParam.java @@ -0,0 +1,46 @@ +package org.tron.core.vm.nativecontract.param; + +import org.tron.protos.contract.Common; + +public class DelegateResourceParam { + + private byte[] ownerAddress; + + private byte[] receiverAddress; + + private long delegateBalance; + + private Common.ResourceCode resourceType; + + public byte[] getOwnerAddress() { + return ownerAddress; + } + + public void setOwnerAddress(byte[] ownerAddress) { + this.ownerAddress = ownerAddress; + } + + public byte[] getReceiverAddress() { + return receiverAddress; + } + + public void setReceiverAddress(byte[] receiverAddress) { + this.receiverAddress = receiverAddress; + } + + public long getDelegateBalance() { + return delegateBalance; + } + + public void setDelegateBalance(long delegateBalance) { + this.delegateBalance = delegateBalance; + } + + public Common.ResourceCode getResourceType() { + return resourceType; + } + + public void setResourceType(Common.ResourceCode resourceType) { + this.resourceType = resourceType; + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/param/FreezeBalanceV2Param.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/FreezeBalanceV2Param.java new file mode 100644 index 00000000000..8aaf00da975 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/FreezeBalanceV2Param.java @@ -0,0 +1,36 @@ +package org.tron.core.vm.nativecontract.param; + +import org.tron.protos.contract.Common; + +public class FreezeBalanceV2Param { + + private byte[] ownerAddress; + + private long frozenBalance; + + private Common.ResourceCode resourceType; + + public byte[] getOwnerAddress() { + return ownerAddress; + } + + public void setOwnerAddress(byte[] ownerAddress) { + this.ownerAddress = ownerAddress; + } + + public long getFrozenBalance() { + return frozenBalance; + } + + public void setFrozenBalance(long frozenBalance) { + this.frozenBalance = frozenBalance; + } + + public Common.ResourceCode getResourceType() { + return resourceType; + } + + public void setResourceType(Common.ResourceCode resourceType) { + this.resourceType = resourceType; + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/param/UnDelegateResourceParam.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/UnDelegateResourceParam.java new file mode 100644 index 00000000000..7a1c76b3c32 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/UnDelegateResourceParam.java @@ -0,0 +1,46 @@ +package org.tron.core.vm.nativecontract.param; + +import org.tron.protos.contract.Common; + +public class UnDelegateResourceParam { + + private byte[] ownerAddress; + + private byte[] receiverAddress; + + private long unDelegateBalance; + + private Common.ResourceCode resourceType; + + public byte[] getOwnerAddress() { + return ownerAddress; + } + + public void setOwnerAddress(byte[] ownerAddress) { + this.ownerAddress = ownerAddress; + } + + public byte[] getReceiverAddress() { + return receiverAddress; + } + + public void setReceiverAddress(byte[] receiverAddress) { + this.receiverAddress = receiverAddress; + } + + public long getUnDelegateBalance() { + return unDelegateBalance; + } + + public void setUnDelegateBalance(long unDelegateBalance) { + this.unDelegateBalance = unDelegateBalance; + } + + public Common.ResourceCode getResourceType() { + return resourceType; + } + + public void setResourceType(Common.ResourceCode resourceType) { + this.resourceType = resourceType; + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/param/UnfreezeBalanceV2Param.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/UnfreezeBalanceV2Param.java new file mode 100644 index 00000000000..81ae0f8d222 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/UnfreezeBalanceV2Param.java @@ -0,0 +1,36 @@ +package org.tron.core.vm.nativecontract.param; + +import org.tron.protos.contract.Common; + +public class UnfreezeBalanceV2Param { + + private byte[] ownerAddress; + + private long unfreezeBalance; + + private Common.ResourceCode resourceType; + + public byte[] getOwnerAddress() { + return ownerAddress; + } + + public void setOwnerAddress(byte[] ownerAddress) { + this.ownerAddress = ownerAddress; + } + + public long getUnfreezeBalance() { + return unfreezeBalance; + } + + public void setUnfreezeBalance(long unfreezeBalance) { + this.unfreezeBalance = unfreezeBalance; + } + + public Common.ResourceCode getResourceType() { + return resourceType; + } + + public void setResourceType(Common.ResourceCode resourceType) { + this.resourceType = resourceType; + } +} diff --git a/actuator/src/main/java/org/tron/core/vm/nativecontract/param/WithdrawExpireUnfreezeParam.java b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/WithdrawExpireUnfreezeParam.java new file mode 100644 index 00000000000..db3cece4126 --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/nativecontract/param/WithdrawExpireUnfreezeParam.java @@ -0,0 +1,15 @@ +package org.tron.core.vm.nativecontract.param; + +public class WithdrawExpireUnfreezeParam { + + // Account address which want to withdraw its reward + private byte[] ownerAddress; + + public byte[] getOwnerAddress() { + return ownerAddress; + } + + public void setOwnerAddress(byte[] ownerAddress) { + this.ownerAddress = ownerAddress; + } +} 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 458d83f5110..e095201e393 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 @@ -1,11 +1,14 @@ package org.tron.core.vm.program; +import org.apache.commons.lang3.tuple.Pair; import org.tron.common.runtime.vm.DataWord; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BytesCapsule; import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.ContractStateCapsule; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.VotesCapsule; import org.tron.core.capsule.WitnessCapsule; @@ -103,11 +106,21 @@ public ContractCapsule getContract(byte[] codeHash) { return repository.getContract(codeHash); } + @Override + public ContractStateCapsule getContractState(byte[] address) { + return repository.getContractState(address); + } + @Override public void updateContract(byte[] address, ContractCapsule contractCapsule) { repository.updateContract(address, contractCapsule); } + @Override + public void updateContractState(byte[] address, ContractStateCapsule contractStateCapsule) { + repository.updateContractState(address, contractStateCapsule); + } + @Override public void updateAccount(byte[] address, AccountCapsule accountCapsule) { repository.updateAccount(address, accountCapsule); @@ -181,6 +194,10 @@ public void putContract(Key key, Value value) { repository.putContract(key, value); } + @Override + public void putContractState(Key key, Value value) { + repository.putContractState(key, value); + } public void putStorage(Key key, Storage cache) { repository.putStorage(key, cache); @@ -207,6 +224,16 @@ public void putDelegation(Key key, Value value) { repository.putDelegation(key, value); } + @Override + public void putDelegatedResourceAccountIndex(Key key, Value value) { + repository.putDelegatedResourceAccountIndex(key, value); + } + + @Override + public void putTransientStorageValue(Key address, Key key, Value value) { + repository.putTransientStorageValue(address, key, value); + } + @Override public long addTokenBalance(byte[] address, byte[] tokenId, long value) { return repository.addTokenBalance(address, tokenId, value); @@ -222,6 +249,21 @@ public long getAccountLeftEnergyFromFreeze(AccountCapsule accountCapsule) { return repository.getAccountLeftEnergyFromFreeze(accountCapsule); } + @Override + public long getAccountEnergyUsage(AccountCapsule accountCapsule) { + return repository.getAccountEnergyUsage(accountCapsule); + } + + @Override + public Pair getAccountEnergyUsageBalanceAndRestoreSeconds(AccountCapsule accountCapsule) { + return repository.getAccountEnergyUsageBalanceAndRestoreSeconds(accountCapsule); + } + + @Override + public Pair getAccountNetUsageBalanceAndRestoreSeconds(AccountCapsule accountCapsule) { + return repository.getAccountNetUsageBalanceAndRestoreSeconds(accountCapsule); + } + @Override public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { return repository.calculateGlobalEnergyLimit(accountCapsule); @@ -272,6 +314,16 @@ public BytesCapsule getDelegation(Key key) { return repository.getDelegation(key); } + @Override + public DelegatedResourceAccountIndexCapsule getDelegatedResourceAccountIndex(byte[] key) { + return repository.getDelegatedResourceAccountIndex(key); + } + + @Override + public byte[] getTransientStorageValue(byte[] address, byte[] key) { + return repository.getTransientStorageValue(address, key); + } + @Override public void updateDynamicProperty(byte[] word, BytesCapsule bytesCapsule) { repository.updateDynamicProperty(word, bytesCapsule); @@ -307,6 +359,16 @@ public void updateDelegation(byte[] word, BytesCapsule bytesCapsule) { repository.updateDelegation(word, bytesCapsule); } + @Override + public void updateDelegatedResourceAccountIndex(byte[] word, DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule) { + repository.updateDelegatedResourceAccountIndex(word, delegatedResourceAccountIndexCapsule); + } + + @Override + public void updateTransientStorageValue(byte[] address, byte[] key, byte[] value) { + repository.updateTransientStorageValue(address, key, value); + } + @Override public void putDynamicProperty(Key key, Value value) { repository.putDynamicProperty(key, value); @@ -327,6 +389,11 @@ public void addTotalEnergyWeight(long amount) { repository.addTotalEnergyWeight(amount); } + @Override + public void addTotalTronPowerWeight(long amount) { + repository.addTotalTronPowerWeight(amount); + } + @Override public void saveTotalNetWeight(long totalNetWeight) { repository.saveTotalNetWeight(totalNetWeight); @@ -337,6 +404,11 @@ public void saveTotalEnergyWeight(long totalEnergyWeight) { repository.saveTotalEnergyWeight(totalEnergyWeight); } + @Override + public void saveTotalTronPowerWeight(long totalTronPowerWeight) { + repository.saveTotalTronPowerWeight(totalTronPowerWeight); + } + @Override public long getTotalNetWeight() { return repository.getTotalNetWeight(); @@ -347,4 +419,19 @@ public long getTotalEnergyWeight() { return repository.getTotalEnergyWeight(); } + @Override + public long getTotalTronPowerWeight() { + return repository.getTotalTronPowerWeight(); + } + + @Override + public long getHeadSlot() { + return repository.getHeadSlot(); + } + + @Override + public long getSlotByTimestampMs(long timestamp) { + return repository.getSlotByTimestampMs(timestamp); + } + } diff --git a/actuator/src/main/java/org/tron/core/vm/program/Memory.java b/actuator/src/main/java/org/tron/core/vm/program/Memory.java index e5cbebad2b9..4249a7e2634 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/Memory.java +++ b/actuator/src/main/java/org/tron/core/vm/program/Memory.java @@ -1,14 +1,16 @@ package org.tron.core.vm.program; -import static java.lang.Math.ceil; -import static java.lang.Math.min; import static java.lang.String.format; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.ceil; +import static org.tron.common.math.Maths.min; import static org.tron.common.utils.ByteUtil.EMPTY_BYTE_ARRAY; import static org.tron.common.utils.ByteUtil.oneByteToHexString; import java.util.LinkedList; import java.util.List; import org.tron.common.runtime.vm.DataWord; +import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.program.listener.ProgramListener; import org.tron.core.vm.program.listener.ProgramListenerAware; @@ -103,17 +105,17 @@ public void extend(int address, int size) { if (size <= 0) { return; } - - final int newSize = Math.addExact(address, size); + final int newSize = addExact(address, size, VMConfig.disableJavaLangMath()); int toAllocate = newSize - internalSize(); if (toAllocate > 0) { - addChunks((int) ceil((double) toAllocate / CHUNK_SIZE)); + addChunks((int) ceil((double) toAllocate / CHUNK_SIZE, VMConfig.disableJavaLangMath())); } toAllocate = newSize - softSize; if (toAllocate > 0) { - toAllocate = (int) ceil((double) toAllocate / WORD_SIZE) * WORD_SIZE; - softSize = Math.addExact(softSize, toAllocate); + toAllocate = (int) ceil((double) toAllocate / WORD_SIZE, + VMConfig.disableJavaLangMath()) * WORD_SIZE; + softSize = addExact(softSize, toAllocate, VMConfig.disableJavaLangMath()); if (programListener != null) { programListener.onMemoryExtend(toAllocate); @@ -181,10 +183,18 @@ public List getChunks() { return new LinkedList<>(chunks); } + public void copy(int destPos, int srcPos, int size) { + if (size <= 0) { + return; + } + byte[] data = read(srcPos, size); + write(destPos, data, size, false); + } + private int captureMax(int chunkIndex, int chunkOffset, int size, byte[] src, int srcPos) { byte[] chunk = chunks.get(chunkIndex); - int toCapture = min(size, chunk.length - chunkOffset); + int toCapture = min(size, chunk.length - chunkOffset, VMConfig.disableJavaLangMath()); System.arraycopy(src, srcPos, chunk, chunkOffset, toCapture); return toCapture; @@ -193,7 +203,7 @@ private int captureMax(int chunkIndex, int chunkOffset, int size, byte[] src, in private int grabMax(int chunkIndex, int chunkOffset, int size, byte[] dest, int destPos) { byte[] chunk = chunks.get(chunkIndex); - int toGrab = min(size, chunk.length - chunkOffset); + int toGrab = min(size, chunk.length - chunkOffset, VMConfig.disableJavaLangMath()); System.arraycopy(chunk, chunkOffset, dest, destPos, toGrab); 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 9ac3619f416..5da0b02ecb7 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 @@ -1,14 +1,21 @@ package org.tron.core.vm.program; -import static java.lang.StrictMath.min; import static java.lang.String.format; import static org.apache.commons.lang3.ArrayUtils.EMPTY_BYTE_ARRAY; import static org.apache.commons.lang3.ArrayUtils.getLength; import static org.apache.commons.lang3.ArrayUtils.isEmpty; import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; import static org.apache.commons.lang3.ArrayUtils.nullToEmpty; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; +import static org.tron.common.math.Maths.multiplyExact; import static org.tron.common.utils.ByteUtil.stripLeadingZeroes; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; +import static org.tron.protos.contract.Common.ResourceCode.UNRECOGNIZED; import com.google.protobuf.ByteString; import java.math.BigInteger; @@ -16,7 +23,12 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; +import lombok.Getter; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.map.LRUMap; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; @@ -30,12 +42,17 @@ import org.tron.common.utils.FastByteComparisons; import org.tron.common.utils.Utils; import org.tron.common.utils.WalletUtil; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.ContractStateCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.VotesCapsule; import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.EnergyProcessor; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.TronException; @@ -49,19 +66,32 @@ import org.tron.core.vm.VMConstant; import org.tron.core.vm.VMUtils; import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.nativecontract.CancelAllUnfreezeV2Processor; +import org.tron.core.vm.nativecontract.DelegateResourceProcessor; import org.tron.core.vm.nativecontract.FreezeBalanceProcessor; +import org.tron.core.vm.nativecontract.FreezeBalanceV2Processor; +import org.tron.core.vm.nativecontract.UnDelegateResourceProcessor; import org.tron.core.vm.nativecontract.UnfreezeBalanceProcessor; +import org.tron.core.vm.nativecontract.UnfreezeBalanceV2Processor; import org.tron.core.vm.nativecontract.VoteWitnessProcessor; +import org.tron.core.vm.nativecontract.WithdrawExpireUnfreezeProcessor; import org.tron.core.vm.nativecontract.WithdrawRewardProcessor; +import org.tron.core.vm.nativecontract.param.CancelAllUnfreezeV2Param; +import org.tron.core.vm.nativecontract.param.DelegateResourceParam; import org.tron.core.vm.nativecontract.param.FreezeBalanceParam; +import org.tron.core.vm.nativecontract.param.FreezeBalanceV2Param; +import org.tron.core.vm.nativecontract.param.UnDelegateResourceParam; import org.tron.core.vm.nativecontract.param.UnfreezeBalanceParam; +import org.tron.core.vm.nativecontract.param.UnfreezeBalanceV2Param; import org.tron.core.vm.nativecontract.param.VoteWitnessParam; +import org.tron.core.vm.nativecontract.param.WithdrawExpireUnfreezeParam; import org.tron.core.vm.nativecontract.param.WithdrawRewardParam; import org.tron.core.vm.program.invoke.ProgramInvoke; import org.tron.core.vm.program.invoke.ProgramInvokeFactory; import org.tron.core.vm.program.listener.CompositeProgramListener; import org.tron.core.vm.program.listener.ProgramListenerAware; import org.tron.core.vm.program.listener.ProgramStorageChangeListener; +import org.tron.core.vm.repository.Key; import org.tron.core.vm.repository.Repository; import org.tron.core.vm.trace.ProgramTrace; import org.tron.core.vm.trace.ProgramTraceListener; @@ -84,6 +114,9 @@ public class Program { private static final String INVALID_TOKEN_ID_MSG = "not valid token id"; private static final String REFUND_ENERGY_FROM_MESSAGE_CALL = "refund energy from message call"; private static final String CALL_PRE_COMPILED = "call pre-compiled"; + private static final int lruCacheSize = CommonParameter.getInstance().getSafeLruCacheSize(); + private static final LRUMap programPrecompileLRUMap + = new LRUMap<>(lruCacheSize); private long nonce; private byte[] rootTransactionId; private InternalTransaction internalTransaction; @@ -99,6 +132,7 @@ public class Program { private ProgramResult result = new ProgramResult(); private ProgramTrace trace = new ProgramTrace(); private byte[] ops; + private byte[] codeAddress; private int pc; private byte lastOp; private byte previouslyExecutedOp; @@ -106,15 +140,19 @@ public class Program { private ProgramPrecompile programPrecompile; private int contractVersion; private DataWord adjustedCallEnergy; - - public Program(byte[] ops, ProgramInvoke programInvoke) { - this(ops, programInvoke, null); - } - - public Program(byte[] ops, ProgramInvoke programInvoke, InternalTransaction internalTransaction) { + @Getter + @Setter + private long contextContractFactor; + @Getter + @Setter + private long callPenaltyEnergy; + + public Program(byte[] ops, byte[] codeAddress, ProgramInvoke programInvoke, + InternalTransaction internalTransaction) { this.invoke = programInvoke; this.internalTransaction = internalTransaction; this.ops = nullToEmpty(ops); + this.codeAddress = codeAddress; traceListener = new ProgramTraceListener(VMConfig.vmTrace()); this.memory = setupProgramListener(new Memory()); @@ -124,11 +162,13 @@ public Program(byte[] ops, ProgramInvoke programInvoke, InternalTransaction inte this.nonce = internalTransaction.getNonce(); } + @SuppressWarnings("unused") static String formatBinData(byte[] binData, int startPC) { StringBuilder ret = new StringBuilder(); for (int i = 0; i < binData.length; i += 16) { ret.append(Utils.align("" + Integer.toHexString(startPC + (i)) + ":", ' ', 8, false)); - ret.append(Hex.toHexString(binData, i, min(16, binData.length - i))).append('\n'); + ret.append(Hex.toHexString(binData, i, min(16, binData.length - i, + VMConfig.disableJavaLangMath()))).append('\n'); } return ret.toString(); } @@ -166,8 +206,20 @@ public void setNonce(long nonceValue) { } public ProgramPrecompile getProgramPrecompile() { + if (isConstantCall()) { + if (programPrecompile == null) { + programPrecompile = ProgramPrecompile.compile(ops); + } + return programPrecompile; + } if (programPrecompile == null) { - programPrecompile = ProgramPrecompile.compile(ops); + Key key = getJumpDestAnalysisCacheKey(); + if (programPrecompileLRUMap.containsKey(key)) { + programPrecompile = programPrecompileLRUMap.get(key); + } else { + programPrecompile = ProgramPrecompile.compile(ops); + programPrecompileLRUMap.put(key, programPrecompile); + } } return programPrecompile; } @@ -228,6 +280,10 @@ public void setLastOp(byte op) { this.lastOp = op; } + public byte getLastOp() { + return this.lastOp; + } + /** * Returns the last fully executed OP. */ @@ -378,6 +434,10 @@ public byte[] memoryChunk(int offset, int size) { return memory.read(offset, size); } + public void memoryCopy(int dst, int src, int size) { + memory.copy(dst, src, size); + } + /** * . Allocates extra memory in the program for a specified size, calculated from a given offset * @@ -407,10 +467,11 @@ public void suicide(DataWord obtainerAddress) { increaseNonce(); - addInternalTx(null, owner, obtainer, balance, null, "suicide", nonce, - getContractState().getAccount(owner).getAssetMapV2()); + InternalTransaction internalTx = addInternalTx(null, owner, obtainer, balance, null, + "suicide", nonce, getContractState().getAccount(owner).getAssetMapV2()); - if (FastByteComparisons.compareTo(owner, 0, 20, obtainer, 0, 20) == 0) { + int ADDRESS_SIZE = VMUtils.getAddressSize(); + if (FastByteComparisons.compareTo(owner, 0, ADDRESS_SIZE, obtainer, 0, ADDRESS_SIZE) == 0) { // if owner == obtainer just zeroing account according to Yellow Paper getContractState().addBalance(owner, -balance); byte[] blackHoleAddress = getContractState().getBlackHoleAddress(); @@ -441,6 +502,16 @@ public void suicide(DataWord obtainerAddress) { transferDelegatedResourceToInheritor(owner, obtainer, getContractState()); } } + if (VMConfig.allowTvmFreezeV2()) { + byte[] Inheritor = + FastByteComparisons.isEqual(owner, obtainer) + ? getContractState().getBlackHoleAddress() + : obtainer; + long expireUnfrozenBalance = transferFrozenV2BalanceToInheritor(owner, Inheritor, getContractState()); + if (expireUnfrozenBalance > 0 && internalTx != null) { + internalTx.setValue(internalTx.getValue() + expireUnfrozenBalance); + } + } getResult().addDeleteAccount(this.getContractAddress()); } @@ -475,6 +546,78 @@ private void transferDelegatedResourceToInheritor(byte[] ownerAddr, byte[] inher repo.addBalance(inheritorAddr, frozenBalanceForBandwidthOfOwner + frozenBalanceForEnergyOfOwner); } + private long transferFrozenV2BalanceToInheritor(byte[] ownerAddr, byte[] inheritorAddr, Repository repo) { + AccountCapsule ownerCapsule = repo.getAccount(ownerAddr); + AccountCapsule inheritorCapsule = repo.getAccount(inheritorAddr); + long now = repo.getHeadSlot(); + + // transfer frozen resource + ownerCapsule.getFrozenV2List().stream() + .filter(freezeV2 -> freezeV2.getAmount() > 0) + .forEach( + freezeV2 -> { + switch (freezeV2.getType()) { + case BANDWIDTH: + inheritorCapsule.addFrozenBalanceForBandwidthV2(freezeV2.getAmount()); + break; + case ENERGY: + inheritorCapsule.addFrozenBalanceForEnergyV2(freezeV2.getAmount()); + break; + case TRON_POWER: + inheritorCapsule.addFrozenForTronPowerV2(freezeV2.getAmount()); + break; + } + }); + + // merge usage + BandwidthProcessor bandwidthProcessor = new BandwidthProcessor(ChainBaseManager.getInstance()); + bandwidthProcessor.updateUsageForDelegated(ownerCapsule); + ownerCapsule.setLatestConsumeTime(now); + if (ownerCapsule.getNetUsage() > 0) { + bandwidthProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule, + ownerCapsule.getNetUsage(), BANDWIDTH, now); + } + + EnergyProcessor energyProcessor = + new EnergyProcessor( + repo.getDynamicPropertiesStore(), ChainBaseManager.getInstance().getAccountStore()); + energyProcessor.updateUsage(ownerCapsule); + ownerCapsule.setLatestConsumeTimeForEnergy(now); + if (ownerCapsule.getEnergyUsage() > 0) { + energyProcessor.unDelegateIncrease(inheritorCapsule, ownerCapsule, + ownerCapsule.getEnergyUsage(), ENERGY, now); + } + + // withdraw expire unfrozen balance + long nowTimestamp = repo.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + long expireUnfrozenBalance = + ownerCapsule.getUnfrozenV2List().stream() + .filter( + unFreezeV2 -> + unFreezeV2.getUnfreezeAmount() > 0 && unFreezeV2.getUnfreezeExpireTime() <= nowTimestamp) + .mapToLong(Protocol.Account.UnFreezeV2::getUnfreezeAmount) + .sum(); + if (expireUnfrozenBalance > 0) { + inheritorCapsule.setBalance(inheritorCapsule.getBalance() + expireUnfrozenBalance); + increaseNonce(); + addInternalTx(null, ownerAddr, inheritorAddr, expireUnfrozenBalance, null, + "withdrawExpireUnfreezeWhileSuiciding", nonce, null); + } + clearOwnerFreezeV2(ownerCapsule); + repo.updateAccount(ownerCapsule.createDbKey(), ownerCapsule); + repo.updateAccount(inheritorCapsule.createDbKey(), inheritorCapsule); + return expireUnfrozenBalance; + } + + private void clearOwnerFreezeV2(AccountCapsule ownerCapsule) { + ownerCapsule.clearFrozenV2(); + ownerCapsule.setNetUsage(0); + ownerCapsule.setNewWindowSize(BANDWIDTH, 0); + ownerCapsule.setEnergyUsage(0); + ownerCapsule.setNewWindowSize(ENERGY, 0); + ownerCapsule.clearUnfrozenV2(); + } + private void withdrawRewardAndCancelVote(byte[] owner, Repository repo) { VoteRewardUtil.withdrawReward(owner, repo); @@ -488,13 +631,14 @@ private void withdrawRewardAndCancelVote(byte[] owner, Repository repo) { votesCapsule.clearNewVotes(); } ownerCapsule.clearVotes(); + ownerCapsule.setOldTronPower(0); repo.updateVotes(owner, votesCapsule); } try { long balance = ownerCapsule.getBalance(); long allowance = ownerCapsule.getAllowance(); ownerCapsule.setInstance(ownerCapsule.getInstance().toBuilder() - .setBalance(Math.addExact(balance, allowance)) + .setBalance(addExact(balance, allowance, VMConfig.disableJavaLangMath())) .setAllowance(0) .setLatestWithdrawTime(getTimestamp().longValue() * 1000) .build()); @@ -507,9 +651,13 @@ private void withdrawRewardAndCancelVote(byte[] owner, Repository repo) { public boolean canSuicide() { byte[] owner = getContextAddress(); AccountCapsule accountCapsule = getContractState().getAccount(owner); - return !VMConfig.allowTvmFreeze() + + boolean freezeCheck = !VMConfig.allowTvmFreeze() || (accountCapsule.getDelegatedFrozenBalanceForBandwidth() == 0 && accountCapsule.getDelegatedFrozenBalanceForEnergy() == 0); + + boolean freezeV2Check = freezeV2Check(accountCapsule); + return freezeCheck && freezeV2Check; // boolean voteCheck = !VMConfig.allowTvmVote() // || (accountCapsule.getVotesList().size() == 0 // && VoteRewardUtil.queryReward(owner, getContractState()) == 0 @@ -518,6 +666,24 @@ public boolean canSuicide() { // return freezeCheck && voteCheck; } + private boolean freezeV2Check(AccountCapsule accountCapsule) { + if (!VMConfig.allowTvmFreezeV2()) { + return true; + } + long now = getContractState().getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + + boolean isDelegatedResourceEmpty = + accountCapsule.getDelegatedFrozenV2BalanceForBandwidth() == 0 + && accountCapsule.getDelegatedFrozenV2BalanceForEnergy() == 0; + boolean isUnFrozenV2ListEmpty = + CollectionUtils.isEmpty( + accountCapsule.getUnfrozenV2List().stream() + .filter(unFreezeV2 -> unFreezeV2.getUnfreezeExpireTime() > now) + .collect(Collectors.toList())); + + return isDelegatedResourceEmpty && isUnFrozenV2ListEmpty; + } + @SuppressWarnings("ThrowableResultOfMethodCallIgnored") public void createContract(DataWord value, DataWord memStart, DataWord memSize) { returnDataBuffer = null; // reset return buffer right before the call @@ -635,12 +801,12 @@ this, new DataWord(newAddress), getContractAddress(), value, DataWord.ZERO(), "Trying to create a contract with existing contract address: 0x" + Hex .toHexString(newAddress))); } else if (isNotEmpty(programCode)) { - Program program = new Program(programCode, programInvoke, internalTx); + Program program = new Program(programCode, newAddress, programInvoke, internalTx); program.setRootTransactionId(this.rootTransactionId); if (VMConfig.allowTvmCompatibleEvm()) { program.setContractVersion(getContractVersion()); } - VM.play(program, OperationRegistry.getTable(OperationRegistry.Version.TRON_V1)); + VM.play(program, OperationRegistry.getTable()); createResult = program.getResult(); getTrace().merge(program.getTrace()); // always commit nonce @@ -866,13 +1032,13 @@ this, new DataWord(contextAddress), if (isConstantCall()) { programInvoke.setConstantCall(); } - Program program = new Program(programCode, programInvoke, internalTx); + Program program = new Program(programCode, codeAddress, programInvoke, internalTx); program.setRootTransactionId(this.rootTransactionId); if (VMConfig.allowTvmCompatibleEvm()) { program.setContractVersion(invoke.getDeposit() .getContract(codeAddress).getContractVersion()); } - VM.play(program, OperationRegistry.getTable(OperationRegistry.Version.TRON_V1)); + VM.play(program, OperationRegistry.getTable()); callResult = program.getResult(); getTrace().merge(program.getTrace()); @@ -954,6 +1120,16 @@ public void spendEnergy(long energyValue, String opName) { getResult().spendEnergy(energyValue); } + public void spendEnergyWithPenalty(long total, long penalty, String opName) { + if (getEnergylimitLeftLong() < total) { + throw new OutOfEnergyException( + "Not enough energy for '%s' operation executing: curInvokeEnergyLimit[%d]," + + " curOpEnergy[%d], penaltyEnergy[%d], usedEnergy[%d]", + opName, invoke.getEnergyLimit(), total - penalty, penalty, getResult().getEnergyUsed()); + } + getResult().spendEnergyWithPenalty(total, penalty); + } + public void checkCPUTimeLimit(String opName) { if (CommonParameter.getInstance().isDebug()) { @@ -1032,6 +1208,24 @@ public byte[] getCodeHashAt(DataWord address) { } } + public byte[] getCodeHash() { + ContractCapsule contract = getContractState().getContract(codeAddress); + byte[] codeHash; + if (contract == null) { + codeHash = Hash.sha3(ops); + } else { + codeHash = contract.getCodeHash(); + if (ByteUtil.isNullOrZeroArray(codeHash)) { + codeHash = Hash.sha3(ops); + } + } + return codeHash; + } + + private Key getJumpDestAnalysisCacheKey() { + return Key.create(ByteUtil.merge(codeAddress, getCodeHash())); + } + public byte[] getContextAddress() { return invoke.getContractAddress().toTronAddress(); } @@ -1042,7 +1236,8 @@ public DataWord getContractAddress() { public DataWord getBlockHash(int index) { if (index < this.getNumber().longValue() - && index >= Math.max(256, this.getNumber().longValue()) - 256) { + && index >= max(256, this.getNumber().longValue(), + VMConfig.disableJavaLangMath()) - 256) { BlockCapsule blockCapsule = contractState.getBlockByNum(index); @@ -1087,7 +1282,7 @@ public DataWord getCallerAddress() { public DataWord getChainId() { byte[] chainId = getContractState().getBlockByNum(0).getBlockId().getBytes(); - if (VMConfig.allowTvmCompatibleEvm()) { + if (VMConfig.allowTvmCompatibleEvm() || VMConfig.allowOptimizedReturnValueOfChainId()) { chainId = Arrays.copyOfRange(chainId, chainId.length - 4, chainId.length); } return new DataWord(chainId).clone(); @@ -1355,7 +1550,6 @@ public void callToPrecompiledAddress(MessageCall msg, return; } - Repository deposit = getContractState().newRepositoryChild(); byte[] senderAddress = getContextAddress(); @@ -1625,9 +1819,9 @@ public boolean freeze(DataWord receiverAddress, DataWord frozenBalance, DataWord repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM Freeze: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM Freeze: validate failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM Freeze: frozenBalance out of long range."); + logger.warn("TVM Freeze: frozenBalance out of long range."); } if (internalTx != null) { internalTx.reject(); @@ -1658,7 +1852,7 @@ public boolean unfreeze(DataWord receiverAddress, DataWord resourceType) { } return true; } catch (ContractValidateException e) { - logger.error("TVM Unfreeze: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM Unfreeze: validate failure. Reason: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -1700,14 +1894,241 @@ public long freezeExpireTime(DataWord targetAddress, DataWord resourceType) { return 0; } + public boolean freezeBalanceV2(DataWord frozenBalance, DataWord resourceType) { + Repository repository = getContractState().newRepositoryChild(); + byte[] owner = getContextAddress(); + + increaseNonce(); + InternalTransaction internalTx = addInternalTx(null, owner, owner, + frozenBalance.longValue(), null, + "freezeBalanceV2For" + convertResourceToString(resourceType), nonce, null); + + try { + FreezeBalanceV2Param param = new FreezeBalanceV2Param(); + param.setOwnerAddress(owner); + param.setResourceType(parseResourceCodeV2(resourceType)); + param.setFrozenBalance(frozenBalance.sValue().longValueExact()); + + FreezeBalanceV2Processor processor = new FreezeBalanceV2Processor(); + processor.validate(param, repository); + processor.execute(param, repository); + repository.commit(); + return true; + } catch (ContractValidateException e) { + logger.warn("TVM FreezeBalanceV2: validate failure. Reason: {}", e.getMessage()); + } catch (ArithmeticException e) { + logger.warn("TVM FreezeBalanceV2: frozenBalance out of long range."); + } + if (internalTx != null) { + internalTx.reject(); + } + return false; + } + + public boolean unfreezeBalanceV2(DataWord unfreezeBalance, DataWord resourceType) { + Repository repository = getContractState().newRepositoryChild(); + byte[] owner = getContextAddress(); + + increaseNonce(); + InternalTransaction internalTx = addInternalTx(null, owner, owner, + unfreezeBalance.longValue(), null, + "unfreezeBalanceV2For" + convertResourceToString(resourceType), nonce, null); + + try { + UnfreezeBalanceV2Param param = new UnfreezeBalanceV2Param(); + param.setOwnerAddress(owner); + param.setUnfreezeBalance(unfreezeBalance.sValue().longValueExact()); + param.setResourceType(parseResourceCodeV2(resourceType)); + + UnfreezeBalanceV2Processor processor = new UnfreezeBalanceV2Processor(); + processor.validate(param, repository); + long unfreezeExpireBalance = processor.execute(param, repository); + repository.commit(); + if (unfreezeExpireBalance > 0) { + increaseNonce(); + addInternalTx(null, owner, owner, unfreezeExpireBalance, null, + "withdrawExpireUnfreezeWhileUnfreezing", nonce, null); + } + return true; + } catch (ContractValidateException e) { + logger.warn("TVM UnfreezeBalanceV2: validate failure. Reason: {}", e.getMessage()); + } catch (ArithmeticException e) { + logger.warn("TVM UnfreezeBalanceV2: balance out of long range."); + } + if (internalTx != null) { + internalTx.reject(); + } + return false; + } + + public long withdrawExpireUnfreeze() { + Repository repository = getContractState().newRepositoryChild(); + byte[] owner = getContextAddress(); + + increaseNonce(); + InternalTransaction internalTx = addInternalTx(null, owner, owner, 0, null, + "withdrawExpireUnfreeze", nonce, null); + + try { + WithdrawExpireUnfreezeParam param = new WithdrawExpireUnfreezeParam(); + param.setOwnerAddress(owner); + + WithdrawExpireUnfreezeProcessor processor = new WithdrawExpireUnfreezeProcessor(); + processor.validate(param, repository); + long expireUnfreezeBalance = processor.execute(param, repository); + repository.commit(); + if (internalTx != null) { + internalTx.setValue(expireUnfreezeBalance); + } + return expireUnfreezeBalance; + } catch (ContractValidateException e) { + logger.warn("TVM WithdrawExpireUnfreeze: validate failure. Reason: {}", e.getMessage()); + } catch (ContractExeException e) { + logger.warn("TVM WithdrawExpireUnfreeze: execute failure. Reason: {}", e.getMessage()); + } + if (internalTx != null) { + internalTx.reject(); + } + return 0; + } + + public boolean cancelAllUnfreezeV2Action() { + Repository repository = getContractState().newRepositoryChild(); + byte[] owner = getContextAddress(); + + increaseNonce(); + InternalTransaction internalTx = addInternalTx(null, owner, owner, 0, null, + "cancelAllUnfreezeV2", nonce, null); + + try { + CancelAllUnfreezeV2Param param = new CancelAllUnfreezeV2Param(); + param.setOwnerAddress(owner); + + CancelAllUnfreezeV2Processor processor = new CancelAllUnfreezeV2Processor(); + processor.validate(param, repository); + Map result = processor.execute(param, repository); + repository.commit(); + + if (result.get(VMConstant.WITHDRAW_EXPIRE_BALANCE) > 0) { + increaseNonce(); + addInternalTx(null, owner, owner, result.get(VMConstant.WITHDRAW_EXPIRE_BALANCE), null, + "withdrawExpireUnfreezeWhileCanceling", nonce, null); + } + + if (internalTx != null && CommonParameter.getInstance().saveCancelAllUnfreezeV2Details) { + internalTx.setExtra(String.format("{\"%s\":%d,\"%s\":%d,\"%s\":%d}", + BANDWIDTH.name(), result.getOrDefault(BANDWIDTH.name(), 0L), + ENERGY.name(), result.getOrDefault(ENERGY.name(), 0L), + TRON_POWER.name(), result.getOrDefault(TRON_POWER.name(), 0L))); + } + + return true; + } catch (ContractValidateException e) { + logger.warn("TVM CancelAllUnfreezeV2: validate failure. Reason: {}", e.getMessage()); + } catch (ContractExeException e) { + logger.warn("TVM CancelAllUnfreezeV2: execute failure. Reason: {}", e.getMessage()); + } + if (internalTx != null) { + internalTx.reject(); + } + return false; + } + + public boolean delegateResource( + DataWord receiverAddress, DataWord delegateBalance, DataWord resourceType) { + Repository repository = getContractState().newRepositoryChild(); + byte[] owner = getContextAddress(); + byte[] receiver = receiverAddress.toTronAddress(); + + increaseNonce(); + InternalTransaction internalTx = addInternalTx(null, owner, receiver, + delegateBalance.longValue(), null, + "delegateResourceOf" + convertResourceToString(resourceType), nonce, null); + + try { + DelegateResourceParam param = new DelegateResourceParam(); + param.setOwnerAddress(owner); + param.setReceiverAddress(receiver); + param.setDelegateBalance(delegateBalance.sValue().longValueExact()); + param.setResourceType(parseResourceCodeV2(resourceType)); + + DelegateResourceProcessor processor = new DelegateResourceProcessor(); + processor.validate(param, repository); + processor.execute(param, repository); + repository.commit(); + return true; + } catch (ContractValidateException e) { + logger.warn("TVM DelegateResource: validate failure. Reason: {}", e.getMessage()); + } catch (ArithmeticException e) { + logger.warn("TVM DelegateResource: balance out of long range."); + } + if (internalTx != null) { + internalTx.reject(); + } + return false; + } + + public boolean unDelegateResource( + DataWord receiverAddress, DataWord unDelegateBalance, DataWord resourceType) { + Repository repository = getContractState().newRepositoryChild(); + byte[] owner = getContextAddress(); + byte[] receiver = receiverAddress.toTronAddress(); + + increaseNonce(); + InternalTransaction internalTx = addInternalTx(null, owner, receiver, + unDelegateBalance.longValue(), null, + "unDelegateResourceOf" + convertResourceToString(resourceType), nonce, null); + + try { + UnDelegateResourceParam param = new UnDelegateResourceParam(); + param.setOwnerAddress(owner); + param.setReceiverAddress(receiver); + param.setUnDelegateBalance(unDelegateBalance.sValue().longValueExact()); + param.setResourceType(parseResourceCodeV2(resourceType)); + + UnDelegateResourceProcessor processor = new UnDelegateResourceProcessor(); + processor.validate(param, repository); + processor.execute(param, repository); + repository.commit(); + return true; + } catch (ContractValidateException e) { + logger.warn("TVM UnDelegateResource: validate failure. Reason: {}", e.getMessage()); + } catch (ArithmeticException e) { + logger.warn("TVM UnDelegateResource: balance out of long range."); + } + if (internalTx != null) { + internalTx.reject(); + } + return false; + } + private Common.ResourceCode parseResourceCode(DataWord resourceType) { switch (resourceType.intValue()) { case 0: - return Common.ResourceCode.BANDWIDTH; + return BANDWIDTH; case 1: - return Common.ResourceCode.ENERGY; + return ENERGY; default: - return Common.ResourceCode.UNRECOGNIZED; + return UNRECOGNIZED; + } + } + + private Common.ResourceCode parseResourceCodeV2(DataWord resourceType) { + try { + byte type = resourceType.sValue().byteValueExact(); + switch (type) { + case 0: + return BANDWIDTH; + case 1: + return ENERGY; + case 2: + return TRON_POWER; + default: + return UNRECOGNIZED; + } + } catch (ArithmeticException e) { + logger.warn("TVM ParseResourceCodeV2: invalid resource code: {}", resourceType.sValue()); + return Common.ResourceCode.UNRECOGNIZED; } } @@ -1717,6 +2138,8 @@ private String convertResourceToString(DataWord resourceType) { return "Bandwidth"; case 1: return "Energy"; + case 2: + return "TronPower"; default: return "UnknownType"; } @@ -1747,11 +2170,12 @@ public boolean voteWitness(int witnessArrayOffset, int witnessArrayLength, try { VoteWitnessParam param = new VoteWitnessParam(); param.setVoterAddress(owner); - - byte[] witnessArrayData = memoryChunk(Math.addExact(witnessArrayOffset, DataWord.WORD_SIZE), - Math.multiplyExact(witnessArrayLength, DataWord.WORD_SIZE)); - byte[] amountArrayData = memoryChunk(Math.addExact(amountArrayOffset, DataWord.WORD_SIZE), - Math.multiplyExact(amountArrayLength, DataWord.WORD_SIZE)); + byte[] witnessArrayData = memoryChunk( + addExact(witnessArrayOffset, DataWord.WORD_SIZE, VMConfig.disableJavaLangMath()), + multiplyExact(witnessArrayLength, DataWord.WORD_SIZE, VMConfig.disableJavaLangMath())); + byte[] amountArrayData = memoryChunk( + addExact(amountArrayOffset, DataWord.WORD_SIZE, VMConfig.disableJavaLangMath()), + multiplyExact(amountArrayLength, DataWord.WORD_SIZE, VMConfig.disableJavaLangMath())); for (int i = 0; i < witnessArrayLength; i++) { DataWord witness = new DataWord(Arrays.copyOfRange(witnessArrayData, @@ -1770,11 +2194,11 @@ public boolean voteWitness(int witnessArrayOffset, int witnessArrayLength, repository.commit(); return true; } catch (ContractValidateException e) { - logger.error("TVM VoteWitness: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM VoteWitness: validate failure. Reason: {}", e.getMessage()); } catch (ContractExeException e) { - logger.error("TVM VoteWitness: execute failure. Reason: {}", e.getMessage()); + logger.warn("TVM VoteWitness: execute failure. Reason: {}", e.getMessage()); } catch (ArithmeticException e) { - logger.error("TVM VoteWitness: int or long out of range. caused by: {}", e.getMessage()); + logger.warn("TVM VoteWitness: int or long out of range. caused by: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -1803,9 +2227,9 @@ public long withdrawReward() { } return allowance; } catch (ContractValidateException e) { - logger.error("TVM WithdrawReward: validate failure. Reason: {}", e.getMessage()); + logger.warn("TVM WithdrawReward: validate failure. Reason: {}", e.getMessage()); } catch (ContractExeException e) { - logger.error("TVM WithdrawReward: execute failure. Reason: {}", e.getMessage()); + logger.warn("TVM WithdrawReward: execute failure. Reason: {}", e.getMessage()); } if (internalTx != null) { internalTx.reject(); @@ -1813,6 +2237,39 @@ public long withdrawReward() { return 0; } + public long updateContextContractFactor() { + ContractStateCapsule contractStateCapsule = + contractState.getContractState(getContextAddress()); + + if (contractStateCapsule == null) { + contractStateCapsule = new ContractStateCapsule( + contractState.getDynamicPropertiesStore().getCurrentCycleNumber()); + contractState.updateContractState(getContextAddress(), contractStateCapsule); + } else { + if (contractStateCapsule.catchUpToCycle( + contractState.getDynamicPropertiesStore().getCurrentCycleNumber(), + VMConfig.getDynamicEnergyThreshold(), + VMConfig.getDynamicEnergyIncreaseFactor(), + VMConfig.getDynamicEnergyMaxFactor(), + VMConfig.allowStrictMath(), + VMConfig.disableJavaLangMath())) { + contractState.updateContractState(getContextAddress(), contractStateCapsule + ); + } + } + contextContractFactor = contractStateCapsule.getEnergyFactor() + + Constant.DYNAMIC_ENERGY_FACTOR_DECIMAL; + return contextContractFactor; + } + + public void addContextContractUsage(long value) { + ContractStateCapsule contractStateCapsule = + contractState.getContractState(getContextAddress()); + + contractStateCapsule.addEnergyUsage(value); + contractState.updateContractState(getContextAddress(), contractStateCapsule); + } + /** * Denotes problem when executing Ethereum bytecode. From blockchain and peer perspective this is * quite normal situation and doesn't mean exceptional situation in terms of the program 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 7e21d187a37..572af048081 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 @@ -11,7 +11,6 @@ import org.tron.common.utils.ByteUtil; import org.tron.core.capsule.StorageRowCapsule; import org.tron.core.store.StorageRowStore; -import org.tron.core.vm.config.VMConfig; public class Storage { @@ -45,7 +44,7 @@ public Storage(Storage storage) { } private byte[] compose(byte[] key, byte[] addrHash) { - if (VMConfig.allowTvmCompatibleEvm() && contractVersion == 1) { + if (contractVersion == 1) { key = Hash.sha3(key); } byte[] result = new byte[key.length]; diff --git a/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java b/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java index 71fd484c7a3..567ac72931a 100644 --- a/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java +++ b/actuator/src/main/java/org/tron/core/vm/program/invoke/ProgramInvokeMockImpl.java @@ -8,6 +8,7 @@ import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.vm.DataWord; import org.tron.core.capsule.ContractCapsule; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; @@ -29,7 +30,6 @@ public ProgramInvokeMockImpl(byte[] msgDataRaw) { } public ProgramInvokeMockImpl() { - this.deposit = RepositoryImpl.createRoot(null); this.deposit.createAccount(ownerAddress, Protocol.AccountType.Normal); @@ -45,6 +45,21 @@ public ProgramInvokeMockImpl() { + "00603f556103e75660005460005360200235")); } + public ProgramInvokeMockImpl(byte[] op, byte[] opAddress) { + this(null, op, opAddress); + } + + public ProgramInvokeMockImpl(StoreFactory storeFactory, byte[] op, byte[] opAddress) { + this.deposit = RepositoryImpl.createRoot(storeFactory); + this.deposit.createAccount(opAddress, Protocol.AccountType.Normal); + + this.deposit.createAccount(opAddress, Protocol.AccountType.Contract); + this.deposit.createContract(opAddress, + new ContractCapsule(SmartContract.newBuilder().setContractAddress( + ByteString.copyFrom(op)).build())); + this.deposit.saveCode(opAddress, op); + } + public ProgramInvokeMockImpl(boolean defaults) { } @@ -195,6 +210,10 @@ public void setOwnerAddress(byte[] ownerAddress) { this.ownerAddress = Arrays.clone(ownerAddress); } + public void setStaticCall(boolean isStatic) { + isStaticCall = isStatic; + } + @Override public boolean isStaticCall() { return isStaticCall; diff --git a/actuator/src/main/java/org/tron/core/vm/repository/Key.java b/actuator/src/main/java/org/tron/core/vm/repository/Key.java index b23a22f7751..8639b55f4db 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/Key.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/Key.java @@ -10,10 +10,6 @@ public class Key { */ private byte[] data = new byte[0]; - /** - * - * @param data - */ public Key(byte[] data) { if (data != null && data.length != 0) { this.data = new byte[data.length]; @@ -21,36 +17,19 @@ public Key(byte[] data) { } } - /** - * - * @param key - */ private Key(Key key) { this.data = new byte[key.getData().length]; System.arraycopy(key.getData(), 0, this.data, 0, this.data.length); } - /** - * - * @param data - * @return - */ public static Key create(byte[] data) { return new Key(data); } - /** - * - * @return - */ public Key clone() { return new Key(this); } - /** - * - * @return - */ public byte[] getData() { return data; } 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 efbbdac1a05..664ee26ee92 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 @@ -1,5 +1,6 @@ package org.tron.core.vm.repository; +import org.apache.commons.lang3.tuple.Pair; import org.tron.common.runtime.vm.DataWord; import org.tron.core.capsule.*; import org.tron.core.store.*; @@ -38,14 +39,22 @@ public interface Repository { BytesCapsule getDelegation(Key key); + DelegatedResourceAccountIndexCapsule getDelegatedResourceAccountIndex(byte[] key); + + byte[] getTransientStorageValue(byte[] address, byte[] key); + void deleteContract(byte[] address); void createContract(byte[] address, ContractCapsule contractCapsule); ContractCapsule getContract(byte[] address); + ContractStateCapsule getContractState(byte[] address); + void updateContract(byte[] address, ContractCapsule contractCapsule); + void updateContractState(byte[] address, ContractStateCapsule contractStateCapsule); + void updateAccount(byte[] address, AccountCapsule accountCapsule); void updateDynamicProperty(byte[] word, BytesCapsule bytesCapsule); @@ -62,6 +71,10 @@ public interface Repository { void updateDelegation(byte[] word, BytesCapsule bytesCapsule); + void updateDelegatedResourceAccountIndex(byte[] word, DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule); + + void updateTransientStorageValue(byte[] address, byte[] key, byte[] value); + void saveCode(byte[] address, byte[] code); byte[] getCode(byte[] address); @@ -88,6 +101,8 @@ public interface Repository { void putContract(Key key, Value value); + void putContractState(Key key, Value value); + void putStorage(Key key, Storage cache); void putAccountValue(byte[] address, AccountCapsule accountCapsule); @@ -100,12 +115,22 @@ public interface Repository { void putDelegation(Key key, Value value); + void putDelegatedResourceAccountIndex(Key key, Value value); + + void putTransientStorageValue(Key address, Key key, Value value); + long addTokenBalance(byte[] address, byte[] tokenId, long value); long getTokenBalance(byte[] address, byte[] tokenId); long getAccountLeftEnergyFromFreeze(AccountCapsule accountCapsule); + long getAccountEnergyUsage(AccountCapsule accountCapsule); + + Pair getAccountEnergyUsageBalanceAndRestoreSeconds(AccountCapsule accountCapsule); + + Pair getAccountNetUsageBalanceAndRestoreSeconds(AccountCapsule accountCapsule); + long calculateGlobalEnergyLimit(AccountCapsule accountCapsule); byte[] getBlackHoleAddress(); @@ -120,12 +145,22 @@ public interface Repository { void addTotalEnergyWeight(long amount); + void addTotalTronPowerWeight(long amount); + void saveTotalNetWeight(long totalNetWeight); void saveTotalEnergyWeight(long totalEnergyWeight); + void saveTotalTronPowerWeight(long totalTronPowerWeight); + long getTotalNetWeight(); long getTotalEnergyWeight(); + long getTotalTronPowerWeight(); + + long getHeadSlot(); + + long getSlotByTimestampMs(long timestamp); + } 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 807f267b9db..a064cbf6c8a 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 @@ -1,13 +1,18 @@ package org.tron.core.vm.repository; -import static java.lang.Long.max; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.round; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import com.google.common.collect.HashBasedTable; import com.google.protobuf.ByteString; import java.util.HashMap; import java.util.Optional; import lombok.Getter; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.Hex; import org.tron.common.crypto.Hash; @@ -26,7 +31,10 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.CodeCapsule; import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.ContractStateCapsule; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.VotesCapsule; import org.tron.core.capsule.WitnessCapsule; @@ -43,7 +51,9 @@ import org.tron.core.store.AssetIssueStore; import org.tron.core.store.AssetIssueV2Store; import org.tron.core.store.CodeStore; +import org.tron.core.store.ContractStateStore; import org.tron.core.store.ContractStore; +import org.tron.core.store.DelegatedResourceAccountIndexStore; import org.tron.core.store.DelegatedResourceStore; import org.tron.core.store.DelegationStore; import org.tron.core.store.DynamicPropertiesStore; @@ -55,16 +65,23 @@ import org.tron.core.vm.program.Program.IllegalOperationException; import org.tron.core.vm.program.Storage; import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.DelegatedResource; +import org.tron.protos.Protocol.Votes; +import org.tron.protos.Protocol.DelegatedResourceAccountIndex; +import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; +import org.tron.protos.contract.Common; +import org.tron.protos.contract.SmartContractOuterClass.ContractState; +import org.tron.protos.contract.SmartContractOuterClass.SmartContract; @Slf4j(topic = "Repository") public class RepositoryImpl implements Repository { private final long precision = Parameter.ChainConstant.PRECISION; - private final long windowSize = Parameter.ChainConstant.WINDOW_SIZE_MS - / BLOCK_PRODUCED_INTERVAL; private static final byte[] TOTAL_NET_WEIGHT = "TOTAL_NET_WEIGHT".getBytes(); private static final byte[] TOTAL_ENERGY_WEIGHT = "TOTAL_ENERGY_WEIGHT".getBytes(); + private static final byte[] TOTAL_TRON_POWER_WEIGHT = "TOTAL_TRON_POWER_WEIGHT".getBytes(); private StoreFactory storeFactory; @Getter @@ -82,6 +99,8 @@ public class RepositoryImpl implements Repository { @Getter private ContractStore contractStore; @Getter + private ContractStateStore contractStateStore; + @Getter private StorageRowStore storageRowStore; @Getter private BlockStore blockStore; @@ -97,19 +116,28 @@ public class RepositoryImpl implements Repository { private VotesStore votesStore; @Getter private DelegationStore delegationStore; + @Getter + private DelegatedResourceAccountIndexStore delegatedResourceAccountIndexStore; private Repository parent = null; - private HashMap accountCache = new HashMap<>(); - private HashMap codeCache = new HashMap<>(); - private HashMap contractCache = new HashMap<>(); - private HashMap storageCache = new HashMap<>(); + private final HashMap> accountCache = new HashMap<>(); + private final HashMap> codeCache = new HashMap<>(); + private final HashMap> contractCache = new HashMap<>(); + private final HashMap> contractStateCache + = new HashMap<>(); + private final HashMap storageCache = new HashMap<>(); - private HashMap assetIssueCache = new HashMap<>(); - private HashMap dynamicPropertiesCache = new HashMap<>(); - private HashMap delegatedResourceCache = new HashMap<>(); - private HashMap votesCache = new HashMap<>(); - private HashMap delegationCache = new HashMap<>(); + private final HashMap> assetIssueCache = new HashMap<>(); + private final HashMap> dynamicPropertiesCache = new HashMap<>(); + private final HashMap> delegatedResourceCache = new HashMap<>(); + private final HashMap> votesCache = new HashMap<>(); + private final HashMap> delegationCache = new HashMap<>(); + private final HashMap> delegatedResourceAccountIndexCache = new HashMap<>(); + private final HashBasedTable> transientStorage = HashBasedTable.create(); + + public static void removeLruCache(byte[] address) { + } public RepositoryImpl(StoreFactory storeFactory, RepositoryImpl repository) { init(storeFactory, repository); @@ -128,6 +156,7 @@ protected void init(StoreFactory storeFactory, RepositoryImpl parent) { abiStore = manager.getAbiStore(); codeStore = manager.getCodeStore(); contractStore = manager.getContractStore(); + contractStateStore = manager.getContractStateStore(); assetIssueStore = manager.getAssetIssueStore(); assetIssueV2Store = manager.getAssetIssueV2Store(); storageRowStore = manager.getStorageRowStore(); @@ -138,6 +167,7 @@ protected void init(StoreFactory storeFactory, RepositoryImpl parent) { delegatedResourceStore = manager.getDelegatedResourceStore(); votesStore = manager.getVotesStore(); delegationStore = manager.getDelegationStore(); + delegatedResourceAccountIndexStore = manager.getDelegatedResourceAccountIndexStore(); } this.parent = parent; } @@ -155,9 +185,68 @@ public long getAccountLeftEnergyFromFreeze(AccountCapsule accountCapsule) { long latestConsumeTime = accountCapsule.getAccountResource().getLatestConsumeTimeForEnergy(); long energyLimit = calculateGlobalEnergyLimit(accountCapsule); - long newEnergyUsage = increase(energyUsage, 0, latestConsumeTime, now); + long windowSize = accountCapsule.getWindowSize(Common.ResourceCode.ENERGY); + + long newEnergyUsage = recover(energyUsage, latestConsumeTime, now, windowSize); + + return max(energyLimit - newEnergyUsage, 0, VMConfig.disableJavaLangMath()); // us + } + + @Override + public long getAccountEnergyUsage(AccountCapsule accountCapsule) { + long now = getHeadSlot(); + long energyUsage = accountCapsule.getEnergyUsage(); + long latestConsumeTime = accountCapsule.getAccountResource().getLatestConsumeTimeForEnergy(); + + long accountWindowSize = accountCapsule.getWindowSize(Common.ResourceCode.ENERGY); + + return recover(energyUsage, latestConsumeTime, now, accountWindowSize); + } + + public Pair getAccountEnergyUsageBalanceAndRestoreSeconds(AccountCapsule accountCapsule) { + long now = getHeadSlot(); + + long energyUsage = accountCapsule.getEnergyUsage(); + long latestConsumeTime = accountCapsule.getAccountResource().getLatestConsumeTimeForEnergy(); + long accountWindowSize = accountCapsule.getWindowSize(Common.ResourceCode.ENERGY); + + if (now >= latestConsumeTime + accountWindowSize) { + return Pair.of(0L, 0L); + } + + long restoreSlots = latestConsumeTime + accountWindowSize - now; + + long newEnergyUsage = recover(energyUsage, latestConsumeTime, now, accountWindowSize); + + long totalEnergyLimit = getDynamicPropertiesStore().getTotalEnergyCurrentLimit(); + long totalEnergyWeight = getTotalEnergyWeight(); + + long balance = (long) ((double) newEnergyUsage * totalEnergyWeight / totalEnergyLimit * TRX_PRECISION); + + return Pair.of(balance, restoreSlots * BLOCK_PRODUCED_INTERVAL / 1_000); + } + + public Pair getAccountNetUsageBalanceAndRestoreSeconds(AccountCapsule accountCapsule) { + long now = getHeadSlot(); + + long netUsage = accountCapsule.getNetUsage(); + long latestConsumeTime = accountCapsule.getLatestConsumeTime(); + long accountWindowSize = accountCapsule.getWindowSize(Common.ResourceCode.BANDWIDTH); + + if (now >= latestConsumeTime + accountWindowSize) { + return Pair.of(0L, 0L); + } + + long restoreSlots = latestConsumeTime + accountWindowSize - now; + + long newNetUsage = recover(netUsage, latestConsumeTime, now, accountWindowSize); + + long totalNetLimit = getDynamicPropertiesStore().getTotalNetLimit(); + long totalNetWeight = getTotalNetWeight(); + + long balance = (long) ((double) newNetUsage * totalNetWeight / totalNetLimit * TRX_PRECISION); - return max(energyLimit - newEnergyUsage, 0); // us + return Pair.of(balance, restoreSlots * BLOCK_PRODUCED_INTERVAL / 1_000); } @Override @@ -165,7 +254,7 @@ public AssetIssueCapsule getAssetIssue(byte[] tokenId) { byte[] tokenIdWithoutLeadingZero = ByteUtil.stripLeadingZeroes(tokenId); Key key = Key.create(tokenIdWithoutLeadingZero); if (assetIssueCache.containsKey(key)) { - return assetIssueCache.get(key).getAssetIssue(); + return new AssetIssueCapsule(assetIssueCache.get(key).getValue()); } AssetIssueCapsule assetIssueCapsule; @@ -177,7 +266,7 @@ public AssetIssueCapsule getAssetIssue(byte[] tokenId) { .get(tokenIdWithoutLeadingZero); } if (assetIssueCapsule != null) { - assetIssueCache.put(key, Value.create(assetIssueCapsule.getData())); + assetIssueCache.put(key, Value.create(assetIssueCapsule)); } return assetIssueCapsule; } @@ -186,7 +275,7 @@ public AssetIssueCapsule getAssetIssue(byte[] tokenId) { public AccountCapsule createAccount(byte[] address, Protocol.AccountType type) { Key key = new Key(address); AccountCapsule account = new AccountCapsule(ByteString.copyFrom(address), type); - accountCache.put(key, new Value(account.getData(), Type.VALUE_TYPE_CREATE)); + accountCache.put(key, Value.create(account, Type.CREATE)); return account; } @@ -197,8 +286,7 @@ public AccountCapsule createAccount(byte[] address, String accountName, AccountCapsule account = new AccountCapsule(ByteString.copyFrom(address), ByteString.copyFromUtf8(accountName), type); - - accountCache.put(key, new Value(account.getData(), Type.VALUE_TYPE_CREATE)); + accountCache.put(key, Value.create(account, Type.CREATE)); return account; } @@ -206,7 +294,7 @@ public AccountCapsule createAccount(byte[] address, String accountName, public AccountCapsule getAccount(byte[] address) { Key key = new Key(address); if (accountCache.containsKey(key)) { - return accountCache.get(key).getAccount(); + return new AccountCapsule(accountCache.get(key).getValue()); } AccountCapsule accountCapsule; @@ -217,7 +305,7 @@ public AccountCapsule getAccount(byte[] address) { } if (accountCapsule != null) { - accountCache.put(key, Value.create(accountCapsule.getData())); + accountCache.put(key, Value.create(accountCapsule)); } return accountCapsule; } @@ -226,7 +314,7 @@ public AccountCapsule getAccount(byte[] address) { public BytesCapsule getDynamicProperty(byte[] word) { Key key = Key.create(word); if (dynamicPropertiesCache.containsKey(key)) { - return dynamicPropertiesCache.get(key).getDynamicProperties(); + return new BytesCapsule(dynamicPropertiesCache.get(key).getValue()); } BytesCapsule bytesCapsule; @@ -251,7 +339,7 @@ public BytesCapsule getDynamicProperty(byte[] word) { public DelegatedResourceCapsule getDelegatedResource(byte[] key) { Key cacheKey = new Key(key); if (delegatedResourceCache.containsKey(cacheKey)) { - return delegatedResourceCache.get(cacheKey).getDelegatedResource(); + return new DelegatedResourceCapsule(delegatedResourceCache.get(cacheKey).getValue()); } DelegatedResourceCapsule delegatedResourceCapsule; @@ -262,7 +350,7 @@ public DelegatedResourceCapsule getDelegatedResource(byte[] key) { } if (delegatedResourceCapsule != null) { - delegatedResourceCache.put(cacheKey, Value.create(delegatedResourceCapsule.getData())); + delegatedResourceCache.put(cacheKey, Value.create(delegatedResourceCapsule)); } return delegatedResourceCapsule; } @@ -271,7 +359,7 @@ public DelegatedResourceCapsule getDelegatedResource(byte[] key) { public VotesCapsule getVotes(byte[] address) { Key cacheKey = new Key(address); if (votesCache.containsKey(cacheKey)) { - return votesCache.get(cacheKey).getVotes(); + return new VotesCapsule(votesCache.get(cacheKey).getValue()); } VotesCapsule votesCapsule; @@ -282,7 +370,7 @@ public VotesCapsule getVotes(byte[] address) { } if (votesCapsule != null) { - votesCache.put(cacheKey, Value.create(votesCapsule.getData())); + votesCache.put(cacheKey, Value.create(votesCapsule)); } return votesCapsule; } @@ -322,7 +410,7 @@ public AccountCapsule getAccountVote(long cycle, byte[] address) { @Override public BytesCapsule getDelegation(Key key) { if (delegationCache.containsKey(key)) { - return delegationCache.get(key).getBytes(); + return new BytesCapsule(delegationCache.get(key).getValue()); } BytesCapsule bytesCapsule; if (parent != null) { @@ -336,6 +424,49 @@ public BytesCapsule getDelegation(Key key) { return bytesCapsule; } + @Override + public DelegatedResourceAccountIndexCapsule getDelegatedResourceAccountIndex(byte[] key) { + Key cacheKey = new Key(key); + if (delegatedResourceAccountIndexCache.containsKey(cacheKey)) { + return new DelegatedResourceAccountIndexCapsule( + delegatedResourceAccountIndexCache.get(cacheKey).getValue()); + } + + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule; + if (parent != null) { + delegatedResourceAccountIndexCapsule = parent.getDelegatedResourceAccountIndex(key); + } else { + delegatedResourceAccountIndexCapsule = getDelegatedResourceAccountIndexStore().get(key); + } + + if (delegatedResourceAccountIndexCapsule != null) { + delegatedResourceAccountIndexCache.put( + cacheKey, Value.create(delegatedResourceAccountIndexCapsule)); + } + return delegatedResourceAccountIndexCapsule; + } + + public byte[] getTransientStorageValue(byte[] address, byte[] key) { + Key cacheAddress = new Key(address); + Key cacheKey = new Key(key); + if (transientStorage.contains(cacheAddress, cacheKey)) { + return transientStorage.get(cacheAddress, cacheKey).getValue(); + } + + byte[] value; + if (parent != null) { + value = parent.getTransientStorageValue(address, key); + } else { + value = null; + } + + if (value != null) { + transientStorage.put(cacheAddress, cacheKey, Value.create(value)); + } + + return value; + } + @Override public void deleteContract(byte[] address) { @@ -346,16 +477,15 @@ public void deleteContract(byte[] address) { @Override public void createContract(byte[] address, ContractCapsule contractCapsule) { - Key key = Key.create(address); - Value value = Value.create(contractCapsule.getData(), Type.VALUE_TYPE_CREATE); - contractCache.put(key, value); + contractCache.put(Key.create(address), + Value.create(contractCapsule, Type.CREATE)); } @Override public ContractCapsule getContract(byte[] address) { Key key = Key.create(address); if (contractCache.containsKey(key)) { - return contractCache.get(key).getContract(); + return new ContractCapsule(contractCache.get(key).getValue()); } ContractCapsule contractCapsule; @@ -366,50 +496,71 @@ public ContractCapsule getContract(byte[] address) { } if (contractCapsule != null) { - contractCache.put(key, Value.create(contractCapsule.getData())); + contractCache.put(key, Value.create(contractCapsule)); } return contractCapsule; } @Override - public void updateContract(byte[] address, ContractCapsule contractCapsule) { + public ContractStateCapsule getContractState(byte[] address) { Key key = Key.create(address); - Value value = Value.create(contractCapsule.getData(), Type.VALUE_TYPE_DIRTY); - contractCache.put(key, value); + if (contractStateCache.containsKey(key)) { + return new ContractStateCapsule(contractStateCache.get(key).getValue()); + } + + ContractStateCapsule contractStateCapsule; + if (parent != null) { + contractStateCapsule = parent.getContractState(address); + } else { + contractStateCapsule = getContractStateStore().get(address); + } + + if (contractStateCapsule != null) { + contractStateCache.put(key, Value.create(contractStateCapsule)); + } + return contractStateCapsule; + } + + @Override + public void updateContract(byte[] address, ContractCapsule contractCapsule) { + contractCache.put(Key.create(address), + Value.create(contractCapsule, Type.DIRTY)); + } + + @Override + public void updateContractState(byte[] address, ContractStateCapsule contractStateCapsule) { + contractStateCache.put(Key.create(address), + Value.create(contractStateCapsule, Type.DIRTY)); } @Override public void updateAccount(byte[] address, AccountCapsule accountCapsule) { - Key key = Key.create(address); - Value value = Value.create(accountCapsule.getData(), Type.VALUE_TYPE_DIRTY); - accountCache.put(key, value); + accountCache.put(Key.create(address), + Value.create(accountCapsule, Type.DIRTY)); } @Override public void updateDynamicProperty(byte[] word, BytesCapsule bytesCapsule) { - Key key = Key.create(word); - Value value = Value.create(bytesCapsule.getData(), Type.VALUE_TYPE_DIRTY); - dynamicPropertiesCache.put(key, value); + dynamicPropertiesCache.put(Key.create(word), + Value.create(bytesCapsule.getData(), Type.DIRTY)); } @Override - public void updateDelegatedResource(byte[] word, DelegatedResourceCapsule delegatedResourceCapsule) { - Key key = Key.create(word); - Value value = Value.create(delegatedResourceCapsule.getData(), Type.VALUE_TYPE_DIRTY); - delegatedResourceCache.put(key, value); + public void updateDelegatedResource(byte[] word, + DelegatedResourceCapsule delegatedResourceCapsule) { + delegatedResourceCache.put(Key.create(word), + Value.create(delegatedResourceCapsule, Type.DIRTY)); } @Override public void updateVotes(byte[] word, VotesCapsule votesCapsule) { - Key key = Key.create(word); - Value value = Value.create(votesCapsule.getData(), Type.VALUE_TYPE_DIRTY); - votesCache.put(key, value); + votesCache.put(Key.create(word), + Value.create(votesCapsule, Type.DIRTY)); } @Override public void updateBeginCycle(byte[] word, long cycle) { - BytesCapsule bytesCapsule = new BytesCapsule(ByteArray.fromLong(cycle)); - updateDelegation(word, bytesCapsule); + updateDelegation(word, new BytesCapsule(ByteArray.fromLong(cycle))); } @Override @@ -428,16 +579,25 @@ public void updateAccountVote(byte[] word, long cycle, AccountCapsule accountCap @Override public void updateDelegation(byte[] word, BytesCapsule bytesCapsule) { - Key key = Key.create(word); - Value value = Value.create(bytesCapsule.getData(), Type.VALUE_TYPE_DIRTY); - delegationCache.put(key, value); + delegationCache.put(Key.create(word), + Value.create(bytesCapsule.getData(), Type.DIRTY)); + } + + @Override + public void updateDelegatedResourceAccountIndex( + byte[] word, DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule) { + delegatedResourceAccountIndexCache.put( + Key.create(word), Value.create(delegatedResourceAccountIndexCapsule, Type.DIRTY)); + } + + @Override + public void updateTransientStorageValue(byte[] address, byte[] key, byte[] value) { + transientStorage.put(Key.create(address), Key.create(key), Value.create(value, Type.DIRTY)); } @Override public void saveCode(byte[] address, byte[] code) { - Key key = Key.create(address); - Value value = Value.create(code, Type.VALUE_TYPE_CREATE); - codeCache.put(key, value); + codeCache.put(Key.create(address), Value.create(code, Type.CREATE)); if (VMConfig.allowTvmConstantinople()) { ContractCapsule contract = getContract(address); @@ -451,7 +611,7 @@ public void saveCode(byte[] address, byte[] code) { public byte[] getCode(byte[] address) { Key key = Key.create(address); if (codeCache.containsKey(key)) { - return codeCache.get(key).getCode().getData(); + return codeCache.get(key).getValue(); } byte[] code; @@ -472,23 +632,19 @@ public byte[] getCode(byte[] address) { @Override public void putStorageValue(byte[] address, DataWord key, DataWord value) { - address = TransactionTrace.convertToTronAddress(address); - if (getAccount(address) == null) { - return; - } - Key addressKey = Key.create(address); - Storage storage; - if (storageCache.containsKey(addressKey)) { - storage = storageCache.get(addressKey); - } else { - storage = getStorage(address); - storageCache.put(addressKey, storage); + Storage storage = getStorageInternal(address); + if (storage != null) { + storage.put(key, value); } - storage.put(key, value); } @Override public DataWord getStorageValue(byte[] address, DataWord key) { + Storage storage = getStorageInternal(address); + return storage == null ? null : storage.getValue(key); + } + + private Storage getStorageInternal(byte[] address) { address = TransactionTrace.convertToTronAddress(address); if (getAccount(address) == null) { return null; @@ -501,7 +657,7 @@ public DataWord getStorageValue(byte[] address, DataWord key) { storage = getStorage(address); storageCache.put(addressKey, storage); } - return storage.getValue(key); + return storage; } @Override @@ -555,11 +711,10 @@ public long addBalance(byte[] address, long value) { StringUtil.createReadableString(accountCapsule.createDbKey()) + " insufficient balance"); } - accountCapsule.setBalance(Math.addExact(balance, value)); + accountCapsule.setBalance(addExact(balance, value, VMConfig.disableJavaLangMath())); Key key = Key.create(address); - Value val = Value.create(accountCapsule.getData(), - Type.VALUE_TYPE_DIRTY | accountCache.get(key).getType().getType()); - accountCache.put(key, val); + accountCache.put(key, Value.create(accountCapsule, + accountCache.get(key).getType().addType(Type.DIRTY))); return accountCapsule.getBalance(); } @@ -577,11 +732,14 @@ public void commit() { commitAccountCache(repository); commitCodeCache(repository); commitContractCache(repository); + commitContractStateCache(repository); commitStorageCache(repository); commitDynamicCache(repository); commitDelegatedResourceCache(repository); commitVotesCache(repository); commitDelegationCache(repository); + commitDelegatedResourceAccountIndexCache(repository); + commitTransientStorage(repository); } @Override @@ -599,6 +757,11 @@ public void putContract(Key key, Value value) { contractCache.put(key, value); } + @Override + public void putContractState(Key key, Value value) { + contractStateCache.put(key, value); + } + @Override public void putStorage(Key key, Storage cache) { storageCache.put(key, cache); @@ -606,8 +769,8 @@ public void putStorage(Key key, Storage cache) { @Override public void putAccountValue(byte[] address, AccountCapsule accountCapsule) { - Key key = new Key(address); - accountCache.put(key, new Value(accountCapsule.getData(), Type.VALUE_TYPE_CREATE)); + accountCache.put(new Key(address), + Value.create(accountCapsule, Type.CREATE)); } @Override @@ -630,6 +793,16 @@ public void putDelegation(Key key, Value value) { delegationCache.put(key, value); } + @Override + public void putDelegatedResourceAccountIndex(Key key, Value value) { + delegatedResourceAccountIndexCache.put(key, value); + } + + @Override + public void putTransientStorageValue(Key address, Key key, Value value) { + transientStorage.put(address, key, value); + } + @Override public long addTokenBalance(byte[] address, byte[] tokenId, long value) { byte[] tokenIdWithoutLeadingZero = ByteUtil.stripLeadingZeroes(tokenId); @@ -637,8 +810,7 @@ public long addTokenBalance(byte[] address, byte[] tokenId, long value) { if (accountCapsule == null) { accountCapsule = createAccount(address, Protocol.AccountType.Normal); } - long balance = accountCapsule.getAssetMapV2() - .getOrDefault(new String(tokenIdWithoutLeadingZero), new Long(0)); + long balance = accountCapsule.getAssetV2(new String(tokenIdWithoutLeadingZero)); if (value == 0) { return balance; } @@ -657,10 +829,9 @@ public long addTokenBalance(byte[] address, byte[] tokenId, long value) { getAssetIssueStore()); } Key key = Key.create(address); - Value V = Value.create(accountCapsule.getData(), - Type.VALUE_TYPE_DIRTY | accountCache.get(key).getType().getType()); - accountCache.put(key, V); - return accountCapsule.getAssetMapV2().get(new String(tokenIdWithoutLeadingZero)); + accountCache.put(key, Value.create(accountCapsule, + accountCache.get(key).getType().addType(Type.DIRTY))); + return accountCapsule.getAssetV2(new String(tokenIdWithoutLeadingZero)); } @Override @@ -670,7 +841,7 @@ public long getTokenBalance(byte[] address, byte[] tokenId) { return 0; } String tokenStr = new String(ByteUtil.stripLeadingZeroes(tokenId)); - return accountCapsule.getAssetMapV2().getOrDefault(tokenStr, 0L); + return accountCapsule.getAssetV2(tokenStr); } @Override @@ -692,8 +863,9 @@ public BlockCapsule getBlockByNum(long num) { } } - private long increase(long lastUsage, long usage, long lastTime, long now) { - return increase(lastUsage, usage, lastTime, now, windowSize); + // new recover method, use personal window size. + private long recover(long lastUsage, long lastTime, long now, long personalWindowSize) { + return increase(lastUsage, 0, lastTime, now, personalWindowSize); } private long increase(long lastUsage, long usage, long lastTime, long now, long windowSize) { @@ -705,7 +877,7 @@ private long increase(long lastUsage, long usage, long lastTime, long now, long if (lastTime + windowSize > now) { long delta = now - lastTime; double decay = (windowSize - delta) / (double) windowSize; - averageLastUsage = Math.round(averageLastUsage * decay); + averageLastUsage = round(averageLastUsage * decay, VMConfig.disableJavaLangMath()); } else { averageLastUsage = 0; } @@ -737,8 +909,11 @@ public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { } public long getHeadSlot() { - return (getDynamicPropertiesStore().getLatestBlockHeaderTimestamp() - - Long.parseLong(CommonParameter.getInstance() + return getSlotByTimestampMs(getDynamicPropertiesStore().getLatestBlockHeaderTimestamp()); + } + + public long getSlotByTimestampMs(long timestamp) { + return (timestamp - Long.parseLong(CommonParameter.getInstance() .getGenesisBlock().getTimestamp())) / BLOCK_PRODUCED_INTERVAL; } @@ -749,7 +924,7 @@ private void commitAccountCache(Repository deposit) { if (deposit != null) { deposit.putAccount(key, value); } else { - getAccountStore().put(key.getData(), value.getAccount()); + getAccountStore().put(key.getData(), new AccountCapsule(value.getValue())); } } }); @@ -761,7 +936,7 @@ private void commitCodeCache(Repository deposit) { if (deposit != null) { deposit.putCode(key, value); } else { - getCodeStore().put(key.getData(), value.getCode()); + getCodeStore().put(key.getData(), new CodeCapsule(value.getValue())); } } })); @@ -773,7 +948,7 @@ private void commitContractCache(Repository deposit) { if (deposit != null) { deposit.putContract(key, value); } else { - ContractCapsule contractCapsule = value.getContract(); + ContractCapsule contractCapsule = new ContractCapsule(value.getValue()); if (!abiStore.has(key.getData())) { abiStore.put(key.getData(), new AbiCapsule(contractCapsule)); } @@ -783,6 +958,19 @@ private void commitContractCache(Repository deposit) { })); } + private void commitContractStateCache(Repository deposit) { + contractStateCache.forEach(((key, value) -> { + if (value.getType().isDirty() || value.getType().isCreate()) { + if (deposit != null) { + deposit.putContractState(key, value); + } else { + ContractStateCapsule contractStateCapsule = new ContractStateCapsule(value.getValue()); + getContractStateStore().put(key.getData(), contractStateCapsule); + } + } + })); + } + private void commitStorageCache(Repository deposit) { storageCache.forEach((Key address, Storage storage) -> { if (deposit != null) { @@ -802,7 +990,7 @@ private void commitDynamicCache(Repository deposit) { if (deposit != null) { deposit.putDynamicProperty(key, value); } else { - getDynamicPropertiesStore().put(key.getData(), value.getDynamicProperties()); + getDynamicPropertiesStore().put(key.getData(), new BytesCapsule(value.getValue())); } } })); @@ -814,7 +1002,7 @@ private void commitDelegatedResourceCache(Repository deposit) { if (deposit != null) { deposit.putDelegatedResource(key, value); } else { - getDelegatedResourceStore().put(key.getData(), value.getDelegatedResource()); + getDelegatedResourceStore().put(key.getData(), new DelegatedResourceCapsule(value.getValue())); } } })); @@ -826,7 +1014,7 @@ private void commitVotesCache(Repository deposit) { if (deposit != null) { deposit.putVotes(key, value); } else { - getVotesStore().put(key.getData(), value.getVotes()); + getVotesStore().put(key.getData(), new VotesCapsule(value.getValue())); } } })); @@ -838,12 +1026,40 @@ private void commitDelegationCache(Repository deposit) { if (deposit != null) { deposit.putDelegation(key, value); } else { - getDelegationStore().put(key.getData(), value.getBytes()); + getDelegationStore().put(key.getData(), new BytesCapsule(value.getValue())); } } }); } + private void commitDelegatedResourceAccountIndexCache(Repository deposit) { + delegatedResourceAccountIndexCache.forEach(((key, value) -> { + if (value.getType().isDirty() || value.getType().isCreate()) { + if (deposit != null) { + deposit.putDelegatedResourceAccountIndex(key, value); + } else { + if (ByteUtil.isNullOrZeroArray(value.getValue().toByteArray())) { + getDelegatedResourceAccountIndexStore().delete(key.getData()); + } else { + getDelegatedResourceAccountIndexStore().put(key.getData(), + new DelegatedResourceAccountIndexCapsule(value.getValue())); + } + } + } + })); + } + + public void commitTransientStorage(Repository deposit) { + if (deposit != null) { + transientStorage.cellSet().forEach(cell -> { + if (cell.getValue().getType().isDirty() || cell.getValue().getType().isCreate()) { + deposit.putTransientStorageValue( + cell.getRowKey(), cell.getColumnKey(), cell.getValue()); + } + }); + } + } + /** * Get the block id from the number. */ @@ -860,7 +1076,7 @@ public AccountCapsule createNormalAccount(byte[] address) { getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(), withDefaultPermission, getDynamicPropertiesStore()); - accountCache.put(key, new Value(account.getData(), Type.VALUE_TYPE_CREATE)); + accountCache.put(key, Value.create(account, Type.CREATE)); return account; } @@ -880,6 +1096,13 @@ public void addTotalEnergyWeight(long amount) { saveTotalEnergyWeight(totalEnergyWeight); } + @Override + public void addTotalTronPowerWeight(long amount) { + long totalTronPowerWeight = getTotalTronPowerWeight(); + totalTronPowerWeight += amount; + saveTotalTronPowerWeight(totalTronPowerWeight); + } + @Override public void saveTotalNetWeight(long totalNetWeight) { updateDynamicProperty(TOTAL_NET_WEIGHT, @@ -892,6 +1115,12 @@ public void saveTotalEnergyWeight(long totalEnergyWeight) { new BytesCapsule(ByteArray.fromLong(totalEnergyWeight))); } + @Override + public void saveTotalTronPowerWeight(long totalTronPowerWeight) { + updateDynamicProperty(TOTAL_TRON_POWER_WEIGHT, + new BytesCapsule(ByteArray.fromLong(totalTronPowerWeight))); + } + @Override public long getTotalNetWeight() { return Optional.ofNullable(getDynamicProperty(TOTAL_NET_WEIGHT)) @@ -910,4 +1139,13 @@ public long getTotalEnergyWeight() { () -> new IllegalArgumentException("not found TOTAL_ENERGY_WEIGHT")); } + @Override + public long getTotalTronPowerWeight() { + return Optional.ofNullable(getDynamicProperty(TOTAL_TRON_POWER_WEIGHT)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found TOTAL_TRON_POWER_WEIGHT")); + } + } diff --git a/actuator/src/main/java/org/tron/core/vm/repository/Type.java b/actuator/src/main/java/org/tron/core/vm/repository/Type.java index 6e822b2e996..e0842e6a593 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/Type.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/Type.java @@ -1,110 +1,61 @@ package org.tron.core.vm.repository; -public class Type { +public class Type implements Cloneable { - /** - * Default Mode : VALUE_TYPE_NORMAL - */ - public static final int VALUE_TYPE_NORMAL = 0; - public static final int VALUE_TYPE_DIRTY = 1 << 0; - public static final int VALUE_TYPE_CREATE = 1 << 1; - public static final int VALUE_TYPE_UNKNOWN = 0xFFFFFFFC; + // Default Mode : NORMAL + public static final int NORMAL = 0; + public static final int DIRTY = 1; + public static final int CREATE = 1 << 1; + public static final int UNKNOWN = 0xFFFFFFFC; - protected int type = VALUE_TYPE_NORMAL; + protected int type = NORMAL; + + public Type() {} - /** - * @param type - */ public Type(int type) { this.type |= type; } - /** - * default constructor - */ - public Type() { - } - - /** - * @param T - */ - private Type(Type T) { - this.type = T.getType(); + private Type(Type t) { + this.type = t.type; } - /** - * @return - */ public Type clone() { return new Type(this); } - /** - * @return - */ public boolean isDirty() { - return (this.type & VALUE_TYPE_DIRTY) == VALUE_TYPE_DIRTY; + return (this.type & DIRTY) == DIRTY; } - /** - * @return - */ public boolean isNormal() { - return this.type == VALUE_TYPE_NORMAL; + return this.type == NORMAL; } - /** - * @return - */ public boolean isCreate() { - return (this.type & VALUE_TYPE_CREATE) == VALUE_TYPE_CREATE; + return (this.type & CREATE) == CREATE; } - /** - * @return - */ public boolean shouldCommit() { - return this.type != VALUE_TYPE_NORMAL; + return this.type != NORMAL; } - /** - * @return - */ - public int getType() { - return type; - } - - /** - * @param type - */ - public void setType(int type) { + public Type setType(int type) { if (isValidType(type)) { this.type = type; } + return this; } - /** - * @param type - * @return - */ public boolean isValidType(int type) { - return (type & VALUE_TYPE_UNKNOWN) == VALUE_TYPE_NORMAL; + return (type & UNKNOWN) == NORMAL; } - /** - * @param type - */ - public void addType(int type) { + public int addType(int type) { if (isValidType(type)) { this.type |= type; } - } - - /** - * @param T - */ - public void addType(Type T) { - addType(T.getType()); + return this.type; } @Override @@ -116,8 +67,8 @@ public boolean equals(Object obj) { return false; } - Type T = (Type) obj; - return this.type == T.getType(); + Type other = (Type) obj; + return this.type == other.type; } @Override @@ -127,8 +78,6 @@ public int hashCode() { @Override public String toString() { - return "Type{" + - "type=" + type + - '}'; + return "Type{" + "type=" + type + '}'; } } diff --git a/actuator/src/main/java/org/tron/core/vm/repository/Value.java b/actuator/src/main/java/org/tron/core/vm/repository/Value.java index 88ae1d1f7b7..bf5d99c9c94 100644 --- a/actuator/src/main/java/org/tron/core/vm/repository/Value.java +++ b/actuator/src/main/java/org/tron/core/vm/repository/Value.java @@ -1,240 +1,46 @@ package org.tron.core.vm.repository; import java.util.Arrays; -import org.apache.commons.lang3.ArrayUtils; -import org.tron.core.capsule.AccountCapsule; -import org.tron.core.capsule.AssetIssueCapsule; -import org.tron.core.capsule.BlockCapsule; -import org.tron.core.capsule.BytesCapsule; -import org.tron.core.capsule.CodeCapsule; -import org.tron.core.capsule.ContractCapsule; -import org.tron.core.capsule.DelegatedResourceCapsule; -import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.capsule.VotesCapsule; -import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.exception.BadItemException; +import java.util.Objects; + +import lombok.Getter; +import org.tron.core.capsule.ProtoCapsule; import org.tron.core.vm.config.VMConfig; -public class Value { +public class Value { + @Getter private Type type; - private byte[] any = null; - /** - * @param any - */ - public Value(byte[] any, Type type) { - if (any != null && any.length > 0) { - this.any = new byte[any.length]; - System.arraycopy(any, 0, this.any, 0, any.length); - this.type = type.clone(); - } - } + @Getter + private T value; - /** - * @param any - * @param type - */ - public Value(byte[] any, int type) { - if (any != null && any.length > 0) { - this.any = new byte[any.length]; - System.arraycopy(any, 0, this.any, 0, any.length); + private Value(T value, int type) { + if (value != null) { + this.value = value; this.type = new Type(type); } else { if (VMConfig.allowMultiSign()) { - this.type = new Type(Type.VALUE_TYPE_UNKNOWN); - } - } - } - - /** - * @param value - */ - private Value(Value value) { - if (value.getAny() != null && value.getAny().length > 0) { - this.any = new byte[value.any.length]; - System.arraycopy(value.getAny(), 0, this.any, 0, value.getAny().length); - this.type = value.getType().clone(); - } else { - if (VMConfig.allowMultiSign()) { - this.type = new Type(Type.VALUE_TYPE_UNKNOWN); + this.type = new Type(Type.UNKNOWN); } } } - public static Value create(byte[] any, int type) { - return new Value(any, type); - } - - public static Value create(byte[] any) { - return new Value(any, Type.VALUE_TYPE_NORMAL); - } - - /** - * @return - */ - public Value clone() { - return new Value(this); - } - - /** - * @return - */ - public byte[] getAny() { - return any; - } - - /** - * @return - */ - public Type getType() { - return type; - } - - /** - * @param type - */ - public void setType(Type type) { - this.type = type; - } - - /** - * @param type - */ - public void addType(Type type) { - this.type.addType(type); - } - - /** - * @param type - */ - public void addType(int type) { - this.type.addType(type); - } - - /** - * @return - */ - public AccountCapsule getAccount() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new AccountCapsule(any); - } - - /** - * @return - */ - public BytesCapsule getBytes() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new BytesCapsule(any); - } - - /** - * - */ - public TransactionCapsule getTransaction() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - try { - return new TransactionCapsule(any); - } catch (BadItemException e) { - return null; - } - } - - /** - * - */ - public BlockCapsule getBlock() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - try { - return new BlockCapsule(any); - } catch (Exception e) { - return null; - } - } - - /** - * @return - */ - public WitnessCapsule getWitness() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new WitnessCapsule(any); - - } - - public VotesCapsule getVotes() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new VotesCapsule(any); + public static Value create(ProtoCapsule capsule, int type) { + return new Value<>(capsule.getInstance(), type); } - /** - * @return - */ - public BytesCapsule getBlockIndex() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new BytesCapsule(any); + public static Value create(ProtoCapsule capsule) { + return create(capsule, Type.NORMAL); } - /** - * @return - */ - public CodeCapsule getCode() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new CodeCapsule(any); + public static Value create(byte[] value, int type) { + return (value == null || value.length ==0) ? new Value<>(null, type) : + new Value<>(Arrays.copyOf(value, value.length), type); } - /** - * @return - */ - public ContractCapsule getContract() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new ContractCapsule(any); - } - - public AssetIssueCapsule getAssetIssue() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new AssetIssueCapsule(any); - } - - public ProposalCapsule getProposal() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new ProposalCapsule(any); - } - - public BytesCapsule getDynamicProperties() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new BytesCapsule(any); - } - - public DelegatedResourceCapsule getDelegatedResource() { - if (ArrayUtils.isEmpty(any)) { - return null; - } - return new DelegatedResourceCapsule(any); + public static Value create(byte[] value) { + return create(value, Type.NORMAL); } @Override @@ -246,19 +52,12 @@ public boolean equals(Object obj) { return false; } - Value V = (Value) obj; - if (Arrays.equals(this.any, V.getAny())) { - return true; - } - return false; + Value other = (Value) obj; + return Objects.equals(this.getValue(), other.getValue()); } -// public static Value create(byte[] any, Type type) { -// return new Value(any, type); -// } - @Override public int hashCode() { - return new Integer(type.hashCode() + Arrays.hashCode(any)).hashCode(); + return new Integer(type.hashCode() + Objects.hashCode(value)).hashCode(); } } diff --git a/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java b/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java new file mode 100644 index 00000000000..762d9318e7b --- /dev/null +++ b/actuator/src/main/java/org/tron/core/vm/utils/FreezeV2Util.java @@ -0,0 +1,263 @@ +package org.tron.core.vm.utils; + +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.lang3.tuple.Triple; +import org.tron.core.actuator.UnfreezeBalanceV2Actuator; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.repository.Repository; +import org.tron.protos.Protocol; + +public class FreezeV2Util { + + private FreezeV2Util() { + } + + public static long queryExpireUnfreezeBalanceV2(byte[] address, long time, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return 0; + } + + AccountCapsule accountCapsule = repository.getAccount(address); + if (accountCapsule == null) { + return 0; + } + + List unfrozenV2List = + accountCapsule.getInstance().getUnfrozenV2List(); + + return getTotalWithdrawUnfreeze(unfrozenV2List, time); + } + + public static long queryUnfreezableBalanceV2(byte[] address, long type, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return 0; + } + + AccountCapsule accountCapsule = repository.getAccount(address); + if (accountCapsule == null) { + return 0; + } + + // BANDWIDTH + if (type == 0) { + return accountCapsule.getFrozenV2BalanceForBandwidth(); + } + + // ENERGY + if (type == 1) { + return accountCapsule.getFrozenV2BalanceForEnergy(); + } + + // POWER + if (type == 2) { + return accountCapsule.getTronPowerFrozenV2Balance(); + } + + return 0; + } + + // only freezeV2. + public static long queryResourceV2(byte[] from, byte[] to, long type, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return 0; + } + + byte[] key = DelegatedResourceCapsule.createDbKeyV2(from, to, false); + byte[] lockKey = DelegatedResourceCapsule.createDbKeyV2(from, to, true); + DelegatedResourceCapsule delegatedResource = repository.getDelegatedResource(key); + DelegatedResourceCapsule lockDelegateResource = repository.getDelegatedResource(lockKey); + if (delegatedResource == null && lockDelegateResource == null) { + return 0; + } + + long amount = 0; + // BANDWIDTH + if (type == 0) { + if (delegatedResource != null) { + amount += delegatedResource.getFrozenBalanceForBandwidth(); + } + if (lockDelegateResource != null) { + amount += lockDelegateResource.getFrozenBalanceForBandwidth(); + } + return amount; + } + + // ENERGY + if (type == 1) { + if (delegatedResource != null) { + amount += delegatedResource.getFrozenBalanceForEnergy(); + } + if (lockDelegateResource != null) { + amount += lockDelegateResource.getFrozenBalanceForEnergy(); + } + return amount; + } + + return 0; + } + + public static Pair queryFrozenBalanceUsage(byte[] address, long type, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return Pair.of(0L, 0L); + } + + AccountCapsule accountCapsule = repository.getAccount(address); + if (accountCapsule == null) { + return Pair.of(0L, 0L); + } + + if (type == 0) { + return repository.getAccountNetUsageBalanceAndRestoreSeconds(accountCapsule); + } else if (type == 1) { + return repository.getAccountEnergyUsageBalanceAndRestoreSeconds(accountCapsule); + } + + return Pair.of(0L, 0L); + } + + public static long queryAvailableUnfreezeV2Size(byte[] address, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return 0L; + } + + AccountCapsule accountCapsule = repository.getAccount(address); + if (accountCapsule == null) { + return 0L; + } + + long now = repository.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + int unfreezingV2Count = accountCapsule.getUnfreezingV2Count(now); + return max(UnfreezeBalanceV2Actuator.getUNFREEZE_MAX_TIMES() - unfreezingV2Count, 0L, + VMConfig.disableJavaLangMath()); + } + + public static long queryDelegatableResource(byte[] address, long type, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return 0L; + } + + AccountCapsule accountCapsule = repository.getAccount(address); + if (accountCapsule == null) { + return 0L; + } + + if (type == 0) { + // self frozenV2 resource + long frozenV2Resource = accountCapsule.getFrozenV2BalanceForBandwidth(); + + // total Usage. + Pair usagePair = + repository.getAccountNetUsageBalanceAndRestoreSeconds(accountCapsule); + if (usagePair == null || usagePair.getLeft() == null) { + return frozenV2Resource; + } + + long usage = usagePair.getLeft(); + if (usage <= 0) { + return frozenV2Resource; + } + + long v2NetUsage = getV2NetUsage(accountCapsule, usage, VMConfig.disableJavaLangMath()); + return max(0L, frozenV2Resource - v2NetUsage, VMConfig.disableJavaLangMath()); + } + + if (type == 1) { + // self frozenV2 resource + long frozenV2Resource = accountCapsule.getFrozenV2BalanceForEnergy(); + + // total Usage. + Pair usagePair = + repository.getAccountEnergyUsageBalanceAndRestoreSeconds(accountCapsule); + if (usagePair == null || usagePair.getLeft() == null) { + return frozenV2Resource; + } + + long usage = usagePair.getLeft(); + if (usage <= 0) { + return frozenV2Resource; + } + + long v2EnergyUsage = getV2EnergyUsage(accountCapsule, usage, VMConfig.disableJavaLangMath()); + return max(0L, frozenV2Resource - v2EnergyUsage, VMConfig.disableJavaLangMath()); + } + + return 0L; + } + + public static Triple checkUndelegateResource(byte[] address, long amount, long type, Repository repository) { + if (!VMConfig.allowTvmFreezeV2()) { + return Triple.of(0L, 0L, 0L); + } + + if (amount <= 0) { + return Triple.of(0L, 0L, 0L); + } + + AccountCapsule accountCapsule = repository.getAccount(address); + if (accountCapsule == null) { + return Triple.of(0L, 0L, 0L); + } + + Pair usagePair; + long resourceLimit; + if (type == 0) { + usagePair = repository.getAccountNetUsageBalanceAndRestoreSeconds(accountCapsule); + resourceLimit = accountCapsule.getAllFrozenBalanceForBandwidth(); + } else if (type == 1) { + usagePair = repository.getAccountEnergyUsageBalanceAndRestoreSeconds(accountCapsule); + resourceLimit = accountCapsule.getAllFrozenBalanceForEnergy(); + } else { + return Triple.of(0L, 0L, 0L); + } + + if (usagePair == null || usagePair.getLeft() == null || usagePair.getRight() == null) { + return Triple.of(0L, 0L, 0L); + } + + amount = min(amount, resourceLimit, VMConfig.disableJavaLangMath()); + if (resourceLimit <= usagePair.getLeft()) { + return Triple.of(0L, amount, usagePair.getRight()); + } + + long clean = (long) (amount * ((double) (resourceLimit - usagePair.getLeft()) / resourceLimit)); + + return Triple.of(clean, amount - clean, usagePair.getRight()); + } + + private static long getTotalWithdrawUnfreeze(List unfrozenV2List, long time) { + return getTotalWithdrawList(unfrozenV2List, time).stream() + .mapToLong(Protocol.Account.UnFreezeV2::getUnfreezeAmount).sum(); + } + + private static List getTotalWithdrawList(List unfrozenV2List, long now) { + return unfrozenV2List.stream().filter(unfrozenV2 -> unfrozenV2.getUnfreezeExpireTime() <= now) + .collect(Collectors.toList()); + } + + public static long getV2NetUsage(AccountCapsule ownerCapsule, long netUsage, boolean + disableJavaLangMath) { + long v2NetUsage= netUsage + - ownerCapsule.getFrozenBalance() + - ownerCapsule.getAcquiredDelegatedFrozenBalanceForBandwidth() + - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); + return max(0, v2NetUsage, disableJavaLangMath); + } + + public static long getV2EnergyUsage(AccountCapsule ownerCapsule, long energyUsage, boolean + disableJavaLangMath) { + long v2EnergyUsage= energyUsage + - ownerCapsule.getEnergyFrozenBalance() + - ownerCapsule.getAcquiredDelegatedFrozenBalanceForEnergy() + - ownerCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy(); + return max(0, v2EnergyUsage, disableJavaLangMath); + } + +} 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 7207126a785..c94f28b3a2f 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 @@ -1,8 +1,11 @@ package org.tron.core.vm.utils; +import org.tron.common.utils.ForkController; import org.tron.core.capsule.AccountCapsule; +import org.tron.core.config.Parameter; import org.tron.core.exception.ContractValidateException; import org.tron.core.vm.VMUtils; +import org.tron.core.vm.program.Program.OutOfTimeException; import org.tron.core.vm.repository.Repository; import org.tron.protos.Protocol; @@ -26,7 +29,7 @@ public static void transferAllToken(Repository deposit, byte[] fromAddress, byte AccountCapsule fromAccountCap = deposit.getAccount(fromAddress); Protocol.Account.Builder fromBuilder = fromAccountCap.getInstance().toBuilder(); AccountCapsule toAccountCap = deposit.getAccount(toAddress); - toAccountCap.importAsset(); + toAccountCap.importAllAsset(); Protocol.Account.Builder toBuilder = toAccountCap.getInstance().toBuilder(); fromAccountCap.getAssetMapV2().forEach((tokenId, amount) -> { toBuilder.putAssetV2(tokenId, toBuilder.getAssetV2Map().getOrDefault(tokenId, 0L) + amount); @@ -55,4 +58,10 @@ public static boolean isNullOrEmpty(String str) { public static boolean isNotNullOrEmpty(String str) { return !isNullOrEmpty(str); } + + public static void checkCPUTime() { + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_7_1)) { + throw new OutOfTimeException("CPU timeout for 0x0a executing"); + } + } } diff --git a/build.gradle b/build.gradle index 60ed31885e4..14b095b1795 100644 --- a/build.gradle +++ b/build.gradle @@ -1,76 +1,91 @@ -allprojects { - version = "1.0.0" - apply plugin: "java" -} - -subprojects { - apply plugin: "java" - apply plugin: "jacoco" - apply plugin: "maven" - apply plugin: "maven-publish" - - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - - [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' - - buildscript { - repositories { - mavenCentral() - jcenter() - maven { url 'https://jitpack.io/' } - } - dependencies { - classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.12' - classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0' - } - } - - repositories { - mavenLocal() - mavenCentral() - maven { url 'https://repo.spring.io/plugins-release' } - maven { url 'https://jitpack.io/' } - } - - dependencies { - compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' - compile group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25' - compile "org.slf4j:jcl-over-slf4j:1.7.25" - compile group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.9' - compileOnly 'org.projectlombok:lombok:1.18.12' - annotationProcessor 'org.projectlombok:lombok:1.18.12' - testCompileOnly 'org.projectlombok:lombok:1.18.12' - testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' - compile group: 'com.google.guava', name: 'guava', version: '24.1-jre' - compile "com.google.code.findbugs:jsr305:3.0.0" - compile group: 'org.springframework', name: 'spring-context', version: '4.2.4.RELEASE' - compile group: 'org.springframework', name: 'spring-tx', version: '4.2.4.RELEASE' - compile "org.apache.commons:commons-lang3:3.4" - compile group: 'org.apache.commons', name: 'commons-math', version: '2.2' - compile "org.apache.commons:commons-collections4:4.0" - compile group: 'joda-time', name: 'joda-time', version: '2.3' - - } - - task sourcesJar(type: Jar, dependsOn: classes) { - classifier = "sources" - from sourceSets.main.allSource - } - - - tasks.withType(AbstractArchiveTask) { - preserveFileTimestamps = false - reproducibleFileOrder = true - } -} - -task copyToParent(type: Copy) { - into "$buildDir/libs" - subprojects { - from tasks.withType(Jar) - } -} - -build.finalizedBy(copyToParent) - +allprojects { + version = "1.0.0" + apply plugin: "java-library" +} + +subprojects { + apply plugin: "jacoco" + apply plugin: "maven-publish" + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + [compileJava, compileTestJava]*.options*.encoding = 'UTF-8' + jacoco { + toolVersion = "0.8.12" // see https://www.jacoco.org/jacoco/trunk/doc/changes.html + } + + buildscript { + repositories { + mavenCentral() + maven { url 'https://jitpack.io/' } + maven { + url "https://plugins.gradle.org/m2/" + } + } + dependencies { + classpath 'com.google.protobuf:protobuf-gradle-plugin:0.9.1' + classpath "gradle.plugin.com.github.johnrengelman:shadow:7.1.2" + } + } + + repositories { + mavenLocal() + mavenCentral() + maven { url 'https://repo.spring.io/plugins-release' } + maven { url 'https://jitpack.io/' } + } + + dependencies { + implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.25' + implementation group: 'org.slf4j', name: 'jcl-over-slf4j', version: '1.7.25' + implementation group: 'ch.qos.logback', name: 'logback-classic', version: '1.2.13' + implementation "com.google.code.findbugs:jsr305:3.0.0" + implementation group: 'org.springframework', name: 'spring-context', version: '5.3.18' + implementation group: 'org.springframework', name: 'spring-tx', version: '5.3.18' + 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 group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' + + compileOnly 'org.projectlombok:lombok:1.18.12' + annotationProcessor 'org.projectlombok:lombok:1.18.12' + testCompileOnly 'org.projectlombok:lombok:1.18.12' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.12' + + testImplementation group: 'junit', name: 'junit', version: '4.13.2' + testImplementation "org.mockito:mockito-core:4.11.0" + testImplementation "org.mockito:mockito-inline:4.11.0" + } + + task sourcesJar(type: Jar, dependsOn: classes) { + classifier = "sources" + from sourceSets.main.allSource + duplicatesStrategy = DuplicatesStrategy.INCLUDE // allow duplicates + } + + + tasks.withType(AbstractArchiveTask) { + preserveFileTimestamps = false + reproducibleFileOrder = true + duplicatesStrategy = DuplicatesStrategy.INCLUDE // allow duplicates + } +} + +task copyToParent(type: Copy) { + into "$buildDir/libs" + subprojects { + from tasks.withType(Jar) + } +} + +build.finalizedBy(copyToParent) + +gradle.buildFinished { + if (project.hasProperty('cleanSubBuild')) { + subprojects { + buildDir.deleteDir() + } + } +} diff --git a/chainbase/build.gradle b/chainbase/build.gradle index 499ef014b32..bc82d9496c3 100644 --- a/chainbase/build.gradle +++ b/chainbase/build.gradle @@ -2,50 +2,16 @@ description = "chainbase – a decentralized database for blockchain." // Dependency versions // --------------------------------------- - -def junitVersion = "4.12" -def mockitoVersion = "2.1.0" -def testNgVersion = "6.11" -def jacocoVersion = "0.8.0" -def leveldbVersion = "1.8" def jansiVersion = "1.16" // -------------------------------------- -static def isWindows() { - return org.gradle.internal.os.OperatingSystem.current().isWindows() -} - -if (isWindows()) { - ext { - leveldbGroup = "org.ethereum" - leveldbName = "leveldbjni-all" - leveldbVersion = "1.18.3" - } -} else { - ext { - leveldbGroup = "org.fusesource.leveldbjni" - leveldbName = "leveldbjni-all" - leveldbVersion = "1.8" - } -} - dependencies { - testImplementation "junit:junit:$junitVersion" - testImplementation "org.mockito:mockito-core:$mockitoVersion" - - testImplementation "org.testng:testng:$testNgVersion" - - compile group: leveldbGroup, name: leveldbName, version: leveldbVersion - compile "org.fusesource.jansi:jansi:$jansiVersion" - compile group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' - compile group: 'com.typesafe', name: 'config', version: '1.3.2' - compile 'com.github.tronprotocol:zksnark-java-sdk:master-SNAPSHOT' - compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.10.3' - compile group: 'com.fasterxml.jackson.core', name: 'jackson-core', version: '2.8.5' - compile project(":protocol") - compile project(":common") - compile project(":crypto") - compile 'org.reflections:reflections:0.9.11' + api project(":protocol") + api project(":common") + api project(":crypto") + api "org.fusesource.jansi:jansi:$jansiVersion" + api 'io.github.tronprotocol:zksnark-java-sdk:1.0.0' + api 'org.reflections:reflections:0.9.11' } @@ -74,35 +40,13 @@ test { } } -task testng(type: Test) { - useTestNG() - testLogging { - events = ["skipped", "failed"] - exceptionFormat = "full" - - debug.events = ["skipped", "failed"] - debug.exceptionFormat = "full" - - info.events = ["failed", "skipped"] - info.exceptionFormat = "full" - - warn.events = ["failed", "skipped"] - warn.exceptionFormat = "full" - } -} - -check.dependsOn testng - -jacoco { - toolVersion = jacocoVersion // See http://www.eclemma.org/jacoco/. -} - jacocoTestReport { + dependsOn(processResources) // explicit_dependency reports { xml.enabled = true html.enabled = true } - executionData.from = '../framework/build/jacoco/jacocoTest.exec' + getExecutionData().setFrom(fileTree('../framework/build/jacoco').include("**.exec")) afterEvaluate { classDirectories.from = classDirectories.files.collect { fileTree(dir: it,) diff --git a/chainbase/src/main/java/org/tron/common/overlay/message/Message.java b/chainbase/src/main/java/org/tron/common/overlay/message/Message.java index 8c7381b7dcc..84c3f695686 100644 --- a/chainbase/src/main/java/org/tron/common/overlay/message/Message.java +++ b/chainbase/src/main/java/org/tron/common/overlay/message/Message.java @@ -21,8 +21,10 @@ public abstract class Message { protected static final Logger logger = LoggerFactory.getLogger("Message"); + // https://developers.google.com/protocol-buffers/docs/proto3#unknowns + // https://github.com/protocolbuffers/protobuf/issues/272 private static final Field field = ReflectionUtils - .findField(CodedInputStream.class, "explicitDiscardUnknownFields"); + .findField(CodedInputStream.class, "shouldDiscardUnknownFields"); @Setter private static DynamicPropertiesStore dynamicPropertiesStore; @@ -67,6 +69,10 @@ public ByteBuf getSendData() { return Unpooled.wrappedBuffer(ArrayUtils.add(this.getData(), 0, type)); } + public byte[] getSendBytes() { + return ArrayUtils.add(this.getData(), 0, type); + } + public Sha256Hash getMessageId() { return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), getData()); diff --git a/chainbase/src/main/java/org/tron/common/runtime/ProgramResult.java b/chainbase/src/main/java/org/tron/common/runtime/ProgramResult.java index 112b7f921af..04228d1316a 100644 --- a/chainbase/src/main/java/org/tron/common/runtime/ProgramResult.java +++ b/chainbase/src/main/java/org/tron/common/runtime/ProgramResult.java @@ -16,7 +16,6 @@ import org.tron.common.logsfilter.trigger.ContractTrigger; import org.tron.common.runtime.vm.DataWord; import org.tron.common.runtime.vm.LogInfo; -import org.tron.common.utils.ByteArraySet; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.protos.Protocol.Transaction.Result.contractResult; @@ -25,6 +24,9 @@ public class ProgramResult { private long energyUsed = 0; //private long futureRefund = 0; + @Getter + private long energyPenaltyTotal = 0; + private byte[] hReturn = EMPTY_BYTE_ARRAY; private byte[] contractAddress = EMPTY_BYTE_ARRAY; private RuntimeException exception; @@ -64,6 +66,11 @@ public void spendEnergy(long energy) { energyUsed += energy; } + public void spendEnergyWithPenalty(long total, long penalty) { + energyPenaltyTotal += penalty; + energyUsed += total; + } + public void setRevert() { this.revert = true; } @@ -76,6 +83,10 @@ public void refundEnergy(long energy) { energyUsed -= energy; } + public void addTotalPenalty(long penalty) { + energyPenaltyTotal += penalty; + } + public byte[] getContractAddress() { return Arrays.copyOf(contractAddress, contractAddress.length); } @@ -227,6 +238,7 @@ public void reset() { public void merge(ProgramResult another) { addInternalTransactions(another.getInternalTransactions()); + addTotalPenalty(another.getEnergyPenaltyTotal()); if (another.getException() == null && !another.isRevert()) { addDeleteAccounts(another.getDeleteAccounts()); addLogInfos(another.getLogInfoList()); diff --git a/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java b/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java index df75d0ecd68..506ecdcb6c7 100644 --- a/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java +++ b/chainbase/src/main/java/org/tron/common/storage/leveldb/LevelDbDataSourceImpl.java @@ -24,6 +24,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -33,37 +34,53 @@ import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.stream.StreamSupport; + +import com.google.common.primitives.Bytes; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.CompressionType; import org.iq80.leveldb.DB; import org.iq80.leveldb.DBIterator; +import org.iq80.leveldb.Logger; import org.iq80.leveldb.Options; import org.iq80.leveldb.ReadOptions; import org.iq80.leveldb.WriteBatch; import org.iq80.leveldb.WriteOptions; +import org.slf4j.LoggerFactory; import org.tron.common.parameter.CommonParameter; import org.tron.common.storage.WriteOptionsWrapper; +import org.tron.common.storage.metric.DbStat; import org.tron.common.utils.FileUtil; import org.tron.common.utils.StorageUtils; import org.tron.core.db.common.DbSourceInter; import org.tron.core.db.common.iterator.StoreIterator; import org.tron.core.db2.common.Instance; +import org.tron.core.db2.common.WrappedByteArray; +import org.tron.core.exception.TronError; @Slf4j(topic = "DB") @NoArgsConstructor -public class LevelDbDataSourceImpl implements DbSourceInter, - Iterable>, Instance { +public class LevelDbDataSourceImpl extends DbStat implements DbSourceInter, + Iterable>, Instance { private String dataBaseName; private DB database; - private boolean alive; + private volatile boolean alive; private String parentPath; private Options options; private WriteOptions writeOptions; private ReadWriteLock resetDbLock = new ReentrantReadWriteLock(); + private static final String LEVELDB = "LEVELDB"; + private static final org.slf4j.Logger innerLogger = LoggerFactory.getLogger(LEVELDB); + private Logger leveldbLogger = new Logger() { + @Override + public void log(String message) { + innerLogger.info("{} {}", dataBaseName, message); + } + }; /** * constructor. @@ -75,7 +92,7 @@ public LevelDbDataSourceImpl(String parentPath, String dataBaseName, Options opt CommonParameter.getInstance().getStorage().getDbDirectory() ).toString(); this.dataBaseName = dataBaseName; - this.options = options; + this.options = options.logger(leveldbLogger); this.writeOptions = writeOptions; initDB(); } @@ -87,7 +104,7 @@ public LevelDbDataSourceImpl(String parentPath, String dataBaseName) { ).toString(); this.dataBaseName = dataBaseName; - options = new Options(); + options = new Options().logger(leveldbLogger); writeOptions = new WriteOptions(); } @@ -95,22 +112,24 @@ public LevelDbDataSourceImpl(String parentPath, String dataBaseName) { public void initDB() { resetDbLock.writeLock().lock(); try { - logger.debug("~> LevelDbDataSourceImpl.initDB(): " + dataBaseName); + logger.debug("Init DB: {}.", dataBaseName); if (isAlive()) { return; } if (dataBaseName == null) { - throw new NullPointerException("no name set to the dbStore"); + throw new IllegalArgumentException("No name set to the dbStore"); } try { openDatabase(options); alive = true; } catch (IOException ioe) { - throw new RuntimeException("Can't initialize database", ioe); + throw new RuntimeException(String.format("Can't initialize database, %s", dataBaseName), + ioe); } + logger.debug("Init DB {} done.", dataBaseName); } finally { resetDbLock.writeLock().unlock(); } @@ -126,33 +145,23 @@ private void openDatabase(Options dbOptions) throws IOException { } try { database = factory.open(dbPath.toFile(), dbOptions); - logger.info("DB {} open success with : writeBufferSize {}M,cacheSize {}M,maxOpenFiles {}.", - this.getDBName(), dbOptions.writeBufferSize() / 1024 / 1024, - dbOptions.cacheSize() / 1024 / 1024, dbOptions.maxOpenFiles()); + if (!this.getDBName().startsWith("checkpoint")) { + logger + .info("DB {} open success with writeBufferSize {} M, cacheSize {} M, maxOpenFiles {}.", + this.getDBName(), dbOptions.writeBufferSize() / 1024 / 1024, + dbOptions.cacheSize() / 1024 / 1024, dbOptions.maxOpenFiles()); + } } catch (IOException e) { if (e.getMessage().contains("Corruption:")) { - factory.repair(dbPath.toFile(), dbOptions); - database = factory.open(dbPath.toFile(), dbOptions); + logger.error("Database {} corrupted, please delete database directory({}) and restart.", + dataBaseName, parentPath, e); } else { - throw e; + logger.error("Open Database {} failed", dataBaseName, e); } + throw new TronError(e, TronError.ErrCode.LEVELDB_INIT); } } - @Deprecated - private Options createDbOptions() { - Options dbOptions = new Options(); - dbOptions.createIfMissing(true); - dbOptions.compressionType(CompressionType.NONE); - dbOptions.blockSize(10 * 1024 * 1024); - dbOptions.writeBufferSize(10 * 1024 * 1024); - dbOptions.cacheSize(0); - dbOptions.paranoidChecks(true); - dbOptions.verifyChecksums(true); - dbOptions.maxOpenFiles(32); - return dbOptions; - } - public Path getDbPath() { return Paths.get(parentPath, dataBaseName); } @@ -161,34 +170,21 @@ public Path getDbPath() { * reset database. */ public void resetDb() { - closeDB(); - FileUtil.recursiveDelete(getDbPath().toString()); - initDB(); - } - - @Override - public boolean isAlive() { - return alive; - } - - /** - * destroy database. - */ - public void destroyDb(File fileLocation) { resetDbLock.writeLock().lock(); try { - logger.debug("Destroying existing database: " + fileLocation); - Options options = new Options(); - try { - factory.destroy(fileLocation, options); - } catch (IOException e) { - logger.error(e.getMessage(), e); - } + closeDB(); + FileUtil.recursiveDelete(getDbPath().toString()); + initDB(); } finally { resetDbLock.writeLock().unlock(); } } + @Override + public boolean isAlive() { + return alive; + } + @Override public String getDBName() { return dataBaseName; @@ -345,21 +341,18 @@ public Map getNext(byte[] key, long limit) { } } - public Set getValuesPrev(byte[] key, long limit) { - if (limit <= 0) { - return Sets.newHashSet(); - } + @Override + public Map prefixQuery(byte[] key) { resetDbLock.readLock().lock(); try (DBIterator iterator = getDBIterator()) { - Set result = Sets.newHashSet(); - long i = 0; - byte[] data = getData(key); - if (Objects.nonNull(data)) { - result.add(data); - i++; - } - for (iterator.seek(key); iterator.hasPrev() && i++ < limit; iterator.prev()) { - result.add(iterator.peekPrev().getValue()); + Map result = new HashMap<>(); + for (iterator.seek(key); iterator.hasNext(); iterator.next()) { + Entry entry = iterator.peekNext(); + if (Bytes.indexOf(entry.getKey(), key) == 0) { + result.put(WrappedByteArray.of(entry.getKey()), entry.getValue()); + } else { + return result; + } } return result; } catch (IOException e) { @@ -456,7 +449,7 @@ public void closeDB() { database.close(); alive = false; } catch (IOException e) { - logger.error("Failed to find the dbStore file on the closeDB: {} ", dataBaseName); + logger.error("Failed to find the dbStore file on the closeDB: {}.", dataBaseName, e); } finally { resetDbLock.writeLock().unlock(); } @@ -471,10 +464,6 @@ public Stream> stream() { return StreamSupport.stream(spliterator(), false); } - public Stream> parallelStream() { - return StreamSupport.stream(spliterator(), true); - } - @Override public LevelDbDataSourceImpl newInstance() { return new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(dataBaseName), @@ -486,4 +475,41 @@ private DBIterator getDBIterator() { return database.iterator(readOptions); } + + /** + * Compactions + * Level Files Size(MB) Time(sec) Read(MB) Write(MB) + * -------------------------------------------------- + * 1 2 2 0 0 2 + * 2 1 1 0 0 1 + */ + @Override + public List getStats() throws Exception { + resetDbLock.readLock().lock(); + try { + if (!isAlive()) { + return Collections.emptyList(); + } + String stat = database.getProperty("leveldb.stats"); + String[] stats = stat.split("\n"); + return Arrays.stream(stats).skip(3).collect(Collectors.toList()); + } finally { + resetDbLock.readLock().unlock(); + } + } + + @Override + public String getEngine() { + return LEVELDB; + } + + @Override + public String getName() { + return this.dataBaseName; + } + + @Override public void stat() { + this.statProperty(); + } + } diff --git a/chainbase/src/main/java/org/tron/common/storage/metric/DbStat.java b/chainbase/src/main/java/org/tron/common/storage/metric/DbStat.java new file mode 100644 index 00000000000..c7fecf2a351 --- /dev/null +++ b/chainbase/src/main/java/org/tron/common/storage/metric/DbStat.java @@ -0,0 +1,34 @@ +package org.tron.common.storage.metric; + +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.Metrics; + +@Slf4j(topic = "metrics") +public abstract class DbStat { + + protected void statProperty() { + try { + getStats().forEach(stat -> { + String[] tmp = stat.trim().replaceAll(" +", ",").split(","); + String level = tmp[0]; + double files = Double.parseDouble(tmp[1]); + double size = Double.parseDouble(tmp[2]) * 1048576.0; + Metrics.gaugeSet(MetricKeys.Gauge.DB_SST_LEVEL, files, getEngine(), getName(), level); + Metrics.gaugeSet(MetricKeys.Gauge.DB_SIZE_BYTES, size, getEngine(), getName(), level); + logger.info("DB {}, level:{},files:{},size:{} M", + getName(), level, files, size / 1048576.0); + }); + } catch (Exception e) { + logger.warn("DB {} stats error", getName(), e); + } + } + + public abstract List getStats() throws Exception; + + public abstract String getEngine(); + + public abstract String getName(); + +} diff --git a/chainbase/src/main/java/org/tron/common/storage/metric/DbStatService.java b/chainbase/src/main/java/org/tron/common/storage/metric/DbStatService.java new file mode 100644 index 00000000000..b6fa25d5901 --- /dev/null +++ b/chainbase/src/main/java/org/tron/common/storage/metric/DbStatService.java @@ -0,0 +1,36 @@ +package org.tron.common.storage.metric; + +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.tron.common.es.ExecutorServiceManager; +import org.tron.common.prometheus.Metrics; +import org.tron.core.db.common.DbSourceInter; +import org.tron.core.db2.common.DB; + +@Slf4j(topic = "metrics") +@Component +public class DbStatService { + private final String esName = "db-stats"; + private final ScheduledExecutorService statExecutor = + ExecutorServiceManager.newSingleThreadScheduledExecutor(esName); + + public void register(DB db) { + if (Metrics.enabled()) { + statExecutor.scheduleWithFixedDelay(db::stat, 0, 6, TimeUnit.HOURS); + } + } + + public void register(DbSourceInter db) { + if (Metrics.enabled()) { + statExecutor.scheduleWithFixedDelay(db::stat, 0, 6, TimeUnit.HOURS); + } + } + + public void shutdown() { + if (Metrics.enabled()) { + ExecutorServiceManager.shutdownAndAwaitTermination(statExecutor, esName); + } + } +} diff --git a/chainbase/src/main/java/org/tron/common/storage/rocksdb/RocksDbDataSourceImpl.java b/chainbase/src/main/java/org/tron/common/storage/rocksdb/RocksDbDataSourceImpl.java index eb85e624457..5c051bdc101 100644 --- a/chainbase/src/main/java/org/tron/common/storage/rocksdb/RocksDbDataSourceImpl.java +++ b/chainbase/src/main/java/org/tron/common/storage/rocksdb/RocksDbDataSourceImpl.java @@ -1,12 +1,14 @@ package org.tron.common.storage.rocksdb; import com.google.common.collect.Sets; +import com.google.common.primitives.Bytes; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; @@ -15,44 +17,52 @@ import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.stream.Collectors; import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.rocksdb.BlockBasedTableConfig; import org.rocksdb.BloomFilter; import org.rocksdb.Checkpoint; import org.rocksdb.DirectComparator; +import org.rocksdb.InfoLogLevel; +import org.rocksdb.Logger; import org.rocksdb.Options; import org.rocksdb.ReadOptions; import org.rocksdb.RocksDB; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; import org.rocksdb.Statistics; +import org.rocksdb.Status; import org.rocksdb.WriteBatch; import org.rocksdb.WriteOptions; +import org.slf4j.LoggerFactory; import org.tron.common.setting.RocksDbSettings; import org.tron.common.storage.WriteOptionsWrapper; +import org.tron.common.storage.metric.DbStat; import org.tron.common.utils.FileUtil; import org.tron.common.utils.PropUtil; import org.tron.core.db.common.DbSourceInter; import org.tron.core.db.common.iterator.RockStoreIterator; import org.tron.core.db2.common.Instance; +import org.tron.core.db2.common.WrappedByteArray; +import org.tron.core.exception.TronError; -@Slf4j +@Slf4j(topic = "DB") @NoArgsConstructor -public class RocksDbDataSourceImpl implements DbSourceInter, +public class RocksDbDataSourceImpl extends DbStat implements DbSourceInter, Iterable>, Instance { ReadOptions readOpts; - private static final String FAIL_TO_INIT_DATABASE = "Failed to initialize database"; private String dataBaseName; private RocksDB database; - private boolean alive; + private volatile boolean alive; private String parentPath; private ReadWriteLock resetDbLock = new ReentrantReadWriteLock(); private static final String KEY_ENGINE = "ENGINE"; private static final String ROCKSDB = "ROCKSDB"; private DirectComparator comparator; + private static final org.slf4j.Logger rocksDbLogger = LoggerFactory.getLogger(ROCKSDB); public RocksDbDataSourceImpl(String parentPath, String name, RocksDbSettings settings, DirectComparator comparator) { @@ -97,6 +107,7 @@ public void closeDB() { database.close(); alive = false; } catch (Exception e) { + logger.error("Failed to find the dbStore file on the closeDB: {}.", dataBaseName, e); } finally { resetDbLock.writeLock().unlock(); } @@ -104,30 +115,37 @@ public void closeDB() { @Override public void resetDb() { - closeDB(); - FileUtil.recursiveDelete(getDbPath().toString()); - initDB(); + resetDbLock.writeLock().lock(); + try { + closeDB(); + FileUtil.recursiveDelete(getDbPath().toString()); + initDB(); + } finally { + resetDbLock.writeLock().unlock(); + } } private boolean quitIfNotAlive() { if (!isAlive()) { - logger.warn("db is not alive"); + logger.warn("DB {} is not alive.", dataBaseName); } return !isAlive(); } @Override public Set allKeys() throws RuntimeException { - if (quitIfNotAlive()) { - return null; - } resetDbLock.readLock().lock(); - Set result = Sets.newHashSet(); - try (final RocksIterator iter = getRocksIterator()) { - for (iter.seekToFirst(); iter.isValid(); iter.next()) { - result.add(iter.key()); + try { + if (quitIfNotAlive()) { + return null; + } + Set result = Sets.newHashSet(); + try (final RocksIterator iter = getRocksIterator()) { + for (iter.seekToFirst(); iter.isValid(); iter.next()) { + result.add(iter.key()); + } + return result; } - return result; } finally { resetDbLock.readLock().unlock(); } @@ -176,8 +194,8 @@ public boolean checkOrInitEngine() { public void initDB() { if (!checkOrInitEngine()) { - logger.error("database engine do not match"); - throw new RuntimeException(FAIL_TO_INIT_DATABASE); + throw new RuntimeException( + String.format("failed to check database: %s, engine do not match", dataBaseName)); } initDB(RocksDbSettings.getSettings()); } @@ -189,7 +207,7 @@ public void initDB(RocksDbSettings settings) { return; } if (dataBaseName == null) { - throw new NullPointerException("no name set to the dbStore"); + throw new IllegalArgumentException("No name set to the dbStore"); } try (Options options = new Options()) { @@ -217,6 +235,12 @@ public void initDB(RocksDbSettings settings) { if (comparator != null) { options.setComparator(comparator); } + options.setLogger(new Logger(options) { + @Override + protected void log(InfoLogLevel infoLogLevel, String logMsg) { + rocksDbLogger.info("{} {}", dataBaseName, logMsg); + } + }); // table options final BlockBasedTableConfig tableCfg; @@ -233,7 +257,7 @@ public void initDB(RocksDbSettings settings) { .setVerifyChecksums(false); try { - logger.debug("Opening database"); + logger.debug("Opening database {}.", dataBaseName); final Path dbPath = getDbPath(); if (!Files.isSymbolicLink(dbPath.getParent())) { @@ -243,18 +267,22 @@ public void initDB(RocksDbSettings settings) { try { database = RocksDB.open(options, dbPath.toString()); } catch (RocksDBException e) { - logger.error(e.getMessage(), e); - throw new RuntimeException(FAIL_TO_INIT_DATABASE, e); + if (Objects.equals(e.getStatus().getCode(), Status.Code.Corruption)) { + logger.error("Database {} corrupted, please delete database directory({}) " + + "and restart.", dataBaseName, parentPath, e); + } else { + logger.error("Open Database {} failed", dataBaseName, e); + } + throw new TronError(e, TronError.ErrCode.ROCKSDB_INIT); } alive = true; - } catch (IOException ioe) { - logger.error(ioe.getMessage(), ioe); - throw new RuntimeException(FAIL_TO_INIT_DATABASE, ioe); + throw new RuntimeException( + String.format("failed to init database: %s", dataBaseName), ioe); } - logger.debug("<~ RocksDbDataSource.initDB(): " + dataBaseName); + logger.debug("Init DB {} done.", dataBaseName); } } finally { resetDbLock.writeLock().unlock(); @@ -263,14 +291,14 @@ public void initDB(RocksDbSettings settings) { @Override public void putData(byte[] key, byte[] value) { - if (quitIfNotAlive()) { - return; - } resetDbLock.readLock().lock(); try { + if (quitIfNotAlive()) { + return; + } database.put(key, value); } catch (RocksDBException e) { - logger.error("RocksDBException:{}", e); + throw new RuntimeException(dataBaseName, e); } finally { resetDbLock.readLock().unlock(); } @@ -278,30 +306,29 @@ public void putData(byte[] key, byte[] value) { @Override public byte[] getData(byte[] key) { - if (quitIfNotAlive()) { - return null; - } resetDbLock.readLock().lock(); try { + if (quitIfNotAlive()) { + return null; + } return database.get(key); } catch (RocksDBException e) { - logger.error("RocksDBException: {}", e); + throw new RuntimeException(dataBaseName, e); } finally { resetDbLock.readLock().unlock(); } - return null; } @Override public void deleteData(byte[] key) { - if (quitIfNotAlive()) { - return; - } resetDbLock.readLock().lock(); try { + if (quitIfNotAlive()) { + return; + } database.delete(key); } catch (RocksDBException e) { - logger.error("RocksDBException:{}", e); + throw new RuntimeException(dataBaseName, e); } finally { resetDbLock.readLock().unlock(); } @@ -352,17 +379,17 @@ private void updateByBatchInner(Map rows, WriteOptions options) @Override public void updateByBatch(Map rows, WriteOptionsWrapper optionsWrapper) { - if (quitIfNotAlive()) { - return; - } resetDbLock.readLock().lock(); try { + if (quitIfNotAlive()) { + return; + } updateByBatchInner(rows, optionsWrapper.rocks); } catch (Exception e) { try { updateByBatchInner(rows); } catch (Exception e1) { - throw new RuntimeException(e); + throw new RuntimeException(dataBaseName, e1); } } finally { resetDbLock.readLock().unlock(); @@ -371,17 +398,17 @@ public void updateByBatch(Map rows, WriteOptionsWrapper optionsW @Override public void updateByBatch(Map rows) { - if (quitIfNotAlive()) { - return; - } resetDbLock.readLock().lock(); try { + if (quitIfNotAlive()) { + return; + } updateByBatchInner(rows); } catch (Exception e) { try { updateByBatchInner(rows); } catch (Exception e1) { - throw new RuntimeException(e); + throw new RuntimeException(dataBaseName, e1); } } finally { resetDbLock.readLock().unlock(); @@ -389,105 +416,113 @@ public void updateByBatch(Map rows) { } public List getKeysNext(byte[] key, long limit) { - if (quitIfNotAlive()) { - return new ArrayList<>(); - } - if (limit <= 0) { - return new ArrayList<>(); - } resetDbLock.readLock().lock(); - try (RocksIterator iter = getRocksIterator()) { - List result = new ArrayList<>(); - long i = 0; - for (iter.seek(key); iter.isValid() && i < limit; iter.next(), i++) { - result.add(iter.key()); + try { + if (quitIfNotAlive()) { + return new ArrayList<>(); + } + if (limit <= 0) { + return new ArrayList<>(); + } + + try (RocksIterator iter = getRocksIterator()) { + List result = new ArrayList<>(); + long i = 0; + for (iter.seek(key); iter.isValid() && i < limit; iter.next(), i++) { + result.add(iter.key()); + } + return result; } - return result; } finally { resetDbLock.readLock().unlock(); } } public Map getNext(byte[] key, long limit) { - if (quitIfNotAlive()) { - return null; - } - if (limit <= 0) { - return Collections.emptyMap(); - } resetDbLock.readLock().lock(); - try (RocksIterator iter = getRocksIterator()) { - Map result = new HashMap<>(); - long i = 0; - for (iter.seek(key); iter.isValid() && i < limit; iter.next(), i++) { - result.put(iter.key(), iter.value()); + try { + if (quitIfNotAlive()) { + return null; + } + if (limit <= 0) { + return Collections.emptyMap(); + } + try (RocksIterator iter = getRocksIterator()) { + Map result = new HashMap<>(); + long i = 0; + for (iter.seek(key); iter.isValid() && i < limit; iter.next(), i++) { + result.put(iter.key(), iter.value()); + } + return result; } - return result; } finally { resetDbLock.readLock().unlock(); } } - public Set getlatestValues(long limit) { - if (quitIfNotAlive()) { - return null; - } - if (limit <= 0) { - return Sets.newHashSet(); - } + @Override + public Map prefixQuery(byte[] key) { resetDbLock.readLock().lock(); - try (RocksIterator iter = getRocksIterator()) { - Set result = Sets.newHashSet(); - long i = 0; - for (iter.seekToLast(); iter.isValid() && i < limit; iter.prev(), i++) { - result.add(iter.value()); + try { + if (quitIfNotAlive()) { + return null; + } + try (RocksIterator iterator = getRocksIterator()) { + Map result = new HashMap<>(); + for (iterator.seek(key); iterator.isValid(); iterator.next()) { + if (Bytes.indexOf(iterator.key(), key) == 0) { + result.put(WrappedByteArray.of(iterator.key()), iterator.value()); + } else { + return result; + } + } + return result; } - return result; } finally { resetDbLock.readLock().unlock(); } } - public Set getValuesPrev(byte[] key, long limit) { - if (quitIfNotAlive()) { - return null; - } - if (limit <= 0) { - return Sets.newHashSet(); - } + public Set getlatestValues(long limit) { resetDbLock.readLock().lock(); - try (RocksIterator iter = getRocksIterator()) { - Set result = Sets.newHashSet(); - long i = 0; - byte[] data = getData(key); - if (Objects.nonNull(data)) { - result.add(data); - i++; + try { + if (quitIfNotAlive()) { + return null; + } + if (limit <= 0) { + return Sets.newHashSet(); } - for (iter.seekForPrev(key); iter.isValid() && i < limit; iter.prev(), i++) { - result.add(iter.value()); + try (RocksIterator iter = getRocksIterator()) { + Set result = Sets.newHashSet(); + long i = 0; + for (iter.seekToLast(); iter.isValid() && i < limit; iter.prev(), i++) { + result.add(iter.value()); + } + return result; } - return result; } finally { resetDbLock.readLock().unlock(); } } + public Set getValuesNext(byte[] key, long limit) { - if (quitIfNotAlive()) { - return null; - } - if (limit <= 0) { - return Sets.newHashSet(); - } resetDbLock.readLock().lock(); - try (RocksIterator iter = getRocksIterator()) { - Set result = Sets.newHashSet(); - long i = 0; - for (iter.seek(key); iter.isValid() && i < limit; iter.next(), i++) { - result.add(iter.value()); + try { + if (quitIfNotAlive()) { + return null; + } + if (limit <= 0) { + return Sets.newHashSet(); + } + try (RocksIterator iter = getRocksIterator()) { + Set result = Sets.newHashSet(); + long i = 0; + for (iter.seek(key); iter.isValid() && i < limit; iter.next(), i++) { + result.add(iter.value()); + } + return result; } - return result; } finally { resetDbLock.readLock().unlock(); } @@ -512,4 +547,46 @@ public boolean deleteDbBakPath(String dir) { public RocksDbDataSourceImpl newInstance() { return new RocksDbDataSourceImpl(parentPath, dataBaseName, RocksDbSettings.getSettings()); } + + + + /** + * Level Files Size(MB) + * -------------------- + * 0 5 10 + * 1 134 254 + * 2 1311 2559 + * 3 1976 4005 + * 4 0 0 + * 5 0 0 + * 6 0 0 + */ + @Override + public List getStats() throws Exception { + resetDbLock.readLock().lock(); + try { + if (!isAlive()) { + return Collections.emptyList(); + } + String stat = database.getProperty("rocksdb.levelstats"); + String[] stats = stat.split("\n"); + return Arrays.stream(stats).skip(2).collect(Collectors.toList()); + } finally { + resetDbLock.readLock().unlock(); + } + } + + @Override + public String getEngine() { + return ROCKSDB; + } + + @Override + public String getName() { + return this.dataBaseName; + } + + @Override public void stat() { + this.statProperty(); + } } diff --git a/chainbase/src/main/java/org/tron/common/utils/Commons.java b/chainbase/src/main/java/org/tron/common/utils/Commons.java index f2f7578d200..b121e84ecfe 100644 --- a/chainbase/src/main/java/org/tron/common/utils/Commons.java +++ b/chainbase/src/main/java/org/tron/common/utils/Commons.java @@ -1,5 +1,8 @@ package org.tron.common.utils; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.subtractExact; + import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.tron.common.parameter.CommonParameter; @@ -55,16 +58,18 @@ public static byte[] decodeFromBase58Check(String addressBase58) { return address; } - public static void adjustBalance(AccountStore accountStore, byte[] accountAddress, long amount) + public static void adjustBalance(AccountStore accountStore, byte[] accountAddress, long amount, + boolean useStrict) throws BalanceInsufficientException { AccountCapsule account = accountStore.getUnchecked(accountAddress); - adjustBalance(accountStore, account, amount); + adjustBalance(accountStore, account, amount, useStrict); } /** * judge balance. */ - public static void adjustBalance(AccountStore accountStore, AccountCapsule account, long amount) + public static void adjustBalance(AccountStore accountStore, AccountCapsule account, long amount, + boolean useStrict) throws BalanceInsufficientException { long balance = account.getBalance(); @@ -74,9 +79,10 @@ public static void adjustBalance(AccountStore accountStore, AccountCapsule accou if (amount < 0 && balance < -amount) { throw new BalanceInsufficientException( - StringUtil.createReadableString(account.createDbKey()) + " insufficient balance"); + String.format("%s insufficient balance, balance: %d, amount: %d", + StringUtil.createReadableString(account.createDbKey()), balance, -amount)); } - account.setBalance(Math.addExact(balance, amount)); + account.setBalance(addExact(balance, amount, useStrict)); accountStore.put(account.getAddress().toByteArray(), account); } @@ -120,22 +126,28 @@ public static void adjustAssetBalanceV2(AccountCapsule account, String AssetID, if (amount < 0) { if (!account.reduceAssetAmountV2(AssetID.getBytes(), -amount, dynamicPropertiesStore, assetIssueStore)) { - throw new BalanceInsufficientException("reduceAssetAmount failed !"); + throw new BalanceInsufficientException( + String.format("reduceAssetAmount failed! account: %s", + StringUtil.encode58Check(account.createDbKey()))); } } else if (amount > 0 && !account.addAssetAmountV2(AssetID.getBytes(), amount, dynamicPropertiesStore, assetIssueStore)) { - throw new BalanceInsufficientException("addAssetAmount failed !"); + throw new BalanceInsufficientException( + String.format("addAssetAmount failed! account: %s", + StringUtil.encode58Check(account.createDbKey()))); } accountStore.put(account.getAddress().toByteArray(), account); } public static void adjustTotalShieldedPoolValue(long valueBalance, DynamicPropertiesStore dynamicPropertiesStore) throws BalanceInsufficientException { - long totalShieldedPoolValue = Math - .subtractExact(dynamicPropertiesStore.getTotalShieldedPoolValue(), valueBalance); + long totalShieldedPoolValue = subtractExact( + dynamicPropertiesStore.getTotalShieldedPoolValue(), valueBalance, + dynamicPropertiesStore.disableJavaLangMath()); if (totalShieldedPoolValue < 0) { - throw new BalanceInsufficientException("Total shielded pool value can not below 0"); + throw new BalanceInsufficientException(String.format( + "total shielded pool value can not below 0, actual: %d", totalShieldedPoolValue)); } dynamicPropertiesStore.saveTotalShieldedPoolValue(totalShieldedPoolValue); } diff --git a/chainbase/src/main/java/org/tron/common/utils/ForkController.java b/chainbase/src/main/java/org/tron/common/utils/ForkController.java index b2cba4929dd..a702234f4cd 100644 --- a/chainbase/src/main/java/org/tron/common/utils/ForkController.java +++ b/chainbase/src/main/java/org/tron/common/utils/ForkController.java @@ -1,5 +1,6 @@ package org.tron.common.utils; +import static org.tron.common.math.Maths.ceil; import static org.tron.common.utils.StringUtil.encode58Check; import com.google.common.collect.Maps; @@ -19,6 +20,7 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.Parameter.ForkBlockVersionEnum; +import org.tron.core.store.DynamicPropertiesStore; @Slf4j(topic = "utils") public class ForkController { @@ -37,6 +39,17 @@ public class ForkController { public void init(ChainBaseManager manager) { this.manager = manager; + DynamicPropertiesStore store = manager.getDynamicPropertiesStore(); + int latestVersion = store.getLatestVersion(); + if (latestVersion == 0) { + for (ForkBlockVersionEnum version : ForkBlockVersionEnum.values()) { + int v = version.getValue(); + if (pass(v) && latestVersion < v) { + latestVersion = v; + } + } + store.saveLatestVersion(latestVersion); + } } public boolean pass(ForkBlockVersionEnum forkBlockVersionEnum) { @@ -44,6 +57,9 @@ public boolean pass(ForkBlockVersionEnum forkBlockVersionEnum) { } public synchronized boolean pass(int version) { + if (manager == null) { + throw new IllegalStateException("not inited"); + } if (version > ForkBlockVersionEnum.VERSION_4_0.getValue()) { return passNew(version); } else { @@ -63,7 +79,7 @@ private boolean passOld(int version) { private boolean passNew(int version) { ForkBlockVersionEnum versionEnum = ForkBlockVersionEnum.getForkBlockVersionEnum(version); if (versionEnum == null) { - logger.error("not exist block version: {}", version); + logger.warn("Not exist block version: {}.", version); return false; } long latestBlockTime = manager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); @@ -83,8 +99,8 @@ private boolean passNew(int version) { ++count; } } - return count >= Math - .ceil((double) versionEnum.getHardForkRate() * manager.getWitnesses().size() / 100); + return count >= ceil((double) versionEnum.getHardForkRate() * stats.length / 100, + manager.getDynamicPropertiesStore().disableJavaLangMath()); } @@ -113,9 +129,9 @@ private boolean check(byte[] stats) { private void downgrade(int version, int slot) { for (ForkBlockVersionEnum versionEnum : ForkBlockVersionEnum.values()) { int versionValue = versionEnum.getValue(); - if (versionValue > version) { + if (versionValue > version && !pass(versionValue)) { byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(versionValue); - if (!check(stats) && Objects.nonNull(stats)) { + if (Objects.nonNull(stats)) { stats[slot] = VERSION_DOWNGRADE; manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); } @@ -126,15 +142,13 @@ private void downgrade(int version, int slot) { private void upgrade(int version, int slotSize) { for (ForkBlockVersionEnum versionEnum : ForkBlockVersionEnum.values()) { int versionValue = versionEnum.getValue(); - if (versionValue < version) { + if (versionValue < version && !pass(versionValue)) { byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(versionValue); - if (!check(stats)) { - if (stats == null || stats.length == 0) { - stats = new byte[slotSize]; - } - Arrays.fill(stats, VERSION_UPGRADE); - manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); + if (stats == null || stats.length == 0) { + stats = new byte[slotSize]; } + Arrays.fill(stats, VERSION_UPGRADE); + manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); } } } @@ -152,6 +166,10 @@ public synchronized void update(BlockCapsule blockCapsule) { return; } + if (manager.getDynamicPropertiesStore().getLatestVersion() >= version) { + return; + } + downgrade(version, slot); byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(version); @@ -159,15 +177,16 @@ public synchronized void update(BlockCapsule blockCapsule) { stats = new byte[witnesses.size()]; } - if (check(stats)) { + if (pass(version)) { upgrade(version, stats.length); + manager.getDynamicPropertiesStore().saveLatestVersion(version); return; } stats[slot] = VERSION_UPGRADE; manager.getDynamicPropertiesStore().statsByVersion(version, stats); logger.info( - "*******update hard fork:{}, witness size:{}, solt:{}, witness:{}, version:{}", + "Update hard fork: {}, witness size: {}, solt: {}, witness: {}, version: {}.", Streams.zip(witnesses.stream(), Stream.of(ArrayUtils.toObject(stats)), Maps::immutableEntry) .map(e -> Maps .immutableEntry(encode58Check(e.getKey().toByteArray()), e.getValue())) @@ -182,11 +201,12 @@ public synchronized void update(BlockCapsule blockCapsule) { } public synchronized void reset() { + int size = manager.getWitnessScheduleStore().getActiveWitnesses().size(); for (ForkBlockVersionEnum versionEnum : ForkBlockVersionEnum.values()) { int versionValue = versionEnum.getValue(); byte[] stats = manager.getDynamicPropertiesStore().statsByVersion(versionValue); if (Objects.nonNull(stats) && !pass(versionValue)) { - Arrays.fill(stats, VERSION_DOWNGRADE); + stats = new byte[size]; manager.getDynamicPropertiesStore().statsByVersion(versionValue, stats); } } @@ -209,4 +229,5 @@ private ForkController getInstance() { return instance; } } + } diff --git a/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java b/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java index 00cd396143c..940a107a2ac 100644 --- a/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java +++ b/chainbase/src/main/java/org/tron/common/utils/LocalWitnesses.java @@ -88,8 +88,8 @@ private void validate(String privateKey) { if (StringUtils.isNotBlank(privateKey) && privateKey.length() != ChainConstant.PRIVATE_KEY_LENGTH) { throw new IllegalArgumentException( - "Private key(" + privateKey + ") must be " + ChainConstant.PRIVATE_KEY_LENGTH - + "-bits hex string."); + String.format("private key must be %d-bits hex string, actual: %d", + ChainConstant.PRIVATE_KEY_LENGTH, privateKey.length())); } } @@ -101,7 +101,7 @@ public void addPrivateKeys(String privateKey) { //get the first one recently public String getPrivateKey() { if (CollectionUtils.isEmpty(privateKeys)) { - logger.warn("privateKey is null"); + logger.warn("PrivateKey is null."); return null; } return privateKeys.get(0); @@ -109,7 +109,7 @@ public String getPrivateKey() { public byte[] getPublicKey() { if (CollectionUtils.isEmpty(privateKeys)) { - logger.warn("privateKey is null"); + logger.warn("PrivateKey is null."); return null; } byte[] privateKey = ByteArray.fromHexString(getPrivateKey()); diff --git a/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java b/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java index bd367393405..330ce35b6e9 100644 --- a/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java +++ b/chainbase/src/main/java/org/tron/common/utils/WalletUtil.java @@ -28,7 +28,8 @@ public static boolean checkPermissionOperations(Permission permission, Contract throws PermissionException { ByteString operations = permission.getOperations(); if (operations.size() != 32) { - throw new PermissionException("operations size must 32"); + throw new PermissionException(String.format("operations size must 32, actual: %d", + operations.size())); } int contractType = contract.getTypeValue(); boolean b = (operations.byteAt(contractType / 8) & (1 << (contractType % 8))) != 0; @@ -131,4 +132,12 @@ public static byte[] getSelector(byte[] data) { return ret; } + public static Long isLong(String s) { + try { + return Long.parseLong(s); + } catch (NumberFormatException ignored) { + return null; + } + } + } diff --git a/chainbase/src/main/java/org/tron/core/ChainBaseManager.java b/chainbase/src/main/java/org/tron/core/ChainBaseManager.java index 7cbb842f622..21f0bac8d77 100644 --- a/chainbase/src/main/java/org/tron/core/ChainBaseManager.java +++ b/chainbase/src/main/java/org/tron/core/ChainBaseManager.java @@ -4,12 +4,14 @@ import com.google.protobuf.ByteString; import java.util.List; +import javax.annotation.PostConstruct; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.common.storage.metric.DbStatService; import org.tron.common.utils.ForkController; import org.tron.common.utils.Sha256Hash; import org.tron.common.zksnark.MerkleContainer; @@ -25,8 +27,8 @@ import org.tron.core.db.KhaosDatabase; import org.tron.core.db.PbftSignDataStore; import org.tron.core.db.RecentBlockStore; +import org.tron.core.db.RecentTransactionStore; import org.tron.core.db.TransactionStore; -import org.tron.core.db2.core.ITronChainBase; import org.tron.core.exception.BadItemException; import org.tron.core.exception.HeaderNotFound; import org.tron.core.exception.ItemNotFoundException; @@ -41,6 +43,7 @@ import org.tron.core.store.AssetIssueV2Store; import org.tron.core.store.BalanceTraceStore; import org.tron.core.store.CodeStore; +import org.tron.core.store.ContractStateStore; import org.tron.core.store.ContractStore; import org.tron.core.store.DelegatedResourceAccountIndexStore; import org.tron.core.store.DelegatedResourceStore; @@ -69,6 +72,9 @@ @Component public class ChainBaseManager { + @Getter + private static volatile ChainBaseManager chainBaseManager; + // db store @Autowired @Getter @@ -138,6 +144,9 @@ public class ChainBaseManager { private ContractStore contractStore; @Autowired @Getter + private ContractStateStore contractStateStore; + @Autowired + @Getter private DelegatedResourceStore delegatedResourceStore; @Autowired @Getter @@ -187,6 +196,9 @@ public class ChainBaseManager { private RecentBlockStore recentBlockStore; @Autowired @Getter + private RecentTransactionStore recentTransactionStore; + @Autowired + @Getter private TransactionHistoryStore transactionHistoryStore; @Getter @@ -221,50 +233,20 @@ public class ChainBaseManager { @Getter private SectionBloomStore sectionBloomStore; - public void closeOneStore(ITronChainBase database) { - logger.info("******** begin to close " + database.getName() + " ********"); - try { - database.close(); - } catch (Exception e) { - logger.info("failed to close " + database.getName() + ". " + e); - } finally { - logger.info("******** end to close " + database.getName() + " ********"); - } - } + @Autowired + private DbStatService dbStatService; - public void closeAllStore() { - closeOneStore(transactionRetStore); - closeOneStore(recentBlockStore); - closeOneStore(transactionHistoryStore); - closeOneStore(transactionStore); - closeOneStore(accountStore); - closeOneStore(blockStore); - closeOneStore(blockIndexStore); - closeOneStore(accountIdIndexStore); - closeOneStore(accountIndexStore); - closeOneStore(witnessScheduleStore); - closeOneStore(assetIssueStore); - closeOneStore(dynamicPropertiesStore); - closeOneStore(abiStore); - closeOneStore(codeStore); - closeOneStore(contractStore); - closeOneStore(storageRowStore); - closeOneStore(exchangeStore); - closeOneStore(proposalStore); - closeOneStore(votesStore); - closeOneStore(delegatedResourceStore); - closeOneStore(delegatedResourceAccountIndexStore); - closeOneStore(assetIssueV2Store); - closeOneStore(exchangeV2Store); - closeOneStore(nullifierStore); - closeOneStore(merkleTreeStore); - closeOneStore(delegationStore); - closeOneStore(proofStore); - closeOneStore(commonStore); - closeOneStore(commonDataBase); - closeOneStore(pbftSignDataStore); - closeOneStore(sectionBloomStore); - } + @Getter + @Setter + private NodeType nodeType; + + @Getter + @Setter + private long lowestBlockNum = -1; // except num = 0. + + @Getter + @Setter + private long latestSaveBlockTime; // for test only public List getWitnesses() { @@ -284,15 +266,12 @@ public BlockCapsule getHead() throws HeaderNotFound { if (CollectionUtils.isNotEmpty(blocks)) { return blocks.get(0); } else { - logger.info("Header block Not Found"); - throw new HeaderNotFound("Header block Not Found"); + throw new HeaderNotFound("header block not found"); } } public synchronized BlockId getHeadBlockId() { - return new BlockId( - dynamicPropertiesStore.getLatestBlockHeaderHash(), - dynamicPropertiesStore.getLatestBlockHeaderNumber()); + return new BlockId(dynamicPropertiesStore.getLatestBlockHeaderHash()); } public long getHeadBlockNum() { @@ -336,6 +315,9 @@ public boolean containBlockInMainChain(BlockId blockId) { } } + public BlockCapsule getKhaosDbHead(){ + return this.khaosDb.getHead(); + } /** * Get a BlockCapsule by id. @@ -388,8 +370,51 @@ public BlockCapsule getBlockByNum(final long num) throws return getBlockById(getBlockIdByNum(num)); } - public void init() { - AssetUtil.setAccountAssetStore(accountAssetStore); - AssetUtil.setDynamicPropertiesStore(dynamicPropertiesStore); + public static ChainBaseManager getInstance() { + return chainBaseManager; + } + + public static synchronized void init(ChainBaseManager manager) { + chainBaseManager = manager; + AssetUtil.setAccountAssetStore(manager.getAccountAssetStore()); + AssetUtil.setDynamicPropertiesStore(manager.getDynamicPropertiesStore()); + } + + public long getNextBlockSlotTime() { + long slotCount = 1; + if (dynamicPropertiesStore.getStateFlag() == 1) { + slotCount += dynamicPropertiesStore.getMaintenanceSkipSlots(); + } + return dynamicPropertiesStore.getLatestBlockHeaderTimestamp() + + slotCount * BLOCK_PRODUCED_INTERVAL; + } + + @PostConstruct + private void init() { + this.lowestBlockNum = this.blockIndexStore.getLimitNumber(1, 1).stream() + .map(BlockId::getNum).findFirst().orElse(0L); + this.nodeType = getLowestBlockNum() > 1 ? NodeType.LITE : NodeType.FULL; + this.latestSaveBlockTime = System.currentTimeMillis(); + } + + public void shutdown() { + dbStatService.shutdown(); + } + + public boolean isLiteNode() { + return getNodeType() == NodeType.LITE; + } + + public enum NodeType { + FULL(0), + LITE(1); + + @Getter + private final int type; + + NodeType(int type) { + this.type = type; + } } } + diff --git a/chainbase/src/main/java/org/tron/core/capsule/AccountAssetCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/AccountAssetCapsule.java deleted file mode 100644 index 81a16f3afd8..00000000000 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountAssetCapsule.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.tron.core.capsule; - -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import lombok.extern.slf4j.Slf4j; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.AccountAsset; -import org.tron.protos.Protocol.AccountAsset.Frozen; - -import java.util.List; -import java.util.Map; - -@Slf4j(topic = "capsule") -public class AccountAssetCapsule implements ProtoCapsule { - - private AccountAsset accountAsset; - - /** - * get accountAssetIssue from bytes data. - */ - public AccountAssetCapsule(byte[] data) { - try { - this.accountAsset = AccountAsset.parseFrom(data); - } catch (InvalidProtocolBufferException e) { - logger.debug(e.getMessage()); - } - } - - public AccountAssetCapsule(ByteString address) { - this.accountAsset = AccountAsset.newBuilder() - .setAddress(address) - .build(); - } - - public AccountAssetCapsule(AccountAsset accountAsset) { - this.accountAsset = accountAsset; - } - - @Override - public byte[] getData() { - return this.accountAsset.toByteArray(); - } - - @Override - public AccountAsset getInstance() { - return this.accountAsset; - } - - public ByteString getAddress() { - return this.accountAsset.getAddress(); - } - - public byte[] createDbKey() { - return getAddress().toByteArray(); - } - - public void setInstance(AccountAsset accountAsset) { - this.accountAsset = accountAsset; - } - - public Map getAssetMap() { - return this.accountAsset.getAssetMap(); - } - - public ByteString getAssetIssuedID() { - return getInstance().getAssetIssuedID(); - } - - public ByteString getAssetIssuedName() { - return getInstance().getAssetIssuedName(); - } - - public Map getAllFreeAssetNetUsage() { - return this.accountAsset.getFreeAssetNetUsageMap(); - } - - public Map getLatestAssetOperationTimeMap() { - return this.accountAsset.getLatestAssetOperationTimeMap(); - } - - public Map getAssetMapV2() { - return this.accountAsset.getAssetV2Map(); - } - - public Map getAllFreeAssetNetUsageV2() { - return this.accountAsset.getFreeAssetNetUsageV2Map(); - } - - public Map getLatestAssetOperationTimeMapV2() { - return this.accountAsset.getLatestAssetOperationTimeV2Map(); - } - - public List getFrozenSupplyList() { - return getInstance().getFrozenSupplyList(); - } - - @Override - public String toString() { - return this.accountAsset.toString(); - } - -} 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 1888724bb5c..1af7b55c8b2 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/AccountCapsule.java @@ -15,15 +15,25 @@ package org.tron.core.capsule; -import com.google.common.collect.Lists; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.subtractExact; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_MS; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; + import com.google.common.collect.Maps; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.List; import java.util.Map; -import lombok.Getter; -import lombok.Setter; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; import org.tron.common.utils.ByteArray; import org.tron.core.capsule.utils.AssetUtil; import org.tron.core.store.AssetIssueStore; @@ -31,7 +41,9 @@ import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Account.AccountResource; import org.tron.protos.Protocol.Account.Builder; +import org.tron.protos.Protocol.Account.FreezeV2; import org.tron.protos.Protocol.Account.Frozen; +import org.tron.protos.Protocol.Account.UnFreezeV2; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Key; import org.tron.protos.Protocol.Permission; @@ -44,10 +56,7 @@ public class AccountCapsule implements ProtoCapsule, Comparable { private Account account; - - @Getter - @Setter - private Boolean isAssetImport = false; + private boolean flag = false; /** * get account from bytes data. @@ -326,24 +335,24 @@ public long getLatestOperationTime() { return this.account.getLatestOprationTime(); } - public void setLatestOperationTime(long latest_time) { - this.account = this.account.toBuilder().setLatestOprationTime(latest_time).build(); + public void setLatestOperationTime(long latestTime) { + this.account = this.account.toBuilder().setLatestOprationTime(latestTime).build(); } public long getLatestConsumeTime() { return this.account.getLatestConsumeTime(); } - public void setLatestConsumeTime(long latest_time) { - this.account = this.account.toBuilder().setLatestConsumeTime(latest_time).build(); + public void setLatestConsumeTime(long latestTime) { + this.account = this.account.toBuilder().setLatestConsumeTime(latestTime).build(); } public long getLatestConsumeFreeTime() { return this.account.getLatestConsumeFreeTime(); } - public void setLatestConsumeFreeTime(long latest_time) { - this.account = this.account.toBuilder().setLatestConsumeFreeTime(latest_time).build(); + public void setLatestConsumeFreeTime(long latestTime) { + this.account = this.account.toBuilder().setLatestConsumeFreeTime(latestTime).build(); } public void addDelegatedFrozenBalanceForBandwidth(long balance) { @@ -351,31 +360,75 @@ public void addDelegatedFrozenBalanceForBandwidth(long balance) { this.account.getDelegatedFrozenBalanceForBandwidth() + balance).build(); } + public void addDelegatedFrozenV2BalanceForBandwidth(long balance) { + this.account = this.account.toBuilder().setDelegatedFrozenV2BalanceForBandwidth( + this.account.getDelegatedFrozenV2BalanceForBandwidth() + balance).build(); + } + public long getAcquiredDelegatedFrozenBalanceForBandwidth() { return this.account.getAcquiredDelegatedFrozenBalanceForBandwidth(); } + public long getAcquiredDelegatedFrozenV2BalanceForBandwidth() { + return this.account.getAcquiredDelegatedFrozenV2BalanceForBandwidth(); + } + + public long getTotalAcquiredDelegatedFrozenBalanceForBandwidth() { + return getAcquiredDelegatedFrozenBalanceForBandwidth() + getAcquiredDelegatedFrozenV2BalanceForBandwidth(); + } + + public void addFrozenBalanceForBandwidthV2(long balance) { + this.addFrozenBalanceForResource(BANDWIDTH, balance); + } + public void setAcquiredDelegatedFrozenBalanceForBandwidth(long balance) { this.account = this.account.toBuilder().setAcquiredDelegatedFrozenBalanceForBandwidth(balance) .build(); } + public void setAcquiredDelegatedFrozenV2BalanceForBandwidth(long balance) { + this.account = this.account.toBuilder().setAcquiredDelegatedFrozenV2BalanceForBandwidth(balance) + .build(); + } + public void addAcquiredDelegatedFrozenBalanceForBandwidth(long balance) { this.account = this.account.toBuilder().setAcquiredDelegatedFrozenBalanceForBandwidth( this.account.getAcquiredDelegatedFrozenBalanceForBandwidth() + balance) .build(); } - public void safeAddAcquiredDelegatedFrozenBalanceForBandwidth(long balance) { + public void addAcquiredDelegatedFrozenV2BalanceForBandwidth(long balance) { + this.account = this.account.toBuilder().setAcquiredDelegatedFrozenV2BalanceForBandwidth( + this.account.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + balance).build(); + } + + public void safeAddAcquiredDelegatedFrozenBalanceForBandwidth(long balance, boolean useStrict) { this.account = this.account.toBuilder().setAcquiredDelegatedFrozenBalanceForBandwidth( - Math.max(0, this.account.getAcquiredDelegatedFrozenBalanceForBandwidth() + balance)) + max(0, this.account.getAcquiredDelegatedFrozenBalanceForBandwidth() + balance, + useStrict)) .build(); } + @SuppressWarnings("unused") + public void safeAddAcquiredDelegatedFrozenV2BalanceForBandwidth(long balance, boolean useStrict) { + this.account = this.account.toBuilder().setAcquiredDelegatedFrozenV2BalanceForBandwidth( + max(0, this.account.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + balance, + useStrict)) + .build(); + } + public long getAcquiredDelegatedFrozenBalanceForEnergy() { return getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(); } + public long getAcquiredDelegatedFrozenV2BalanceForEnergy() { + return getAccountResource().getAcquiredDelegatedFrozenV2BalanceForEnergy(); + } + + public long getTotalAcquiredDelegatedFrozenBalanceForEnergy() { + return getAcquiredDelegatedFrozenBalanceForEnergy() + getAcquiredDelegatedFrozenV2BalanceForEnergy(); + } + public void setAcquiredDelegatedFrozenBalanceForEnergy(long balance) { AccountResource newAccountResource = getAccountResource().toBuilder() .setAcquiredDelegatedFrozenBalanceForEnergy(balance).build(); @@ -385,14 +438,36 @@ public void setAcquiredDelegatedFrozenBalanceForEnergy(long balance) { .build(); } + public void setAcquiredDelegatedFrozenV2BalanceForEnergy(long balance) { + AccountResource newAccountResource = getAccountResource().toBuilder() + .setAcquiredDelegatedFrozenV2BalanceForEnergy(balance).build(); + this.account = this.account.toBuilder().setAccountResource(newAccountResource).build(); + } + public long getDelegatedFrozenBalanceForEnergy() { return getAccountResource().getDelegatedFrozenBalanceForEnergy(); } + public long getDelegatedFrozenV2BalanceForEnergy() { + return getAccountResource().getDelegatedFrozenV2BalanceForEnergy(); + } + + public long getTotalDelegatedFrozenBalanceForEnergy() { + return getDelegatedFrozenBalanceForEnergy() + getDelegatedFrozenV2BalanceForEnergy(); + } + public long getDelegatedFrozenBalanceForBandwidth() { return this.account.getDelegatedFrozenBalanceForBandwidth(); } + public long getDelegatedFrozenV2BalanceForBandwidth() { + return this.account.getDelegatedFrozenV2BalanceForBandwidth(); + } + + public long getTotalDelegatedFrozenBalanceForBandwidth() { + return getDelegatedFrozenBalanceForBandwidth() + getDelegatedFrozenV2BalanceForBandwidth(); + } + public void setDelegatedFrozenBalanceForBandwidth(long balance) { this.account = this.account.toBuilder() .setDelegatedFrozenBalanceForBandwidth(balance) @@ -418,10 +493,18 @@ public void addAcquiredDelegatedFrozenBalanceForEnergy(long balance) { .build(); } - public void safeAddAcquiredDelegatedFrozenBalanceForEnergy(long balance) { + public void addAcquiredDelegatedFrozenV2BalanceForEnergy(long balance) { + AccountResource newAccountResource = getAccountResource().toBuilder() + .setAcquiredDelegatedFrozenV2BalanceForEnergy(getAccountResource() + .getAcquiredDelegatedFrozenV2BalanceForEnergy() + balance).build(); + this.account = this.account.toBuilder().setAccountResource(newAccountResource).build(); + } + + public void safeAddAcquiredDelegatedFrozenBalanceForEnergy(long balance, boolean useStrict) { AccountResource newAccountResource = getAccountResource().toBuilder() .setAcquiredDelegatedFrozenBalanceForEnergy( - Math.max(0, getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy() + balance)) + max(0, getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy() + balance, + useStrict)) .build(); this.account = this.account.toBuilder() @@ -429,6 +512,14 @@ public void safeAddAcquiredDelegatedFrozenBalanceForEnergy(long balance) { .build(); } + @SuppressWarnings("unused") + public void safeAddAcquiredDelegatedFrozenV2BalanceForEnergy(long balance, boolean useStrict) { + AccountResource newAccountResource = getAccountResource().toBuilder() + .setAcquiredDelegatedFrozenV2BalanceForEnergy(max(0, getAccountResource() + .getAcquiredDelegatedFrozenV2BalanceForEnergy() + balance, useStrict)).build(); + this.account = this.account.toBuilder().setAccountResource(newAccountResource).build(); + } + public void addDelegatedFrozenBalanceForEnergy(long balance) { AccountResource newAccountResource = getAccountResource().toBuilder() .setDelegatedFrozenBalanceForEnergy( @@ -439,6 +530,42 @@ public void addDelegatedFrozenBalanceForEnergy(long balance) { .build(); } + public void addDelegatedFrozenV2BalanceForEnergy(long balance) { + AccountResource newAccountResource = getAccountResource().toBuilder() + .setDelegatedFrozenV2BalanceForEnergy( + getAccountResource().getDelegatedFrozenV2BalanceForEnergy() + balance).build(); + + this.account = this.account.toBuilder().setAccountResource(newAccountResource).build(); + } + + public void addFrozenBalanceForEnergyV2(long balance) { + this.addFrozenBalanceForResource(ENERGY, balance); + } + + private void addFrozenBalanceForResource(ResourceCode type, long balance) { + boolean doUpdate = false; + for (int i = 0; i < this.account.getFrozenV2List().size(); i++) { + if (this.account.getFrozenV2List().get(i).getType().equals(type)) { + long newAmount = this.account.getFrozenV2(i).getAmount() + balance; + FreezeV2 freezeV2 = FreezeV2.newBuilder() + .setType(type) + .setAmount(newAmount) + .build(); + this.updateFrozenV2List(i, freezeV2); + doUpdate = true; + break; + } + } + + if (!doUpdate) { + FreezeV2 freezeV2 = FreezeV2.newBuilder() + .setType(type) + .setAmount(balance) + .build(); + this.addFrozenV2List(freezeV2); + } + } + @Override public String toString() { return this.account.toString(); @@ -453,22 +580,17 @@ public void addVotes(ByteString voteAddress, long voteAdd) { .build(); } - public void clearAssetV2() { - importAsset(); - this.account = this.account.toBuilder() - .clearAssetV2() - .build(); + public void addAllVotes(List votesToAdd) { + this.account = this.account.toBuilder().addAllVotes(votesToAdd).build(); } public void clearLatestAssetOperationTimeV2() { - importAsset(); this.account = this.account.toBuilder() .clearLatestAssetOperationTimeV2() .build(); } public void clearFreeAssetNetUsageV2() { - importAsset(); this.account = this.account.toBuilder() .clearFreeAssetNetUsageV2() .build(); @@ -484,19 +606,14 @@ public void clearVotes() { * get votes. */ public List getVotesList() { - if (this.account.getVotesList() != null) { - return this.account.getVotesList(); - } else { - return Lists.newArrayList(); - } + return this.account.getVotesList(); } public long getTronPowerUsage() { - if (this.account.getVotesList() != null) { - return this.account.getVotesList().stream().mapToLong(Vote::getVoteCount).sum(); - } else { + if (getVotesList().isEmpty()) { return 0L; } + return this.account.getVotesList().stream().mapToLong(Vote::getVoteCount).sum(); } //tp:Tron_Power @@ -509,34 +626,81 @@ public long getTronPower() { tp += account.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); tp += account.getDelegatedFrozenBalanceForBandwidth(); tp += account.getAccountResource().getDelegatedFrozenBalanceForEnergy(); + + tp += getFrozenV2List().stream().filter(o -> o.getType() != TRON_POWER) + .mapToLong(FreezeV2::getAmount).sum(); + tp += account.getDelegatedFrozenV2BalanceForBandwidth(); + tp += account.getAccountResource().getDelegatedFrozenV2BalanceForEnergy(); return tp; } public long getAllTronPower() { if (account.getOldTronPower() == -1) { - return getTronPowerFrozenBalance(); + return getTronPowerFrozenBalance() + getTronPowerFrozenV2Balance(); } else if (account.getOldTronPower() == 0) { - return getTronPower() + getTronPowerFrozenBalance(); + return getTronPower() + getTronPowerFrozenBalance() + getTronPowerFrozenV2Balance(); } else { - return account.getOldTronPower() + getTronPowerFrozenBalance(); + return account.getOldTronPower() + getTronPowerFrozenBalance() + + getTronPowerFrozenV2Balance(); } } - /** - * asset balance enough - */ - public boolean assetBalanceEnough(byte[] key, long amount) { - importAsset(); - Map assetMap = this.account.getAssetMap(); - String nameKey = ByteArray.toStr(key); - Long currentAmount = assetMap.get(nameKey); - return amount > 0 && null != currentAmount && amount <= currentAmount; + + public List getFrozenV2List() { + return account.getFrozenV2List(); + } + + public List getUnfrozenV2List() { + return account.getUnfrozenV2List(); + } + + public void updateFrozenV2List(int index, FreezeV2 frozenV2) { + if (Objects.isNull(frozenV2)) { + return; + } + this.account = this.account.toBuilder().setFrozenV2(index, frozenV2).build(); + } + + public void addFrozenV2List(FreezeV2 frozenV2) { + this.account = this.account.toBuilder().addFrozenV2(frozenV2).build(); + } + + public void addUnfrozenV2List(ResourceCode type, long unfreezeAmount, long expireTime) { + UnFreezeV2 unFreezeV2 = UnFreezeV2.newBuilder() + .setType(type) + .setUnfreezeAmount(unfreezeAmount) + .setUnfreezeExpireTime(expireTime) + .build(); + this.account = this.account.toBuilder().addUnfrozenV2(unFreezeV2).build(); + } + + + public int getUnfreezingV2Count(long now) { + int count = 0; + List unFreezeV2List = account.getUnfrozenV2List(); + for (UnFreezeV2 item : unFreezeV2List) { + if (item.getUnfreezeExpireTime() > now) { + count++; + } + } + return count; + } + + + /*************************** start asset ****************************************/ + + public boolean getAssetOptimized() { + return this.account.getAssetOptimized(); + } + + public void setAssetOptimized(boolean flag) { + this.account = this.account.toBuilder().setAssetOptimized(flag).build(); } public boolean assetBalanceEnoughV2(byte[] key, long amount, DynamicPropertiesStore dynamicPropertiesStore) { - importAsset(); + importAsset(key); Map assetMap; String nameKey; Long currentAmount; @@ -553,117 +717,115 @@ public boolean assetBalanceEnoughV2(byte[] key, long amount, return amount > 0 && null != currentAmount && amount <= currentAmount; } - /** - * reduce asset amount. - */ - public boolean reduceAssetAmount(byte[] key, long amount) { - importAsset(); + public boolean addAssetAmount(byte[] key, long amount, boolean useStrict) { Map assetMap = this.account.getAssetMap(); String nameKey = ByteArray.toStr(key); Long currentAmount = assetMap.get(nameKey); - if (amount > 0 && null != currentAmount && amount <= currentAmount) { - this.account = this.account.toBuilder() - .putAsset(nameKey, Math.subtractExact(currentAmount, amount)).build(); - return true; + if (currentAmount == null) { + currentAmount = 0L; } - - return false; + this.account = this.account.toBuilder().putAsset(nameKey, + addExact(currentAmount, amount, useStrict)) + .build(); + return true; } - /** - * reduce asset amount. - */ - public boolean reduceAssetAmountV2(byte[] key, long amount, + public boolean addAssetAmountV2(byte[] key, long amount, DynamicPropertiesStore dynamicPropertiesStore, AssetIssueStore assetIssueStore) { + importAsset(key); + boolean disableJavaLangMath = dynamicPropertiesStore.disableJavaLangMath(); //key is token name - importAsset(); if (dynamicPropertiesStore.getAllowSameTokenName() == 0) { Map assetMap = this.account.getAssetMap(); AssetIssueCapsule assetIssueCapsule = assetIssueStore.get(key); String tokenID = assetIssueCapsule.getId(); String nameKey = ByteArray.toStr(key); Long currentAmount = assetMap.get(nameKey); - if (amount > 0 && null != currentAmount && amount <= currentAmount) { - this.account = this.account.toBuilder() - .putAsset(nameKey, Math.subtractExact(currentAmount, amount)) - .putAssetV2(tokenID, Math.subtractExact(currentAmount, amount)) - .build(); - return true; + if (currentAmount == null) { + currentAmount = 0L; } + this.account = this.account.toBuilder() + .putAsset(nameKey, addExact(currentAmount, amount, disableJavaLangMath)) + .putAssetV2(tokenID, addExact(currentAmount, amount, disableJavaLangMath)) + .build(); } //key is token id if (dynamicPropertiesStore.getAllowSameTokenName() == 1) { - String tokenID = ByteArray.toStr(key); + String tokenIDStr = ByteArray.toStr(key); Map assetMapV2 = this.account.getAssetV2Map(); - Long currentAmount = assetMapV2.get(tokenID); - if (amount > 0 && null != currentAmount && amount <= currentAmount) { - this.account = this.account.toBuilder() - .putAssetV2(tokenID, Math.subtractExact(currentAmount, amount)) - .build(); - return true; + Long currentAmount = assetMapV2.get(tokenIDStr); + if (currentAmount == null) { + currentAmount = 0L; } + this.account = this.account.toBuilder() + .putAssetV2(tokenIDStr, addExact(currentAmount, amount, disableJavaLangMath)) + .build(); } - - return false; + return true; } - /** - * add asset amount. - */ - public boolean addAssetAmount(byte[] key, long amount) { - importAsset(); + public boolean reduceAssetAmount(byte[] key, long amount, boolean disableJavaLangMath) { Map assetMap = this.account.getAssetMap(); String nameKey = ByteArray.toStr(key); Long currentAmount = assetMap.get(nameKey); - if (currentAmount == null) { - currentAmount = 0L; + if (amount > 0 && null != currentAmount && amount <= currentAmount) { + this.account = this.account.toBuilder() + .putAsset(nameKey, subtractExact(currentAmount, amount, disableJavaLangMath)).build(); + return true; } - this.account = this.account.toBuilder().putAsset(nameKey, Math.addExact(currentAmount, amount)) - .build(); - return true; + + return false; } - /** - * add asset amount. - */ - public boolean addAssetAmountV2(byte[] key, long amount, - DynamicPropertiesStore dynamicPropertiesStore, AssetIssueStore assetIssueStore) { - importAsset(); + public boolean reduceAssetAmountV2(byte[] key, long amount, + DynamicPropertiesStore dynamicPropertiesStore, AssetIssueStore assetIssueStore) { + importAsset(key); //key is token name + boolean disableJavaLangMath = dynamicPropertiesStore.disableJavaLangMath(); if (dynamicPropertiesStore.getAllowSameTokenName() == 0) { Map assetMap = this.account.getAssetMap(); AssetIssueCapsule assetIssueCapsule = assetIssueStore.get(key); String tokenID = assetIssueCapsule.getId(); String nameKey = ByteArray.toStr(key); Long currentAmount = assetMap.get(nameKey); - if (currentAmount == null) { - currentAmount = 0L; + if (amount > 0 && null != currentAmount && amount <= currentAmount) { + this.account = this.account.toBuilder() + .putAsset(nameKey, subtractExact(currentAmount, amount, disableJavaLangMath)) + .putAssetV2(tokenID, subtractExact(currentAmount, amount, disableJavaLangMath)) + .build(); + return true; } - this.account = this.account.toBuilder() - .putAsset(nameKey, Math.addExact(currentAmount, amount)) - .putAssetV2(tokenID, Math.addExact(currentAmount, amount)) - .build(); } //key is token id if (dynamicPropertiesStore.getAllowSameTokenName() == 1) { - String tokenIDStr = ByteArray.toStr(key); + String tokenID = ByteArray.toStr(key); Map assetMapV2 = this.account.getAssetV2Map(); - Long currentAmount = assetMapV2.get(tokenIDStr); - if (currentAmount == null) { - currentAmount = 0L; + Long currentAmount = assetMapV2.get(tokenID); + if (amount > 0 && null != currentAmount && amount <= currentAmount) { + this.account = this.account.toBuilder() + .putAssetV2(tokenID, subtractExact(currentAmount, amount, disableJavaLangMath)) + .build(); + return true; } - this.account = this.account.toBuilder() - .putAssetV2(tokenIDStr, Math.addExact(currentAmount, amount)) - .build(); } - return true; + + return false; + } + + public void clearAssetV2() { + this.account = this.account.toBuilder() + .clearAssetV2() + .build(); + } + + public void clearAsset() { + this.account = this.account.toBuilder() + .clearAsset() + .clearAssetV2() + .build(); } - /** - * add asset. - */ public boolean addAsset(byte[] key, long value) { - importAsset(); Map assetMap = this.account.getAssetMap(); String nameKey = ByteArray.toStr(key); if (!assetMap.isEmpty() && assetMap.containsKey(nameKey)) { @@ -674,81 +836,89 @@ public boolean addAsset(byte[] key, long value) { } public boolean addAssetV2(byte[] key, long value) { - importAsset(); - String tokenID = ByteArray.toStr(key); - Map assetV2Map = this.account.getAssetV2Map(); - if (!assetV2Map.isEmpty() && assetV2Map.containsKey(tokenID)) { + if (AssetUtil.hasAssetV2(this.account, key)) { return false; } this.account = this.account.toBuilder() - .putAssetV2(tokenID, value) + .putAssetV2(ByteArray.toStr(key), value) .build(); return true; } - /** - * add asset. - */ - public boolean addAssetMapV2(Map assetMap) { - importAsset(); + public void addAssetMapV2(Map assetMap) { this.account = this.account.toBuilder().putAllAssetV2(assetMap).build(); - return true; + } + + public Long getAsset(DynamicPropertiesStore dynamicStore, String key) { + Long balance; + if (dynamicStore.getAllowSameTokenName() == 0) { + balance = this.account.getAssetMap().get(key); + } else { + importAsset(key.getBytes()); + balance = this.account.getAssetV2Map().get(key); + } + return balance; + } + + public long getAssetV2(String key) { + importAsset(key.getBytes()); + Long balance = this.account.getAssetV2Map().get(key); + return balance == null ? 0 : balance; } public Map getAssetMap() { - importAsset(); Map assetMap = this.account.getAssetMap(); if (assetMap.isEmpty()) { assetMap = Maps.newHashMap(); } - return assetMap; } public Map getAssetMapV2() { - importAsset(); + importAllAsset(); Map assetMap = this.account.getAssetV2Map(); if (assetMap.isEmpty()) { assetMap = Maps.newHashMap(); } - return assetMap; } - public boolean addAllLatestAssetOperationTimeV2(Map map) { - importAsset(); + public Map getAssetMapForTest() { + return getAssetMap(); + } + + public Map getAssetV2MapForTest() { + return getAssetMapV2(); + } + + /*************************** end asset ****************************************/ + + public void addAllLatestAssetOperationTimeV2(Map map) { this.account = this.account.toBuilder().putAllLatestAssetOperationTimeV2(map).build(); - return true; } public Map getLatestAssetOperationTimeMap() { - importAsset(); return this.account.getLatestAssetOperationTimeMap(); } public Map getLatestAssetOperationTimeMapV2() { - importAsset(); return this.account.getLatestAssetOperationTimeV2Map(); } public long getLatestAssetOperationTime(String assetName) { - importAsset(); return this.account.getLatestAssetOperationTimeOrDefault(assetName, 0); } public long getLatestAssetOperationTimeV2(String assetName) { - importAsset(); return this.account.getLatestAssetOperationTimeV2OrDefault(assetName, 0); } public void putLatestAssetOperationTimeMap(String key, Long value) { - importAsset(); this.account = this.account.toBuilder().putLatestAssetOperationTime(key, value).build(); } public void putLatestAssetOperationTimeMapV2(String key, Long value) { - importAsset(); this.account = this.account.toBuilder().putLatestAssetOperationTimeV2(key, value).build(); } @@ -768,17 +938,25 @@ public long getFrozenBalance() { return frozenBalance[0]; } + public long getFrozenV2BalanceForBandwidth() { + List frozenList = getFrozenV2List(); + if (frozenList.isEmpty()) { + return 0; + } + return frozenList.stream().filter(o -> o.getType() == BANDWIDTH) + .mapToLong(FreezeV2::getAmount).sum(); + } + public long getAllFrozenBalanceForBandwidth() { - return getFrozenBalance() + getAcquiredDelegatedFrozenBalanceForBandwidth(); + return getFrozenBalance() + getAcquiredDelegatedFrozenBalanceForBandwidth() + + getFrozenV2BalanceForBandwidth() + getAcquiredDelegatedFrozenV2BalanceForBandwidth(); } public int getFrozenSupplyCount() { - importAsset(); return getInstance().getFrozenSupplyCount(); } public List getFrozenSupplyList() { - importAsset(); return getInstance().getFrozenSupplyList(); } @@ -791,23 +969,19 @@ public long getFrozenSupplyBalance() { } public ByteString getAssetIssuedName() { - importAsset(); return getInstance().getAssetIssuedName(); } public void setAssetIssuedName(byte[] nameKey) { - importAsset(); ByteString assetIssuedName = ByteString.copyFrom(nameKey); this.account = this.account.toBuilder().setAssetIssuedName(assetIssuedName).build(); } public ByteString getAssetIssuedID() { - importAsset(); return getInstance().getAssetIssuedID(); } public void setAssetIssuedID(byte[] id) { - importAsset(); ByteString assetIssuedID = ByteString.copyFrom(id); this.account = this.account.toBuilder().setAssetIssuedID(assetIssuedID).build(); } @@ -883,6 +1057,14 @@ public long getNetUsage() { return this.account.getNetUsage(); } + public long getUsage(ResourceCode resourceCode) { + if (resourceCode == BANDWIDTH) { + return this.account.getNetUsage(); + } else { + return this.account.getAccountResource().getEnergyUsage(); + } + } + public void setNetUsage(long netUsage) { this.account = this.account.toBuilder() .setNetUsage(netUsage).build(); @@ -910,6 +1092,15 @@ public long getEnergyFrozenBalance() { return this.account.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); } + public long getFrozenV2BalanceForEnergy() { + List frozenList = getFrozenV2List(); + if (frozenList.isEmpty()) { + return 0; + } + return frozenList.stream().filter(o -> o.getType() == ENERGY) + .mapToLong(FreezeV2::getAmount).sum(); + } + public boolean oldTronPowerIsNotInitialized() { return this.account.getOldTronPower() == 0; } @@ -952,10 +1143,19 @@ public void setFrozenForTronPower(long frozenBalance, long expireTime) { .build()); } + public void addFrozenForTronPowerV2(long balance) { + this.addFrozenBalanceForResource(TRON_POWER, balance); + } + public long getTronPowerFrozenBalance() { return this.account.getTronPower().getFrozenBalance(); } + public long getTronPowerFrozenV2Balance() { + return getFrozenV2List().stream().filter(o-> o.getType() == TRON_POWER) + .mapToLong(FreezeV2::getAmount).sum(); + } + public long getEnergyUsage() { return this.account.getAccountResource().getEnergyUsage(); } @@ -968,17 +1168,18 @@ public void setEnergyUsage(long energyUsage) { } public long getAllFrozenBalanceForEnergy() { - return getEnergyFrozenBalance() + getAcquiredDelegatedFrozenBalanceForEnergy(); + return getEnergyFrozenBalance() + getAcquiredDelegatedFrozenBalanceForEnergy() + + getFrozenV2BalanceForEnergy() + getAcquiredDelegatedFrozenV2BalanceForEnergy(); } public long getLatestConsumeTimeForEnergy() { return this.account.getAccountResource().getLatestConsumeTimeForEnergy(); } - public void setLatestConsumeTimeForEnergy(long latest_time) { + public void setLatestConsumeTimeForEnergy(long latestTime) { this.account = this.account.toBuilder() .setAccountResource( - this.account.getAccountResource().toBuilder().setLatestConsumeTimeForEnergy(latest_time) + this.account.getAccountResource().toBuilder().setLatestConsumeTimeForEnergy(latestTime) .build()).build(); } @@ -987,44 +1188,35 @@ public long getFreeNetUsage() { } public void setFreeNetUsage(long freeNetUsage) { - this.account = this.account.toBuilder() - .setFreeNetUsage(freeNetUsage).build(); + this.account = this.account.toBuilder().setFreeNetUsage(freeNetUsage).build(); } - public boolean addAllFreeAssetNetUsageV2(Map map) { - importAsset(); + public void addAllFreeAssetNetUsageV2(Map map) { this.account = this.account.toBuilder().putAllFreeAssetNetUsageV2(map).build(); - return true; } public long getFreeAssetNetUsage(String assetName) { - importAsset(); return this.account.getFreeAssetNetUsageOrDefault(assetName, 0); } public long getFreeAssetNetUsageV2(String assetName) { - importAsset(); return this.account.getFreeAssetNetUsageV2OrDefault(assetName, 0); } public Map getAllFreeAssetNetUsage() { - importAsset(); return this.account.getFreeAssetNetUsageMap(); } public Map getAllFreeAssetNetUsageV2() { - importAsset(); return this.account.getFreeAssetNetUsageV2Map(); } public void putFreeAssetNetUsage(String s, long freeAssetNetUsage) { - importAsset(); this.account = this.account.toBuilder() .putFreeAssetNetUsage(s, freeAssetNetUsage).build(); } public void putFreeAssetNetUsageV2(String s, long freeAssetNetUsage) { - importAsset(); this.account = this.account.toBuilder() .putFreeAssetNetUsageV2(s, freeAssetNetUsage).build(); } @@ -1135,22 +1327,153 @@ public void updateAccountType(AccountType accountType) { public void clearDelegatedResource() { Builder builder = account.toBuilder(); AccountResource newAccountResource = getAccountResource().toBuilder() - .setAcquiredDelegatedFrozenBalanceForEnergy(0L).build(); + .setAcquiredDelegatedFrozenBalanceForEnergy(0L) + .setAcquiredDelegatedFrozenV2BalanceForEnergy(0L) + .build(); builder.setAccountResource(newAccountResource); - builder.setAcquiredDelegatedFrozenBalanceForBandwidth(0L); + builder.setAcquiredDelegatedFrozenBalanceForBandwidth(0L) + .setAcquiredDelegatedFrozenV2BalanceForBandwidth(0L); this.account = builder.build(); } - public void importAsset() { - if (!AssetUtil.isAllowAssetOptimization()) { + public void importAsset(byte[] key) { + this.account = AssetUtil.importAsset(this.account, key); + } + + public void importAllAsset() { + if (!flag) { + this.account = AssetUtil.importAllAsset(this.account); + flag = true; + } + } + + public void addUnfrozenV2(UnFreezeV2 unfrozenV2) { + if (Objects.isNull(unfrozenV2)) { return; } - if (!this.isAssetImport) { - Account account = AssetUtil.importAsset(this.account); - if (null != account) { - this.account = account; - } - this.isAssetImport = true; + this.account = this.account.toBuilder().addUnfrozenV2(unfrozenV2).build(); + } + + public void addAllUnfrozenV2(List unFreezeV2List) { + if (CollectionUtils.isEmpty(unFreezeV2List)) { + return; + } + this.account = this.account.toBuilder().addAllUnfrozenV2(unFreezeV2List).build(); + } + + public void clearUnfrozenV2() { + this.account = this.account.toBuilder().clearUnfrozenV2().build(); + } + + public void clearFrozenV2() { + this.account = this.account.toBuilder().clearFrozenV2().build(); + } + + public void setNewWindowSize(ResourceCode resourceCode, long newWindowSize) { + if (resourceCode == BANDWIDTH) { + this.account = this.account.toBuilder().setNetWindowSize(newWindowSize).build(); + } else { + this.account = this.account.toBuilder().setAccountResource(this.account.getAccountResource() + .toBuilder().setEnergyWindowSize(newWindowSize).build()).build(); + } + } + + public long getWindowSize(ResourceCode resourceCode) { + long windowSize; + boolean windowOptimized; + if (resourceCode == BANDWIDTH) { + windowSize = this.account.getNetWindowSize(); + windowOptimized = this.account.getNetWindowOptimized(); + } else { + windowSize = this.account.getAccountResource().getEnergyWindowSize(); + windowOptimized = this.account.getAccountResource().getEnergyWindowOptimized(); + } + if (windowSize == 0) { + return WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL; + } + if (windowOptimized) { + return windowSize < WINDOW_SIZE_PRECISION ? WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL : + windowSize / WINDOW_SIZE_PRECISION; + } else { + return windowSize; + } + } + + public long getWindowSizeV2(ResourceCode resourceCode) { + long windowSize; + boolean windowOptimized; + if (resourceCode == BANDWIDTH) { + windowSize = this.account.getNetWindowSize(); + windowOptimized = this.account.getNetWindowOptimized(); + } else { + windowSize = this.account.getAccountResource().getEnergyWindowSize(); + windowOptimized = this.account.getAccountResource().getEnergyWindowOptimized(); + } + if (windowSize == 0) { + return WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL * WINDOW_SIZE_PRECISION; + } + if (windowOptimized) { + return windowSize; + } else { + return windowSize * WINDOW_SIZE_PRECISION; + } + } + + public boolean getWindowOptimized(ResourceCode resourceCode) { + boolean windowOptimized; + if (resourceCode == BANDWIDTH) { + windowOptimized = this.account.getNetWindowOptimized(); + } else { + windowOptimized = this.account.getAccountResource().getEnergyWindowOptimized(); + } + return windowOptimized; + } + + public void setWindowOptimized(ResourceCode resourceCode, boolean windowOptimized) { + if (resourceCode == BANDWIDTH) { + this.account = this.account.toBuilder().setNetWindowOptimized(windowOptimized).build(); + } else { + this.account = this.account.toBuilder().setAccountResource(this.account.getAccountResource() + .toBuilder().setEnergyWindowOptimized(windowOptimized).build()).build(); + } + } + + public long getLastConsumeTime(ResourceCode resourceCode) { + if (resourceCode == BANDWIDTH) { + return this.account.getLatestConsumeTime(); + } else { + return this.account.getAccountResource().getLatestConsumeTimeForEnergy(); + } + } + + public long getFrozenV2BalanceWithDelegated(ResourceCode resourceCode) { + if (resourceCode == BANDWIDTH) { + return getFrozenV2BalanceForBandwidth() + getDelegatedFrozenV2BalanceForBandwidth(); + } else { + return getFrozenV2BalanceForEnergy() + getDelegatedFrozenV2BalanceForEnergy(); + } + } + + public void setNewWindowSizeV2( ResourceCode resourceCode, long newWindowSize) { + this.setNewWindowSize(resourceCode, newWindowSize); + if (!this.getWindowOptimized(resourceCode)) { + this.setWindowOptimized(resourceCode, true); + } + } + + public void setUsage(ResourceCode resourceCode, long usage) { + if (resourceCode == BANDWIDTH) { + setNetUsage(usage); + } else { + setEnergyUsage(usage); + } + } + + public void setLatestTime(ResourceCode resourceCode, long time) { + if (resourceCode == BANDWIDTH) { + setLatestConsumeTime(time); + } else { + setLatestConsumeTimeForEnergy(time); } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java index 5979ae5bf83..01ff7fb5365 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java @@ -56,7 +56,6 @@ public class BlockCapsule implements ProtoCapsule { private Block block; private List transactions = new ArrayList<>(); - private StringBuilder toStringBuff = new StringBuilder(); private boolean isSwitch; @Getter @Setter @@ -143,6 +142,13 @@ public void addTransaction(TransactionCapsule pendingTrx) { getTransactions().add(pendingTrx); } + public void addAllTransactions(List pendingTrxs) { + List list = pendingTrxs.stream().map(TransactionCapsule::getInstance).collect( + Collectors.toList()); + this.block = this.block.toBuilder().addAllTransactions(list).build(); + getTransactions().addAll(pendingTrxs); + } + public List getTransactions() { return transactions; } @@ -277,6 +283,10 @@ public Block getInstance() { return this.block; } + public long getSerializedSize() { + return this.block.getSerializedSize(); + } + public Sha256Hash getParentHash() { return Sha256Hash.wrap(this.block.getBlockHeader().getRawData().getParentHash()); } @@ -303,7 +313,7 @@ public boolean hasWitnessSignature() { @Override public String toString() { - toStringBuff.setLength(0); + StringBuilder toStringBuff = new StringBuilder(); toStringBuff.append("BlockCapsule \n[ "); toStringBuff.append("hash=").append(getBlockId()).append("\n"); diff --git a/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java index 2204b6446a3..f566a128d6b 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ContractCapsule.java @@ -15,8 +15,8 @@ package org.tron.core.capsule; -import static java.lang.Math.max; -import static java.lang.Math.min; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; import com.google.protobuf.Any; import com.google.protobuf.ByteString; @@ -109,9 +109,9 @@ public byte[] getOriginAddress() { return this.smartContract.getOriginAddress().toByteArray(); } - public long getConsumeUserResourcePercent() { + public long getConsumeUserResourcePercent(boolean disableMath) { long percent = this.smartContract.getConsumeUserResourcePercent(); - return max(0, min(percent, Constant.ONE_HUNDRED)); + return max(0, min(percent, Constant.ONE_HUNDRED, disableMath), disableMath); } public long getOriginEnergyLimit() { @@ -133,4 +133,5 @@ public byte[] getTrxHash() { public int getContractVersion() { return this.smartContract.getVersion(); } + } diff --git a/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java new file mode 100644 index 00000000000..bd932ea50ae --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/capsule/ContractStateCapsule.java @@ -0,0 +1,154 @@ +package org.tron.core.capsule; + +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; +import static org.tron.common.math.Maths.pow; +import static org.tron.core.Constant.DYNAMIC_ENERGY_DECREASE_DIVISION; +import static org.tron.core.Constant.DYNAMIC_ENERGY_FACTOR_DECIMAL; + +import com.google.protobuf.InvalidProtocolBufferException; +import lombok.extern.slf4j.Slf4j; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.contract.SmartContractOuterClass; +import org.tron.protos.contract.SmartContractOuterClass.ContractState; + +@Slf4j(topic = "capsule") +public class ContractStateCapsule implements ProtoCapsule { + + private ContractState contractState; + + public ContractStateCapsule(ContractState contractState) { + this.contractState = contractState; + } + + public ContractStateCapsule(byte[] data) { + try { + this.contractState = SmartContractOuterClass.ContractState.parseFrom(data); + } catch (InvalidProtocolBufferException e) { + // logger.debug(e.getMessage()); + } + } + + public ContractStateCapsule(long currentCycle) { + reset(currentCycle); + } + + @Override + public byte[] getData() { + return this.contractState.toByteArray(); + } + + @Override + public ContractState getInstance() { + return this.contractState; + } + + public long getEnergyUsage() { + return this.contractState.getEnergyUsage(); + } + + public void setEnergyUsage(long value) { + this.contractState = this.contractState.toBuilder().setEnergyUsage(value).build(); + } + + public void addEnergyUsage(long toAdd) { + setEnergyUsage(getEnergyUsage() + toAdd); + } + + public long getEnergyFactor() { + return this.contractState.getEnergyFactor(); + } + + public void setEnergyFactor(long value) { + this.contractState = this.contractState.toBuilder().setEnergyFactor(value).build(); + } + + public long getUpdateCycle() { + return this.contractState.getUpdateCycle(); + } + + public void setUpdateCycle(long value) { + this.contractState = this.contractState.toBuilder().setUpdateCycle(value).build(); + } + + public void addUpdateCycle(long toAdd) { + setUpdateCycle(getUpdateCycle() + toAdd); + } + + public boolean catchUpToCycle(DynamicPropertiesStore dps) { + return catchUpToCycle( + dps.getCurrentCycleNumber(), + dps.getDynamicEnergyThreshold(), + dps.getDynamicEnergyIncreaseFactor(), + dps.getDynamicEnergyMaxFactor(), + dps.allowStrictMath(), + dps.disableJavaLangMath() + ); + } + + public boolean catchUpToCycle( + long newCycle, long threshold, long increaseFactor, long maxFactor, + boolean useStrictMath, boolean disableMath + ) { + long lastCycle = getUpdateCycle(); + + // Updated within this cycle + if (lastCycle == newCycle) { + return false; + } + + // Guard judge and uninitialized state + if (lastCycle > newCycle || lastCycle == 0L) { + reset(newCycle); + return true; + } + + final long precisionFactor = DYNAMIC_ENERGY_FACTOR_DECIMAL; + + // Increase the last cycle + // fix the threshold = 0 caused incompatible + if (getEnergyUsage() > threshold) { + lastCycle += 1; + double increasePercent = 1 + (double) increaseFactor / precisionFactor; + this.contractState = ContractState.newBuilder() + .setUpdateCycle(lastCycle) + .setEnergyFactor(min( + maxFactor, + (long) ((getEnergyFactor() + precisionFactor) * increasePercent) - precisionFactor, + disableMath)) + .build(); + } + + // No need to decrease + long cycleCount = newCycle - lastCycle; + if (cycleCount <= 0) { + return true; + } + + // Calc the decrease percent (decrease factor [75% ~ 100%]) + double decreasePercent = pow( + 1 - (double) increaseFactor / DYNAMIC_ENERGY_DECREASE_DIVISION / precisionFactor, + cycleCount, useStrictMath + ); + + // Decrease to this cycle + // (If long time no tx and factor is 100%, + // we just calc it again and result factor is still 100%. + // That means we merge this special case to normal cases) + this.contractState = ContractState.newBuilder() + .setUpdateCycle(newCycle) + .setEnergyFactor(max( + 0, + (long) ((getEnergyFactor() + precisionFactor) * decreasePercent) - precisionFactor, + disableMath)) + .build(); + + return true; + } + + public void reset(long latestCycle) { + this.contractState = ContractState.newBuilder() + .setUpdateCycle(latestCycle) + .build(); + } +} diff --git a/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceAccountIndexCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceAccountIndexCapsule.java index 7c7a37fa609..9874c7de503 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceAccountIndexCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceAccountIndexCapsule.java @@ -93,6 +93,15 @@ public void removeToAccount(ByteString toAccount) { } } + public void setTimestamp(long time) { + this.delegatedResourceAccountIndex = this.delegatedResourceAccountIndex.toBuilder() + .setTimestamp(time) + .build(); + } + + public long getTimestamp() { + return this.delegatedResourceAccountIndex.getTimestamp(); + } public byte[] createDbKey() { return getAccount().toByteArray(); diff --git a/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceCapsule.java index 0eb6dc8ec09..05324bb267e 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/DelegatedResourceCapsule.java @@ -1,5 +1,6 @@ package org.tron.core.capsule; +import com.google.common.primitives.Bytes; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import lombok.extern.slf4j.Slf4j; @@ -9,6 +10,9 @@ @Slf4j(topic = "capsule") public class DelegatedResourceCapsule implements ProtoCapsule { + protected static final byte[] V2_PREFIX = new byte[]{0x01}; + protected static final byte[] V2_LOCK_PREFIX = new byte[]{0x02}; + private DelegatedResource delegatedResource; public DelegatedResourceCapsule(final DelegatedResource delegatedResource) { @@ -37,6 +41,13 @@ public static byte[] createDbKey(byte[] from, byte[] to) { return key; } + public static byte[] createDbKeyV2(byte[] from, byte[] to, boolean lock) { + if (lock) { + return Bytes.concat(V2_LOCK_PREFIX, from, to); + } + return Bytes.concat(V2_PREFIX, from, to); + } + public ByteString getFrom() { return this.delegatedResource.getFrom(); } @@ -67,17 +78,26 @@ public long getFrozenBalanceForBandwidth() { return this.delegatedResource.getFrozenBalanceForBandwidth(); } - public void setFrozenBalanceForBandwidth(long Bandwidth, long expireTime) { + public long getFrozenBalance(boolean isBandwidth) { + if (isBandwidth) { + return getFrozenBalanceForBandwidth(); + } else { + return getFrozenBalanceForEnergy(); + } + + } + + public void setFrozenBalanceForBandwidth(long bandwidth, long expireTime) { this.delegatedResource = this.delegatedResource.toBuilder() - .setFrozenBalanceForBandwidth(Bandwidth) + .setFrozenBalanceForBandwidth(bandwidth) .setExpireTimeForBandwidth(expireTime) .build(); } - public void addFrozenBalanceForBandwidth(long Bandwidth, long expireTime) { + public void addFrozenBalanceForBandwidth(long bandwidth, long expireTime) { this.delegatedResource = this.delegatedResource.toBuilder() .setFrozenBalanceForBandwidth(this.delegatedResource.getFrozenBalanceForBandwidth() - + Bandwidth) + + bandwidth) .setExpireTimeForBandwidth(expireTime) .build(); } @@ -90,9 +110,9 @@ public long getExpireTimeForEnergy() { return this.delegatedResource.getExpireTimeForEnergy(); } - public void setExpireTimeForBandwidth(long ExpireTime) { + public void setExpireTimeForBandwidth(long expireTime) { this.delegatedResource = this.delegatedResource.toBuilder() - .setExpireTimeForBandwidth(ExpireTime) + .setExpireTimeForBandwidth(expireTime) .build(); } @@ -104,9 +124,9 @@ public long getExpireTimeForEnergy(DynamicPropertiesStore dynamicPropertiesStore } } - public void setExpireTimeForEnergy(long ExpireTime) { + public void setExpireTimeForEnergy(long expireTime) { this.delegatedResource = this.delegatedResource.toBuilder() - .setExpireTimeForEnergy(ExpireTime) + .setExpireTimeForEnergy(expireTime) .build(); } diff --git a/chainbase/src/main/java/org/tron/core/capsule/ExchangeCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ExchangeCapsule.java index 1cf91301b43..0dec7d60820 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ExchangeCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ExchangeCapsule.java @@ -112,9 +112,9 @@ public byte[] createDbKey() { return calculateDbKey(getID()); } - public long transaction(byte[] sellTokenID, long sellTokenQuant) { + public long transaction(byte[] sellTokenID, long sellTokenQuant, boolean useStrictMath) { long supply = 1_000_000_000_000_000_000L; - ExchangeProcessor processor = new ExchangeProcessor(supply); + ExchangeProcessor processor = new ExchangeProcessor(supply, useStrictMath); long buyTokenQuant = 0; long firstTokenBalance = this.exchange.getFirstTokenBalance(); diff --git a/chainbase/src/main/java/org/tron/core/capsule/ExchangeProcessor.java b/chainbase/src/main/java/org/tron/core/capsule/ExchangeProcessor.java index e1b536b3e7a..91f5c101b58 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ExchangeProcessor.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ExchangeProcessor.java @@ -1,14 +1,17 @@ package org.tron.core.capsule; import lombok.extern.slf4j.Slf4j; +import org.tron.common.math.Maths; @Slf4j(topic = "capsule") public class ExchangeProcessor { private long supply; + private final boolean useStrictMath; - public ExchangeProcessor(long supply) { + public ExchangeProcessor(long supply, boolean useStrictMath) { this.supply = supply; + this.useStrictMath = useStrictMath; } private long exchangeToSupply(long balance, long quant) { @@ -16,7 +19,8 @@ private long exchangeToSupply(long balance, long quant) { long newBalance = balance + quant; logger.debug("balance + quant: " + newBalance); - double issuedSupply = -supply * (1.0 - Math.pow(1.0 + (double) quant / newBalance, 0.0005)); + double issuedSupply = -supply * (1.0 + - Maths.pow(1.0 + (double) quant / newBalance, 0.0005, this.useStrictMath)); logger.debug("issuedSupply: " + issuedSupply); long out = (long) issuedSupply; supply += out; @@ -27,8 +31,8 @@ private long exchangeToSupply(long balance, long quant) { private long exchangeFromSupply(long balance, long supplyQuant) { supply -= supplyQuant; - double exchangeBalance = - balance * (Math.pow(1.0 + (double) supplyQuant / supply, 2000.0) - 1.0); + double exchangeBalance = balance + * (Maths.pow(1.0 + (double) supplyQuant / supply, 2000.0, this.useStrictMath) - 1.0); logger.debug("exchangeBalance: " + exchangeBalance); return (long) exchangeBalance; diff --git a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java index 3124494c67e..06513a0edc7 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/ReceiptCapsule.java @@ -1,5 +1,8 @@ package org.tron.core.capsule; +import static org.tron.common.math.Maths.min; +import static org.tron.common.math.Maths.multiplyExact; + import java.util.Objects; import lombok.Getter; import lombok.Setter; @@ -20,10 +23,15 @@ public class ReceiptCapsule { private ResourceReceipt receipt; + @Getter @Setter private long multiSignFee; + @Getter + @Setter + private long memoFee; + /** * Available energy of contract deployer before executing transaction */ @@ -36,6 +44,63 @@ public class ReceiptCapsule { @Setter private long callerEnergyLeft; + /** + * Energy usage of caller before merging frozen energy + */ + @Getter + @Setter + private long callerEnergyUsage; + + /** + * Energy usage of caller after merging frozen energy + */ + @Getter + @Setter + private long callerEnergyMergedUsage; + + /** + * Energy usage of origin after merging frozen energy + */ + @Getter + @Setter + private long originEnergyMergedUsage; + + /** + * Window size of caller before merging frozen energy + */ + @Getter + @Setter + private long callerEnergyWindowSize; + + @Getter + @Setter + private long callerEnergyWindowSizeV2; + + /** + * Window size of caller after merging frozen energy + */ + @Getter + @Setter + private long callerEnergyMergedWindowSize; + + /** + * Window size of origin before merging frozen energy + */ + @Getter + @Setter + private long originEnergyWindowSize; + + @Getter + @Setter + private long originEnergyWindowSizeV2; + + /** + * Window size of origin after merging frozen energy + */ + @Getter + @Setter + private long originEnergyMergedWindowSize; + private Sha256Hash receiptAddress; public ReceiptCapsule(ResourceReceipt data, Sha256Hash receiptAddress) { @@ -106,6 +171,14 @@ public void setEnergyUsageTotal(long energyUsage) { this.receipt = this.receipt.toBuilder().setEnergyUsageTotal(energyUsage).build(); } + public long getEnergyPenaltyTotal() { + return this.receipt.getEnergyPenaltyTotal(); + } + + public void setEnergyPenaltyTotal(long penalty) { + this.receipt = this.receipt.toBuilder().setEnergyPenaltyTotal(penalty).build(); + } + public long getNetUsage() { return this.receipt.getNetUsage(); } @@ -130,6 +203,12 @@ public void payEnergyBill(DynamicPropertiesStore dynamicPropertiesStore, AccountCapsule caller, long percent, long originEnergyLimit, EnergyProcessor energyProcessor, long now) throws BalanceInsufficientException { + + // Reset origin energy usage here! Because after stake 2.0, this field are reused for + // recording pre-merge frozen energy for origin account. If total energy usage is zero, this + // field will be a dirty record. + this.setOriginEnergyUsage(0); + if (receipt.getEnergyUsageTotal() <= 0) { return; } @@ -139,12 +218,14 @@ public void payEnergyBill(DynamicPropertiesStore dynamicPropertiesStore, receipt.getEnergyUsageTotal(), receipt.getResult(), energyProcessor, now); return; } + boolean disableJavaLangMath = dynamicPropertiesStore.disableJavaLangMath(); - if ((!Objects.isNull(origin))&&caller.getAddress().equals(origin.getAddress())) { + if ((!Objects.isNull(origin)) && caller.getAddress().equals(origin.getAddress())) { payEnergyBill(dynamicPropertiesStore, accountStore, forkController, caller, receipt.getEnergyUsageTotal(), receipt.getResult(), energyProcessor, now); } else { - long originUsage = Math.multiplyExact(receipt.getEnergyUsageTotal(), percent) / 100; + long originUsage = multiplyExact(receipt.getEnergyUsageTotal(), percent, disableJavaLangMath) + / 100; originUsage = getOriginUsage(dynamicPropertiesStore, origin, originEnergyLimit, energyProcessor, originUsage); @@ -160,16 +241,20 @@ public void payEnergyBill(DynamicPropertiesStore dynamicPropertiesStore, private long getOriginUsage(DynamicPropertiesStore dynamicPropertiesStore, AccountCapsule origin, long originEnergyLimit, EnergyProcessor energyProcessor, long originUsage) { - - if (dynamicPropertiesStore.getAllowTvmFreeze() == 1) { - return Math.min(originUsage, Math.min(originEnergyLeft, originEnergyLimit)); + boolean disableJavaLangMath = dynamicPropertiesStore.disableJavaLangMath(); + if (dynamicPropertiesStore.getAllowTvmFreeze() == 1 + || dynamicPropertiesStore.supportUnfreezeDelay()) { + return min(originUsage, min(originEnergyLeft, originEnergyLimit, disableJavaLangMath), + disableJavaLangMath); } if (checkForEnergyLimit(dynamicPropertiesStore)) { - return Math.min(originUsage, - Math.min(energyProcessor.getAccountLeftEnergyFromFreeze(origin), originEnergyLimit)); + return min(originUsage, + min(energyProcessor.getAccountLeftEnergyFromFreeze(origin), originEnergyLimit, + disableJavaLangMath), disableJavaLangMath); } - return Math.min(originUsage, energyProcessor.getAccountLeftEnergyFromFreeze(origin)); + return min(originUsage, energyProcessor.getAccountLeftEnergyFromFreeze(origin), + disableJavaLangMath); } private void payEnergyBill( @@ -181,7 +266,8 @@ private void payEnergyBill( EnergyProcessor energyProcessor, long now) throws BalanceInsufficientException { long accountEnergyLeft; - if (dynamicPropertiesStore.getAllowTvmFreeze() == 1) { + if (dynamicPropertiesStore.getAllowTvmFreeze() == 1 + || dynamicPropertiesStore.supportUnfreezeDelay()) { accountEnergyLeft = callerEnergyLeft; } else { accountEnergyLeft = energyProcessor.getAccountLeftEnergyFromFreeze(account); @@ -223,7 +309,7 @@ private void payEnergyBill( } else { //send to blackHole Commons.adjustBalance(accountStore, accountStore.getBlackhole(), - energyFee); + energyFee, dynamicPropertiesStore.disableJavaLangMath()); } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java index cd35bf4a253..95f436b19f0 100755 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionCapsule.java @@ -17,12 +17,14 @@ import static org.tron.common.utils.StringUtil.encode58Check; import static org.tron.common.utils.WalletUtil.checkPermissionOperations; +import static org.tron.core.Constant.MAX_CONTRACT_RESULT_SIZE; import static org.tron.core.exception.P2pException.TypeEnum.PROTOBUF_ERROR; import com.google.common.primitives.Bytes; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.GeneratedMessageV3; import com.google.protobuf.Internal; import com.google.protobuf.InvalidProtocolBufferException; @@ -32,7 +34,6 @@ import java.util.HashMap; import java.util.List; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicInteger; import lombok.Getter; @@ -42,12 +43,15 @@ import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.crypto.SignInterface; import org.tron.common.crypto.SignUtils; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.overlay.message.Message; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.ForkController; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.core.actuator.TransactionFactory; +import org.tron.core.config.Parameter; import org.tron.core.db.TransactionContext; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.BadItemException; @@ -55,6 +59,7 @@ import org.tron.core.exception.P2pException; import org.tron.core.exception.PermissionException; import org.tron.core.exception.SignatureFormatException; +import org.tron.core.exception.TransactionExpirationException; import org.tron.core.exception.ValidateSignatureException; import org.tron.core.store.AccountStore; import org.tron.core.store.DynamicPropertiesStore; @@ -83,8 +88,9 @@ @Slf4j(topic = "capsule") public class TransactionCapsule implements ProtoCapsule { - private static final ExecutorService executorService = Executors - .newFixedThreadPool(CommonParameter.getInstance() + private static final String esName = "valid-contract-proto"; + private static final ExecutorService executorService = ExecutorServiceManager + .newFixedThreadPool(esName, CommonParameter.getInstance() .getValidContractProtoThreadNum()); private static final String OWNER_ADDRESS = "ownerAddress_"; @@ -98,13 +104,29 @@ public class TransactionCapsule implements ProtoCapsule { @Setter private TransactionTrace trxTrace; - private StringBuilder toStringBuff = new StringBuilder(); @Getter @Setter private long time; @Getter @Setter private long order; + private byte[] ownerAddress; + private Sha256Hash id; + + @Getter + @Setter + private boolean isTransactionCreate = false; + @Getter + @Setter + private boolean isInBlock = false; + + public byte[] getOwnerAddress() { + if (this.ownerAddress == null) { + this.ownerAddress = getOwner(this.transaction.getRawData().getContract(0)); + } + return this.ownerAddress; + } + /** * constructor TransactionCapsule. @@ -198,6 +220,11 @@ public static long getWeight(Permission permission, byte[] address) { return 0; } + /** + * make sure ForkController.init(ChainBaseManager) is invoked before invoke this method. + * + * @see ForkController#init(org.tron.core.ChainBaseManager) + */ public static long checkWeight(Permission permission, List sigs, byte[] hash, List approveList) throws SignatureException, PermissionException, SignatureFormatException { @@ -222,6 +249,9 @@ public static long checkWeight(Permission permission, List sigs, byt ByteArray.toHexString(sig.toByteArray()) + " is signed by " + encode58Check(address) + " but it is not contained of permission."); } + if (ForkController.instance().pass(Parameter.ForkBlockVersionEnum.VERSION_4_7_1)) { + base64 = encode58Check(address); + } if (addMap.containsKey(base64)) { throw new PermissionException(encode58Check(address) + " has signed twice!"); } @@ -308,19 +338,23 @@ public static byte[] getOwner(Transaction.Contract contract) { Class clazz = TransactionFactory .getContract(contract.getType()); if (clazz == null) { - logger.error("not exist {}", contract.getType()); + logger.warn("not exist {}", contract.getType()); return new byte[0]; } GeneratedMessageV3 generatedMessageV3 = contractParameter.unpack(clazz); owner = ReflectUtils.getFieldValue(generatedMessageV3, OWNER_ADDRESS); if (owner == null) { - logger.error("not exist [{}] field,{}", OWNER_ADDRESS, clazz); + logger.warn("not exist [{}] field,{}", OWNER_ADDRESS, clazz); return new byte[0]; } break; } } return owner.toByteArray(); + } catch (InvalidProtocolBufferException invalidProtocolBufferException) { + logger.warn("InvalidProtocolBufferException occurred because {}, please verify the interface " + + "input parameters", invalidProtocolBufferException.getMessage()); + return new byte[0]; } catch (Exception ex) { logger.error(ex.getMessage()); return new byte[0]; @@ -479,7 +513,7 @@ public void setReference(long blockNum, byte[] blockHash) { .setRefBlockHash(ByteString.copyFrom(ByteArray.subArray(blockHash, 8, 16))) .setRefBlockBytes(ByteString.copyFrom(ByteArray.subArray(refBlockNum, 6, 8))) .build(); - this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); + setRawData(rawData); } public long getExpiration() { @@ -492,27 +526,38 @@ public long getExpiration() { public void setExpiration(long expiration) { Transaction.raw rawData = this.transaction.getRawData().toBuilder().setExpiration(expiration) .build(); - this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); + setRawData(rawData); } public void setTimestamp() { Transaction.raw rawData = this.transaction.getRawData().toBuilder() .setTimestamp(System.currentTimeMillis()) .build(); - this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); + setRawData(rawData); } public void setTimestamp(long timestamp) { Transaction.raw rawData = this.transaction.getRawData().toBuilder() .setTimestamp(timestamp) .build(); - this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); + setRawData(rawData); } public long getTimestamp() { return transaction.getRawData().getTimestamp(); } + public void setFeeLimit(long feeLimit) { + Transaction.raw rawData = this.transaction.getRawData().toBuilder() + .setFeeLimit(feeLimit) + .build(); + setRawData(rawData); + } + + public long getFeeLimit() { + return transaction.getRawData().getFeeLimit(); + } + @Deprecated public void createTransaction(com.google.protobuf.Message message, ContractType contractType) { Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( @@ -536,7 +581,7 @@ public void sign(byte[] privateKey) { SignInterface cryptoEngine = SignUtils .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(getRawHash().getBytes()))); + .signHash(getTransactionId().getBytes()))); this.transaction = this.transaction.toBuilder().addSignature(sig).build(); } @@ -544,7 +589,7 @@ public void addSign(byte[] privateKey, AccountStore accountStore) throws PermissionException, SignatureException, SignatureFormatException { Transaction.Contract contract = this.transaction.getRawData().getContract(0); int permissionId = contract.getPermissionId(); - byte[] owner = getOwner(contract); + byte[] owner = getOwnerAddress(); AccountCapsule account = accountStore.get(owner); if (account == null) { throw new PermissionException("Account is not exist!"); @@ -559,7 +604,8 @@ public void addSign(byte[] privateKey, AccountStore accountStore) .fromPrivate(privateKey, CommonParameter.getInstance().isECKeyCryptoEngine()); byte[] address = cryptoEngine.getAddress(); if (this.transaction.getSignatureCount() > 0) { - checkWeight(permission, this.transaction.getSignatureList(), this.getRawHash().getBytes(), + checkWeight(permission, this.transaction.getSignatureList(), + this.getTransactionId().getBytes(), approveList); if (approveList.contains(ByteString.copyFrom(address))) { throw new PermissionException(encode58Check(address) + " had signed!"); @@ -573,7 +619,7 @@ public void addSign(byte[] privateKey, AccountStore accountStore) + " but it is not contained of permission."); } ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(getRawHash().getBytes()))); + .signHash(getTransactionId().getBytes()))); this.transaction = this.transaction.toBuilder().addSignature(sig).build(); } @@ -605,7 +651,7 @@ public boolean validatePubSignature(AccountStore accountStore, throw new ValidateSignatureException("too many signatures"); } - byte[] hash = this.getRawHash().getBytes(); + byte[] hash = getTransactionId().getBytes(); try { if (!validateSignature(this.transaction, hash, accountStore, dynamicPropertiesStore)) { @@ -632,7 +678,7 @@ public boolean validateSignature(AccountStore accountStore, if (contract.getType() != ContractType.ShieldedTransferContract) { validatePubSignature(accountStore, dynamicPropertiesStore); } else { //ShieldedTransfer - byte[] owner = getOwner(contract); + byte[] owner = getOwnerAddress(); if (!ArrayUtils.isEmpty(owner)) { //transfer from transparent address validatePubSignature(accountStore, dynamicPropertiesStore); } else { //transfer from shielded address @@ -648,7 +694,16 @@ public boolean validateSignature(AccountStore accountStore, } public Sha256Hash getTransactionId() { - return getRawHash(); + if (this.id == null) { + this.id = getRawHash(); + } + return this.id; + } + + private void setRawData(Transaction.raw rawData) { + this.transaction = this.transaction.toBuilder().setRawData(rawData).build(); + // invalidate trxId + this.id = null; } @Override @@ -660,6 +715,18 @@ public long getSerializedSize() { return this.transaction.getSerializedSize(); } + /** + * Compute the number of bytes that would be needed to encode an embedded message field, including + * tag. + * message Block { + * repeated Transaction transactions = 1; + * BlockHeader block_header = 2; + * } + */ + public long computeTrxSizeForBlockMessage() { + return CodedOutputStream.computeMessageSize(1, this.transaction); + } + public long getResultSerializedSize() { long size = 0; for (Result result : this.transaction.getRetList()) { @@ -668,6 +735,15 @@ public long getResultSerializedSize() { return size; } + public long getResultSizeWithMaxContractRet() { + long size = 0; + for (Result result : this.transaction.getRetList()) { + size += result.toBuilder().clearContractRet().build().getSerializedSize() + + MAX_CONTRACT_RESULT_SIZE; + } + return size; + } + @Override public Transaction getInstance() { return this.transaction; @@ -675,8 +751,7 @@ public Transaction getInstance() { @Override public String toString() { - - toStringBuff.setLength(0); + StringBuilder toStringBuff = new StringBuilder(); toStringBuff.append("TransactionCapsule \n[ "); toStringBuff.append("hash=").append(getTransactionId()).append("\n"); @@ -781,4 +856,39 @@ public BalanceContract.TransferContract getTransferContract() { return null; } } + + public void removeRedundantRet() { + Transaction tx = this.getInstance(); + List tmpList = new ArrayList<>(tx.getRetList()); + int contractCount = tx.getRawData().getContractCount(); + if (tx.getRetCount() > contractCount && contractCount > 0) { + Transaction.Builder transactionBuilder = tx.toBuilder().clearRet(); + for (int i = 0; i < contractCount; i++) { + Result result = tmpList.get(i); + transactionBuilder.addRet(result); + } + this.transaction = transactionBuilder.build(); + } + } + + public void checkExpiration(long nextSlotTime) throws TransactionExpirationException { + if (getExpiration() < nextSlotTime) { + throw new TransactionExpirationException(String.format( + "Transaction expiration time is %d, but next slot time is %d", + getExpiration(), nextSlotTime)); + } + } + + public boolean retCountIsGreatThanContractCount() { + int contractCount = getContractCount(); + return getRetCount() > contractCount && contractCount > 0; + } + + public int getRetCount() { + return this.getInstance().getRetCount(); + } + + public int getContractCount() { + return this.getInstance().getRawData().getContractCount(); + } } diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java index f82ec427a0f..8ff3064b73c 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionResultCapsule.java @@ -3,6 +3,7 @@ import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.util.List; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.tron.core.exception.BadItemException; import org.tron.protos.Protocol.MarketOrderDetail; @@ -80,6 +81,24 @@ public void setWithdrawAmount(long amount) { this.transactionResult = this.transactionResult.toBuilder().setWithdrawAmount(amount).build(); } + public long getWithdrawExpireAmount() { + return transactionResult.getWithdrawExpireAmount(); + } + + public void setWithdrawExpireAmount(long amount) { + this.transactionResult = this.transactionResult.toBuilder() + .setWithdrawExpireAmount(amount).build(); + } + + public Map getCancelUnfreezeV2AmountMap() { + return transactionResult.getCancelUnfreezeV2AmountMap(); + } + + public void putAllCancelUnfreezeV2AmountMap(Map map) { + this.transactionResult = this.transactionResult.toBuilder() + .putAllCancelUnfreezeV2Amount(map).build(); + } + public long getExchangeReceivedAmount() { return transactionResult.getExchangeReceivedAmount(); } diff --git a/chainbase/src/main/java/org/tron/core/capsule/TransactionRetCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/TransactionRetCapsule.java index 499cbcb3b42..94188229d98 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/TransactionRetCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/TransactionRetCapsule.java @@ -1,6 +1,7 @@ package org.tron.core.capsule; import com.google.protobuf.InvalidProtocolBufferException; +import java.util.List; import java.util.Objects; import lombok.extern.slf4j.Slf4j; import org.tron.core.exception.BadItemException; @@ -29,7 +30,7 @@ public TransactionRetCapsule() { public TransactionRetCapsule(byte[] data) throws BadItemException { try { - this.transactionRet = transactionRet.parseFrom(data); + this.transactionRet = TransactionRet.parseFrom(data); } catch (InvalidProtocolBufferException e) { throw new BadItemException("TransactionInfoCapsule proto data parse exception"); } @@ -39,6 +40,10 @@ public void addTransactionInfo(TransactionInfo result) { this.transactionRet = this.transactionRet.toBuilder().addTransactioninfo(result).build(); } + public void addAllTransactionInfos(List results) { + this.transactionRet = this.transactionRet.toBuilder().addAllTransactioninfo(results).build(); + } + @Override public byte[] getData() { if (Objects.isNull(transactionRet)) { diff --git a/chainbase/src/main/java/org/tron/core/capsule/VotesCapsule.java b/chainbase/src/main/java/org/tron/core/capsule/VotesCapsule.java index a3692d52627..6e92dff56d4 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/VotesCapsule.java +++ b/chainbase/src/main/java/org/tron/core/capsule/VotesCapsule.java @@ -84,6 +84,10 @@ public void addNewVotes(ByteString voteAddress, long voteCount) { .build(); } + public void addAllNewVotes(List votesToAdd) { + this.votes = this.votes.toBuilder().addAllNewVotes(votesToAdd).build(); + } + public void addOldVotes(ByteString voteAddress, long voteCount) { this.votes = this.votes.toBuilder() .addOldVotes(Vote.newBuilder().setVoteAddress(voteAddress).setVoteCount(voteCount).build()) diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/AssetUtil.java b/chainbase/src/main/java/org/tron/core/capsule/utils/AssetUtil.java index 966cadae852..abdb8098643 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/AssetUtil.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/AssetUtil.java @@ -1,18 +1,12 @@ package org.tron.core.capsule.utils; -import com.google.protobuf.ByteString; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.tron.core.capsule.AccountAssetCapsule; +import com.google.common.primitives.Bytes; +import java.util.HashMap; +import java.util.Map; +import org.tron.common.utils.ByteArray; import org.tron.core.store.AccountAssetStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.AccountAsset; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; public class AssetUtil { @@ -20,114 +14,41 @@ public class AssetUtil { private static DynamicPropertiesStore dynamicPropertiesStore; - public static AccountAsset getAsset(Account account) { - if (!hasAsset(account)) { - return null; + public static boolean hasAssetV2(Account account, byte[] key) { + if (!account.getAssetV2Map().isEmpty() + && account.getAssetV2Map().containsKey(ByteArray.toStr(key))) { + return true; } - return AccountAsset.newBuilder() - .setAddress(account.getAddress()) - .setAssetIssuedID(account.getAssetIssuedID()) - .setAssetIssuedName(account.getAssetIssuedName()) - .putAllAsset(account.getAssetMap()) - .putAllAssetV2(account.getAssetV2Map()) - .putAllFreeAssetNetUsage(account.getFreeAssetNetUsageMap()) - .putAllFreeAssetNetUsageV2(account.getFreeAssetNetUsageV2Map()) - .putAllLatestAssetOperationTime(account.getLatestAssetOperationTimeMap()) - .putAllLatestAssetOperationTimeV2( - account.getLatestAssetOperationTimeV2Map()) - .addAllFrozenSupply(getFrozen(account.getFrozenSupplyList())) - .build(); - } - - private static List getFrozen(List frozenSupplyList) { - return frozenSupplyList - .stream() - .map(frozen -> AccountAsset.Frozen.newBuilder() - .setExpireTime(frozen.getExpireTime()) - .setFrozenBalance(frozen.getFrozenBalance()) - .build()) - .collect(Collectors.toList()); + if (!isAllowAssetOptimization()) { + return false; + } + byte[] dbKey = Bytes.concat(account.getAddress().toByteArray(), key); + return accountAssetStore.get(dbKey) != null; } - - public static Account importAsset(Account account) { - if (AssetUtil.hasAsset(account)) { - return null; + public static Account importAsset(Account account, byte[] key) { + if (!isAllowAssetOptimization()) { + return account; } - AccountAssetCapsule accountAssetCapsule = accountAssetStore.get(account.getAddress().toByteArray()); - if (accountAssetCapsule == null) { - return null; - } - - return account.toBuilder() - .setAssetIssuedID(accountAssetCapsule.getAssetIssuedID()) - .setAssetIssuedName(accountAssetCapsule.getAssetIssuedName()) - .putAllAsset(accountAssetCapsule.getAssetMap()) - .putAllAssetV2(accountAssetCapsule.getAssetMapV2()) - .putAllFreeAssetNetUsage(accountAssetCapsule.getAllFreeAssetNetUsage()) - .putAllFreeAssetNetUsageV2(accountAssetCapsule.getAllFreeAssetNetUsageV2()) - .putAllLatestAssetOperationTime(accountAssetCapsule.getLatestAssetOperationTimeMap()) - .putAllLatestAssetOperationTimeV2( - accountAssetCapsule.getLatestAssetOperationTimeMapV2()) - .addAllFrozenSupply(getAccountFrozenSupplyList(accountAssetCapsule.getFrozenSupplyList())) - .build(); - } - private static List getAccountFrozenSupplyList(List frozenSupplyList) { - return Optional.ofNullable(frozenSupplyList) - .orElseGet(ArrayList::new) - .stream() - .map(frozen -> Account.Frozen.newBuilder() - .setExpireTime(frozen.getExpireTime()) - .setFrozenBalance(frozen.getFrozenBalance()) - .build()) - .collect(Collectors.toList()); - } + String sKey = ByteArray.toStr(key); + if (account.getAssetV2Map().containsKey(sKey)) { + return account; + } - public static Account clearAsset(Account account) { - return account.toBuilder() - .clearAssetIssuedID() - .clearAssetIssuedName() - .clearAsset() - .clearAssetV2() - .clearFreeAssetNetUsage() - .clearFreeAssetNetUsageV2() - .clearLatestAssetOperationTime() - .clearLatestAssetOperationTimeV2() - .clearFrozenSupply() - .build(); + long balance = accountAssetStore.getBalance(account, key); + Map map = new HashMap<>(); + map.putAll(account.getAssetV2Map()); + map.put(sKey, balance); + return account.toBuilder().clearAssetV2().putAllAssetV2(map).build(); } - public static boolean hasAsset(Account account) { - if (MapUtils.isNotEmpty(account.getAssetMap()) || - MapUtils.isNotEmpty(account.getAssetV2Map())) { - return true; - } - ByteString assetIssuedName = account.getAssetIssuedName(); - if (assetIssuedName != null && !assetIssuedName.isEmpty()) { - return true; - } - ByteString assetIssuedID = account.getAssetIssuedID(); - if (assetIssuedID != null && !assetIssuedID.isEmpty()) { - return true; - } - if (MapUtils.isNotEmpty(account.getLatestAssetOperationTimeMap()) || - MapUtils.isNotEmpty(account.getLatestAssetOperationTimeV2Map())) { - return true; - } - if (MapUtils.isNotEmpty(account.getFreeAssetNetUsageMap())) { - return true; - } - if (MapUtils.isNotEmpty(account.getFreeAssetNetUsageV2Map())) { - return true; - } - List frozenSupplyList = - account.getFrozenSupplyList(); - if (CollectionUtils.isNotEmpty(frozenSupplyList) - && frozenSupplyList.size() > 0) { - return true; + public static Account importAllAsset(Account account) { + if (!isAllowAssetOptimization()) { + return account; } - return false; + Map map = accountAssetStore.getAllAssets(account); + return account.toBuilder().clearAssetV2().putAllAssetV2(map).build(); } public static void setAccountAssetStore( @@ -140,7 +61,7 @@ public static void setDynamicPropertiesStore(DynamicPropertiesStore dynamicPrope } public static boolean isAllowAssetOptimization() { - return dynamicPropertiesStore.supportAllowAccountAssetOptimization(); + return dynamicPropertiesStore.supportAllowAssetOptimization(); } -} \ No newline at end of file +} diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java b/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java index f345a96df81..d711ac0d63b 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/MarketUtils.java @@ -15,6 +15,10 @@ package org.tron.core.capsule.utils; +import static org.tron.common.math.Maths.addExact; +import static org.tron.common.math.Maths.floorDiv; +import static org.tron.common.math.Maths.multiplyExact; + import com.google.protobuf.ByteString; import java.math.BigInteger; import java.util.Arrays; @@ -230,8 +234,8 @@ public static byte[] createPairKey(byte[] sellTokenId, byte[] buyTokenId) { public static int comparePrice(long price1SellQuantity, long price1BuyQuantity, long price2SellQuantity, long price2BuyQuantity) { try { - return Long.compare(Math.multiplyExact(price1BuyQuantity, price2SellQuantity), - Math.multiplyExact(price2BuyQuantity, price1SellQuantity)); + return Long.compare(multiplyExact(price1BuyQuantity, price2SellQuantity, true), + multiplyExact(price2BuyQuantity, price1SellQuantity, true)); } catch (ArithmeticException ex) { // do nothing here, because we will use BigInteger to compute again @@ -246,25 +250,6 @@ public static int comparePrice(long price1SellQuantity, long price1BuyQuantity, .compareTo(price2BuyQuantityBI.multiply(price1SellQuantityBI)); } - /** - * ex. - * for sellToken is A, buyToken is TRX. - * price_A_maker * sellQuantity_maker = Price_TRX * buyQuantity_maker - * ==> price_A_maker = Price_TRX * buyQuantity_maker/sellQuantity_maker - * - * price_A_maker_1 < price_A_maker_2 - * ==> buyQuantity_maker_1/sellQuantity_maker_1 < buyQuantity_maker_2/sellQuantity_maker_2 - * ==> buyQuantity_maker_1*sellQuantity_maker_2 < buyQuantity_maker_2 * sellQuantity_maker_1 - */ - public static int comparePrice(MarketPrice price1, MarketPrice price2) { - return comparePrice(price1.getSellTokenQuantity(), price1.getBuyTokenQuantity(), - price2.getSellTokenQuantity(), price2.getBuyTokenQuantity()); - } - - public static boolean isLowerPrice(MarketPrice price1, MarketPrice price2) { - return comparePrice(price1, price2) == -1; - } - /** * if takerPrice >= makerPrice, return True * note: here are two different token pairs @@ -297,10 +282,10 @@ public static void updateOrderState(MarketOrderCapsule orderCapsule, } } - public static long multiplyAndDivide(long a, long b, long c) { + public static long multiplyAndDivide(long a, long b, long c, boolean disableMath) { try { - long tmp = Math.multiplyExact(a, b); - return Math.floorDiv(tmp, c); + long tmp = multiplyExact(a, b, disableMath); + return floorDiv(tmp, c, disableMath); } catch (ArithmeticException ex) { // do nothing here, because we will use BigInteger to compute again } @@ -320,8 +305,9 @@ public static void returnSellTokenRemain(MarketOrderCapsule orderCapsule, byte[] sellTokenId = orderCapsule.getSellTokenId(); long sellTokenQuantityRemain = orderCapsule.getSellTokenQuantityRemain(); if (Arrays.equals(sellTokenId, "_".getBytes())) { - accountCapsule.setBalance(Math.addExact( - accountCapsule.getBalance(), sellTokenQuantityRemain)); + accountCapsule.setBalance(addExact( + accountCapsule.getBalance(), sellTokenQuantityRemain, + dynamicStore.disableJavaLangMath())); } else { accountCapsule .addAssetAmountV2(sellTokenId, sellTokenQuantityRemain, dynamicStore, assetIssueStore); diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java index 47ac45c9fb8..94d22f4b474 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/MerkleTree.java @@ -5,10 +5,12 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import lombok.Getter; +import net.jcip.annotations.NotThreadSafe; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Sha256Hash; @Getter +@NotThreadSafe public class MerkleTree { private static volatile MerkleTree instance; diff --git a/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java b/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java index a2c3facd565..c9e0d30b1e6 100644 --- a/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java +++ b/chainbase/src/main/java/org/tron/core/capsule/utils/TransactionUtil.java @@ -72,9 +72,9 @@ public static TransactionInfoCapsule buildTransactionInfoInstance(TransactionCap } builder.setId(ByteString.copyFrom(trxCap.getTransactionId().getBytes())); ProgramResult programResult = trace.getRuntimeResult(); - long fee = - programResult.getRet().getFee() + traceReceipt.getEnergyFee() - + traceReceipt.getNetFee() + traceReceipt.getMultiSignFee(); + long fee = programResult.getRet().getFee() + traceReceipt.getEnergyFee() + + traceReceipt.getNetFee() + traceReceipt.getMultiSignFee() + + traceReceipt.getMemoFee(); boolean supportTransactionFeePool = trace.getTransactionContext().getStoreFactory() .getChainBaseManager().getDynamicPropertiesStore().supportTransactionFeePool(); @@ -90,15 +90,17 @@ public static TransactionInfoCapsule buildTransactionInfoInstance(TransactionCap } ByteString contractResult = ByteString.copyFrom(programResult.getHReturn()); - ByteString ContractAddress = ByteString.copyFrom(programResult.getContractAddress()); + ByteString contractAddress = ByteString.copyFrom(programResult.getContractAddress()); builder.setFee(fee); builder.addContractResult(contractResult); - builder.setContractAddress(ContractAddress); + builder.setContractAddress(contractAddress); builder.setUnfreezeAmount(programResult.getRet().getUnfreezeAmount()); builder.setAssetIssueID(programResult.getRet().getAssetIssueID()); builder.setExchangeId(programResult.getRet().getExchangeId()); builder.setWithdrawAmount(programResult.getRet().getWithdrawAmount()); + builder.setWithdrawExpireAmount(programResult.getRet().getWithdrawExpireAmount()); + builder.putAllCancelUnfreezeV2Amount(programResult.getRet().getCancelUnfreezeV2AmountMap()); builder.setExchangeReceivedAmount(programResult.getRet().getExchangeReceivedAmount()); builder.setExchangeInjectAnotherAmount(programResult.getRet().getExchangeInjectAnotherAmount()); builder.setExchangeWithdrawAnotherAmount( @@ -123,8 +125,18 @@ public static TransactionInfoCapsule buildTransactionInfoInstance(TransactionCap builder.setReceipt(traceReceipt.getReceipt()); if (CommonParameter.getInstance().isSaveInternalTx()) { - programResult.getInternalTransactions().forEach(it -> - builder.addInternalTransactions(buildInternalTransaction(it))); + if (CommonParameter.getInstance().isSaveFeaturedInternalTx()) { + programResult.getInternalTransactions().forEach(it -> + builder.addInternalTransactions(buildInternalTransaction(it))); + } else { + programResult.getInternalTransactions().stream() + .filter(it -> + "call".equals(it.getNote()) + || "create".equals(it.getNote()) + || "suicide".equals(it.getNote())) + .forEach(it -> + builder.addInternalTransactions(buildInternalTransaction(it))); + } } return new TransactionInfoCapsule(builder.build()); diff --git a/chainbase/src/main/java/org/tron/core/db/AbstractRevokingStore.java b/chainbase/src/main/java/org/tron/core/db/AbstractRevokingStore.java deleted file mode 100644 index 725456ce39e..00000000000 --- a/chainbase/src/main/java/org/tron/core/db/AbstractRevokingStore.java +++ /dev/null @@ -1,477 +0,0 @@ -package org.tron.core.db; - -import static org.tron.core.db2.core.SnapshotManager.simpleDecode; - -import com.google.common.collect.Maps; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Deque; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.stream.Collectors; -import lombok.AllArgsConstructor; -import lombok.EqualsAndHashCode; -import lombok.Getter; -import lombok.ToString; -import lombok.extern.slf4j.Slf4j; -import org.iq80.leveldb.Options; -import org.iq80.leveldb.WriteOptions; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.storage.WriteOptionsWrapper; -import org.tron.common.storage.leveldb.LevelDbDataSourceImpl; -import org.tron.common.utils.FileUtil; -import org.tron.common.utils.StorageUtils; -import org.tron.common.utils.Utils; -import org.tron.core.db.common.SourceInter; -import org.tron.core.db2.ISession; -import org.tron.core.db2.common.IRevokingDB; -import org.tron.core.db2.core.Chainbase; -import org.tron.core.db2.core.RevokingDBWithCachingOldValue; -import org.tron.core.exception.RevokingStoreIllegalStateException; - -@Slf4j(topic = "DB") -@Getter // only for unit test -public abstract class AbstractRevokingStore implements RevokingDatabase { - - private static final int DEFAULT_STACK_MAX_SIZE = 256; - private static String ACTIVE_DIALOG_POSITIVE = "activeDialog has to be greater than 0"; - private Deque stack = new LinkedList<>(); - private boolean disabled = true; - private int activeDialog = 0; - private AtomicInteger maxSize = new AtomicInteger(DEFAULT_STACK_MAX_SIZE); - private WriteOptionsWrapper writeOptionsWrapper = WriteOptionsWrapper.getInstance() - .sync(CommonParameter.getInstance().getStorage().isDbSync()); - private List dbs = new ArrayList<>(); - - @Override - public ISession buildSession() { - return buildSession(false); - } - - @Override - public synchronized ISession buildSession(boolean forceEnable) { - if (disabled && !forceEnable) { - return new Dialog(this); - } - - boolean disableOnExit = disabled && forceEnable; - if (forceEnable) { - disabled = false; - } - - while (stack.size() > maxSize.get()) { - stack.poll(); - } - - stack.add(new RevokingState()); - ++activeDialog; - return new Dialog(this, disableOnExit); - } - - @Override - public void setCursor(Chainbase.Cursor cursor) { - - } - - @Override - public void setCursor(Chainbase.Cursor cursor, long offset) { - - } - - @Override - public synchronized void check() { - LevelDbDataSourceImpl check = - new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName("tmp"), "tmp", - new Options(), - new WriteOptions()); - check.initDB(); - - if (!check.allKeys().isEmpty()) { - Map dbMap = dbs.stream() - .map(db -> Maps.immutableEntry(db.getDBName(), db)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - - for (Map.Entry e : check) { - byte[] key = e.getKey(); - byte[] value = e.getValue(); - String db = simpleDecode(key); - if (dbMap.get(db) == null) { - continue; - } - byte[] realKey = Arrays.copyOfRange(key, db.getBytes().length + 4, key.length); - - byte[] realValue = value.length == 1 ? null : Arrays.copyOfRange(value, 1, value.length); - if (realValue != null) { - dbMap.get(db).putData(realKey, realValue); - } else { - dbMap.get(db).deleteData(realKey); - } - } - } - - check.closeDB(); - FileUtil.recursiveDelete(check.getDbPath().toString()); - } - - @Override - public void add(IRevokingDB revokingDB) { - dbs.add(((RevokingDBWithCachingOldValue) revokingDB).getDbSource()); - } - - public synchronized void onCreate(RevokingTuple tuple, byte[] value) { - if (disabled) { - return; - } - - addIfEmpty(); - RevokingState state = stack.peekLast(); - state.newIds.add(tuple); - } - - public synchronized void onModify(RevokingTuple tuple, byte[] value) { - if (disabled) { - return; - } - - addIfEmpty(); - RevokingState state = stack.peekLast(); - if (state.newIds.contains(tuple) || state.oldValues.containsKey(tuple)) { - return; - } - - state.oldValues.put(tuple, Utils.clone(value)); - } - - public synchronized void onRemove(RevokingTuple tuple, byte[] value) { - if (disabled) { - return; - } - - addIfEmpty(); - RevokingState state = stack.peekLast(); - if (state.newIds.contains(tuple)) { - state.newIds.remove(tuple); - return; - } - - if (state.oldValues.containsKey(tuple)) { - state.removed.put(tuple, state.oldValues.get(tuple)); - state.oldValues.remove(tuple); - return; - } - - if (state.removed.containsKey(tuple)) { - return; - } - - state.removed.put(tuple, Utils.clone(value)); - } - - @Override - public synchronized void merge() { - if (activeDialog <= 0) { - throw new RevokingStoreIllegalStateException(ACTIVE_DIALOG_POSITIVE); - } - - if (activeDialog == 1 && stack.size() == 1) { - stack.pollLast(); - --activeDialog; - return; - } - - if (stack.size() < 2) { - return; - } - - RevokingState state = stack.peekLast(); - @SuppressWarnings("unchecked") - List list = (List) stack; - RevokingState prevState = list.get(stack.size() - 2); - - state.oldValues.entrySet().stream() - .filter(e -> !prevState.newIds.contains(e.getKey())) - .filter(e -> !prevState.oldValues.containsKey(e.getKey())) - .forEach(e -> prevState.oldValues.put(e.getKey(), e.getValue())); - - prevState.newIds.addAll(state.newIds); - - state.removed.entrySet().stream() - .filter(e -> { - boolean has = prevState.newIds.contains(e.getKey()); - if (has) { - prevState.newIds.remove(e.getKey()); - } - - return !has; - }) - .filter(e -> { - boolean has = prevState.oldValues.containsKey(e.getKey()); - if (has) { - prevState.removed.put(e.getKey(), prevState.oldValues.get(e.getKey())); - prevState.oldValues.remove(e.getKey()); - } - - return !has; - }) - .forEach(e -> prevState.removed.put(e.getKey(), e.getValue())); - - stack.pollLast(); - --activeDialog; - } - - @Override - public synchronized void revoke() { - if (disabled) { - return; - } - - if (activeDialog <= 0) { - throw new RevokingStoreIllegalStateException(ACTIVE_DIALOG_POSITIVE); - } - - disabled = true; - - try { - RevokingState state = stack.peekLast(); - if (Objects.isNull(state)) { - return; - } - - state.oldValues.forEach((k, v) -> k.database.putData(k.key, v)); - state.newIds.forEach(e -> e.database.deleteData(e.key)); - state.removed.forEach((k, v) -> k.database.putData(k.key, v)); - stack.pollLast(); - } finally { - disabled = false; - } - --activeDialog; - } - - @Override - public synchronized void commit() { - if (activeDialog <= 0) { - throw new RevokingStoreIllegalStateException(ACTIVE_DIALOG_POSITIVE); - } - - --activeDialog; - } - - @Override - public synchronized void pop() { - prune(writeOptionsWrapper); - } - - @Override - public synchronized void fastPop() { - prune(WriteOptionsWrapper.getInstance()); - } - - private synchronized void prune(WriteOptionsWrapper optionsWrapper) { - if (activeDialog != 0) { - throw new RevokingStoreIllegalStateException("activeDialog has to be equal 0"); - } - - if (stack.isEmpty()) { - throw new RevokingStoreIllegalStateException("stack is empty"); - } - - disabled = true; - - try { - RevokingState state = stack.peekLast(); - state.oldValues.forEach((k, v) -> k.database.putData(k.key, v)); - state.newIds.forEach(e -> e.database.deleteData(e.key)); - state.removed.forEach((k, v) -> k.database.putData(k.key, v)); - stack.pollLast(); - } finally { - disabled = false; - } - } - - @Override - public synchronized void enable() { - disabled = false; - } - - @Override - public synchronized void disable() { - disabled = true; - } - - private void addIfEmpty() { - if (stack.isEmpty()) { - stack.add(new RevokingState()); - } - } - - @Override - public synchronized int size() { - return stack.size(); - } - - public int getMaxSize() { - return maxSize.get(); - } - - @Override - public void setMaxSize(int maxSize) { - this.maxSize.set(maxSize); - } - - @Override - public void setMaxFlushCount(int maxFlushCount) { - } - - public synchronized void shutdown() { - System.err.println("******** begin to pop revokingDb ********"); - System.err.println("******** before revokingDb size:" + size()); - try { - disable(); - while (true) { - try { - commit(); - } catch (RevokingStoreIllegalStateException e) { - break; - } - if (activeDialog <= 0) { - break; - } - } - - while (true) { - try { - pop(); - } catch (RevokingStoreIllegalStateException e) { - break; - } - if (activeDialog != 0) { - break; - } - if (stack.isEmpty()) { - break; - } - } - } catch (Exception e) { - System.err.println("******** failed to pop revokingStore. " + e); - } finally { - System.err.println("******** after revokingStore size:" + stack.size()); - System.err.println("******** after revokingStore contains:" + stack); - System.err.println("******** end to pop revokingStore ********"); - } - } - - @Slf4j(topic = "DB") - @Getter // only for unit test - public static class Dialog implements ISession { - - private RevokingDatabase revokingDatabase; - private boolean applyRevoking = true; - private boolean disableOnExit = false; - - public Dialog(Dialog dialog) { - this.revokingDatabase = dialog.revokingDatabase; - this.applyRevoking = dialog.applyRevoking; - dialog.applyRevoking = false; - } - - public Dialog(RevokingDatabase revokingDatabase) { - this(revokingDatabase, false); - } - - public Dialog(RevokingDatabase revokingDatabase, boolean disableOnExit) { - this.revokingDatabase = revokingDatabase; - this.disableOnExit = disableOnExit; - } - - @Override - public void commit() { - applyRevoking = false; - revokingDatabase.commit(); - } - - @Override - public void revoke() { - if (applyRevoking) { - revokingDatabase.revoke(); - } - - applyRevoking = false; - } - - @Override - public void merge() { - if (applyRevoking) { - revokingDatabase.merge(); - } - - applyRevoking = false; - } - - void copy(Dialog dialog) { - if (this.equals(dialog)) { - return; - } - - if (applyRevoking) { - revokingDatabase.revoke(); - } - applyRevoking = dialog.applyRevoking; - dialog.applyRevoking = false; - } - - @Override - public void destroy() { - try { - if (applyRevoking) { - revokingDatabase.revoke(); - } - } catch (Exception e) { - logger.error("revoke database error.", e); - } - if (disableOnExit) { - revokingDatabase.disable(); - } - } - - @Override - public void close() { - try { - if (applyRevoking) { - revokingDatabase.revoke(); - } - } catch (Exception e) { - logger.error("revoke database error.", e); - throw new RevokingStoreIllegalStateException(e); - } - if (disableOnExit) { - revokingDatabase.disable(); - } - } - } - - @ToString - @Getter // only for unit test - static class RevokingState { - - private Map oldValues = new HashMap<>(); - private Set newIds = new HashSet<>(); - private Map removed = new HashMap<>(); - } - - @AllArgsConstructor - @EqualsAndHashCode - @Getter - @ToString - public static class RevokingTuple { - - private SourceInter database; - private byte[] key; - } - -} diff --git a/chainbase/src/main/java/org/tron/core/db/BandwidthProcessor.java b/chainbase/src/main/java/org/tron/core/db/BandwidthProcessor.java new file mode 100644 index 00000000000..2488686bfb0 --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/db/BandwidthProcessor.java @@ -0,0 +1,545 @@ +package org.tron.core.db; + +import static org.tron.core.Constant.PER_SIGN_LENGTH; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.Protocol.Transaction.Contract.ContractType.ShieldedTransferContract; +import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferAssetContract; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; + +import com.google.protobuf.ByteString; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Commons; +import org.tron.common.utils.StringUtil; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.AssetIssueCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.exception.AccountResourceInsufficientException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TooBigTransactionResultException; +import org.tron.protos.Protocol.Transaction.Contract; +import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; +import org.tron.protos.contract.BalanceContract.TransferContract; + +@Slf4j(topic = "DB") +public class BandwidthProcessor extends ResourceProcessor { + + private ChainBaseManager chainBaseManager; + + public BandwidthProcessor(ChainBaseManager chainBaseManager) { + super(chainBaseManager.getDynamicPropertiesStore(), chainBaseManager.getAccountStore()); + this.chainBaseManager = chainBaseManager; + } + + public void updateUsageForDelegated(AccountCapsule ac) { + long now = chainBaseManager.getHeadSlot(); + long oldNetUsage = ac.getNetUsage(); + long latestConsumeTime = ac.getLatestConsumeTime(); + ac.setNetUsage(increase(ac, BANDWIDTH, oldNetUsage, 0, latestConsumeTime, now)); + } + + public void updateUsage(AccountCapsule accountCapsule) { + long now = chainBaseManager.getHeadSlot(); + long oldNetUsage = accountCapsule.getNetUsage(); + long latestConsumeTime = accountCapsule.getLatestConsumeTime(); + accountCapsule.setNetUsage(increase(accountCapsule, BANDWIDTH, + oldNetUsage, 0, latestConsumeTime, now)); + long oldFreeNetUsage = accountCapsule.getFreeNetUsage(); + long latestConsumeFreeTime = accountCapsule.getLatestConsumeFreeTime(); + accountCapsule.setFreeNetUsage(increase(oldFreeNetUsage, 0, latestConsumeFreeTime, now)); + + if (chainBaseManager.getDynamicPropertiesStore().getAllowSameTokenName() == 0) { + Map assetMap = accountCapsule.getAssetMap(); + assetMap.forEach((assetName, balance) -> { + long oldFreeAssetNetUsage = accountCapsule.getFreeAssetNetUsage(assetName); + long latestAssetOperationTime = accountCapsule.getLatestAssetOperationTime(assetName); + accountCapsule.putFreeAssetNetUsage(assetName, + increase(oldFreeAssetNetUsage, 0, latestAssetOperationTime, now)); + }); + } + Map assetMapV2 = accountCapsule.getAssetMapV2(); + Map map = new HashMap<>(assetMapV2); + accountCapsule.getAllFreeAssetNetUsageV2().forEach((k, v) -> { + if (!map.containsKey(k)) { + map.put(k, 0L); + } + }); + map.forEach((assetName, balance) -> { + long oldFreeAssetNetUsage = accountCapsule.getFreeAssetNetUsageV2(assetName); + long latestAssetOperationTime = accountCapsule.getLatestAssetOperationTimeV2(assetName); + accountCapsule.putFreeAssetNetUsageV2(assetName, + increase(oldFreeAssetNetUsage, 0, latestAssetOperationTime, now)); + }); + } + + // update usage for asset issue + public void updateUsage(AssetIssueCapsule assetIssueCapsule) { + long now = chainBaseManager.getHeadSlot(); + updateUsage(assetIssueCapsule, now); + } + + public void updateUsage(AssetIssueCapsule assetIssueCapsule, long now) { + long publicFreeAssetNetUsage = assetIssueCapsule.getPublicFreeAssetNetUsage(); + long publicLatestFreeNetTime = assetIssueCapsule.getPublicLatestFreeNetTime(); + + assetIssueCapsule.setPublicFreeAssetNetUsage(increase(publicFreeAssetNetUsage, 0, + publicLatestFreeNetTime, now)); + } + + + @Override + public void consume(TransactionCapsule trx, TransactionTrace trace) + throws ContractValidateException, AccountResourceInsufficientException, + TooBigTransactionResultException, TooBigTransactionException { + List contracts = trx.getInstance().getRawData().getContractList(); + long resultSizeWithMaxContractRet = trx.getResultSizeWithMaxContractRet(); + boolean optimizeTxs = !trx.isInBlock() || chainBaseManager + .getDynamicPropertiesStore().allowConsensusLogicOptimization(); + if (!trx.isInBlock() && resultSizeWithMaxContractRet > + Constant.MAX_RESULT_SIZE_IN_TX * contracts.size()) { + throw new TooBigTransactionResultException(String.format( + "Too big transaction result, TxId %s, the result size is %d bytes, maxResultSize %d", + trx.getTransactionId(), resultSizeWithMaxContractRet, Constant.MAX_RESULT_SIZE_IN_TX)); + } + if (trx.getResultSerializedSize() > Constant.MAX_RESULT_SIZE_IN_TX * contracts.size()) { + throw new TooBigTransactionResultException(); + } + + long bytesSize; + + if (chainBaseManager.getDynamicPropertiesStore().supportVM()) { + bytesSize = trx.getInstance().toBuilder().clearRet().build().getSerializedSize(); + } else { + bytesSize = trx.getSerializedSize(); + } + + for (Contract contract : contracts) { + if (contract.getType() == ShieldedTransferContract) { + continue; + } + if (chainBaseManager.getDynamicPropertiesStore().supportVM()) { + bytesSize += Constant.MAX_RESULT_SIZE_IN_TX; + } + + logger.debug("TxId {}, bandwidth cost: {}.", trx.getTransactionId(), bytesSize); + trace.setNetBill(bytesSize, 0); + byte[] address = TransactionCapsule.getOwner(contract); + AccountCapsule accountCapsule = chainBaseManager.getAccountStore().get(address); + if (accountCapsule == null) { + throw new ContractValidateException(String.format("account [%s] does not exist", + StringUtil.encode58Check(address))); + } + long now = chainBaseManager.getHeadSlot(); + if (contractCreateNewAccount(contract)) { + if (optimizeTxs) { + long maxCreateAccountTxSize = dynamicPropertiesStore.getMaxCreateAccountTxSize(); + int signatureCount = trx.getInstance().getSignatureCount(); + long createAccountBytesSize = trx.getInstance().toBuilder().clearRet() + .build().getSerializedSize() - (signatureCount * PER_SIGN_LENGTH); + if (createAccountBytesSize > maxCreateAccountTxSize) { + throw new TooBigTransactionException(String.format( + "Too big new account transaction, TxId %s, the size is %d bytes, maxTxSize %d", + trx.getTransactionId(), createAccountBytesSize, maxCreateAccountTxSize)); + } + } + consumeForCreateNewAccount(accountCapsule, bytesSize, now, trace); + continue; + } + + if (contract.getType() == TransferAssetContract && useAssetAccountNet(contract, + accountCapsule, now, bytesSize)) { + continue; + } + + if (useAccountNet(accountCapsule, bytesSize, now)) { + continue; + } + + if (useFreeNet(accountCapsule, bytesSize, now)) { + continue; + } + + if (useTransactionFee(accountCapsule, bytesSize, trace)) { + continue; + } + + long fee = chainBaseManager.getDynamicPropertiesStore().getTransactionFee() * bytesSize; + throw new AccountResourceInsufficientException( + String.format( + "account [%s] has insufficient bandwidth[%d] and balance[%d] to create new account", + StringUtil.encode58Check(address), bytesSize, fee)); + } + } + + private boolean useTransactionFee(AccountCapsule accountCapsule, long bytes, + TransactionTrace trace) { + long fee = chainBaseManager.getDynamicPropertiesStore().getTransactionFee() * bytes; + if (consumeFeeForBandwidth(accountCapsule, fee)) { + trace.setNetBill(0, fee); + chainBaseManager.getDynamicPropertiesStore().addTotalTransactionCost(fee); + return true; + } else { + return false; + } + } + + private void consumeForCreateNewAccount(AccountCapsule accountCapsule, long bytes, + long now, TransactionTrace trace) + throws AccountResourceInsufficientException { + boolean ret = consumeBandwidthForCreateNewAccount(accountCapsule, bytes, now, trace); + + if (!ret) { + ret = consumeFeeForCreateNewAccount(accountCapsule, trace); + if (!ret) { + throw new AccountResourceInsufficientException(String.format( + "account [%s] has insufficient bandwidth[%d] and balance[%d] to create new account", + StringUtil.encode58Check(accountCapsule.createDbKey()), bytes, + chainBaseManager.getDynamicPropertiesStore().getCreateAccountFee())); + } + } + } + + public boolean consumeBandwidthForCreateNewAccount(AccountCapsule accountCapsule, long bytes, + long now, TransactionTrace trace) { + + long createNewAccountBandwidthRatio = chainBaseManager.getDynamicPropertiesStore() + .getCreateNewAccountBandwidthRate(); + + long netUsage = accountCapsule.getNetUsage(); + long latestConsumeTime = accountCapsule.getLatestConsumeTime(); + long netLimit = calculateGlobalNetLimit(accountCapsule); + long newNetUsage; + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newNetUsage = increase(netUsage, 0, latestConsumeTime, now); + } else { + // only participate in the calculation as a temporary variable, without disk flushing + newNetUsage = recovery(accountCapsule, BANDWIDTH, netUsage, latestConsumeTime, now); + } + + long netCost = bytes * createNewAccountBandwidthRatio; + if (netCost <= (netLimit - newNetUsage)) { + long latestOperationTime = chainBaseManager.getHeadBlockTimeStamp(); + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newNetUsage = increase(newNetUsage, netCost, now, now); + } else { + // Participate in calculation and flush disk persistence + newNetUsage = increase(accountCapsule, BANDWIDTH, + netUsage, netCost, latestConsumeTime, now); + } + accountCapsule.setLatestConsumeTime(now); + accountCapsule.setLatestOperationTime(latestOperationTime); + accountCapsule.setNetUsage(newNetUsage); + + trace.setNetBillForCreateNewAccount(netCost, 0); + chainBaseManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + return true; + } + return false; + } + + public boolean consumeFeeForCreateNewAccount(AccountCapsule accountCapsule, + TransactionTrace trace) { + long fee = chainBaseManager.getDynamicPropertiesStore().getCreateAccountFee(); + if (consumeFeeForNewAccount(accountCapsule, fee)) { + trace.setNetBillForCreateNewAccount(0, fee); + chainBaseManager.getDynamicPropertiesStore().addTotalCreateAccountCost(fee); + return true; + } else { + return false; + } + } + + public boolean contractCreateNewAccount(Contract contract) { + AccountCapsule toAccount; + switch (contract.getType()) { + case AccountCreateContract: + return true; + case TransferContract: + TransferContract transferContract; + try { + transferContract = contract.getParameter().unpack(TransferContract.class); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + toAccount = + chainBaseManager.getAccountStore().get(transferContract.getToAddress().toByteArray()); + return toAccount == null; + case TransferAssetContract: + TransferAssetContract transferAssetContract; + try { + transferAssetContract = contract.getParameter().unpack(TransferAssetContract.class); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + toAccount = chainBaseManager.getAccountStore() + .get(transferAssetContract.getToAddress().toByteArray()); + return toAccount == null; + default: + return false; + } + } + + + private boolean useAssetAccountNet(Contract contract, AccountCapsule accountCapsule, long now, + long bytes) + throws ContractValidateException { + + ByteString assetName; + try { + assetName = contract.getParameter().unpack(TransferAssetContract.class).getAssetName(); + } catch (Exception ex) { + throw new RuntimeException(ex.getMessage()); + } + + AssetIssueCapsule assetIssueCapsule; + AssetIssueCapsule assetIssueCapsuleV2; + assetIssueCapsule = Commons.getAssetIssueStoreFinal( + chainBaseManager.getDynamicPropertiesStore(), + chainBaseManager.getAssetIssueStore(), chainBaseManager.getAssetIssueV2Store()) + .get(assetName.toByteArray()); + if (assetIssueCapsule == null) { + throw new ContractValidateException(String.format("asset [%s] does not exist", assetName)); + } + + String tokenName = ByteArray.toStr(assetName.toByteArray()); + String tokenID = assetIssueCapsule.getId(); + if (assetIssueCapsule.getOwnerAddress() == accountCapsule.getAddress()) { + return useAccountNet(accountCapsule, bytes, now); + } + + long publicFreeAssetNetLimit = assetIssueCapsule.getPublicFreeAssetNetLimit(); + long publicFreeAssetNetUsage = assetIssueCapsule.getPublicFreeAssetNetUsage(); + long publicLatestFreeNetTime = assetIssueCapsule.getPublicLatestFreeNetTime(); + + long newPublicFreeAssetNetUsage = increase(publicFreeAssetNetUsage, 0, + publicLatestFreeNetTime, now); + + if (bytes > (publicFreeAssetNetLimit - newPublicFreeAssetNetUsage)) { + logger.debug("The {} public free bandwidth is not enough." + + " Bytes: {}, publicFreeAssetNetLimit: {}, newPublicFreeAssetNetUsage: {}.", + tokenID, bytes, publicFreeAssetNetLimit, newPublicFreeAssetNetUsage); + return false; + } + + long freeAssetNetLimit = assetIssueCapsule.getFreeAssetNetLimit(); + + long freeAssetNetUsage; + long latestAssetOperationTime; + if (chainBaseManager.getDynamicPropertiesStore().getAllowSameTokenName() == 0) { + freeAssetNetUsage = accountCapsule + .getFreeAssetNetUsage(tokenName); + latestAssetOperationTime = accountCapsule + .getLatestAssetOperationTime(tokenName); + } else { + freeAssetNetUsage = accountCapsule.getFreeAssetNetUsageV2(tokenID); + latestAssetOperationTime = accountCapsule.getLatestAssetOperationTimeV2(tokenID); + } + + long newFreeAssetNetUsage = increase(freeAssetNetUsage, 0, + latestAssetOperationTime, now); + + if (bytes > (freeAssetNetLimit - newFreeAssetNetUsage)) { + logger.debug("The {} free bandwidth is not enough." + + " Bytes: {}, freeAssetNetLimit: {}, newFreeAssetNetUsage:{}.", + tokenID, bytes, freeAssetNetLimit, newFreeAssetNetUsage); + return false; + } + + AccountCapsule issuerAccountCapsule = chainBaseManager.getAccountStore() + .get(assetIssueCapsule.getOwnerAddress().toByteArray()); + + long issuerNetUsage = issuerAccountCapsule.getNetUsage(); + long latestConsumeTime = issuerAccountCapsule.getLatestConsumeTime(); + long issuerNetLimit = calculateGlobalNetLimit(issuerAccountCapsule); + long newIssuerNetUsage; + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newIssuerNetUsage = increase(issuerNetUsage, 0, latestConsumeTime, now); + } else { + // only participate in the calculation as a temporary variable, without disk flushing + newIssuerNetUsage = recovery(issuerAccountCapsule, BANDWIDTH, issuerNetUsage, + latestConsumeTime, now); + } + + if (bytes > (issuerNetLimit - newIssuerNetUsage)) { + logger.debug("The {} issuer's bandwidth is not enough." + + " Bytes: {}, issuerNetLimit: {}, newIssuerNetUsage:{}.", + tokenID, bytes, issuerNetLimit, newIssuerNetUsage); + return false; + } + + latestAssetOperationTime = now; + publicLatestFreeNetTime = now; + long latestOperationTime = chainBaseManager.getHeadBlockTimeStamp(); + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newIssuerNetUsage = increase(newIssuerNetUsage, bytes, now, now); + } else { + // Participate in calculation and flush disk persistence + newIssuerNetUsage = increase(issuerAccountCapsule, BANDWIDTH, + issuerNetUsage, bytes, latestConsumeTime, now); + } + + newFreeAssetNetUsage = increase(newFreeAssetNetUsage, + bytes, latestAssetOperationTime, now); + newPublicFreeAssetNetUsage = increase(newPublicFreeAssetNetUsage, bytes, + publicLatestFreeNetTime, now); + + issuerAccountCapsule.setNetUsage(newIssuerNetUsage); + issuerAccountCapsule.setLatestConsumeTime(now); + + assetIssueCapsule.setPublicFreeAssetNetUsage(newPublicFreeAssetNetUsage); + assetIssueCapsule.setPublicLatestFreeNetTime(publicLatestFreeNetTime); + + accountCapsule.setLatestOperationTime(latestOperationTime); + if (chainBaseManager.getDynamicPropertiesStore().getAllowSameTokenName() == 0) { + accountCapsule.putLatestAssetOperationTimeMap(tokenName, + latestAssetOperationTime); + accountCapsule.putFreeAssetNetUsage(tokenName, newFreeAssetNetUsage); + accountCapsule.putLatestAssetOperationTimeMapV2(tokenID, + latestAssetOperationTime); + accountCapsule.putFreeAssetNetUsageV2(tokenID, newFreeAssetNetUsage); + + chainBaseManager.getAssetIssueStore().put(assetIssueCapsule.createDbKey(), assetIssueCapsule); + + assetIssueCapsuleV2 = + chainBaseManager.getAssetIssueV2Store().get(assetIssueCapsule.createDbV2Key()); + assetIssueCapsuleV2.setPublicFreeAssetNetUsage(newPublicFreeAssetNetUsage); + assetIssueCapsuleV2.setPublicLatestFreeNetTime(publicLatestFreeNetTime); + chainBaseManager.getAssetIssueV2Store() + .put(assetIssueCapsuleV2.createDbV2Key(), assetIssueCapsuleV2); + } else { + accountCapsule.putLatestAssetOperationTimeMapV2(tokenID, + latestAssetOperationTime); + accountCapsule.putFreeAssetNetUsageV2(tokenID, newFreeAssetNetUsage); + chainBaseManager.getAssetIssueV2Store() + .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + } + + chainBaseManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + chainBaseManager.getAccountStore().put(issuerAccountCapsule.createDbKey(), + issuerAccountCapsule); + + return true; + + } + + public long calculateGlobalNetLimit(AccountCapsule accountCapsule) { + long frozeBalance = accountCapsule.getAllFrozenBalanceForBandwidth(); + if (dynamicPropertiesStore.supportUnfreezeDelay()) { + return calculateGlobalNetLimitV2(frozeBalance); + } + if (frozeBalance < TRX_PRECISION) { + return 0; + } + long netWeight = frozeBalance / TRX_PRECISION; + long totalNetLimit = chainBaseManager.getDynamicPropertiesStore().getTotalNetLimit(); + long totalNetWeight = chainBaseManager.getDynamicPropertiesStore().getTotalNetWeight(); + if (dynamicPropertiesStore.allowNewReward() && totalNetWeight <= 0) { + return 0; + } + if (totalNetWeight == 0) { + return 0; + } + return (long) (netWeight * ((double) totalNetLimit / totalNetWeight)); + } + + public long calculateGlobalNetLimitV2(long frozeBalance) { + double netWeight = (double) frozeBalance / TRX_PRECISION; + long totalNetLimit = dynamicPropertiesStore.getTotalNetLimit(); + long totalNetWeight = dynamicPropertiesStore.getTotalNetWeight(); + if (totalNetWeight == 0) { + return 0; + } + return (long) (netWeight * ((double) totalNetLimit / totalNetWeight)); + } + + private boolean useAccountNet(AccountCapsule accountCapsule, long bytes, long now) { + + long netUsage = accountCapsule.getNetUsage(); + long latestConsumeTime = accountCapsule.getLatestConsumeTime(); + long netLimit = calculateGlobalNetLimit(accountCapsule); + + long newNetUsage; + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newNetUsage = increase(netUsage, 0, latestConsumeTime, now); + } else { + // only participate in the calculation as a temporary variable, without disk flushing + newNetUsage = recovery(accountCapsule, BANDWIDTH, netUsage, latestConsumeTime, now); + } + + + if (bytes > (netLimit - newNetUsage)) { + logger.debug("Net usage is running out, now use free net usage." + + " Bytes: {}, netLimit: {}, newNetUsage: {}.", + bytes, netLimit, newNetUsage); + return false; + } + + long latestOperationTime = chainBaseManager.getHeadBlockTimeStamp(); + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newNetUsage = increase(newNetUsage, bytes, now, now); + } else { + // Participate in calculation and flush disk persistence + newNetUsage = increase(accountCapsule, BANDWIDTH, netUsage, bytes, latestConsumeTime, now); + } + + accountCapsule.setNetUsage(newNetUsage); + accountCapsule.setLatestOperationTime(latestOperationTime); + accountCapsule.setLatestConsumeTime(now); + + chainBaseManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + return true; + } + + private boolean useFreeNet(AccountCapsule accountCapsule, long bytes, long now) { + + long freeNetLimit = chainBaseManager.getDynamicPropertiesStore().getFreeNetLimit(); + long freeNetUsage = accountCapsule.getFreeNetUsage(); + long latestConsumeFreeTime = accountCapsule.getLatestConsumeFreeTime(); + long newFreeNetUsage = increase(freeNetUsage, 0, latestConsumeFreeTime, now); + + if (bytes > (freeNetLimit - newFreeNetUsage)) { + logger.debug("Free net usage is running out." + + " Bytes: {}, freeNetLimit: {}, newFreeNetUsage: {}.", + bytes, freeNetLimit, newFreeNetUsage); + return false; + } + + long publicNetLimit = chainBaseManager.getDynamicPropertiesStore().getPublicNetLimit(); + long publicNetUsage = chainBaseManager.getDynamicPropertiesStore().getPublicNetUsage(); + long publicNetTime = chainBaseManager.getDynamicPropertiesStore().getPublicNetTime(); + + long newPublicNetUsage = increase(publicNetUsage, 0, publicNetTime, now); + + if (bytes > (publicNetLimit - newPublicNetUsage)) { + logger.debug("Free public net usage is running out." + + " Bytes: {}, publicNetLimit: {}, newPublicNetUsage: {}.", + bytes, publicNetLimit, newPublicNetUsage); + return false; + } + + latestConsumeFreeTime = now; + long latestOperationTime = chainBaseManager.getHeadBlockTimeStamp(); + publicNetTime = now; + newFreeNetUsage = increase(newFreeNetUsage, bytes, latestConsumeFreeTime, now); + newPublicNetUsage = increase(newPublicNetUsage, bytes, publicNetTime, now); + accountCapsule.setFreeNetUsage(newFreeNetUsage); + accountCapsule.setLatestConsumeFreeTime(latestConsumeFreeTime); + accountCapsule.setLatestOperationTime(latestOperationTime); + + chainBaseManager.getDynamicPropertiesStore().savePublicNetUsage(newPublicNetUsage); + chainBaseManager.getDynamicPropertiesStore().savePublicNetTime(publicNetTime); + chainBaseManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + return true; + + } + +} + + diff --git a/chainbase/src/main/java/org/tron/core/db/BlockIndexStore.java b/chainbase/src/main/java/org/tron/core/db/BlockIndexStore.java index 2cfd3d7ae28..5722d3506af 100644 --- a/chainbase/src/main/java/org/tron/core/db/BlockIndexStore.java +++ b/chainbase/src/main/java/org/tron/core/db/BlockIndexStore.java @@ -1,6 +1,10 @@ package org.tron.core.db; -import java.util.Arrays; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -12,6 +16,7 @@ import org.tron.core.exception.ItemNotFoundException; @Component +@Slf4j(topic = "DB") public class BlockIndexStore extends TronStoreWithRevoking { @@ -29,7 +34,7 @@ public BlockId get(Long num) throws ItemNotFoundException { BytesCapsule value = getUnchecked(ByteArray.fromLong(num)); if (value == null || value.getData() == null) { - throw new ItemNotFoundException("number: " + num + " is not found!"); + throw new ItemNotFoundException(String.format("number: %d is not found!", num)); } return new BlockId(Sha256Hash.wrap(value.getData()), num); } @@ -39,8 +44,22 @@ public BytesCapsule get(byte[] key) throws ItemNotFoundException { byte[] value = revokingDB.getUnchecked(key); if (ArrayUtils.isEmpty(value)) { - throw new ItemNotFoundException("number: " + Arrays.toString(key) + " is not found!"); + throw new ItemNotFoundException(String.format("number: %d is not found!", + ByteArray.toLong(key))); } return new BytesCapsule(value); } -} \ No newline at end of file + + public List getLimitNumber(long startNumber, long limit) { + return pack(revokingDB.getValuesNext(ByteArray.fromLong(startNumber), limit)); + } + + private List pack(Set values) { + List blocks = new ArrayList<>(); + for (byte[] bytes : values) { + blocks.add(new BlockId(Sha256Hash.wrap(bytes))); + } + blocks.sort(Comparator.comparing(BlockId::getNum)); + return blocks; + } +} diff --git a/chainbase/src/main/java/org/tron/core/db/BlockStore.java b/chainbase/src/main/java/org/tron/core/db/BlockStore.java index e4efe388043..9198b1c5198 100644 --- a/chainbase/src/main/java/org/tron/core/db/BlockStore.java +++ b/chainbase/src/main/java/org/tron/core/db/BlockStore.java @@ -15,14 +15,15 @@ package org.tron.core.db; +import java.util.ArrayList; import java.util.Comparator; import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; +import java.util.Set; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.tron.common.error.TronDBException; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; @@ -39,31 +40,24 @@ private BlockStore(@Value("block") String dbName) { public List getLimitNumber(long startNumber, long limit) { BlockId startBlockId = new BlockId(Sha256Hash.ZERO_HASH, startNumber); - return revokingDB.getValuesNext(startBlockId.getBytes(), limit).stream() - .map(bytes -> { - try { - return new BlockCapsule(bytes); - } catch (BadItemException ignored) { - } - return null; - }) - .filter(Objects::nonNull) - .sorted(Comparator.comparing(BlockCapsule::getNum)) - .collect(Collectors.toList()); + return pack(revokingDB.getValuesNext(startBlockId.getBytes(), limit)); } public List getBlockByLatestNum(long getNum) { + return pack(revokingDB.getlatestValues(getNum)); + } - return revokingDB.getlatestValues(getNum).stream() - .map(bytes -> { - try { - return new BlockCapsule(bytes); - } catch (BadItemException ignored) { - } - return null; - }) - .filter(Objects::nonNull) - .sorted(Comparator.comparing(BlockCapsule::getNum)) - .collect(Collectors.toList()); + private List pack(Set values) { + List blocks = new ArrayList<>(); + for (byte[] bytes : values) { + try { + blocks.add(new BlockCapsule(bytes)); + } catch (BadItemException e) { + logger.error("Find bad item: {}", e.getMessage()); + // throw new TronDBException(e); + } + } + blocks.sort(Comparator.comparing(BlockCapsule::getNum)); + return blocks; } } diff --git a/chainbase/src/main/java/org/tron/core/db/CommonDataBase.java b/chainbase/src/main/java/org/tron/core/db/CommonDataBase.java index a607bb1e44f..a72b581a97c 100644 --- a/chainbase/src/main/java/org/tron/core/db/CommonDataBase.java +++ b/chainbase/src/main/java/org/tron/core/db/CommonDataBase.java @@ -5,7 +5,7 @@ import org.springframework.stereotype.Component; import org.tron.common.utils.ByteArray; -@Slf4j +@Slf4j(topic = "DB") @Component public class CommonDataBase extends TronDatabase { @@ -37,7 +37,7 @@ public boolean has(byte[] key) { public void saveLatestPbftBlockNum(long number) { if (number <= getLatestPbftBlockNum()) { - logger.warn("pbft number {} <= latest number {}", number, getLatestPbftBlockNum()); + logger.warn("PBFT number {} <= latest number {}.", number, getLatestPbftBlockNum()); return; } this.put(LATEST_PBFT_BLOCK_NUM, ByteArray.fromLong(number)); 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 ff95f9058f1..30d778d0990 100644 --- a/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/EnergyProcessor.java @@ -1,6 +1,7 @@ package org.tron.core.db; -import static java.lang.Long.max; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; @@ -15,6 +16,8 @@ import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Account.AccountResource; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + @Slf4j(topic = "DB") public class EnergyProcessor extends ResourceProcessor { @@ -29,7 +32,6 @@ public static long getHeadSlot(DynamicPropertiesStore dynamicPropertiesStore) { / BLOCK_PRODUCED_INTERVAL; } - @Override public void updateUsage(AccountCapsule accountCapsule) { long now = getHeadSlot(); updateUsage(accountCapsule, now); @@ -41,7 +43,8 @@ private void updateUsage(AccountCapsule accountCapsule, long now) { long oldEnergyUsage = accountResource.getEnergyUsage(); long latestConsumeTime = accountResource.getLatestConsumeTimeForEnergy(); - accountCapsule.setEnergyUsage(increase(oldEnergyUsage, 0, latestConsumeTime, now)); + accountCapsule.setEnergyUsage(increase(accountCapsule, ENERGY, + oldEnergyUsage, 0, latestConsumeTime, now)); } public void updateTotalEnergyAverageUsage() { @@ -76,16 +79,13 @@ public void updateAdaptiveTotalEnergyLimit() { / AdaptiveResourceLimitConstants.EXPAND_RATE_DENOMINATOR; // logger.info(totalEnergyAverageUsage + "<" + targetTotalEnergyLimit + "\n" + result); } - - result = Math.min( - Math.max(result, totalEnergyLimit), - totalEnergyLimit * dynamicPropertiesStore.getAdaptiveResourceLimitMultiplier() - ); + result = min(max(result, totalEnergyLimit, this.disableJavaLangMath()), + totalEnergyLimit * dynamicPropertiesStore.getAdaptiveResourceLimitMultiplier(), + this.disableJavaLangMath()); dynamicPropertiesStore.saveTotalEnergyCurrentLimit(result); - logger.debug( - "adjust totalEnergyCurrentLimit, old[" + totalEnergyCurrentLimit + "], new[" + result - + "]"); + logger.debug("Adjust totalEnergyCurrentLimit, old: {}, new: {}.", + totalEnergyCurrentLimit, result); } @Override @@ -100,20 +100,33 @@ public boolean useEnergy(AccountCapsule accountCapsule, long energy, long now) { long energyUsage = accountCapsule.getEnergyUsage(); long latestConsumeTime = accountCapsule.getAccountResource().getLatestConsumeTimeForEnergy(); long energyLimit = calculateGlobalEnergyLimit(accountCapsule); - - long newEnergyUsage = increase(energyUsage, 0, latestConsumeTime, now); + long newEnergyUsage; + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newEnergyUsage = increase(energyUsage, 0, latestConsumeTime, now); + } else { + // only participate in the calculation as a temporary variable, without disk flushing + newEnergyUsage = recovery(accountCapsule, ENERGY, energyUsage, + latestConsumeTime, now); + } if (energy > (energyLimit - newEnergyUsage) - && dynamicPropertiesStore.getAllowTvmFreeze() == 0) { + && dynamicPropertiesStore.getAllowTvmFreeze() == 0 + && !dynamicPropertiesStore.supportUnfreezeDelay()) { return false; } - latestConsumeTime = now; long latestOperationTime = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); - newEnergyUsage = increase(newEnergyUsage, energy, latestConsumeTime, now); + if (!dynamicPropertiesStore.supportUnfreezeDelay()) { + newEnergyUsage = increase(newEnergyUsage, energy, now, now); + } else { + // Participate in calculation and flush disk persistence + newEnergyUsage = increase(accountCapsule, ENERGY, energyUsage, energy, + latestConsumeTime, now); + } + accountCapsule.setEnergyUsage(newEnergyUsage); accountCapsule.setLatestOperationTime(latestOperationTime); - accountCapsule.setLatestConsumeTimeForEnergy(latestConsumeTime); + accountCapsule.setLatestConsumeTimeForEnergy(now); accountStore.put(accountCapsule.createDbKey(), accountCapsule); @@ -127,6 +140,9 @@ public boolean useEnergy(AccountCapsule accountCapsule, long energy, long now) { public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { long frozeBalance = accountCapsule.getAllFrozenBalanceForEnergy(); + if (dynamicPropertiesStore.supportUnfreezeDelay()) { + return calculateGlobalEnergyLimitV2(frozeBalance); + } if (frozeBalance < TRX_PRECISION) { return 0; } @@ -134,21 +150,34 @@ public long calculateGlobalEnergyLimit(AccountCapsule accountCapsule) { long energyWeight = frozeBalance / TRX_PRECISION; long totalEnergyLimit = dynamicPropertiesStore.getTotalEnergyCurrentLimit(); long totalEnergyWeight = dynamicPropertiesStore.getTotalEnergyWeight(); + if (dynamicPropertiesStore.allowNewReward() && totalEnergyWeight <= 0) { + return 0; + } else { + assert totalEnergyWeight > 0; + } + return (long) (energyWeight * ((double) totalEnergyLimit / totalEnergyWeight)); + } - assert totalEnergyWeight > 0; - + public long calculateGlobalEnergyLimitV2(long frozeBalance) { + double energyWeight = (double) frozeBalance / TRX_PRECISION; + long totalEnergyLimit = dynamicPropertiesStore.getTotalEnergyCurrentLimit(); + long totalEnergyWeight = dynamicPropertiesStore.getTotalEnergyWeight(); + if (totalEnergyWeight == 0) { + return 0; + } return (long) (energyWeight * ((double) totalEnergyLimit / totalEnergyWeight)); } + public long getAccountLeftEnergyFromFreeze(AccountCapsule accountCapsule) { long now = getHeadSlot(); long energyUsage = accountCapsule.getEnergyUsage(); long latestConsumeTime = accountCapsule.getAccountResource().getLatestConsumeTimeForEnergy(); long energyLimit = calculateGlobalEnergyLimit(accountCapsule); - long newEnergyUsage = increase(energyUsage, 0, latestConsumeTime, now); + long newEnergyUsage = recovery(accountCapsule, ENERGY, energyUsage, latestConsumeTime, now); - return max(energyLimit - newEnergyUsage, 0); // us + return max(energyLimit - newEnergyUsage, 0, this.disableJavaLangMath()); // us } private long getHeadSlot() { diff --git a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java index 9c9c968aa73..c1d3bceeb4b 100644 --- a/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/KhaosDatabase.java @@ -110,12 +110,13 @@ public BlockCapsule push(BlockCapsule blk) if (kblock != null) { if (blk.getNum() != kblock.num + 1) { throw new BadNumberBlockException( - "parent number :" + kblock.num + ",block number :" + blk.getNum()); + String.format("parent number: %d , block number: %d", kblock.num, blk.getNum()) + ); } block.setParent(kblock); } else { miniUnlinkedStore.insert(block); - logger.error("blk:{}, head:{}, miniStore:{}, miniUnlinkedStore:{}", + logger.error("Block: {}, head: {}, miniStore: {}, miniUnlinkedStore: {}.", blk, head, miniStore, @@ -327,7 +328,7 @@ protected boolean removeEldestEntry(Map.Entry> entry numKblkMap.remove(k); v.forEach(b -> { hashKblkMap.remove(b.id); - logger.info("remove from khaosDatabase:{}", b.id); + logger.info("Remove from khaosDatabase: {}.", b.id); }); }); diff --git a/chainbase/src/main/java/org/tron/core/db/PbftSignDataStore.java b/chainbase/src/main/java/org/tron/core/db/PbftSignDataStore.java index 784abca70aa..d65e24ce6de 100644 --- a/chainbase/src/main/java/org/tron/core/db/PbftSignDataStore.java +++ b/chainbase/src/main/java/org/tron/core/db/PbftSignDataStore.java @@ -6,7 +6,7 @@ import org.tron.core.capsule.PbftSignCapsule; import org.tron.protos.Protocol.PBFTMessage.DataType; -@Slf4j +@Slf4j(topic = "DB") @Component public class PbftSignDataStore extends TronDatabase { diff --git a/chainbase/src/main/java/org/tron/core/db/RecentBlockStore.java b/chainbase/src/main/java/org/tron/core/db/RecentBlockStore.java index 53beed8bc6b..0b90cbc8ed0 100644 --- a/chainbase/src/main/java/org/tron/core/db/RecentBlockStore.java +++ b/chainbase/src/main/java/org/tron/core/db/RecentBlockStore.java @@ -17,7 +17,6 @@ private RecentBlockStore(@Value("recent-block") String dbName) { @Override public BytesCapsule get(byte[] key) throws ItemNotFoundException { byte[] value = revokingDB.get(key); - return new BytesCapsule(value); } } diff --git a/chainbase/src/main/java/org/tron/core/db/RecentTransactionItem.java b/chainbase/src/main/java/org/tron/core/db/RecentTransactionItem.java new file mode 100644 index 00000000000..150b1a9dfc0 --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/db/RecentTransactionItem.java @@ -0,0 +1,23 @@ +package org.tron.core.db; + +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +public class RecentTransactionItem { + @Getter + @Setter + private long num; + + @Getter + @Setter + private List transactionIds; + + public RecentTransactionItem() {} + + public RecentTransactionItem(long num, List transactionIds) { + this.num = num; + this.transactionIds = transactionIds; + } +} diff --git a/chainbase/src/main/java/org/tron/core/db/RecentTransactionStore.java b/chainbase/src/main/java/org/tron/core/db/RecentTransactionStore.java new file mode 100644 index 00000000000..359a202351e --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/db/RecentTransactionStore.java @@ -0,0 +1,22 @@ +package org.tron.core.db; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.exception.ItemNotFoundException; + +@Component +public class RecentTransactionStore extends TronStoreWithRevoking { + + @Autowired + private RecentTransactionStore(@Value("recent-transaction") String dbName) { + super(dbName); + } + + @Override + public BytesCapsule get(byte[] key) throws ItemNotFoundException { + byte[] value = revokingDB.get(key); + return new BytesCapsule(value); + } +} 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 09bac96e0ae..7e170f9dab5 100644 --- a/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java +++ b/chainbase/src/main/java/org/tron/core/db/ResourceProcessor.java @@ -1,6 +1,9 @@ package org.tron.core.db; +import static org.tron.common.math.Maths.min; +import static org.tron.common.math.Maths.round; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_PRECISION; import org.tron.common.utils.Commons; import org.tron.core.capsule.AccountCapsule; @@ -10,9 +13,11 @@ import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.store.AccountStore; import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.contract.Common.ResourceCode; abstract class ResourceProcessor { @@ -22,7 +27,7 @@ abstract class ResourceProcessor { protected long windowSize; protected long averageWindowSize; - public ResourceProcessor(DynamicPropertiesStore dynamicPropertiesStore, + protected ResourceProcessor(DynamicPropertiesStore dynamicPropertiesStore, AccountStore accountStore) { this.dynamicPropertiesStore = dynamicPropertiesStore; this.accountStore = accountStore; @@ -32,10 +37,8 @@ public ResourceProcessor(DynamicPropertiesStore dynamicPropertiesStore, AdaptiveResourceLimitConstants.PERIODS_MS / BLOCK_PRODUCED_INTERVAL; } - abstract void updateUsage(AccountCapsule accountCapsule); - abstract void consume(TransactionCapsule trx, TransactionTrace trace) - throws ContractValidateException, AccountResourceInsufficientException, TooBigTransactionResultException; + throws ContractValidateException, AccountResourceInsufficientException, TooBigTransactionResultException, TooBigTransactionException; protected long increase(long lastUsage, long usage, long lastTime, long now) { return increase(lastUsage, usage, lastTime, now, windowSize); @@ -50,7 +53,8 @@ protected long increase(long lastUsage, long usage, long lastTime, long now, lon if (lastTime + windowSize > now) { long delta = now - lastTime; double decay = (windowSize - delta) / (double) windowSize; - averageLastUsage = Math.round(averageLastUsage * decay); + averageLastUsage = round(averageLastUsage * decay, + this.disableJavaLangMath()); } else { averageLastUsage = 0; } @@ -59,6 +63,150 @@ protected long increase(long lastUsage, long usage, long lastTime, long now, lon return getUsage(averageLastUsage, windowSize); } + public long recovery(AccountCapsule accountCapsule, ResourceCode resourceCode, + long lastUsage, long lastTime, long now) { + long oldWindowSize = accountCapsule.getWindowSize(resourceCode); + return increase(lastUsage, 0, lastTime, now, oldWindowSize); + } + + public long increase(AccountCapsule accountCapsule, ResourceCode resourceCode, + long lastUsage, long usage, long lastTime, long now) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + return increaseV2(accountCapsule, resourceCode, lastUsage, usage, lastTime, now); + } + long oldWindowSize = accountCapsule.getWindowSize(resourceCode); + long averageLastUsage = divideCeil(lastUsage * this.precision, oldWindowSize); + long averageUsage = divideCeil(usage * this.precision, this.windowSize); + + if (lastTime != now) { + if (lastTime + oldWindowSize > now) { + long delta = now - lastTime; + double decay = (oldWindowSize - delta) / (double) oldWindowSize; + averageLastUsage = round(averageLastUsage * decay, + this.disableJavaLangMath()); + } else { + averageLastUsage = 0; + } + } + + long newUsage = getUsage(averageLastUsage, oldWindowSize, averageUsage, this.windowSize); + if (dynamicPropertiesStore.supportUnfreezeDelay()) { + long remainUsage = getUsage(averageLastUsage, oldWindowSize); + if (remainUsage == 0) { + accountCapsule.setNewWindowSize(resourceCode, this.windowSize); + return newUsage; + } + long remainWindowSize = oldWindowSize - (now - lastTime); + long newWindowSize = getNewWindowSize(remainUsage, remainWindowSize, usage, + windowSize, newUsage); + accountCapsule.setNewWindowSize(resourceCode, newWindowSize); + } + return newUsage; + } + + public long increaseV2(AccountCapsule accountCapsule, ResourceCode resourceCode, + long lastUsage, long usage, long lastTime, long now) { + long oldWindowSizeV2 = accountCapsule.getWindowSizeV2(resourceCode); + long oldWindowSize = accountCapsule.getWindowSize(resourceCode); + long averageLastUsage = divideCeil(lastUsage * this.precision, oldWindowSize); + long averageUsage = divideCeil(usage * this.precision, this.windowSize); + + if (lastTime != now) { + if (lastTime + oldWindowSize > now) { + long delta = now - lastTime; + double decay = (oldWindowSize - delta) / (double) oldWindowSize; + averageLastUsage = round(averageLastUsage * decay, + this.disableJavaLangMath()); + } else { + averageLastUsage = 0; + } + } + + long newUsage = getUsage(averageLastUsage, oldWindowSize, averageUsage, this.windowSize); + long remainUsage = getUsage(averageLastUsage, oldWindowSize); + if (remainUsage == 0) { + accountCapsule.setNewWindowSizeV2(resourceCode, this.windowSize * WINDOW_SIZE_PRECISION); + return newUsage; + } + + long remainWindowSize = oldWindowSizeV2 - (now - lastTime) * WINDOW_SIZE_PRECISION; + long newWindowSize = divideCeil( + remainUsage * remainWindowSize + usage * this.windowSize * WINDOW_SIZE_PRECISION, newUsage); + newWindowSize = min(newWindowSize, this.windowSize * WINDOW_SIZE_PRECISION, + this.disableJavaLangMath()); + accountCapsule.setNewWindowSizeV2(resourceCode, newWindowSize); + return newUsage; + } + + public void unDelegateIncrease(AccountCapsule owner, final AccountCapsule receiver, + long transferUsage, ResourceCode resourceCode, long now) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + unDelegateIncreaseV2(owner, receiver, transferUsage, resourceCode, now); + return; + } + long lastOwnerTime = owner.getLastConsumeTime(resourceCode); + long ownerUsage = owner.getUsage(resourceCode); + // Update itself first + ownerUsage = increase(owner, resourceCode, ownerUsage, 0, lastOwnerTime, now); + + long remainOwnerWindowSize = owner.getWindowSize(resourceCode); + long remainReceiverWindowSize = receiver.getWindowSize(resourceCode); + remainOwnerWindowSize = remainOwnerWindowSize < 0 ? 0 : remainOwnerWindowSize; + remainReceiverWindowSize = remainReceiverWindowSize < 0 ? 0 : remainReceiverWindowSize; + + long newOwnerUsage = ownerUsage + transferUsage; + // mean ownerUsage == 0 and transferUsage == 0 + if (newOwnerUsage == 0) { + owner.setNewWindowSize(resourceCode, this.windowSize); + owner.setUsage(resourceCode, 0); + owner.setLatestTime(resourceCode, now); + return; + } + // calculate new windowSize + long newOwnerWindowSize = getNewWindowSize(ownerUsage, remainOwnerWindowSize, transferUsage, + remainReceiverWindowSize, newOwnerUsage); + owner.setNewWindowSize(resourceCode, newOwnerWindowSize); + owner.setUsage(resourceCode, newOwnerUsage); + owner.setLatestTime(resourceCode, now); + } + + public void unDelegateIncreaseV2(AccountCapsule owner, final AccountCapsule receiver, + long transferUsage, ResourceCode resourceCode, long now) { + long lastOwnerTime = owner.getLastConsumeTime(resourceCode); + long ownerUsage = owner.getUsage(resourceCode); + // Update itself first + ownerUsage = increase(owner, resourceCode, ownerUsage, 0, lastOwnerTime, now); + long newOwnerUsage = ownerUsage + transferUsage; + // mean ownerUsage == 0 and transferUsage == 0 + if (newOwnerUsage == 0) { + owner.setNewWindowSizeV2(resourceCode, this.windowSize * WINDOW_SIZE_PRECISION); + owner.setUsage(resourceCode, 0); + owner.setLatestTime(resourceCode, now); + return; + } + + long remainOwnerWindowSizeV2 = owner.getWindowSizeV2(resourceCode); + long remainReceiverWindowSizeV2 = receiver.getWindowSizeV2(resourceCode); + remainOwnerWindowSizeV2 = remainOwnerWindowSizeV2 < 0 ? 0 : remainOwnerWindowSizeV2; + remainReceiverWindowSizeV2 = remainReceiverWindowSizeV2 < 0 ? 0 : remainReceiverWindowSizeV2; + + // calculate new windowSize + long newOwnerWindowSize = + divideCeil( + ownerUsage * remainOwnerWindowSizeV2 + transferUsage * remainReceiverWindowSizeV2, + newOwnerUsage); + newOwnerWindowSize = min(newOwnerWindowSize, this.windowSize * WINDOW_SIZE_PRECISION, + this.disableJavaLangMath()); + owner.setNewWindowSizeV2(resourceCode, newOwnerWindowSize); + owner.setUsage(resourceCode, newOwnerUsage); + owner.setLatestTime(resourceCode, now); + } + + private long getNewWindowSize(long lastUsage, long lastWindowSize, long usage, + long windowSize, long newUsage) { + return (lastUsage * lastWindowSize + usage * windowSize) / newUsage; + } + private long divideCeil(long numerator, long denominator) { return (numerator / denominator) + ((numerator % denominator) > 0 ? 1 : 0); } @@ -67,17 +215,23 @@ private long getUsage(long usage, long windowSize) { return usage * windowSize / precision; } + private long getUsage(long oldUsage, long oldWindowSize, long newUsage, long newWindowSize) { + return (oldUsage * oldWindowSize + newUsage * newWindowSize) / precision; + } + protected boolean consumeFeeForBandwidth(AccountCapsule accountCapsule, long fee) { try { long latestOperationTime = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); accountCapsule.setLatestOperationTime(latestOperationTime); - Commons.adjustBalance(accountStore, accountCapsule, -fee); + Commons.adjustBalance(accountStore, accountCapsule, -fee, + this.disableJavaLangMath()); if (dynamicPropertiesStore.supportTransactionFeePool()) { dynamicPropertiesStore.addTransactionFeePool(fee); } else if (dynamicPropertiesStore.supportBlackHoleOptimization()) { dynamicPropertiesStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee); + Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee, + this.disableJavaLangMath()); } return true; @@ -86,16 +240,17 @@ protected boolean consumeFeeForBandwidth(AccountCapsule accountCapsule, long fee } } - protected boolean consumeFeeForNewAccount(AccountCapsule accountCapsule, long fee) { try { long latestOperationTime = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); accountCapsule.setLatestOperationTime(latestOperationTime); - Commons.adjustBalance(accountStore, accountCapsule, -fee); + Commons.adjustBalance(accountStore, accountCapsule, -fee, + this.disableJavaLangMath()); if (dynamicPropertiesStore.supportBlackHoleOptimization()) { dynamicPropertiesStore.burnTrx(fee); } else { - Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee); + Commons.adjustBalance(accountStore, accountStore.getBlackhole().createDbKey(), +fee, + this.disableJavaLangMath()); } return true; @@ -103,4 +258,8 @@ protected boolean consumeFeeForNewAccount(AccountCapsule accountCapsule, long fe return false; } } + + protected boolean disableJavaLangMath() { + return dynamicPropertiesStore.disableJavaLangMath(); + } } diff --git a/chainbase/src/main/java/org/tron/core/db/RevokingStore.java b/chainbase/src/main/java/org/tron/core/db/RevokingStore.java deleted file mode 100644 index 7b641cf6bc3..00000000000 --- a/chainbase/src/main/java/org/tron/core/db/RevokingStore.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.tron.core.db; - -public class RevokingStore extends AbstractRevokingStore { - - public RevokingStore() { - } - - public static RevokingStore getInstance() { - return RevokingEnum.INSTANCE.getInstance(); - } - - private enum RevokingEnum { - INSTANCE; - - private RevokingStore instance; - - RevokingEnum() { - instance = new RevokingStore(); - } - - private RevokingStore getInstance() { - return instance; - } - } -} diff --git a/chainbase/src/main/java/org/tron/core/db/StorageMarket.java b/chainbase/src/main/java/org/tron/core/db/StorageMarket.java deleted file mode 100644 index 66c0904b622..00000000000 --- a/chainbase/src/main/java/org/tron/core/db/StorageMarket.java +++ /dev/null @@ -1,241 +0,0 @@ -package org.tron.core.db; - -import lombok.extern.slf4j.Slf4j; -import org.tron.core.capsule.AccountCapsule; -import org.tron.core.store.AccountStore; -import org.tron.core.store.DynamicPropertiesStore; - -@Slf4j(topic = "DB") -public class StorageMarket { - - private static final long MS_PER_YEAR = 365 * 24 * 3600 * 1000L; - private static final String NEW_TOTAL_RESERVED = " newTotalReserved: "; - private static final String NEW_STORAGE_LIMIT = " newStorageLimit: "; - private static final String NEW_TOTAL_POOL = "newTotalPool: "; - private AccountStore accountStore; - private DynamicPropertiesStore dynamicPropertiesStore; - private long supply = 1_000_000_000_000_000L; - - - public StorageMarket(AccountStore accountStore, DynamicPropertiesStore dynamicPropertiesStore) { - this.accountStore = accountStore; - this.dynamicPropertiesStore = dynamicPropertiesStore; - } - - private long exchangeToSupply(boolean isTRX, long quant) { - logger.info("isTRX: " + isTRX); - long balance = isTRX ? dynamicPropertiesStore.getTotalStoragePool() : - dynamicPropertiesStore.getTotalStorageReserved(); - logger.info("balance: " + balance); - long newBalance = balance + quant; - logger.info("balance + quant: " + (balance + quant)); - -// if (isTRX) { -// dbManager.getDynamicPropertiesStore().saveTotalStoragePool(newBalance); -// } else { -// dbManager.getDynamicPropertiesStore().saveTotalStorageReserved(newBalance); -// } - - double issuedSupply = -supply * (1.0 - Math.pow(1.0 + (double) quant / newBalance, 0.0005)); - logger.info("issuedSupply: " + issuedSupply); - long out = (long) issuedSupply; - supply += out; - - return out; - } - - private long exchangeToSupply2(boolean isTRX, long quant) { - logger.info("isTRX: " + isTRX); - long balance = isTRX ? dynamicPropertiesStore.getTotalStoragePool() : - dynamicPropertiesStore.getTotalStorageReserved(); - logger.info("balance: " + balance); - long newBalance = balance - quant; - logger.info("balance - quant: " + (balance - quant)); - -// if (isTRX) { -// dbManager.getDynamicPropertiesStore().saveTotalStoragePool(newBalance); -// } else { -// dbManager.getDynamicPropertiesStore().saveTotalStorageReserved(newBalance); -// } - - double issuedSupply = -supply * (1.0 - Math.pow(1.0 + (double) quant / newBalance, 0.0005)); - logger.info("issuedSupply: " + issuedSupply); - long out = (long) issuedSupply; - supply += out; - - return out; - } - - private long exchange_from_supply(boolean isTRX, long supplyQuant) { - long balance = isTRX ? dynamicPropertiesStore.getTotalStoragePool() : - dynamicPropertiesStore.getTotalStorageReserved(); - supply -= supplyQuant; - - double exchangeBalance = - balance * (Math.pow(1.0 + (double) supplyQuant / supply, 2000.0) - 1.0); - logger.info("exchangeBalance: " + exchangeBalance); - long out = (long) exchangeBalance; - - if (isTRX) { - out = Math.round(exchangeBalance / 100000) * 100000; - logger.info("---out: " + out); - } - - return out; - } - - public long exchange(long from, boolean isTRX) { - long relay = exchangeToSupply(isTRX, from); - return exchange_from_supply(!isTRX, relay); - } - - public long calculateTax(long duration, long limit) { - // todo: Support for change by the committee - double ratePerYear = dynamicPropertiesStore.getStorageExchangeTaxRate() / 100.0; - double millisecondPerYear = MS_PER_YEAR; - double feeRate = duration / millisecondPerYear * ratePerYear; - long storageTax = (long) (limit * feeRate); - logger.info("storageTax: " + storageTax); - return storageTax; - } - - - public long tryPayTax(long duration, long limit) { - long storageTax = calculateTax(duration, limit); - long tax = exchange(storageTax, false); - logger.info("tax: " + tax); - - long newTotalTax = dynamicPropertiesStore.getTotalStorageTax() + tax; - long newTotalPool = dynamicPropertiesStore.getTotalStoragePool() - tax; - long newTotalReserved = dynamicPropertiesStore.getTotalStorageReserved() - + storageTax; - logger.info("reserved: " + dynamicPropertiesStore.getTotalStorageReserved()); - boolean eq = dynamicPropertiesStore.getTotalStorageReserved() - == 128L * 1024 * 1024 * 1024; - logger.info("reserved == 128GB: " + eq); - logger.info("newTotalTax: " + newTotalTax + " newTotalPool: " + newTotalPool - + NEW_TOTAL_RESERVED + newTotalReserved); - - return storageTax; - } - - public long payTax(long duration, long limit) { - long storageTax = calculateTax(duration, limit); - long tax = exchange(storageTax, false); - logger.info("tax: " + tax); - - long newTotalTax = dynamicPropertiesStore.getTotalStorageTax() + tax; - long newTotalPool = dynamicPropertiesStore.getTotalStoragePool() - tax; - long newTotalReserved = dynamicPropertiesStore.getTotalStorageReserved() - + storageTax; - logger.info("reserved: " + dynamicPropertiesStore.getTotalStorageReserved()); - boolean eq = dynamicPropertiesStore.getTotalStorageReserved() - == 128L * 1024 * 1024 * 1024; - logger.info("reserved == 128GB: " + eq); - logger.info("newTotalTax: " + newTotalTax + " newTotalPool: " + newTotalPool - + NEW_TOTAL_RESERVED + newTotalReserved); - dynamicPropertiesStore.saveTotalStorageTax(newTotalTax); - dynamicPropertiesStore.saveTotalStoragePool(newTotalPool); - dynamicPropertiesStore.saveTotalStorageReserved(newTotalReserved); - - return storageTax; - } - - public long tryBuyStorageBytes(long storageBought) { - long relay = exchangeToSupply2(false, storageBought); - return exchange_from_supply(true, relay); - } - - public long tryBuyStorage(long quant) { - return exchange(quant, true); - } - - public long trySellStorage(long bytes) { - return exchange(bytes, false); - } - - public AccountCapsule buyStorageBytes(AccountCapsule accountCapsule, long storageBought) { - long now = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); - long currentStorageLimit = accountCapsule.getStorageLimit(); - - long relay = exchangeToSupply2(false, storageBought); - long quant = exchange_from_supply(true, relay); - - long newBalance = accountCapsule.getBalance() - quant; - logger.info("newBalance: " + newBalance); - - long newStorageLimit = currentStorageLimit + storageBought; - logger.info( - "storageBought: " + storageBought + NEW_STORAGE_LIMIT - + newStorageLimit); - - accountCapsule.setLatestExchangeStorageTime(now); - accountCapsule.setStorageLimit(newStorageLimit); - accountCapsule.setBalance(newBalance); - accountStore.put(accountCapsule.createDbKey(), accountCapsule); - - long newTotalPool = dynamicPropertiesStore.getTotalStoragePool() + quant; - long newTotalReserved = dynamicPropertiesStore.getTotalStorageReserved() - - storageBought; - logger.info(NEW_TOTAL_POOL + newTotalPool + NEW_TOTAL_RESERVED + newTotalReserved); - dynamicPropertiesStore.saveTotalStoragePool(newTotalPool); - dynamicPropertiesStore.saveTotalStorageReserved(newTotalReserved); - return accountCapsule; - } - - - public void buyStorage(AccountCapsule accountCapsule, long quant) { - long now = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); - long currentStorageLimit = accountCapsule.getStorageLimit(); - - long newBalance = accountCapsule.getBalance() - quant; - logger.info("newBalance: " + newBalance); - - long storageBought = exchange(quant, true); - long newStorageLimit = currentStorageLimit + storageBought; - logger.info( - "storageBought: " + storageBought + NEW_STORAGE_LIMIT - + newStorageLimit); - - accountCapsule.setLatestExchangeStorageTime(now); - accountCapsule.setStorageLimit(newStorageLimit); - accountCapsule.setBalance(newBalance); - accountStore.put(accountCapsule.createDbKey(), accountCapsule); - - long newTotalPool = dynamicPropertiesStore.getTotalStoragePool() + quant; - long newTotalReserved = dynamicPropertiesStore.getTotalStorageReserved() - - storageBought; - logger.info(NEW_TOTAL_POOL + newTotalPool + NEW_TOTAL_RESERVED + newTotalReserved); - dynamicPropertiesStore.saveTotalStoragePool(newTotalPool); - dynamicPropertiesStore.saveTotalStorageReserved(newTotalReserved); - - } - - public void sellStorage(AccountCapsule accountCapsule, long bytes) { - long now = dynamicPropertiesStore.getLatestBlockHeaderTimestamp(); - long currentStorageLimit = accountCapsule.getStorageLimit(); - - long quant = exchange(bytes, false); - long newBalance = accountCapsule.getBalance() + quant; - - long newStorageLimit = currentStorageLimit - bytes; - logger.info("quant: " + quant + NEW_STORAGE_LIMIT + newStorageLimit); - - accountCapsule.setLatestExchangeStorageTime(now); - accountCapsule.setStorageLimit(newStorageLimit); - accountCapsule.setBalance(newBalance); - accountStore.put(accountCapsule.createDbKey(), accountCapsule); - - long newTotalPool = dynamicPropertiesStore.getTotalStoragePool() - quant; - long newTotalReserved = dynamicPropertiesStore.getTotalStorageReserved() - + bytes; - logger.info(NEW_TOTAL_POOL + newTotalPool + NEW_TOTAL_RESERVED + newTotalReserved); - dynamicPropertiesStore.saveTotalStoragePool(newTotalPool); - dynamicPropertiesStore.saveTotalStorageReserved(newTotalReserved); - - } - - public long getAccountLeftStorageInByteFromBought(AccountCapsule accountCapsule) { - return accountCapsule.getStorageLimit() - accountCapsule.getStorageUsage(); - } -} diff --git a/chainbase/src/main/java/org/tron/core/db/TransactionCache.java b/chainbase/src/main/java/org/tron/core/db/TransactionCache.java new file mode 100644 index 00000000000..58ed9be9145 --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/db/TransactionCache.java @@ -0,0 +1,25 @@ +package org.tron.core.db; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.db2.common.TxCacheDB; +import org.tron.core.store.DynamicPropertiesStore; + +@Slf4j +@Component +public class TransactionCache extends TronStoreWithRevoking { + + @Autowired + public TransactionCache(@Value("trans-cache") String dbName, + @Autowired RecentTransactionStore recentTransactionStore, + @Autowired DynamicPropertiesStore dynamicPropertiesStore) { + super(new TxCacheDB(dbName, recentTransactionStore, dynamicPropertiesStore)); + } + + public void initCache() { + ((TxCacheDB) getDb()).init(); + } +} diff --git a/chainbase/src/main/java/org/tron/core/db/TransactionStore.java b/chainbase/src/main/java/org/tron/core/db/TransactionStore.java index 342550ecb4a..c0067b77934 100644 --- a/chainbase/src/main/java/org/tron/core/db/TransactionStore.java +++ b/chainbase/src/main/java/org/tron/core/db/TransactionStore.java @@ -52,6 +52,9 @@ private TransactionCapsule getTransactionFromBlockStore(byte[] key, long blockNu private TransactionCapsule getTransactionFromKhaosDatabase(byte[] key, long high) { List khaosBlocks = khaosDatabase.getMiniStore().getBlockByNum(high); + if (khaosBlocks == null) { + return null; + } for (KhaosBlock bl : khaosBlocks) { for (TransactionCapsule e : bl.getBlk().getTransactions()) { if (e.getTransactionId().equals(Sha256Hash.wrap(key))) { diff --git a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java index 6a74d6d015f..c3776921244 100644 --- a/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java +++ b/chainbase/src/main/java/org/tron/core/db/TransactionTrace.java @@ -1,13 +1,15 @@ package org.tron.core.db; +import static org.tron.common.math.Maths.max; +import static org.tron.common.math.Maths.min; import static org.tron.common.runtime.InternalTransaction.TrxType.TRX_CONTRACT_CALL_TYPE; import static org.tron.common.runtime.InternalTransaction.TrxType.TRX_CONTRACT_CREATION_TYPE; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import java.util.Objects; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; import org.springframework.util.StringUtils; import org.tron.common.runtime.InternalTransaction.TrxType; import org.tron.common.runtime.ProgramResult; @@ -41,7 +43,7 @@ import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -@Slf4j(topic = "TransactionTrace") +@Slf4j(topic = "DB") public class TransactionTrace { private TransactionCapsule trx; @@ -138,11 +140,10 @@ public void checkIsConstant() throws ContractValidateException, VMIllegalExcepti ContractCapsule contract = contractStore .get(triggerContractFromTransaction.getContractAddress().toByteArray()); if (contract == null) { - logger.info("contract: {} is not in contract store", StringUtil - .encode58Check(triggerContractFromTransaction.getContractAddress().toByteArray())); - throw new ContractValidateException("contract: " + StringUtil - .encode58Check(triggerContractFromTransaction.getContractAddress().toByteArray()) - + " is not in contract store"); + throw new ContractValidateException(String.format("contract: %s is not in contract store", + StringUtil.encode58Check(triggerContractFromTransaction + .getContractAddress().toByteArray()))); + } ABI abi = contract.getInstance().getAbi(); if (WalletUtil.isConstant(abi, triggerContractFromTransaction)) { @@ -159,6 +160,13 @@ public void setBill(long energyUsage) { receipt.setEnergyUsageTotal(energyUsage); } + public void setPenalty(long energyPenalty) { + if (energyPenalty < 0) { + energyPenalty = 0L; + } + receipt.setEnergyPenaltyTotal(energyPenalty); + } + //set net bill public void setNetBill(long netUsage, long netFee) { receipt.setNetUsage(netUsage); @@ -180,6 +188,7 @@ public void exec() /* VM execute */ runtime.execute(transactionContext); setBill(transactionContext.getProgramResult().getEnergyUsed()); + setPenalty(transactionContext.getProgramResult().getEnergyPenaltyTotal()); // if (TrxType.TRX_PRECOMPILED_TYPE != trxType) { // if (contractResult.OUT_OF_TIME @@ -224,7 +233,7 @@ public void pay() throws BalanceInsufficientException { long originEnergyLimit = 0; switch (trxType) { case TRX_CONTRACT_CREATION_TYPE: - callerAccount = TransactionCapsule.getOwner(trx.getInstance().getRawData().getContract(0)); + callerAccount = trx.getOwnerAddress(); originAccount = callerAccount; break; case TRX_CONTRACT_CALL_TYPE: @@ -235,9 +244,11 @@ public void pay() throws BalanceInsufficientException { callerAccount = callContract.getOwnerAddress().toByteArray(); originAccount = contractCapsule.getOriginAddress(); - percent = Math - .max(Constant.ONE_HUNDRED - contractCapsule.getConsumeUserResourcePercent(), 0); - percent = Math.min(percent, Constant.ONE_HUNDRED); + boolean disableJavaLangMath = dynamicPropertiesStore.disableJavaLangMath(); + percent = max(Constant.ONE_HUNDRED - contractCapsule.getConsumeUserResourcePercent( + disableJavaLangMath), 0, disableJavaLangMath); + percent = min(percent, Constant.ONE_HUNDRED, + disableJavaLangMath); originEnergyLimit = contractCapsule.getOriginEnergyLimit(); break; default: @@ -247,6 +258,26 @@ public void pay() throws BalanceInsufficientException { // originAccount Percent = 30% AccountCapsule origin = accountStore.get(originAccount); AccountCapsule caller = accountStore.get(callerAccount); + if (dynamicPropertiesStore.supportUnfreezeDelay() + && getRuntimeResult().getException() == null && !getRuntimeResult().isRevert()) { + + // just fo caller is not origin, we set the related field for origin account + if (origin != null && !caller.getAddress().equals(origin.getAddress())) { + resetAccountUsage(origin, + receipt.getOriginEnergyUsage(), + receipt.getOriginEnergyWindowSize(), + receipt.getOriginEnergyMergedUsage(), + receipt.getOriginEnergyMergedWindowSize(), + receipt.getOriginEnergyWindowSizeV2()); + } + + resetAccountUsage(caller, + receipt.getCallerEnergyUsage(), + receipt.getCallerEnergyWindowSize(), + receipt.getCallerEnergyMergedUsage(), + receipt.getCallerEnergyMergedWindowSize(), + receipt.getCallerEnergyWindowSizeV2()); + } receipt.payEnergyBill( dynamicPropertiesStore, accountStore, forkController, origin, @@ -256,6 +287,43 @@ public void pay() throws BalanceInsufficientException { EnergyProcessor.getHeadSlot(dynamicPropertiesStore)); } + private void resetAccountUsage(AccountCapsule accountCap, + long usage, long size, long mergedUsage, long mergedSize, long size2) { + if (dynamicPropertiesStore.supportAllowCancelAllUnfreezeV2()) { + resetAccountUsageV2(accountCap, usage, size, mergedUsage, mergedSize, size2); + return; + } + long currentSize = accountCap.getWindowSize(ENERGY); + long currentUsage = accountCap.getEnergyUsage(); + // Drop the pre consumed frozen energy + long newArea = currentUsage * currentSize + - (mergedUsage * mergedSize - usage * size); + // If area merging happened during suicide, use the current window size + long newSize = mergedSize == currentSize ? size : currentSize; + // Calc new usage by fixed x-axes + long newUsage = max(0, newArea / newSize, dynamicPropertiesStore.disableJavaLangMath()); + // Reset account usage and window size + accountCap.setEnergyUsage(newUsage); + accountCap.setNewWindowSize(ENERGY, newUsage == 0 ? 0L : newSize); + } + + private void resetAccountUsageV2(AccountCapsule accountCap, + long usage, long size, long mergedUsage, long mergedSize, long size2) { + long currentSize = accountCap.getWindowSize(ENERGY); + long currentSize2 = accountCap.getWindowSizeV2(ENERGY); + long currentUsage = accountCap.getEnergyUsage(); + // Drop the pre consumed frozen energy + long newArea = currentUsage * currentSize - (mergedUsage * mergedSize - usage * size); + // If area merging happened during suicide, use the current window size + long newSize = mergedSize == currentSize ? size : currentSize; + long newSize2 = mergedSize == currentSize ? size2 : currentSize2; + // Calc new usage by fixed x-axes + long newUsage = max(0, newArea / newSize, dynamicPropertiesStore.disableJavaLangMath()); + // Reset account usage and window size + accountCap.setEnergyUsage(newUsage); + accountCap.setNewWindowSizeV2(ENERGY, newUsage == 0 ? 0L : newSize2); + } + public boolean checkNeedRetry() { if (!needVM()) { return false; @@ -269,14 +337,13 @@ public void check() throws ReceiptCheckErrException { return; } if (Objects.isNull(trx.getContractRet())) { - throw new ReceiptCheckErrException("null resultCode"); + throw new ReceiptCheckErrException( + String.format("null resultCode id: %s", trx.getTransactionId())); } if (!trx.getContractRet().equals(receipt.getResult())) { - logger.info( - "this tx id: {}, the resultCode in received block: {}, the resultCode in self: {}", - Hex.toHexString(trx.getTransactionId().getBytes()), trx.getContractRet(), - receipt.getResult()); - throw new ReceiptCheckErrException("Different resultCode"); + throw new ReceiptCheckErrException(String.format( + "different resultCode txId: %s, expect: %s, actual: %s", + trx.getTransactionId(), trx.getContractRet(), receipt.getResult())); } } @@ -313,7 +380,7 @@ public void deleteContract(byte[] address) { public static byte[] convertToTronAddress(byte[] address) { if (address.length == 20) { byte[] newAddress = new byte[21]; - byte[] temp = new byte[]{DecodeUtil.addressPreFixByte}; + byte[] temp = new byte[] {DecodeUtil.addressPreFixByte}; System.arraycopy(temp, 0, newAddress, 0, temp.length); System.arraycopy(address, 0, newAddress, temp.length, address.length); address = newAddress; diff --git a/chainbase/src/main/java/org/tron/core/db/TronDatabase.java b/chainbase/src/main/java/org/tron/core/db/TronDatabase.java index 5b8762ec9ad..d791e189eb4 100644 --- a/chainbase/src/main/java/org/tron/core/db/TronDatabase.java +++ b/chainbase/src/main/java/org/tron/core/db/TronDatabase.java @@ -3,15 +3,22 @@ import com.google.protobuf.InvalidProtocolBufferException; import java.nio.file.Paths; import java.util.Iterator; +import java.util.Map; import java.util.Map.Entry; +import javax.annotation.PostConstruct; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.WriteOptions; +import org.rocksdb.DirectComparator; +import org.springframework.beans.factory.annotation.Autowired; import org.tron.common.parameter.CommonParameter; +import org.tron.common.storage.WriteOptionsWrapper; import org.tron.common.storage.leveldb.LevelDbDataSourceImpl; +import org.tron.common.storage.metric.DbStatService; import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl; import org.tron.common.utils.StorageUtils; import org.tron.core.db.common.DbSourceInter; +import org.tron.core.db2.common.WrappedByteArray; import org.tron.core.db2.core.ITronChainBase; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ItemNotFoundException; @@ -22,6 +29,11 @@ public abstract class TronDatabase implements ITronChainBase { protected DbSourceInter dbSource; @Getter private String dbName; + private WriteOptionsWrapper writeOptions = WriteOptionsWrapper.getInstance() + .sync(CommonParameter.getInstance().getStorage().isDbSync()); + + @Autowired + private DbStatService dbStatService; protected TronDatabase(String dbName) { this.dbName = dbName; @@ -31,7 +43,7 @@ protected TronDatabase(String dbName) { dbSource = new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(dbName), dbName, - StorageUtils.getOptionsByDbName(dbName), + getOptionsByDbNameForLevelDB(dbName), new WriteOptions().sync(CommonParameter.getInstance() .getStorage().isDbSync())); } else if ("ROCKSDB".equals(CommonParameter.getInstance() @@ -40,19 +52,36 @@ protected TronDatabase(String dbName) { CommonParameter.getInstance().getStorage().getDbDirectory()).toString(); dbSource = new RocksDbDataSourceImpl(parentName, dbName, CommonParameter.getInstance() - .getRocksDBCustomSettings()); + .getRocksDBCustomSettings(), getDirectComparator()); } dbSource.initDB(); } + @PostConstruct + protected void init() { + dbStatService.register(dbSource); + } + protected TronDatabase() { } + protected org.iq80.leveldb.Options getOptionsByDbNameForLevelDB(String dbName) { + return StorageUtils.getOptionsByDbName(dbName); + } + + protected DirectComparator getDirectComparator() { + return null; + } + public DbSourceInter getDbSource() { return dbSource; } + public void updateByBatch(Map rows) { + this.dbSource.updateByBatch(rows, writeOptions); + } + /** * reset the database. */ @@ -65,7 +94,14 @@ public void reset() { */ @Override public void close() { - dbSource.closeDB(); + logger.info("******** Begin to close {}. ********", getName()); + try { + dbSource.closeDB(); + } catch (Exception e) { + logger.warn("Failed to close {}.", getName(), e); + } finally { + logger.info("******** End to close {}. ********", getName()); + } } public abstract void put(byte[] key, T item); @@ -75,10 +111,20 @@ public void close() { public abstract T get(byte[] key) throws InvalidProtocolBufferException, ItemNotFoundException, BadItemException; + @Override + public T getFromRoot(byte[] key) + throws InvalidProtocolBufferException, BadItemException, ItemNotFoundException { + return get(key); + } + public T getUnchecked(byte[] key) { return null; } + public Map prefixQuery(byte[] key) { + return dbSource.prefixQuery(key); + } + public abstract boolean has(byte[] key); @Override diff --git a/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java b/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java index d6ff34e4d1e..4b75ddee3a4 100644 --- a/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java +++ b/chainbase/src/main/java/org/tron/core/db/TronStoreWithRevoking.java @@ -11,15 +11,16 @@ import java.util.Iterator; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; import javax.annotation.PostConstruct; import lombok.Getter; import lombok.extern.slf4j.Slf4j; -import org.iq80.leveldb.Options; import org.iq80.leveldb.WriteOptions; import org.rocksdb.DirectComparator; import org.springframework.beans.factory.annotation.Autowired; import org.tron.common.parameter.CommonParameter; import org.tron.common.storage.leveldb.LevelDbDataSourceImpl; +import org.tron.common.storage.metric.DbStatService; import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl; import org.tron.common.utils.StorageUtils; import org.tron.core.capsule.ProtoCapsule; @@ -28,9 +29,9 @@ import org.tron.core.db2.common.IRevokingDB; import org.tron.core.db2.common.LevelDB; import org.tron.core.db2.common.RocksDB; +import org.tron.core.db2.common.WrappedByteArray; import org.tron.core.db2.core.Chainbase; import org.tron.core.db2.core.ITronChainBase; -import org.tron.core.db2.core.RevokingDBWithCachingOldValue; import org.tron.core.db2.core.SnapshotRoot; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ItemNotFoundException; @@ -47,35 +48,33 @@ public abstract class TronStoreWithRevoking implements I @Autowired private RevokingDatabase revokingDatabase; + @Autowired + private DbStatService dbStatService; + + @Getter + private final DB db; + protected TronStoreWithRevoking(String dbName) { - int dbVersion = CommonParameter.getInstance().getStorage().getDbVersion(); String dbEngine = CommonParameter.getInstance().getStorage().getDbEngine(); - if (dbVersion == 1) { - this.revokingDB = new RevokingDBWithCachingOldValue(dbName, - getOptionsByDbNameForLevelDB(dbName)); - } else if (dbVersion == 2) { - if ("LEVELDB".equals(dbEngine.toUpperCase())) { - this.revokingDB = new Chainbase(new SnapshotRoot( - new LevelDB( - new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(dbName), - dbName, - getOptionsByDbNameForLevelDB(dbName), - new WriteOptions().sync(CommonParameter.getInstance() - .getStorage().isDbSync()))))); - } else if ("ROCKSDB".equals(dbEngine.toUpperCase())) { - String parentPath = Paths - .get(StorageUtils.getOutputDirectoryByDbName(dbName), CommonParameter - .getInstance().getStorage().getDbDirectory()).toString(); - - this.revokingDB = new Chainbase(new SnapshotRoot( - new RocksDB( - new RocksDbDataSourceImpl(parentPath, - dbName, CommonParameter.getInstance() - .getRocksDBCustomSettings(), getDirectComparator())))); - } + if ("LEVELDB".equals(dbEngine.toUpperCase())) { + this.db = new LevelDB( + new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(dbName), + dbName, + getOptionsByDbNameForLevelDB(dbName), + new WriteOptions().sync(CommonParameter.getInstance() + .getStorage().isDbSync()))); + } else if ("ROCKSDB".equals(dbEngine.toUpperCase())) { + String parentPath = Paths + .get(StorageUtils.getOutputDirectoryByDbName(dbName), CommonParameter + .getInstance().getStorage().getDbDirectory()).toString(); + this.db = new RocksDB( + new RocksDbDataSourceImpl(parentPath, + dbName, CommonParameter.getInstance() + .getRocksDBCustomSettings(), getDirectComparator())); } else { - throw new RuntimeException("db version is error."); + throw new RuntimeException(String.format("db engine %s is error", dbEngine)); } + this.revokingDB = new Chainbase(new SnapshotRoot(this.db)); } protected org.iq80.leveldb.Options getOptionsByDbNameForLevelDB(String dbName) { @@ -87,25 +86,8 @@ protected DirectComparator getDirectComparator() { } protected TronStoreWithRevoking(DB db) { - int dbVersion = CommonParameter.getInstance().getStorage().getDbVersion(); - if (dbVersion == 2) { - this.revokingDB = new Chainbase(new SnapshotRoot(db)); - } else { - throw new RuntimeException("db version is only 2.(" + dbVersion + ")"); - } - } - - // only for test - protected TronStoreWithRevoking(String dbName, RevokingDatabase revokingDatabase) { - this.revokingDB = new RevokingDBWithCachingOldValue(dbName, - (AbstractRevokingStore) revokingDatabase); - } - - // only for test - protected TronStoreWithRevoking(String dbName, Options options, - RevokingDatabase revokingDatabase) { - this.revokingDB = new RevokingDBWithCachingOldValue(dbName, options, - (AbstractRevokingStore) revokingDatabase); + this.db = db; + this.revokingDB = new Chainbase(new SnapshotRoot(db)); } @Override @@ -116,6 +98,7 @@ public String getDbName() { @PostConstruct private void init() { revokingDatabase.add(revokingDB); + dbStatService.register(db); } @Override @@ -148,6 +131,12 @@ public T getUnchecked(byte[] key) { } } + @Override + public T getFromRoot(byte[] key) throws ItemNotFoundException, BadItemException{ + return of(revokingDB.getFromRoot(key)) ; + + } + public T of(byte[] value) throws BadItemException { try { Constructor constructor = token.getRawType().getConstructor(byte[].class); @@ -181,7 +170,7 @@ private void closeJniIterator(Iterator iterator) { try { ((DBIterator) iterator).close(); } catch (IOException e) { - logger.error("", e); + logger.error("Close jni iterator.", e); } } } @@ -193,7 +182,14 @@ public String getName() { @Override public void close() { - revokingDB.close(); + logger.info("******** Begin to close {}. ********", getName()); + try { + revokingDB.close(); + } catch (Exception e) { + logger.warn("Failed to close {}.", getName(), e); + } finally { + logger.info("******** End to close {}. ********", getName()); + } } @Override @@ -219,4 +215,16 @@ public long size() { public void setCursor(Chainbase.Cursor cursor) { revokingDB.setCursor(cursor); } + + public Map prefixQuery(byte[] key) { + return revokingDB.prefixQuery(key).entrySet().stream().collect( + Collectors.toMap(Map.Entry::getKey, e -> { + try { + return of(e.getValue()); + } catch (BadItemException e1) { + throw new RuntimeException(e1); + } + } + )); + } } diff --git a/chainbase/src/main/java/org/tron/core/db/accountstate/AccountStateEntity.java b/chainbase/src/main/java/org/tron/core/db/accountstate/AccountStateEntity.java index 858543986fc..d52eb7a0af2 100644 --- a/chainbase/src/main/java/org/tron/core/db/accountstate/AccountStateEntity.java +++ b/chainbase/src/main/java/org/tron/core/db/accountstate/AccountStateEntity.java @@ -1,5 +1,6 @@ package org.tron.core.db.accountstate; +import com.google.protobuf.InvalidProtocolBufferException; import lombok.extern.slf4j.Slf4j; import org.tron.common.utils.StringUtil; import org.tron.protos.Protocol.Account; @@ -24,8 +25,8 @@ public AccountStateEntity(Account account) { public static AccountStateEntity parse(byte[] data) { try { return new AccountStateEntity().setAccount(Account.parseFrom(data)); - } catch (Exception e) { - logger.error("parse to AccountStateEntity error! reason: {}", e.getMessage()); + } catch (InvalidProtocolBufferException e) { + logger.error("Parse to AccountStateEntity error! reason: {}", e.getMessage()); } return null; } diff --git a/chainbase/src/main/java/org/tron/core/db/common/DbSourceInter.java b/chainbase/src/main/java/org/tron/core/db/common/DbSourceInter.java index e823da1bde9..0823b7a7cf4 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/DbSourceInter.java +++ b/chainbase/src/main/java/org/tron/core/db/common/DbSourceInter.java @@ -17,6 +17,8 @@ */ package org.tron.core.db.common; +import org.tron.core.db2.common.WrappedByteArray; + import java.util.Map; import java.util.Set; @@ -42,4 +44,8 @@ public interface DbSourceInter extends BatchSourceInter, long getTotal() throws RuntimeException; + void stat(); + + Map prefixQuery(byte[] key); + } diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java index f706623693f..afbacac35db 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/DBIterator.java @@ -1,9 +1,71 @@ package org.tron.core.db.common.iterator; +import com.google.common.collect.Iterators; +import com.google.common.collect.UnmodifiableIterator; +import com.google.common.primitives.Bytes; import java.io.Closeable; import java.util.Iterator; import java.util.Map.Entry; +import java.util.NoSuchElementException; -public interface DBIterator extends Iterator>, Closeable { +public interface DBIterator extends Iterator>, AutoCloseable, Closeable { + void seek(byte[] key); + + void seekToFirst(); + + void seekToLast(); + + /** + * An iterator is either positioned at a key/value pair, or + * not valid. This method returns true iff the iterator is valid. + * + * REQUIRES: iterator not closed + * + * @throws IllegalStateException if the iterator is closed. + * @return an iterator is either positioned at a key/value pair + */ + boolean valid(); + + /** + * The underlying storage for + * the returned slice is valid only until the next modification of + * the iterator. + * + * REQUIRES: valid() && !closed + * + * @throws IllegalStateException if the iterator is closed. + * @throws NoSuchElementException if the iterator is not valid. + * + * @return the key for the current entry + */ + byte[] getKey(); + + /** + * The underlying storage for + * the returned slice is valid only until the next modification of + * the iterator. + * + * REQUIRES: valid() && !closed + * + * @throws IllegalStateException if the iterator is closed. + * @throws NoSuchElementException if the iterator is not valid. + * + * @return the value for the current entry + */ + byte[] getValue(); + + /** + * @throws IllegalStateException if the iterator is closed. + */ + void checkState(); + + /** + * @throws NoSuchElementException if the iterator is not valid. + */ + default void checkValid() { + if (!valid()) { + throw new NoSuchElementException(); + } + } } diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java index f095ec5ab5d..541f71348af 100644 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/RockStoreIterator.java @@ -3,27 +3,35 @@ import java.io.IOException; import java.util.Map.Entry; import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import org.rocksdb.RocksIterator; -@Slf4j +@Slf4j(topic = "DB") public final class RockStoreIterator implements DBIterator { - private RocksIterator dbIterator; + private final RocksIterator dbIterator; private boolean first = true; + private final AtomicBoolean close = new AtomicBoolean(false); + public RockStoreIterator(RocksIterator dbIterator) { this.dbIterator = dbIterator; } @Override public void close() throws IOException { - dbIterator.close(); + if (close.compareAndSet(false, true)) { + dbIterator.close(); + } } @Override public boolean hasNext() { + if (close.get()) { + return false; + } boolean hasNext = false; // true is first item try { @@ -32,14 +40,14 @@ public boolean hasNext() { first = false; } if (!(hasNext = dbIterator.isValid())) { // false is last item - dbIterator.close(); + close(); } } catch (Exception e) { - System.out.println("e:" + e); + logger.error(e.getMessage(), e); try { - dbIterator.close(); + close(); } catch (Exception e1) { - System.out.println("e1:" + e1); + logger.error(e.getMessage(), e); } } return hasNext; @@ -47,7 +55,7 @@ public boolean hasNext() { @Override public Entry next() { - if (!dbIterator.isValid()) { + if (close.get()) { throw new NoSuchElementException(); } byte[] key = dbIterator.key(); @@ -70,4 +78,50 @@ public byte[] setValue(byte[] value) { } }; } -} \ No newline at end of file + + @Override + public void seek(byte[] key) { + checkState(); + dbIterator.seek(key); + this.first = false; + } + + @Override + public void seekToFirst() { + checkState(); + dbIterator.seekToFirst(); + this.first = false; + } + + @Override + public void seekToLast() { + checkState(); + dbIterator.seekToLast(); + this.first = false; + } + + @Override + public boolean valid() { + checkState(); + return dbIterator.isValid(); + } + + @Override + public byte[] getKey() { + checkValid(); + return dbIterator.key(); + } + + @Override + public byte[] getValue() { + checkValid(); + return dbIterator.value(); + } + + @Override + public void checkState() { + if (close.get()) { + throw new IllegalStateException("iterator has been closed"); + } + } +} diff --git a/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java b/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java index 997d13dd293..d771716a7e8 100755 --- a/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java +++ b/chainbase/src/main/java/org/tron/core/db/common/iterator/StoreIterator.java @@ -2,26 +2,37 @@ import java.io.IOException; import java.util.Map.Entry; +import java.util.NoSuchElementException; +import java.util.concurrent.atomic.AtomicBoolean; import lombok.extern.slf4j.Slf4j; import org.iq80.leveldb.DBIterator; + @Slf4j(topic = "DB") public final class StoreIterator implements org.tron.core.db.common.iterator.DBIterator { - private DBIterator dbIterator; + private final DBIterator dbIterator; private boolean first = true; + private final AtomicBoolean close = new AtomicBoolean(false); + public StoreIterator(DBIterator dbIterator) { this.dbIterator = dbIterator; } @Override public void close() throws IOException { - dbIterator.close(); + if (close.compareAndSet(false, true)) { + dbIterator.close(); + } } @Override public boolean hasNext() { + if (close.get()) { + return false; + } + boolean hasNext = false; // true is first item try { @@ -31,10 +42,10 @@ public boolean hasNext() { } if (!(hasNext = dbIterator.hasNext())) { // false is last item - dbIterator.close(); + close(); } } catch (Exception e) { - logger.debug(e.getMessage(), e); + logger.error(e.getMessage(), e); } return hasNext; @@ -42,6 +53,9 @@ public boolean hasNext() { @Override public Entry next() { + if (close.get()) { + throw new NoSuchElementException(); + } return dbIterator.next(); } @@ -49,4 +63,51 @@ public Entry next() { public void remove() { throw new UnsupportedOperationException(); } + + @Override + public void seek(byte[] key) { + checkState(); + dbIterator.seek(key); + this.first = false; + } + + @Override + public void seekToFirst() { + checkState(); + dbIterator.seekToFirst(); + this.first = false; + } + + @Override + public void seekToLast() { + checkState(); + dbIterator.seekToLast(); + this.first = false; + } + + @Override + public boolean valid() { + checkState(); + return dbIterator.hasNext(); + } + + @Override + public byte[] getKey() { + checkValid(); + return dbIterator.peekNext().getKey(); + } + + @Override + public byte[] getValue() { + checkValid(); + return dbIterator.peekNext().getValue(); + } + + @Override + public void checkState() { + if (close.get()) { + throw new IllegalStateException("iterator has been closed"); + } + } } + diff --git a/chainbase/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java b/chainbase/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java index d6492cc2eaf..ac5eb6d6580 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/ConcurrentHashDB.java @@ -55,4 +55,9 @@ public void close() { public DB newInstance() { return null; } + + @Override + public void stat() { + + } } diff --git a/chainbase/src/main/java/org/tron/core/db2/common/DB.java b/chainbase/src/main/java/org/tron/core/db2/common/DB.java index e58ba6df3e5..eae529c5ca9 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/DB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/DB.java @@ -15,9 +15,11 @@ public interface DB extends Iterable>, Instance> void remove(K k); - Iterator iterator(); + Iterator> iterator(); void close(); String getDbName(); + + void stat(); } diff --git a/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java b/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java index 87612f1d81f..85b81ed37e8 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/HashDB.java @@ -1,6 +1,5 @@ package org.tron.core.db2.common; -import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -58,4 +57,9 @@ public void close() { public HashDB newInstance() { return new HashDB(name); } + + @Override + public void stat() { + + } } diff --git a/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java b/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java index 445972417df..8b0b023e8f4 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/IRevokingDB.java @@ -17,6 +17,8 @@ public interface IRevokingDB extends Iterable> { byte[] get(byte[] key) throws ItemNotFoundException; + byte[] getFromRoot(byte[] key) throws ItemNotFoundException; + byte[] getUnchecked(byte[] key); void close(); @@ -37,6 +39,8 @@ public interface IRevokingDB extends Iterable> { List getKeysNext(byte[] key, long limit); + Map prefixQuery(byte[] key); + default Map getNext(byte[] key, long limit) { return Collections.emptyMap(); } diff --git a/chainbase/src/main/java/org/tron/core/db2/common/LevelDB.java b/chainbase/src/main/java/org/tron/core/db2/common/LevelDB.java index b0d885ce81f..b5616f87b8a 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/LevelDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/LevelDB.java @@ -77,4 +77,9 @@ public void reset() { public LevelDB newInstance() { return new LevelDB(db.newInstance()); } + + @Override + public void stat() { + this.db.stat(); + } } diff --git a/chainbase/src/main/java/org/tron/core/db2/common/RocksDB.java b/chainbase/src/main/java/org/tron/core/db2/common/RocksDB.java index 6855bc08a77..31970b185cc 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/RocksDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/RocksDB.java @@ -78,4 +78,9 @@ public void reset() { public DB newInstance() { return new RocksDB(db.newInstance()); } + + @Override + public void stat() { + this.db.stat(); + } } \ No newline at end of file diff --git a/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java b/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java index fcd31b5cad4..9d2409685c9 100644 --- a/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java +++ b/chainbase/src/main/java/org/tron/core/db2/common/TxCacheDB.java @@ -1,93 +1,196 @@ package org.tron.core.db2.common; -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.Iterators; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; +import com.google.common.hash.BloomFilter; +import com.google.common.hash.Funnels; +import com.google.common.hash.HashCode; +import com.google.common.hash.Hashing; +import com.google.common.io.ByteSource; import com.google.common.primitives.Longs; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.Reader; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Collection; +import java.nio.file.StandardOpenOption; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; -import java.util.WeakHashMap; +import java.util.Objects; +import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import lombok.Getter; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; +import org.bouncycastle.util.encoders.Hex; import org.iq80.leveldb.WriteOptions; import org.tron.common.parameter.CommonParameter; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.Metrics; import org.tron.common.storage.leveldb.LevelDbDataSourceImpl; import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.JsonUtil; import org.tron.common.utils.StorageUtils; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.db.RecentTransactionItem; +import org.tron.core.db.RecentTransactionStore; import org.tron.core.db.common.iterator.DBIterator; +import org.tron.core.store.DynamicPropertiesStore; @Slf4j(topic = "DB") public class TxCacheDB implements DB, Flusher { // > 65_536(= 2^16) blocks, that is the number of the reference block - private final int BLOCK_COUNT = 70_000; + private static final long MAX_BLOCK_SIZE = 65536; + // estimated number transactions in one block + private final int TRANSACTION_COUNT; - private Map db = new WeakHashMap<>(); - private Multimap blockNumMap = ArrayListMultimap.create(); - private String name; + private static final long INVALID_BLOCK = -1; + + // Since the filter cannot query for specific record information, + // FAKE_TRANSACTION represent the record presence. + private final byte[] FAKE_TRANSACTION = ByteArray.fromLong(0); + + // a pair of bloom filters record the recent transactions + private BloomFilter[] bloomFilters = new BloomFilter[2]; + // filterStartBlock record the start block of the active filter + private volatile long filterStartBlock = INVALID_BLOCK; + // currentFilterIndex records the index of the active filter + private volatile int currentFilterIndex = 0; + + // record the last metric block to avoid duplication + private long lastMetricBlock = 0; + + private final String name; // add a persistent storage, the store name is: trans-cache // when fullnode startup, transactionCache initializes transactions from this store private DB persistentStore; - public TxCacheDB(String name) { - this.name = name; + // replace persistentStore and optimizes startup performance + private RecentTransactionStore recentTransactionStore; - int dbVersion = CommonParameter.getInstance().getStorage().getDbVersion(); + private DynamicPropertiesStore dynamicPropertiesStore; + + private final Path cacheFile0; + private final Path cacheFile1; + private String crc32c0; + private String crc32c1; + private final Path cacheProperties; + private final Path cacheDir; + private AtomicBoolean isValid = new AtomicBoolean(false); + private boolean txCacheInitOptimization; + + @Getter + @Setter + private volatile boolean alive; + + public TxCacheDB(String name, RecentTransactionStore recentTransactionStore, + DynamicPropertiesStore dynamicPropertiesStore) { + this.name = name; + this.TRANSACTION_COUNT = + CommonParameter.getInstance().getStorage().getEstimatedBlockTransactions(); + this.recentTransactionStore = recentTransactionStore; + this.dynamicPropertiesStore = dynamicPropertiesStore; String dbEngine = CommonParameter.getInstance().getStorage().getDbEngine(); - if (dbVersion == 2) { - if ("LEVELDB".equals(dbEngine.toUpperCase())) { - this.persistentStore = new LevelDB( - new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(name), - name, StorageUtils.getOptionsByDbName(name), - new WriteOptions().sync(CommonParameter.getInstance() - .getStorage().isDbSync()))); - } else if ("ROCKSDB".equals(dbEngine.toUpperCase())) { - String parentPath = Paths - .get(StorageUtils.getOutputDirectoryByDbName(name), CommonParameter - .getInstance().getStorage().getDbDirectory()).toString(); - - this.persistentStore = new RocksDB( - new RocksDbDataSourceImpl(parentPath, - name, CommonParameter.getInstance() - .getRocksDBCustomSettings())); - } else { - throw new RuntimeException("db type is not supported."); - } + if ("LEVELDB".equals(dbEngine.toUpperCase())) { + this.persistentStore = new LevelDB( + new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(name), + name, StorageUtils.getOptionsByDbName(name), + new WriteOptions().sync(CommonParameter.getInstance() + .getStorage().isDbSync()))); + } else if ("ROCKSDB".equals(dbEngine.toUpperCase())) { + String parentPath = Paths + .get(StorageUtils.getOutputDirectoryByDbName(name), CommonParameter + .getInstance().getStorage().getDbDirectory()).toString(); + + this.persistentStore = new RocksDB( + new RocksDbDataSourceImpl(parentPath, + name, CommonParameter.getInstance() + .getRocksDBCustomSettings())); } else { - throw new RuntimeException("db version is not supported."); + throw new RuntimeException(String.format("db type: %s is not supported", dbEngine)); } - // init cache from persistent store - init(); + this.bloomFilters[0] = BloomFilter.create(Funnels.byteArrayFunnel(), + MAX_BLOCK_SIZE * TRANSACTION_COUNT); + this.bloomFilters[1] = BloomFilter.create(Funnels.byteArrayFunnel(), + MAX_BLOCK_SIZE * TRANSACTION_COUNT); + cacheDir = Paths.get(CommonParameter.getInstance().getOutputDirectory(), ".cache"); + this.cacheFile0 = Paths.get(cacheDir.toString(), "bloomFilters_0"); + this.cacheFile1 = Paths.get(cacheDir.toString(), "bloomFilters_1"); + this.cacheProperties = Paths.get(cacheDir.toString(), "txCache.properties"); + this.txCacheInitOptimization = CommonParameter.getInstance() + .getStorage().isTxCacheInitOptimization(); + } /** * this method only used for init, put all data in tran-cache into the two maps. */ - private void init() { + private void initCache() { + long start = System.currentTimeMillis(); DBIterator iterator = (DBIterator) persistentStore.iterator(); + long persistentSize = 0; while (iterator.hasNext()) { Entry entry = iterator.next(); - byte[] key = entry.getKey(); - byte[] value = entry.getValue(); - if (key == null || value == null) { + if (ArrayUtils.isEmpty(entry.getKey()) || ArrayUtils.isEmpty(entry.getValue())) { return; } - Key k = Key.copyOf(key); - Long v = Longs.fromByteArray(value); - blockNumMap.put(v, k); - db.put(k, v); + bloomFilters[1].put(entry.getKey()); + persistentSize++; } + logger.info("Load cache from persistentStore, db: {}, filter: {}, filter-fpp: {}, cost: {} ms.", + persistentSize, + bloomFilters[1].approximateElementCount(), bloomFilters[1].expectedFpp(), + System.currentTimeMillis() - start); + } + + public void init() { + if (recovery()) { + isValid.set(true); + setAlive(true); + return; + } + long size = recentTransactionStore.size(); + if (size != MAX_BLOCK_SIZE) { + // 0. load from persistentStore + initCache(); + } + + // 1. load from recentTransactionStore + long start = System.currentTimeMillis(); + for (Entry bytesCapsuleEntry : recentTransactionStore) { + byte[] data = bytesCapsuleEntry.getValue().getData(); + RecentTransactionItem trx = + JsonUtil.json2Obj(new String(data), RecentTransactionItem.class); + + trx.getTransactionIds().forEach(tid -> bloomFilters[1].put(Hex.decode(tid))); + } + + logger.info("Load cache from recentTransactionStore, filter: {}, filter-fpp: {}, cost: {} ms.", + bloomFilters[1].approximateElementCount(), bloomFilters[1].expectedFpp(), + System.currentTimeMillis() - start); + isValid.set(true); + setAlive(true); } @Override public byte[] get(byte[] key) { - Long v = db.get(Key.of(key)); - return v == null ? null : Longs.toByteArray(v); + if (!bloomFilters[0].mightContain(key) && !bloomFilters[1].mightContain(key)) { + return null; + } + // this means exist + return FAKE_TRANSACTION; } @Override @@ -96,46 +199,54 @@ public void put(byte[] key, byte[] value) { return; } - Key k = Key.copyOf(key); - Long v = Longs.fromByteArray(value); - blockNumMap.put(v, k); - db.put(k, v); - // put the data into persistent storage - persistentStore.put(key, value); - removeEldest(); - } + long blockNum = Longs.fromByteArray(value); + if (filterStartBlock == INVALID_BLOCK) { + // init active filter start block + filterStartBlock = blockNum; + currentFilterIndex = 0; + logger.info("Init tx cache bloomFilters at {}.", blockNum); + } else if (blockNum - filterStartBlock > MAX_BLOCK_SIZE) { + // active filter is full + logger.info( + "Active bloomFilters is full (size = {} fpp = {}), create a new one (start = {}).", + bloomFilters[currentFilterIndex].approximateElementCount(), + bloomFilters[currentFilterIndex].expectedFpp(), + blockNum); - private void removeEldest() { - Set keys = blockNumMap.keySet(); - if (keys.size() > BLOCK_COUNT) { - keys.stream() - .min(Long::compareTo) - .ifPresent(k -> { - Collection trxHashs = blockNumMap.get(k); - // remove transaction from persistentStore, - // if foreach is inefficient, change remove-foreach to remove-batch - trxHashs.forEach(key -> persistentStore.remove(key.getBytes())); - blockNumMap.removeAll(k); - logger.debug("******removeEldest block number:{}, block count:{}", k, keys.size()); - }); + if (currentFilterIndex == 0) { + currentFilterIndex = 1; + } else { + currentFilterIndex = 0; + } + + filterStartBlock = blockNum; + bloomFilters[currentFilterIndex] = + BloomFilter.create(Funnels.byteArrayFunnel(), + MAX_BLOCK_SIZE * TRANSACTION_COUNT); + } + bloomFilters[currentFilterIndex].put(key); + if (lastMetricBlock != blockNum) { + lastMetricBlock = blockNum; + Metrics.gaugeSet(MetricKeys.Gauge.TX_CACHE, + bloomFilters[currentFilterIndex].approximateElementCount(), "count"); + Metrics.gaugeSet(MetricKeys.Gauge.TX_CACHE, + bloomFilters[currentFilterIndex].expectedFpp(), "fpp"); } } @Override public long size() { - return db.size(); + throw new UnsupportedOperationException("TxCacheDB size"); } @Override public boolean isEmpty() { - return db.isEmpty(); + throw new UnsupportedOperationException("TxCacheDB isEmpty"); } @Override public void remove(byte[] key) { - if (key != null) { - db.remove(Key.of(key)); - } + throw new UnsupportedOperationException("TxCacheDB remove"); } @Override @@ -145,31 +256,210 @@ public String getDbName() { @Override public Iterator> iterator() { - return Iterators.transform(db.entrySet().iterator(), - e -> Maps.immutableEntry(e.getKey().getBytes(), Longs.toByteArray(e.getValue()))); + throw new UnsupportedOperationException("TxCacheDB iterator"); } @Override - public void flush(Map batch) { + public synchronized void flush(Map batch) { + isValid.set(false); batch.forEach((k, v) -> this.put(k.getBytes(), v.getBytes())); + isValid.set(true); } @Override public void close() { - reset(); - db = null; - blockNumMap = null; + if (!isAlive()) { + return; + } + dump(); + bloomFilters[0] = null; + bloomFilters[1] = null; persistentStore.close(); + setAlive(false); } @Override public void reset() { - db.clear(); - blockNumMap.clear(); + } + + private boolean recovery() { + if (!txCacheInitOptimization) { + logger.info("txCache init optimization is disabled, skip fast recovery mode."); + logger.info("If you want fast recovery mode," + + " please set `storage.txCache.initOptimization = true` in config.conf."); + return false; + } + FileUtil.createDirIfNotExists(this.cacheDir.toString()); + logger.info("recovery bloomFilters start."); + CompletableFuture loadProperties = CompletableFuture.supplyAsync(this::loadProperties); + CompletableFuture tk0 = loadProperties.thenApplyAsync( + v -> recovery(0, this.cacheFile0)); + CompletableFuture tk1 = loadProperties.thenApplyAsync( + v -> recovery(1, this.cacheFile1)); + + try { + return CompletableFuture.allOf(tk0, tk1).thenApply(v -> { + logger.info("recovery bloomFilters success."); + return true; + }).exceptionally(this::handleException).join(); + } finally { + clearCrc32c(); + } + } + + private boolean recovery(int index, Path file) { + checkCrc32c(index, file); + try (InputStream in = new BufferedInputStream(Files.newInputStream(file, + StandardOpenOption.READ, StandardOpenOption.DELETE_ON_CLOSE))) { + logger.info("recovery bloomFilter[{}] from file.", index); + long start = System.currentTimeMillis(); + bloomFilters[index] = BloomFilter.readFrom(in, Funnels.byteArrayFunnel()); + logger.info("recovery bloomFilter[{}] from file done,filter: {}, filter-fpp: {}, cost {} ms.", + index, bloomFilters[index].approximateElementCount(), bloomFilters[index].expectedFpp(), + System.currentTimeMillis() - start); + return true; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private boolean handleException(Throwable e) { + bloomFilters[0] = BloomFilter.create(Funnels.byteArrayFunnel(), + MAX_BLOCK_SIZE * TRANSACTION_COUNT); + bloomFilters[1] = BloomFilter.create(Funnels.byteArrayFunnel(), + MAX_BLOCK_SIZE * TRANSACTION_COUNT); + try { + Files.deleteIfExists(this.cacheFile0); + Files.deleteIfExists(this.cacheFile1); + } catch (Exception ignored) { + + } + logger.info("recovery bloomFilters failed. {}", e.getMessage()); + logger.info("rollback to previous mode."); + return false; + } + + private void dump() { + if (!isValid.get()) { + logger.info("bloomFilters is not valid."); + return; + } + FileUtil.createDirIfNotExists(this.cacheDir.toString()); + logger.info("dump bloomFilters start."); + CompletableFuture task0 = CompletableFuture.runAsync( + () -> dump(0, this.cacheFile0)); + CompletableFuture task1 = CompletableFuture.runAsync( + () -> dump(1, this.cacheFile1)); + try { + CompletableFuture.allOf(task0, task1).thenRun(() -> { + writeProperties(); + logger.info("dump bloomFilters done."); + }).exceptionally(e -> { + logger.info("dump bloomFilters to file failed. {}", e.getMessage()); + return null; + }).join(); + } finally { + clearCrc32c(); + } + } + + private void dump(int index, Path file) { + logger.info("dump bloomFilters[{}] to file.", index); + long start = System.currentTimeMillis(); + try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(file))) { + bloomFilters[index].writeTo(out); + } catch (Exception e) { + throw new RuntimeException(e); + } + try { + String crc32c = getCrc32c(file); + if (index == 0) { + this.crc32c0 = crc32c; + } else { + this.crc32c1 = crc32c; + } + logger.info("dump bloomFilters[{}] to file done,filter: {}, filter-fpp: {}, " + + "crc32c: {}, cost {} ms.", + index, bloomFilters[index].approximateElementCount(), bloomFilters[index].expectedFpp(), + crc32c, System.currentTimeMillis() - start); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private boolean loadProperties() { + try (Reader r = new InputStreamReader(new BufferedInputStream(Files.newInputStream( + this.cacheProperties, StandardOpenOption.READ, StandardOpenOption.DELETE_ON_CLOSE)), + StandardCharsets.UTF_8)) { + Properties properties = new Properties(); + properties.load(r); + filterStartBlock = Long.parseLong(properties.getProperty("filterStartBlock")); + long currentBlockNum = Long.parseLong(properties.getProperty("currentBlockNum")); + long currentBlockNumFromDB = dynamicPropertiesStore.getLatestBlockHeaderNumberFromDB(); + currentFilterIndex = Integer.parseInt(properties.getProperty("currentFilterIndex")); + if (currentBlockNum != currentBlockNumFromDB) { + throw new IllegalStateException( + String.format("currentBlockNum not match. filter: %d, db: %d", + currentBlockNum, currentBlockNumFromDB)); + } + this.crc32c0 = properties.getProperty("crc32c0"); + this.crc32c1 = properties.getProperty("crc32c1"); + logger.info("filterStartBlock: {}, currentBlockNum: {}, currentFilterIndex: {}, load done.", + filterStartBlock, currentBlockNum, currentFilterIndex); + return true; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void writeProperties() { + try (Writer w = Files.newBufferedWriter(this.cacheProperties, StandardCharsets.UTF_8)) { + Properties properties = new Properties(); + long currentBlockNum = dynamicPropertiesStore.getLatestBlockHeaderNumberFromDB(); + properties.setProperty("filterStartBlock", String.valueOf(filterStartBlock)); + properties.setProperty("currentBlockNum", String.valueOf(currentBlockNum)); + properties.setProperty("currentFilterIndex", String.valueOf(currentFilterIndex)); + properties.setProperty("crc32c0", this.crc32c0); + properties.setProperty("crc32c1", this.crc32c1); + properties.store(w, "Generated by the application. PLEASE DO NOT EDIT! "); + logger.info("filterStartBlock: {}, currentBlockNum: {}, currentFilterIndex: {}, write done.", + filterStartBlock, currentBlockNum, currentFilterIndex); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private String getCrc32c(Path file) throws IOException { + ByteSource byteSource = com.google.common.io.Files.asByteSource(file.toFile()); + HashCode hc = byteSource.hash(Hashing.crc32c()); + return hc.toString(); + } + + private void checkCrc32c(int index, Path file) { + try { + String actual = getCrc32c(file); + String expect = index == 0 ? this.crc32c0 : this.crc32c1; + if (!Objects.equals(actual, expect)) { + throw new IllegalStateException("crc32c not match. index: " + index + ", expect: " + expect + + ", actual: " + actual); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private void clearCrc32c() { + this.crc32c0 = null; + this.crc32c1 = null; } @Override public TxCacheDB newInstance() { - return new TxCacheDB(name); + return new TxCacheDB(name, recentTransactionStore, dynamicPropertiesStore); + } + + @Override + public void stat() { } } + diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java index ee77c6cbc1b..17a047f78ae 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Chainbase.java @@ -11,7 +11,9 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; + import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.Pair; import org.tron.core.capsule.utils.MarketUtils; import org.tron.core.db2.common.IRevokingDB; import org.tron.core.db2.common.LevelDB; @@ -137,6 +139,15 @@ public byte[] get(byte[] key) throws ItemNotFoundException { return value; } + @Override + public byte[] getFromRoot(byte[] key) throws ItemNotFoundException { + byte[] value = head().getRoot().get(key); + if (value == null) { + throw new ItemNotFoundException(); + } + return value; + } + @Override public byte[] getUnchecked(byte[] key) { return head().get(key); @@ -337,4 +348,34 @@ private Map getNext(Snapshot head, byte[] key, long limit) { .limit(limit) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } + + public Map prefixQuery(byte[] key) { + Map result = prefixQueryRoot(key); + Map snapshot = prefixQuerySnapshot(key); + result.putAll(snapshot); + result.entrySet().removeIf(e -> e.getValue() == null); + return result; + } + + private Map prefixQueryRoot(byte[] key) { + Map result = new HashMap<>(); + if (((SnapshotRoot) head.getRoot()).db.getClass() == LevelDB.class) { + result = ((LevelDB) ((SnapshotRoot) head.getRoot()).db).getDb().prefixQuery(key); + } else if (((SnapshotRoot) head.getRoot()).db.getClass() == RocksDB.class) { + result = ((RocksDB) ((SnapshotRoot) head.getRoot()).db).getDb().prefixQuery(key); + } + return result; + } + + private Map prefixQuerySnapshot(byte[] key) { + Map result = new HashMap<>(); + Snapshot snapshot = head(); + if (!snapshot.equals(head.getRoot())) { + Map all = new HashMap<>(); + ((SnapshotImpl) snapshot).collect(all, key); + all.forEach((k, v) -> result.put(k, v.getBytes())); + } + return result; + } + } diff --git a/chainbase/src/main/java/org/tron/core/db2/core/ITronChainBase.java b/chainbase/src/main/java/org/tron/core/db2/core/ITronChainBase.java index 9baf647c989..e62c0520ac8 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/ITronChainBase.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/ITronChainBase.java @@ -24,6 +24,9 @@ public interface ITronChainBase extends Iterable>, Quitable T get(byte[] key) throws InvalidProtocolBufferException, ItemNotFoundException, BadItemException; + T getFromRoot(byte[] key) throws InvalidProtocolBufferException, ItemNotFoundException, + BadItemException; + T getUnchecked(byte[] key); boolean has(byte[] key); diff --git a/chainbase/src/main/java/org/tron/core/db2/core/RevokingDBWithCachingOldValue.java b/chainbase/src/main/java/org/tron/core/db2/core/RevokingDBWithCachingOldValue.java deleted file mode 100644 index 89dd75597af..00000000000 --- a/chainbase/src/main/java/org/tron/core/db2/core/RevokingDBWithCachingOldValue.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.tron.core.db2.core; - -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import lombok.Getter; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.ArrayUtils; -import org.iq80.leveldb.Options; -import org.iq80.leveldb.WriteOptions; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.storage.leveldb.LevelDbDataSourceImpl; -import org.tron.common.utils.StorageUtils; -import org.tron.core.db.AbstractRevokingStore; -import org.tron.core.db.RevokingStore; -import org.tron.core.db2.common.IRevokingDB; -import org.tron.core.db2.core.Chainbase.Cursor; -import org.tron.core.exception.ItemNotFoundException; - -@Slf4j -public class RevokingDBWithCachingOldValue implements IRevokingDB { - - private AbstractRevokingStore revokingDatabase; - @Getter - private LevelDbDataSourceImpl dbSource; - - public RevokingDBWithCachingOldValue(String dbName) { - this(dbName, RevokingStore.getInstance()); - } - - // add for user defined option, ex: comparator - public RevokingDBWithCachingOldValue(String dbName, Options options) { - this(dbName, options, RevokingStore.getInstance()); - } - - // set public only for unit test - public RevokingDBWithCachingOldValue(String dbName, AbstractRevokingStore revokingDatabase) { - dbSource = new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(dbName), - dbName, - StorageUtils.getOptionsByDbName(dbName), - new WriteOptions().sync(CommonParameter.getInstance().getStorage().isDbSync())); - dbSource.initDB(); - this.revokingDatabase = revokingDatabase; - } - - public RevokingDBWithCachingOldValue(String dbName, Options options, - AbstractRevokingStore revokingDatabase) { - dbSource = new LevelDbDataSourceImpl(StorageUtils.getOutputDirectoryByDbName(dbName), - dbName, - options, - new WriteOptions().sync(CommonParameter.getInstance().getStorage().isDbSync())); - dbSource.initDB(); - this.revokingDatabase = revokingDatabase; - } - - @Override - public void put(byte[] key, byte[] newValue) { - if (Objects.isNull(key) || Objects.isNull(newValue)) { - return; - } - byte[] value = dbSource.getData(key); - if (ArrayUtils.isNotEmpty(value)) { - onModify(key, value); - } - - dbSource.putData(key, newValue); - - if (ArrayUtils.isEmpty(value)) { - onCreate(key); - } - } - - @Override - public void delete(byte[] key) { - onDelete(key); - dbSource.deleteData(key); - } - - @Override - public boolean has(byte[] key) { - return dbSource.getData(key) != null; - } - - @Override - public byte[] get(byte[] key) throws ItemNotFoundException { - byte[] value = dbSource.getData(key); - if (ArrayUtils.isEmpty(value)) { - throw new ItemNotFoundException(); - } - return value; - } - - @Override - public byte[] getUnchecked(byte[] key) { - try { - return get(key); - } catch (ItemNotFoundException e) { - return null; - } - } - - @Override - public void close() { - dbSource.closeDB(); - } - - @Override - public void reset() { - dbSource.resetDb(); - } - - @Override - public void setCursor(Chainbase.Cursor cursor) { - } - - @Override - public void setCursor(Chainbase.Cursor cursor, long offset) { - } - - /** - * This should be never called - */ - @Override - public Chainbase.Cursor getCursor() { - logger.error("RevokingDBWithCachingOldValue getCursor is called, this should not be happened"); - return Cursor.HEAD; - } - - /** - * This should be called just after an object is created - */ - private void onCreate(byte[] key) { - revokingDatabase.onCreate(new AbstractRevokingStore.RevokingTuple(dbSource, key), null); - } - - /** - * This should be called just before an object is modified - */ - private void onModify(byte[] key, byte[] value) { - revokingDatabase.onModify(new AbstractRevokingStore.RevokingTuple(dbSource, key), value); - } - - /** - * This should be called just before an object is removed. - */ - private void onDelete(byte[] key) { - byte[] value; - if (Objects.nonNull(value = dbSource.getData(key))) { - revokingDatabase.onRemove(new AbstractRevokingStore.RevokingTuple(dbSource, key), value); - } - } - - @Override - public Iterator> iterator() { - return dbSource.iterator(); - } - - @Override - public Set getlatestValues(long limit) { - return dbSource.getlatestValues(limit); - } - - @Override - public Set getValuesNext(byte[] key, long limit) { - return dbSource.getValuesNext(key, limit); - } - - @Override - public List getKeysNext(byte[] key, long limit) { - return dbSource.getKeysNext(key, limit); - } -} diff --git a/chainbase/src/main/java/org/tron/core/db2/core/Snapshot.java b/chainbase/src/main/java/org/tron/core/db2/core/Snapshot.java index db59713f34d..75545dc29b4 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/Snapshot.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/Snapshot.java @@ -48,4 +48,6 @@ static boolean isImpl(Snapshot snapshot) { String getDbName(); boolean isOptimized(); + + void reloadToMem(); } diff --git a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java index d71c97ccf73..bc31b406b30 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotImpl.java @@ -4,10 +4,12 @@ import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.common.collect.Streams; +import com.google.common.primitives.Bytes; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; +import java.util.Objects; import java.util.Set; import lombok.Getter; import org.tron.core.db2.common.HashDB; @@ -28,15 +30,9 @@ public class SnapshotImpl extends AbstractSnapshot { } previous = snapshot; snapshot.setNext(this); - // inherit isOptimized = snapshot.isOptimized(); - // merge for DynamicPropertiesStore,about 100 keys - if (isOptimized) { - if (root == previous ){ - Streams.stream(root.iterator()).forEach( e -> put(e.getKey(),e.getValue())); - }else { - merge(previous); - } + if (isOptimized && root == previous) { + Streams.stream(root.iterator()).forEach( e -> put(e.getKey(),e.getValue())); } } @@ -48,10 +44,7 @@ public byte[] get(byte[] key) { private byte[] get(Snapshot head, byte[] key) { Snapshot snapshot = head; Value value; - if (isOptimized) { - value = db.get(Key.of(key)); - return value == null ? null: value.getBytes(); - } + while (Snapshot.isImpl(snapshot)) { if ((value = ((SnapshotImpl) snapshot).db.get(Key.of(key))) != null) { return value.getBytes(); @@ -95,6 +88,19 @@ public void merge(Snapshot from) { Streams.stream(fromImpl.db).forEach(e -> db.put(e.getKey(), e.getValue())); } + public void mergeAhead(Snapshot from) { + if (from instanceof SnapshotRoot) { + return ; + } + SnapshotImpl fromImpl = (SnapshotImpl) from; + Streams.stream(fromImpl.db).forEach(e -> { + if (db.get(e.getKey()) == null) { + db.put(e.getKey(), e.getValue()); + } + } + ); + } + @Override public Snapshot retreat() { return previous; @@ -129,6 +135,17 @@ synchronized void collect(Map all) { } } + synchronized void collect(Map all, byte[] prefix) { + Snapshot next = getRoot().getNext(); + while (next != null) { + Streams.stream(((SnapshotImpl) next).db).filter(e -> Bytes.indexOf( + Objects.requireNonNull(e.getKey().getBytes()), prefix) == 0) + .forEach(e -> all.put(WrappedByteArray.of(e.getKey().getBytes()), + WrappedByteArray.of(e.getValue().getBytes()))); + next = next.getNext(); + } + } + /** * Note: old --> new * In the snapshot, there may be same keys. @@ -178,4 +195,9 @@ public String getDbName() { public Snapshot newInstance() { return new SnapshotImpl(this); } + + @Override + public void reloadToMem() { + mergeAhead(previous); + } } diff --git a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java index 7e2d8f5074a..eb27141a82c 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotManager.java @@ -7,16 +7,19 @@ import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.ListeningExecutorService; import com.google.common.util.concurrent.MoreExecutors; +import java.io.File; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ExecutionException; -import java.util.concurrent.Executors; import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.LockSupport; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import lombok.Getter; @@ -24,9 +27,13 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.tron.common.error.TronDBException; +import org.tron.common.es.ExecutorServiceManager; import org.tron.common.parameter.CommonParameter; import org.tron.common.storage.WriteOptionsWrapper; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.StorageUtils; import org.tron.core.db.RevokingDatabase; +import org.tron.core.db.TronDatabase; import org.tron.core.db2.ISession; import org.tron.core.db2.common.DB; import org.tron.core.db2.common.IRevokingDB; @@ -34,14 +41,17 @@ import org.tron.core.db2.common.Value; import org.tron.core.db2.common.WrappedByteArray; import org.tron.core.exception.RevokingStoreIllegalStateException; +import org.tron.core.exception.TronError; +import org.tron.core.store.CheckPointV2Store; import org.tron.core.store.CheckTmpStore; @Slf4j(topic = "DB") public class SnapshotManager implements RevokingDatabase { - public static final int DEFAULT_MAX_FLUSH_COUNT = 500; public static final int DEFAULT_MIN_FLUSH_COUNT = 1; private static final int DEFAULT_STACK_MAX_SIZE = 256; + private static final long ONE_MINUTE_MILLS = 60*1000L; + private static final String CHECKPOINT_V2_DIR = "checkpoint"; @Getter private List dbs = new ArrayList<>(); @Getter @@ -58,11 +68,13 @@ public class SnapshotManager implements RevokingDatabase { private volatile int flushCount = 0; - private Thread exitThread; private volatile boolean hitDown; private Map flushServices = new HashMap<>(); + private ScheduledExecutorService pruneCheckpointThread = null; + private final String pruneName = "checkpoint-prune"; + @Autowired @Setter @Getter @@ -71,20 +83,27 @@ public class SnapshotManager implements RevokingDatabase { @Setter private volatile int maxFlushCount = DEFAULT_MIN_FLUSH_COUNT; + private int checkpointVersion = 1; // default v1 + public SnapshotManager(String checkpointPath) { } @PostConstruct public void init() { - exitThread = new Thread(() -> { - LockSupport.park(); - // to Guarantee Some other thread invokes unpark with the current thread as the target - if (hitDown) { - System.exit(1); - } - }); - exitThread.setName("exit-thread"); - exitThread.start(); + checkpointVersion = CommonParameter.getInstance().getStorage().getCheckpointVersion(); + // prune checkpoint + if (isV2Open()) { + pruneCheckpointThread = ExecutorServiceManager.newSingleThreadScheduledExecutor(pruneName); + pruneCheckpointThread.scheduleWithFixedDelay(() -> { + try { + if (!unChecked) { + pruneCheckpoint(); + } + } catch (Throwable t) { + logger.error("Exception in prune checkpoint", t); + } + }, 10000, 3600, TimeUnit.MILLISECONDS); + } } public static String simpleDecode(byte[] bytes) { @@ -135,7 +154,8 @@ public void add(IRevokingDB db) { Chainbase revokingDB = (Chainbase) db; dbs.add(revokingDB); flushServices.put(revokingDB.getDbName(), - MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor())); + MoreExecutors.listeningDecorator(ExecutorServiceManager.newSingleThreadExecutor( + "flush-service-" + revokingDB.getDbName()))); } private void advance() { @@ -150,7 +170,7 @@ private void retreat() { public void merge() { if (activeSession <= 0) { - throw new RevokingStoreIllegalStateException("activeDialog has to be greater than 0"); + throw new RevokingStoreIllegalStateException(activeSession); } if (size < 2) { @@ -168,7 +188,7 @@ public synchronized void revoke() { } if (activeSession <= 0) { - throw new RevokingStoreIllegalStateException("activeSession has to be greater than 0"); + throw new RevokingStoreIllegalStateException(activeSession); } if (size <= 0) { @@ -187,19 +207,27 @@ public synchronized void revoke() { public synchronized void commit() { if (activeSession <= 0) { - throw new RevokingStoreIllegalStateException("activeSession has to be greater than 0"); + throw new RevokingStoreIllegalStateException(activeSession); } --activeSession; + + dbs.forEach(db -> { + if (db.getHead().isOptimized()) { + db.getHead().reloadToMem(); + } + }); } public synchronized void pop() { if (activeSession != 0) { - throw new RevokingStoreIllegalStateException("activeSession has to be equal 0"); + throw new RevokingStoreIllegalStateException( + String.format("activeSession has to be equal 0, current %d", activeSession)); } if (size <= 0) { - throw new RevokingStoreIllegalStateException("there is not snapshot to be popped"); + throw new RevokingStoreIllegalStateException( + String.format("there is not snapshot to be popped, current: %d", size)); } disabled = true; @@ -240,10 +268,9 @@ public synchronized void disable() { @Override public void shutdown() { - System.err.println("******** begin to pop revokingDb ********"); - System.err.println("******** before revokingDb size:" + size); - checkTmpStore.close(); - System.err.println("******** end to pop revokingDb ********"); + ExecutorServiceManager.shutdownAndAwaitTermination(pruneCheckpointThread, pruneName); + flushServices.forEach((key, value) -> ExecutorServiceManager.shutdownAndAwaitTermination(value, + "flush-service-" + key)); } public void updateSolidity(int hops) { @@ -254,7 +281,7 @@ public void updateSolidity(int hops) { } } - private boolean shouldBeRefreshed() { + public boolean shouldBeRefreshed() { return flushCount >= maxFlushCount; } @@ -307,25 +334,30 @@ public void flush() { if (shouldBeRefreshed()) { try { long start = System.currentTimeMillis(); - deleteCheckpoint(); + if (!isV2Open()) { + deleteCheckpoint(); + } createCheckpoint(); + long checkPointEnd = System.currentTimeMillis(); refresh(); flushCount = 0; - logger.info("flush cost:{}, create checkpoint cost:{}, refresh cost:{}", + logger.info("Flush cost: {} ms, create checkpoint cost: {} ms, refresh cost: {} ms.", System.currentTimeMillis() - start, checkPointEnd - start, System.currentTimeMillis() - checkPointEnd ); } catch (TronDBException e) { - logger.error(" Find fatal error , program will be exited soon", e); + logger.error(" Find fatal error, program will be exited soon.", e); hitDown = true; - LockSupport.unpark(exitThread); + throw new TronError(e, TronError.ErrCode.DB_FLUSH); } } } - private void createCheckpoint() { + public void createCheckpoint() { + TronDatabase checkPointStore = null; + boolean syncFlag; try { Map batch = new HashMap<>(); for (Chainbase db : dbs) { @@ -335,6 +367,12 @@ private void createCheckpoint() { } String dbName = db.getDbName(); + + if (Objects.equals(dbName, "trans-cache")) { + // trans-cache is deprecated + continue; + } + Snapshot next = head.getRoot(); for (int i = 0; i < flushCount; ++i) { next = next.getNext(); @@ -348,70 +386,172 @@ private void createCheckpoint() { } } } + if (isV2Open()) { + String dbName = String.valueOf(System.currentTimeMillis()); + checkPointStore = getCheckpointDB(dbName); + syncFlag = CommonParameter.getInstance().getStorage().isCheckpointSync(); + } else { + checkPointStore = checkTmpStore; + syncFlag = CommonParameter.getInstance().getStorage().isDbSync(); + } - checkTmpStore.getDbSource().updateByBatch(batch.entrySet().stream() + checkPointStore.getDbSource().updateByBatch(batch.entrySet().stream() .map(e -> Maps.immutableEntry(e.getKey().getBytes(), e.getValue().getBytes())) .collect(HashMap::new, (m, k) -> m.put(k.getKey(), k.getValue()), HashMap::putAll), - WriteOptionsWrapper.getInstance().sync(CommonParameter - .getInstance().getStorage().isDbSync())); + WriteOptionsWrapper.getInstance().sync(syncFlag)); - } catch ( Exception e) { + } catch (Exception e) { throw new TronDBException(e); + } finally { + if (isV2Open() && checkPointStore != null) { + checkPointStore.close(); + } } } + private TronDatabase getCheckpointDB(String dbName) { + return new CheckPointV2Store(CHECKPOINT_V2_DIR+"/"+dbName); + } + + public List getCheckpointList() { + String dbPath = Paths.get(StorageUtils.getOutputDirectoryByDbName(CHECKPOINT_V2_DIR), + CommonParameter.getInstance().getStorage().getDbDirectory()).toString(); + File file = new File(Paths.get(dbPath, CHECKPOINT_V2_DIR).toString()); + if (file.exists() && file.isDirectory()) { + String[] subDirs = file.list(); + if (subDirs != null) { + return Arrays.stream(subDirs).sorted().collect(Collectors.toList()); + } + } + return null; + } + private void deleteCheckpoint() { try { Map hmap = new HashMap<>(); - if (!checkTmpStore.getDbSource().allKeys().isEmpty()) { - for (Map.Entry e : checkTmpStore.getDbSource()) { - hmap.put(e.getKey(), null); - } + for (Map.Entry e : checkTmpStore.getDbSource()) { + hmap.put(e.getKey(), null); + } + if (hmap.size() != 0) { + checkTmpStore.getDbSource().updateByBatch(hmap); } - - checkTmpStore.getDbSource().updateByBatch(hmap); } catch (Exception e) { throw new TronDBException(e); } } + private void pruneCheckpoint() { + if (unChecked) { + return; + } + List cpList = getCheckpointList(); + if (cpList == null) { + return; + } + if (cpList.size() < 3) { + return; + } + long latestTimestamp = Long.parseLong(cpList.get(cpList.size()-1)); + for (String cp: cpList.subList(0, cpList.size()-3)) { + long timestamp = Long.parseLong(cp); + if (latestTimestamp - timestamp <= ONE_MINUTE_MILLS*2) { + break; + } + String checkpointPath = Paths.get(StorageUtils.getOutputDirectoryByDbName(CHECKPOINT_V2_DIR), + CommonParameter.getInstance().getStorage().getDbDirectory(), CHECKPOINT_V2_DIR).toString(); + if (!FileUtil.recursiveDelete(Paths.get(checkpointPath, cp).toString())) { + logger.error("checkpoint prune failed, timestamp: {}", timestamp); + return; + } + logger.debug("checkpoint prune success, timestamp: {}", timestamp); + } + } + // ensure run this method first after process start. @Override public void check() { - for (Chainbase db : dbs) { + if (!isV2Open()) { + List cpList = getCheckpointList(); + if (cpList != null && cpList.size() != 0) { + String msg = "checkpoint check failed, the checkpoint version of database not match your " + + "config file, please set storage.checkpoint.version = 2 in your config file " + + "and restart the node."; + throw new TronError(msg, TronError.ErrCode.CHECKPOINT_VERSION); + } + checkV1(); + } else { + checkV2(); + } + } + + private void checkV1() { + for (Chainbase db: dbs) { if (!Snapshot.isRoot(db.getHead())) { - throw new IllegalStateException("first check."); + throw new IllegalStateException("First check."); } } + recover(checkTmpStore); + logger.info("checkpoint v1 recover success"); + unChecked = false; + } - if (!checkTmpStore.getDbSource().allKeys().isEmpty()) { - Map dbMap = dbs.stream() - .map(db -> Maps.immutableEntry(db.getDbName(), db)) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - advance(); - for (Map.Entry e : checkTmpStore.getDbSource()) { - byte[] key = e.getKey(); - byte[] value = e.getValue(); - String db = simpleDecode(key); - if (dbMap.get(db) == null) { - continue; - } - byte[] realKey = Arrays.copyOfRange(key, db.getBytes().length + 4, key.length); + private void checkV2() { + logger.info("checkpoint version: {}", CommonParameter.getInstance().getStorage().getCheckpointVersion()); + logger.info("checkpoint sync: {}", CommonParameter.getInstance().getStorage().isCheckpointSync()); + List cpList = getCheckpointList(); + if (cpList == null || cpList.size() == 0) { + logger.info("checkpoint size is 0, using v1 recover"); + checkV1(); + deleteCheckpoint(); + return; + } - byte[] realValue = value.length == 1 ? null : Arrays.copyOfRange(value, 1, value.length); - if (realValue != null) { - dbMap.get(db).getHead().put(realKey, realValue); - } else { + long latestTimestamp = Long.parseLong(cpList.get(cpList.size()-1)); + for (String cp: cpList) { + long timestamp = Long.parseLong(cp); + if (latestTimestamp - timestamp > ONE_MINUTE_MILLS*2) { + continue; + } + TronDatabase checkPointV2Store = getCheckpointDB(cp); + recover(checkPointV2Store); + checkPointV2Store.close(); + } + logger.info("checkpoint v2 recover success"); + unChecked = false; + } + + private void recover(TronDatabase tronDatabase) { + Map dbMap = dbs.stream() + .map(db -> Maps.immutableEntry(db.getDbName(), db)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + advance(); + for (Map.Entry e: tronDatabase.getDbSource()) { + byte[] key = e.getKey(); + byte[] value = e.getValue(); + String db = simpleDecode(key); + if (dbMap.get(db) == null) { + continue; + } + byte[] realKey = Arrays.copyOfRange(key, db.getBytes().length + 4, key.length); + byte[] realValue = value.length == 1 ? null : Arrays.copyOfRange(value, 1, value.length); + if (realValue != null) { + dbMap.get(db).getHead().put(realKey, realValue); + } else { + byte op = value[0]; + if (Value.Operator.DELETE.getValue() == op) { dbMap.get(db).getHead().remove(realKey); + } else { + dbMap.get(db).getHead().put(realKey, new byte[0]); } - } - - dbs.forEach(db -> db.getHead().getRoot().merge(db.getHead())); - retreat(); } - unChecked = false; + dbs.forEach(db -> db.getHead().getRoot().merge(db.getHead())); + retreat(); + } + + private boolean isV2Open() { + return checkpointVersion == 2; } private byte[] simpleEncode(String s) { @@ -471,7 +611,7 @@ public void destroy() { snapshotManager.revoke(); } } catch (Exception e) { - logger.error("revoke database error.", e); + logger.error("Revoke database error.", e); } if (disableOnExit) { snapshotManager.disable(); @@ -485,7 +625,7 @@ public void close() { snapshotManager.revoke(); } } catch (Exception e) { - logger.error("revoke database error.", e); + logger.error("Revoke database error.", e); throw new RevokingStoreIllegalStateException(e); } if (disableOnExit) { diff --git a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotRoot.java b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotRoot.java index b69d55098c8..f95cf68dafe 100644 --- a/chainbase/src/main/java/org/tron/core/db2/core/SnapshotRoot.java +++ b/chainbase/src/main/java/org/tron/core/db2/core/SnapshotRoot.java @@ -6,36 +6,87 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.stream.Collectors; import lombok.Getter; +import org.tron.common.cache.CacheManager; +import org.tron.common.cache.CacheType; +import org.tron.common.cache.TronCache; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.AccountCapsule; import org.tron.core.db2.common.DB; import org.tron.core.db2.common.Flusher; import org.tron.core.db2.common.WrappedByteArray; +import org.tron.core.store.AccountAssetStore; public class SnapshotRoot extends AbstractSnapshot { @Getter private Snapshot solidity; + private boolean isAccountDB; + + private TronCache cache; + private static final List CACHE_DBS = CommonParameter.getInstance() + .getStorage().getCacheDbs(); public SnapshotRoot(DB db) { this.db = db; solidity = this; + isAccountDB = "account".equalsIgnoreCase(db.getDbName()); + if (CACHE_DBS.contains(this.db.getDbName())) { + this.cache = CacheManager.allocate(CacheType.findByType(this.db.getDbName())); + } isOptimized = "properties".equalsIgnoreCase(db.getDbName()); } + private boolean needOptAsset() { + return isAccountDB && ChainBaseManager.getInstance().getDynamicPropertiesStore() + .getAllowAccountAssetOptimizationFromRoot() == 1; + } + @Override public byte[] get(byte[] key) { - return db.get(key); + WrappedByteArray cache = getCache(key); + if (cache != null) { + return cache.getBytes(); + } + byte[] value = db.get(key); + putCache(key, value); + return value; } @Override public void put(byte[] key, byte[] value) { - db.put(key, value); + byte[] v = value; + if (needOptAsset()) { + if (ByteArray.isEmpty(value)) { + remove(key); + return; + } + AccountAssetStore assetStore = + ChainBaseManager.getInstance().getAccountAssetStore(); + AccountCapsule item = new AccountCapsule(value); + if (!item.getAssetOptimized()) { + assetStore.deleteAccount(item.createDbKey()); + item.setAssetOptimized(true); + } + assetStore.putAccount(item.getInstance()); + item.clearAsset(); + v = item.getData(); + } + db.put(key, v); + putCache(key, v); } @Override public void remove(byte[] key) { + if (needOptAsset()) { + ChainBaseManager.getInstance().getAccountAssetStore().deleteAccount(key); + } db.remove(key); + putCache(key, null); } @Override @@ -45,7 +96,12 @@ public void merge(Snapshot from) { .map(e -> Maps.immutableEntry(WrappedByteArray.of(e.getKey().getBytes()), WrappedByteArray.of(e.getValue().getBytes()))) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); - ((Flusher) db).flush(batch); + if (needOptAsset()) { + processAccount(batch); + } else { + ((Flusher) db).flush(batch); + putCache(batch); + } } public void merge(List snapshots) { @@ -57,10 +113,65 @@ public void merge(List snapshots) { WrappedByteArray.of(e.getValue().getBytes()))) .forEach(e -> batch.put(e.getKey(), e.getValue())); } + if (needOptAsset()) { + processAccount(batch); + } else { + ((Flusher) db).flush(batch); + putCache(batch); + } + } - ((Flusher) db).flush(batch); + private void processAccount(Map batch) { + AccountAssetStore assetStore = ChainBaseManager.getInstance().getAccountAssetStore(); + Map accounts = new HashMap<>(); + Map assets = new HashMap<>(); + batch.forEach((k, v) -> { + if (ByteArray.isEmpty(v.getBytes())) { + accounts.put(k, v); + assets.putAll(assetStore.getDeletedAssets(k.getBytes())); + } else { + AccountCapsule item = new AccountCapsule(v.getBytes()); + if (!item.getAssetOptimized()) { + assets.putAll(assetStore.getDeletedAssets(k.getBytes())); + item.setAssetOptimized(true); + } + assets.putAll(assetStore.getAssets(item.getInstance())); + item.clearAsset(); + accounts.put(k, WrappedByteArray.of(item.getData())); + } + }); + ((Flusher) db).flush(accounts); + putCache(accounts); + if (assets.size() > 0) { + assetStore.updateByBatch(AccountAssetStore.convert(assets)); + } } + private boolean cached() { + return Objects.nonNull(this.cache); + } + + private void putCache(byte[] key, byte[] value) { + if (cached()) { + cache.put(WrappedByteArray.of(key), WrappedByteArray.of(value)); + } + } + + private void putCache(Map values) { + if (cached()) { + values.forEach(cache::put); + } + } + + private WrappedByteArray getCache(byte[] key) { + if (cached()) { + return cache.getIfPresent(WrappedByteArray.of(key)); + } + return null; + } + + // second cache + @Override public Snapshot retreat() { return this; @@ -78,11 +189,17 @@ public Iterator> iterator() { @Override public void close() { + if (cached()) { + CacheManager.release(cache); + } ((Flusher) db).close(); } @Override public void reset() { + if (cached()) { + CacheManager.release(cache); + } ((Flusher) db).reset(); } @@ -105,4 +222,7 @@ public String getDbName() { public Snapshot newInstance() { return new SnapshotRoot(db.newInstance()); } + + @Override + public void reloadToMem() { } } diff --git a/chainbase/src/main/java/org/tron/core/service/MortgageService.java b/chainbase/src/main/java/org/tron/core/service/MortgageService.java index f11c0693a77..b1fd279c2db 100644 --- a/chainbase/src/main/java/org/tron/core/service/MortgageService.java +++ b/chainbase/src/main/java/org/tron/core/service/MortgageService.java @@ -1,30 +1,26 @@ package org.tron.core.service; -import com.google.protobuf.ByteString; +import static org.tron.common.math.Maths.min; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; import java.util.List; -import java.util.Map; - +import java.util.stream.Collectors; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.bouncycastle.util.encoders.Hex; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import org.tron.common.utils.Pair; import org.tron.common.utils.StringUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.store.AccountStore; import org.tron.core.store.DelegationStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.store.WitnessStore; -import org.tron.protos.Protocol.Vote; @Slf4j(topic = "mortgage") @Component @@ -43,6 +39,9 @@ public class MortgageService { @Setter private AccountStore accountStore; + @Autowired + private RewardViCalService rewardViCalService; + public void initStore(WitnessStore witnessStore, DelegationStore delegationStore, DynamicPropertiesStore dynamicPropertiesStore, AccountStore accountStore) { this.witnessStore = witnessStore; @@ -52,41 +51,28 @@ public void initStore(WitnessStore witnessStore, DelegationStore delegationStore } public void payStandbyWitness() { - List witnessCapsules = witnessStore.getAllWitnesses(); - Map witnessCapsuleMap = new HashMap<>(); - List witnessAddressList = new ArrayList<>(); - for (WitnessCapsule witnessCapsule : witnessCapsules) { - witnessAddressList.add(witnessCapsule.getAddress()); - witnessCapsuleMap.put(witnessCapsule.getAddress(), witnessCapsule); - } - witnessAddressList.sort(Comparator.comparingLong((ByteString b) -> witnessCapsuleMap.get(b).getVoteCount()) - .reversed().thenComparing(Comparator.comparingInt(ByteString::hashCode).reversed())); - if (witnessAddressList.size() > ChainConstant.WITNESS_STANDBY_LENGTH) { - witnessAddressList = witnessAddressList.subList(0, ChainConstant.WITNESS_STANDBY_LENGTH); + List witnessStandbys = witnessStore.getWitnessStandby( + dynamicPropertiesStore.allowWitnessSortOptimization()); + long voteSum = witnessStandbys.stream().mapToLong(WitnessCapsule::getVoteCount).sum(); + if (voteSum < 1) { + return; } - long voteSum = 0; long totalPay = dynamicPropertiesStore.getWitness127PayPerBlock(); - for (ByteString b : witnessAddressList) { - voteSum += witnessCapsuleMap.get(b).getVoteCount(); - } - - if (voteSum > 0) { - for (ByteString b : witnessAddressList) { - double eachVotePay = (double) totalPay / voteSum; - long pay = (long) (witnessCapsuleMap.get(b).getVoteCount() * eachVotePay); - logger.debug("pay {} stand reward {}", Hex.toHexString(b.toByteArray()), pay); - payReward(b.toByteArray(), pay); - } + double eachVotePay = (double) totalPay / voteSum; + for (WitnessCapsule w : witnessStandbys) { + long pay = (long) (w.getVoteCount() * eachVotePay); + payReward(w.getAddress().toByteArray(), pay); + logger.debug("Pay {} stand reward {}.", Hex.toHexString(w.getAddress().toByteArray()), pay); } } public void payBlockReward(byte[] witnessAddress, long value) { - logger.debug("pay {} block reward {}", Hex.toHexString(witnessAddress), value); + logger.debug("Pay {} block reward {}.", Hex.toHexString(witnessAddress), value); payReward(witnessAddress, value); } public void payTransactionFeeReward(byte[] witnessAddress, long value) { - logger.debug("pay {} transaction fee reward {}", Hex.toHexString(witnessAddress), value); + logger.debug("Pay {} transaction fee reward {}.", Hex.toHexString(witnessAddress), value); payReward(witnessAddress, value); } @@ -125,7 +111,7 @@ public void withdrawReward(byte[] address) { reward = computeReward(beginCycle, endCycle, account); adjustAllowance(address, reward); reward = 0; - logger.info("latest cycle reward {},{}", beginCycle, account.getVotesList()); + logger.info("Latest cycle reward {}, {}.", beginCycle, account.getVotesList()); } beginCycle += 1; } @@ -142,8 +128,8 @@ public void withdrawReward(byte[] address) { delegationStore.setBeginCycle(address, endCycle); delegationStore.setEndCycle(address, endCycle + 1); delegationStore.setAccountVote(endCycle, address, accountCapsule); - logger.info("adjust {} allowance {}, now currentCycle {}, beginCycle {}, endCycle {}, " - + "account vote {},", Hex.toHexString(address), reward, currentCycle, + logger.info("Adjust {} allowance {}, now currentCycle {}, beginCycle {}, endCycle {}, " + + "account vote {}.", Hex.toHexString(address), reward, currentCycle, beginCycle, endCycle, accountCapsule.getVotesList()); } @@ -182,21 +168,21 @@ public long queryReward(byte[] address) { return reward + accountCapsule.getAllowance(); } - private long computeReward(long cycle, AccountCapsule accountCapsule) { + private long computeReward(long cycle, List> votes) { long reward = 0; - for (Vote vote : accountCapsule.getVotesList()) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); + for (Pair vote : votes) { + byte[] srAddress = vote.getKey(); long totalReward = delegationStore.getReward(cycle, srAddress); + if (totalReward <= 0) { + continue; + } long totalVote = delegationStore.getWitnessVote(cycle, srAddress); if (totalVote == DelegationStore.REMARK || totalVote == 0) { continue; } - long userVote = vote.getVoteCount(); + long userVote = vote.getValue(); double voteRate = (double) userVote / totalVote; reward += voteRate * totalReward; - logger.debug("computeReward {} {} {} {},{},{},{}", cycle, - Hex.toHexString(accountCapsule.getAddress().toByteArray()), Hex.toHexString(srAddress), - userVote, totalVote, totalReward, reward); } return reward; } @@ -217,23 +203,25 @@ private long computeReward(long beginCycle, long endCycle, AccountCapsule accoun long reward = 0; long newAlgorithmCycle = dynamicPropertiesStore.getNewRewardAlgorithmEffectiveCycle(); + List> srAddresses = accountCapsule.getVotesList().stream() + .map(vote -> new Pair<>(vote.getVoteAddress().toByteArray(), vote.getVoteCount())) + .collect(Collectors.toList()); if (beginCycle < newAlgorithmCycle) { - long oldEndCycle = Math.min(endCycle, newAlgorithmCycle); - for (long cycle = beginCycle; cycle < oldEndCycle; cycle++) { - reward += computeReward(cycle, accountCapsule); - } + long oldEndCycle = min(endCycle, newAlgorithmCycle, + dynamicPropertiesStore.disableJavaLangMath()); + reward = getOldReward(beginCycle, oldEndCycle, srAddresses); beginCycle = oldEndCycle; } if (beginCycle < endCycle) { - for (Vote vote : accountCapsule.getVotesList()) { - byte[] srAddress = vote.getVoteAddress().toByteArray(); + for (Pair vote : srAddresses) { + byte[] srAddress = vote.getKey(); BigInteger beginVi = delegationStore.getWitnessVi(beginCycle - 1, srAddress); BigInteger endVi = delegationStore.getWitnessVi(endCycle - 1, srAddress); BigInteger deltaVi = endVi.subtract(beginVi); if (deltaVi.signum() <= 0) { continue; } - long userVote = vote.getVoteCount(); + long userVote = vote.getValue(); reward += deltaVi.multiply(BigInteger.valueOf(userVote)) .divide(DelegationStore.DECIMAL_OF_VI_REWARD).longValue(); } @@ -241,10 +229,6 @@ private long computeReward(long beginCycle, long endCycle, AccountCapsule accoun return reward; } - public WitnessCapsule getWitnessByAddress(ByteString address) { - return witnessStore.get(address.toByteArray()); - } - public void adjustAllowance(byte[] address, long amount) { try { if (amount <= 0) { @@ -252,7 +236,7 @@ public void adjustAllowance(byte[] address, long amount) { } adjustAllowance(accountStore, address, amount); } catch (BalanceInsufficientException e) { - logger.error("withdrawReward error: {},{}", Hex.toHexString(address), address, e); + logger.error("WithdrawReward error: {}.", e.getMessage()); } } @@ -266,14 +250,21 @@ public void adjustAllowance(AccountStore accountStore, byte[] accountAddress, lo if (amount < 0 && allowance < -amount) { throw new BalanceInsufficientException( - StringUtil.createReadableString(accountAddress) + " insufficient balance"); + String.format("%s insufficient balance, amount: %d, allowance: %d", + StringUtil.createReadableString(accountAddress), amount, allowance)); } account.setAllowance(allowance + amount); accountStore.put(account.createDbKey(), account); } - private void sortWitness(List list) { - list.sort(Comparator.comparingLong((ByteString b) -> getWitnessByAddress(b).getVoteCount()) - .reversed().thenComparing(Comparator.comparingInt(ByteString::hashCode).reversed())); + private long getOldReward(long begin, long end, List> votes) { + if (dynamicPropertiesStore.allowOldRewardOpt()) { + return rewardViCalService.getNewRewardAlgorithmReward(begin, end, votes); + } + long reward = 0; + for (long cycle = begin; cycle < end; cycle++) { + reward += computeReward(cycle, votes); + } + return reward; } } diff --git a/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java new file mode 100644 index 00000000000..f88fd02c539 --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/service/RewardViCalService.java @@ -0,0 +1,287 @@ +package org.tron.core.service; + +import static org.tron.core.store.DelegationStore.DECIMAL_OF_VI_REWARD; +import static org.tron.core.store.DelegationStore.REMARK; + +import com.google.common.collect.Streams; +import com.google.common.primitives.Bytes; +import com.google.protobuf.ByteString; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import javax.annotation.PreDestroy; +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.tron.common.error.TronDBException; +import org.tron.common.es.ExecutorServiceManager; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.MerkleRoot; +import org.tron.common.utils.Pair; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.db.common.iterator.DBIterator; +import org.tron.core.db2.common.DB; +import org.tron.core.exception.TronError; +import org.tron.core.store.DelegationStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.RewardViStore; +import org.tron.core.store.WitnessStore; + +@Component +@Slf4j(topic = "rewardViCalService") +public class RewardViCalService { + + private final DB propertiesStore; + private final DB delegationStore; + private final DB witnessStore; + + @Autowired + private RewardViStore rewardViStore; + + private static final byte[] IS_DONE_KEY = new byte[]{0x00}; + private static final byte[] IS_DONE_VALUE = new byte[]{0x01}; + + private long newRewardCalStartCycle = Long.MAX_VALUE; + + private volatile long lastBlockNumber = -1; + + private static final String MAIN_NET_ROOT_HEX = + "9debcb9924055500aaae98cdee10501c5c39d4daa75800a996f4bdda73dbccd8"; + + private final Sha256Hash rewardViRoot = CommonParameter.getInstance().getStorage().getDbRoot( + "reward-vi", Sha256Hash.wrap(ByteString.fromHex(MAIN_NET_ROOT_HEX))); + + private final CountDownLatch lock = new CountDownLatch(1); + + private final ScheduledExecutorService es = ExecutorServiceManager + .newSingleThreadScheduledExecutor("rewardViCalService"); + + + @Autowired + public RewardViCalService(@Autowired DynamicPropertiesStore propertiesStore, + @Autowired DelegationStore delegationStore, @Autowired WitnessStore witnessStore) { + this.propertiesStore = propertiesStore.getDb(); + this.delegationStore = delegationStore.getDb(); + this.witnessStore = witnessStore.getDb(); + } + + public void init() { + // after init, we can get the latest block header number from db + this.newRewardCalStartCycle = this.getNewRewardAlgorithmEffectiveCycle(); + boolean ret = this.newRewardCalStartCycle != Long.MAX_VALUE; + if (ret) { + // checkpoint is flushed to db, we can start rewardViCalService immediately + lastBlockNumber = Long.MAX_VALUE; + } + ExecutorServiceManager.scheduleWithFixedDelay(es, this::maybeRun, 0, 3, TimeUnit.SECONDS); + } + + private boolean enableNewRewardAlgorithm() { + this.newRewardCalStartCycle = this.getNewRewardAlgorithmEffectiveCycle(); + boolean ret = this.newRewardCalStartCycle != Long.MAX_VALUE; + if (ret && lastBlockNumber == -1) { + lastBlockNumber = this.getLatestBlockHeaderNumber(); + } + return ret; + } + + private boolean isDone() { + return rewardViStore.has(IS_DONE_KEY); + } + + private void maybeRun() { + try { + if (enableNewRewardAlgorithm()) { + if (this.newRewardCalStartCycle > 1) { + if (isDone()) { + this.clearUp(true); + logger.info("rewardViCalService is already done"); + } else { + if (lastBlockNumber == Long.MAX_VALUE // start rewardViCalService immediately + || this.getLatestBlockHeaderNumber() > lastBlockNumber) { + // checkpoint is flushed to db, so we can start rewardViCalService + startRewardCal(); + clearUp(true); + } else { + logger.info("startRewardCal will run after checkpoint is flushed to db"); + } + } + } else { + clearUp(false); + logger.info("rewardViCalService is no need to run"); + } + } + } catch (Exception e) { + logger.error(" Find fatal error, program will be exited soon.", e); + throw new TronError(e, TronError.ErrCode.REWARD_VI_CALCULATOR); + } + } + + private void clearUp(boolean isDone) { + lock.countDown(); + if (isDone) { + calcMerkleRoot(); + } + es.shutdown(); + } + + @PreDestroy + private void destroy() { + es.shutdownNow(); + } + + + public long getNewRewardAlgorithmReward(long beginCycle, long endCycle, + List> votes) { + if (!isDone()) { + logger.warn("rewardViCalService is not done, wait for it"); + try { + lock.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TronDBException(e); + } + } + + long reward = 0; + if (beginCycle < endCycle) { + for (Pair vote : votes) { + byte[] srAddress = vote.getKey(); + BigInteger beginVi = getWitnessVi(beginCycle - 1, srAddress); + BigInteger endVi = getWitnessVi(endCycle - 1, srAddress); + BigInteger deltaVi = endVi.subtract(beginVi); + if (deltaVi.signum() <= 0) { + continue; + } + long userVote = vote.getValue(); + reward += deltaVi.multiply(BigInteger.valueOf(userVote)) + .divide(DelegationStore.DECIMAL_OF_VI_REWARD).longValue(); + } + } + return reward; + + } + + private void calcMerkleRoot() { + logger.info("calcMerkleRoot start"); + DBIterator iterator = rewardViStore.iterator(); + iterator.seekToFirst(); + ArrayList ids = Streams.stream(iterator) + .map(this::getHash) + .collect(Collectors.toCollection(ArrayList::new)); + + Sha256Hash rewardViRootLocal = MerkleRoot.root(ids); + if (!Objects.equals(rewardViRoot, rewardViRootLocal)) { + logger.warn("Merkle root mismatch, expect: {}, actual: {}." + + " If you are quite sure that there is no miscalculation (not on the main network)" + + ", please configure 'storage.merkleRoot.reward-vi = {}'" + + "(for a specific network such as Nile, etc.) in config.conf to fix the hints", + rewardViRoot, rewardViRootLocal, rewardViRootLocal); + } + logger.info("calcMerkleRoot: {}", rewardViRootLocal); + } + + private Sha256Hash getHash(Map.Entry entry) { + return Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), + Bytes.concat(entry.getKey(), entry.getValue())); + } + + private void startRewardCal() { + logger.info("rewardViCalService start"); + rewardViStore.reset(); + DBIterator iterator = (DBIterator) witnessStore.iterator(); + iterator.seekToFirst(); + iterator.forEachRemaining(e -> accumulateWitnessReward(e.getKey())); + rewardViStore.put(IS_DONE_KEY, IS_DONE_VALUE); + logger.info("rewardViCalService is done"); + + } + + private void accumulateWitnessReward(byte[] witness) { + long startCycle = 1; + LongStream.range(startCycle, newRewardCalStartCycle) + .forEach(cycle -> accumulateWitnessVi(cycle, witness)); + } + + private void accumulateWitnessVi(long cycle, byte[] address) { + BigInteger preVi = getWitnessVi(cycle - 1, address); + long voteCount = getWitnessVote(cycle, address); + long reward = getReward(cycle, address); + if (reward == 0 || voteCount == 0) { // Just forward pre vi + if (!BigInteger.ZERO.equals(preVi)) { // Zero vi will not be record + setWitnessVi(cycle, address, preVi); + } + } else { // Accumulate delta vi + BigInteger deltaVi = BigInteger.valueOf(reward) + .multiply(DECIMAL_OF_VI_REWARD) + .divide(BigInteger.valueOf(voteCount)); + setWitnessVi(cycle, address, preVi.add(deltaVi)); + } + } + + private void setWitnessVi(long cycle, byte[] address, BigInteger value) { + byte[] k = buildViKey(cycle, address); + byte[] v = value.toByteArray(); + rewardViStore.put(k, v); + } + + private BigInteger getWitnessVi(long cycle, byte[] address) { + + byte[] v = rewardViStore.get(buildViKey(cycle, address)); + if (v == null) { + return BigInteger.ZERO; + } else { + return new BigInteger(v); + } + } + + private byte[] buildViKey(long cycle, byte[] address) { + return generateKey(cycle, address, "vi"); + } + + private long getReward(long cycle, byte[] address) { + byte[] value = this.delegationStore.get(generateKey(cycle, address, "reward")); + return value == null ? 0 : ByteArray.toLong(value); + } + + private long getWitnessVote(long cycle, byte[] address) { + byte[] value = this.delegationStore.get(generateKey(cycle, address, "vote")); + return value == null ? REMARK : ByteArray.toLong(value); + } + + private byte[] generateKey(long cycle, byte[] address, String suffix) { + return generateKey(cycle + "", address, suffix); + } + + private byte[] generateKey(String prefix, byte[] address, String suffix) { + StringBuilder sb = new StringBuilder(); + if (prefix != null) { + sb.append(prefix).append("-"); + } + sb.append(Hex.toHexString(address)); + if (suffix != null) { + sb.append("-").append(suffix); + } + return sb.toString().getBytes(); + } + + private long getNewRewardAlgorithmEffectiveCycle() { + byte[] value = this.propertiesStore.get("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes()); + return value == null ? Long.MAX_VALUE : ByteArray.toLong(value); + } + + private long getLatestBlockHeaderNumber() { + byte[] value = this.propertiesStore.get("latest_block_header_number".getBytes()); + return value == null ? 1 : ByteArray.toLong(value); + } +} + diff --git a/chainbase/src/main/java/org/tron/core/store/AccountAssetStore.java b/chainbase/src/main/java/org/tron/core/store/AccountAssetStore.java index 5d4e0d6f91a..6e970a136d3 100644 --- a/chainbase/src/main/java/org/tron/core/store/AccountAssetStore.java +++ b/chainbase/src/main/java/org/tron/core/store/AccountAssetStore.java @@ -1,25 +1,110 @@ package org.tron.core.store; -import lombok.extern.slf4j.Slf4j; +import com.google.common.primitives.Bytes; +import com.google.common.primitives.Longs; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import org.tron.core.capsule.AccountAssetCapsule; -import org.tron.core.db.TronStoreWithRevoking; +import org.tron.common.utils.ByteArray; +import org.tron.core.db.TronDatabase; +import org.tron.core.db2.common.WrappedByteArray; +import org.tron.protos.Protocol; + +import java.util.HashMap; +import java.util.Map; -@Slf4j(topic = "DB") @Component -public class AccountAssetStore extends TronStoreWithRevoking { +public class AccountAssetStore extends TronDatabase { @Autowired - protected AccountAssetStore(@Value("account-asset-issue") String dbName) { + protected AccountAssetStore(@Value("account-asset") String dbName) { super(dbName); } @Override - public AccountAssetCapsule get(byte[] key) { - byte[] value = revokingDB.getUnchecked(key); - return ArrayUtils.isEmpty(value) ? null : new AccountAssetCapsule(value); + public void put(byte[] key, byte[] item) { + dbSource.putData(key, item); + } + + @Override + public void delete(byte[] key) { + dbSource.deleteData(key); + } + + @Override + public byte[] get(byte[] key) { + return dbSource.getData(key); + } + + @Override + public boolean has(byte[] key) { + return dbSource.getData(key) != null; + } + + public void putAccount(Protocol.Account account) { + Map assets = convert(getAssets(account)); + if (!assets.isEmpty()) { + updateByBatch(assets); + } + } + + public void deleteAccount(byte[] key) { + Map assets = convert(getDeletedAssets(key)); + if (!assets.isEmpty()) { + updateByBatch(assets); + } + } + + public Map getAssets(Protocol.Account account) { + Map assets = new HashMap<>(); + account.getAssetV2Map().forEach((k, v) -> { + byte[] key = Bytes.concat(account.getAddress().toByteArray(), k.getBytes()); + if (v == 0) { + assets.put(WrappedByteArray.of(key), WrappedByteArray.of(null)); + } else { + assets.put(WrappedByteArray.of(key), WrappedByteArray.of(Longs.toByteArray(v))); + } + }); + return assets; + } + + public Map getDeletedAssets(byte[] key) { + Map assets = new HashMap<>(); + prefixQuery(key).forEach((k, v) -> + assets.put(WrappedByteArray.of(k.getBytes()), WrappedByteArray.of(null))); + return assets; + } + + public static Map convert(Map map) { + Map assets = new HashMap<>(); + map.forEach((k, v) -> assets.put(k.getBytes(), v.getBytes())); + return assets; + } + + public long getBalance(Protocol.Account account, byte[] key) { + if (!account.getAssetOptimized()) { + return 0; + } + byte[] k = Bytes.concat(account.getAddress().toByteArray(), key); + byte[] value = get(k); + if (ArrayUtils.isEmpty(value)) { + return 0; + } + return Longs.fromByteArray(value); + } + + public Map getAllAssets(Protocol.Account account) { + Map assets = new HashMap<>(); + if (account.getAssetOptimized()) { + Map map = prefixQuery(account.getAddress().toByteArray()); + map.forEach((k, v) -> { + byte[] assetID = ByteArray.subArray(k.getBytes(), + account.getAddress().toByteArray().length, k.getBytes().length); + assets.put(ByteArray.toStr(assetID), Longs.fromByteArray(v)); + }); + } + account.getAssetV2Map().forEach((k, v) -> assets.put(k, v)); + return assets; } } diff --git a/chainbase/src/main/java/org/tron/core/store/AccountStore.java b/chainbase/src/main/java/org/tron/core/store/AccountStore.java index d98a94a84b8..4d39049ee79 100644 --- a/chainbase/src/main/java/org/tron/core/store/AccountStore.java +++ b/chainbase/src/main/java/org/tron/core/store/AccountStore.java @@ -2,21 +2,16 @@ import com.google.protobuf.ByteString; import com.typesafe.config.ConfigObject; -import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; 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.Commons; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.capsule.utils.AssetUtil; import org.tron.core.db.TronStoreWithRevoking; import org.tron.core.db.accountstate.AccountStateCallBackUtils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.AccountAsset; import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace; import org.tron.protos.contract.BalanceContract.TransactionBalanceTrace.Operation; @@ -25,7 +20,6 @@ import java.util.Map; import java.util.OptionalLong; -@Slf4j(topic = "DB") @Component public class AccountStore extends TronStoreWithRevoking { @@ -40,9 +34,6 @@ public class AccountStore extends TronStoreWithRevoking { @Autowired private AccountTraceStore accountTraceStore; - @Autowired - private AccountAssetStore accountAssetStore; - @Autowired private DynamicPropertiesStore dynamicPropertiesStore; @@ -87,18 +78,6 @@ public void put(byte[] key, AccountCapsule item) { } } } - - if (AssetUtil.isAllowAssetOptimization()) { - Account account = item.getInstance(); - AccountAsset accountAsset = AssetUtil.getAsset(account); - if (null != accountAsset) { - accountAssetStore.put(key, new AccountAssetCapsule( - accountAsset)); - account = AssetUtil.clearAsset(account); - item.setIsAssetImport(false); - item.setInstance(account); - } - } super.put(key, item); accountStateCallBackUtils.accountCallBack(key, item); } @@ -116,12 +95,7 @@ public void delete(byte[] key) { accountTraceStore.recordBalanceWithBlock(key, blockId.getNum(), 0); } } - super.delete(key); - - if (AssetUtil.isAllowAssetOptimization()) { - accountAssetStore.delete(key); - } } /** diff --git a/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java b/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java index d38a5f0677e..4f69a6c3c66 100644 --- a/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java +++ b/chainbase/src/main/java/org/tron/core/store/AssetIssueStore.java @@ -43,13 +43,6 @@ private List getAssetIssuesPaginated(List return null; } -// return Streams.stream(iterator()) -// .map(Entry::getValue) -// .sorted(Comparator.comparing(a -> a.getName().toStringUtf8(), String::compareTo)) -// .skip(offset) -// .limit(Math.min(limit, ASSET_ISSUE_COUNT_LIMIT_MAX)) -// .collect(Collectors.toList()); - if (assetIssueList.size() <= offset) { return null; } diff --git a/chainbase/src/main/java/org/tron/core/store/CheckPointV2Store.java b/chainbase/src/main/java/org/tron/core/store/CheckPointV2Store.java new file mode 100644 index 00000000000..2f952e6b82a --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/store/CheckPointV2Store.java @@ -0,0 +1,70 @@ +package org.tron.core.store; + +import com.google.protobuf.InvalidProtocolBufferException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.tron.core.db.TronDatabase; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ItemNotFoundException; + +import java.util.Spliterator; +import java.util.function.Consumer; + +@Slf4j(topic = "DB") +public class CheckPointV2Store extends TronDatabase { + + @Autowired + public CheckPointV2Store(String dbPath) { + super(dbPath); + } + + @Override + public void put(byte[] key, byte[] item) { + } + + @Override + public void delete(byte[] key) { + getDbSource().deleteData(key); + } + + @Override + public byte[] get(byte[] key) + throws InvalidProtocolBufferException, ItemNotFoundException, BadItemException { + return null; + } + + @Override + public boolean has(byte[] key) { + return false; + } + + @Override + public void forEach(Consumer action) { + + } + + @Override + public Spliterator spliterator() { + return null; + } + + @Override + protected void init() { + } + + /** + * close the database. + */ + @Override + public void close() { + logger.debug("******** Begin to close {}. ********", getName()); + try { + dbSource.closeDB(); + } catch (Exception e) { + logger.warn("Failed to close {}.", getName(), e); + } finally { + logger.debug("******** End to close {}. ********", getName()); + } + } + +} diff --git a/chainbase/src/main/java/org/tron/core/store/CheckTmpStore.java b/chainbase/src/main/java/org/tron/core/store/CheckTmpStore.java index 870aa9aa1b8..09f60c83898 100644 --- a/chainbase/src/main/java/org/tron/core/store/CheckTmpStore.java +++ b/chainbase/src/main/java/org/tron/core/store/CheckTmpStore.java @@ -24,7 +24,6 @@ public void put(byte[] key, byte[] item) { @Override public void delete(byte[] key) { - } @Override diff --git a/chainbase/src/main/java/org/tron/core/store/ContractStateStore.java b/chainbase/src/main/java/org/tron/core/store/ContractStateStore.java new file mode 100644 index 00000000000..19dfb11cdcd --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/store/ContractStateStore.java @@ -0,0 +1,35 @@ +package org.tron.core.store; + +import java.util.Objects; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.core.capsule.ContractStateCapsule; +import org.tron.core.db.TronStoreWithRevoking; + +@Slf4j(topic = "DB") +@Component +public class ContractStateStore extends TronStoreWithRevoking { + + @Autowired + private ContractStateStore(@Value("contract-state") String dbName) { + super(dbName); + } + + @Override + public ContractStateCapsule get(byte[] key) { + return getUnchecked(key); + } + + @Override + public void put(byte[] key, ContractStateCapsule item) { + if (Objects.isNull(key) || Objects.isNull(item)) { + return; + } + + revokingDB.put(key, item.getData()); + } + +} diff --git a/chainbase/src/main/java/org/tron/core/store/DelegatedResourceAccountIndexStore.java b/chainbase/src/main/java/org/tron/core/store/DelegatedResourceAccountIndexStore.java index b3eb5675873..2afa2cf6917 100644 --- a/chainbase/src/main/java/org/tron/core/store/DelegatedResourceAccountIndexStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DelegatedResourceAccountIndexStore.java @@ -1,5 +1,13 @@ package org.tron.core.store; +import com.google.common.primitives.Bytes; +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import lombok.Getter; import org.apache.commons.lang3.ArrayUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -11,6 +19,14 @@ public class DelegatedResourceAccountIndexStore extends TronStoreWithRevoking { + private static final byte[] FROM_PREFIX = {0x01}; + private static final byte[] TO_PREFIX = {0x02}; + + @Getter + private static final byte[] V2_FROM_PREFIX = {0x03}; + @Getter + private static final byte[] V2_TO_PREFIX = {0x04}; + @Autowired public DelegatedResourceAccountIndexStore(@Value("DelegatedResourceAccountIndex") String dbName) { super(dbName); @@ -23,4 +39,102 @@ public DelegatedResourceAccountIndexCapsule get(byte[] key) { return ArrayUtils.isEmpty(value) ? null : new DelegatedResourceAccountIndexCapsule(value); } + public void convert(byte[] address) { + DelegatedResourceAccountIndexCapsule indexCapsule = this.get(address); + if (indexCapsule == null) { + // convert complete or have no delegate + return; + } + // convert old data + List toList = indexCapsule.getToAccountsList(); + for (int i = 0; i < toList.size(); i++) { + // use index as the timestamp, just to keep index in order + this.delegate(address, toList.get(i).toByteArray(), i + 1L); + } + + List fromList = indexCapsule.getFromAccountsList(); + for (int i = 0; i < fromList.size(); i++) { + // use index as the timestamp, just to keep index in order + this.delegate(fromList.get(i).toByteArray(), address, i + 1L); + } + this.delete(address); + } + + public void delegate(byte[] from, byte[] to, long time) { + byte[] fromKey = Bytes.concat(FROM_PREFIX, from, to); + DelegatedResourceAccountIndexCapsule toIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(to)); + toIndexCapsule.setTimestamp(time); + this.put(fromKey, toIndexCapsule); + + byte[] toKey = Bytes.concat(TO_PREFIX, to, from); + DelegatedResourceAccountIndexCapsule fromIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(from)); + fromIndexCapsule.setTimestamp(time); + this.put(toKey, fromIndexCapsule); + } + + public void delegateV2(byte[] from, byte[] to, long time) { + byte[] fromKey = Bytes.concat(V2_FROM_PREFIX, from, to); + DelegatedResourceAccountIndexCapsule toIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(to)); + toIndexCapsule.setTimestamp(time); + this.put(fromKey, toIndexCapsule); + + byte[] toKey = Bytes.concat(V2_TO_PREFIX, to, from); + DelegatedResourceAccountIndexCapsule fromIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(from)); + fromIndexCapsule.setTimestamp(time); + this.put(toKey, fromIndexCapsule); + } + + public void unDelegate(byte[] from, byte[] to) { + byte[] fromKey = Bytes.concat(FROM_PREFIX, from, to); + this.delete(fromKey); + byte[] toKey = Bytes.concat(TO_PREFIX, to, from); + this.delete(toKey); + } + + + public void unDelegateV2(byte[] from, byte[] to) { + byte[] fromKey = Bytes.concat(V2_FROM_PREFIX, from, to); + this.delete(fromKey); + byte[] toKey = Bytes.concat(V2_TO_PREFIX, to, from); + this.delete(toKey); + } + + public DelegatedResourceAccountIndexCapsule getIndex(byte[] address) { + DelegatedResourceAccountIndexCapsule indexCapsule = get(address); + if (indexCapsule != null) { + return indexCapsule; + } + return getWithPrefix(FROM_PREFIX, TO_PREFIX, address); + } + + public DelegatedResourceAccountIndexCapsule getV2Index(byte[] address) { + return getWithPrefix(V2_FROM_PREFIX, V2_TO_PREFIX, address); + } + + private DelegatedResourceAccountIndexCapsule getWithPrefix(byte[] fromPrefix, byte[] toPrefix, byte[] address) { + DelegatedResourceAccountIndexCapsule tmpIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom(address)); + + byte[] key = Bytes.concat(fromPrefix, address); + List tmpToList = + new ArrayList<>(this.prefixQuery(key).values()); + tmpToList.sort(Comparator.comparing(DelegatedResourceAccountIndexCapsule::getTimestamp)); + List list = tmpToList.stream() + .map(DelegatedResourceAccountIndexCapsule::getAccount).collect(Collectors.toList()); + tmpIndexCapsule.setAllToAccounts(list); + + key = Bytes.concat(toPrefix, address); + List tmpFromList = + new ArrayList<>(this.prefixQuery(key).values()); + tmpFromList.sort(Comparator.comparing(DelegatedResourceAccountIndexCapsule::getTimestamp)); + list = tmpFromList.stream().map(DelegatedResourceAccountIndexCapsule::getAccount).collect( + Collectors.toList()); + tmpIndexCapsule.setAllFromAccounts(list); + return tmpIndexCapsule; + } + } \ No newline at end of file diff --git a/chainbase/src/main/java/org/tron/core/store/DelegatedResourceStore.java b/chainbase/src/main/java/org/tron/core/store/DelegatedResourceStore.java index 725c2d005ce..48bc51892f6 100644 --- a/chainbase/src/main/java/org/tron/core/store/DelegatedResourceStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DelegatedResourceStore.java @@ -1,5 +1,6 @@ package org.tron.core.store; +import com.google.protobuf.ByteString; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -33,4 +34,42 @@ public List getByFrom(byte[] key) { .collect(Collectors.toList()); } + public void unLockExpireResource(byte[] from, byte[] to, long now) { + byte[] lockKey = DelegatedResourceCapsule + .createDbKeyV2(from, to, true); + DelegatedResourceCapsule lockResource = get(lockKey); + if (lockResource == null) { + return; + } + if (lockResource.getExpireTimeForEnergy() >= now + && lockResource.getExpireTimeForBandwidth() >= now) { + return; + } + + byte[] unlockKey = DelegatedResourceCapsule + .createDbKeyV2(from, to, false); + DelegatedResourceCapsule unlockResource = get(unlockKey); + if (unlockResource == null) { + unlockResource = new DelegatedResourceCapsule(ByteString.copyFrom(from), + ByteString.copyFrom(to)); + } + if (lockResource.getExpireTimeForEnergy() < now) { + unlockResource.addFrozenBalanceForEnergy( + lockResource.getFrozenBalanceForEnergy(), 0); + lockResource.setFrozenBalanceForEnergy(0, 0); + } + if (lockResource.getExpireTimeForBandwidth() < now) { + unlockResource.addFrozenBalanceForBandwidth( + lockResource.getFrozenBalanceForBandwidth(), 0); + lockResource.setFrozenBalanceForBandwidth(0, 0); + } + if (lockResource.getFrozenBalanceForBandwidth() == 0 + && lockResource.getFrozenBalanceForEnergy() == 0) { + delete(lockKey); + } else { + put(lockKey, lockResource); + } + put(unlockKey, unlockResource); + } + } \ No newline at end of file diff --git a/chainbase/src/main/java/org/tron/core/store/DelegationStore.java b/chainbase/src/main/java/org/tron/core/store/DelegationStore.java index 8c799a4250b..4e95e480cfd 100644 --- a/chainbase/src/main/java/org/tron/core/store/DelegationStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DelegationStore.java @@ -13,7 +13,7 @@ import java.math.BigInteger; -@Slf4j +@Slf4j(topic = "DB") @Component public class DelegationStore extends TronStoreWithRevoking { 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 907d44a85aa..91b0cff68a0 100644 --- a/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java +++ b/chainbase/src/main/java/org/tron/core/store/DynamicPropertiesStore.java @@ -1,5 +1,9 @@ package org.tron.core.store; +import static org.tron.common.math.Maths.max; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; + import com.google.protobuf.ByteString; import java.util.Arrays; import java.util.Optional; @@ -14,9 +18,10 @@ import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.BytesCapsule; -import org.tron.core.config.Parameter; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.db.TronStoreWithRevoking; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ItemNotFoundException; @Slf4j(topic = "DB") @Component @@ -75,6 +80,9 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking "CREATE_NEW_ACCOUNT_BANDWIDTH_RATE" .getBytes(); private static final byte[] TRANSACTION_FEE = "TRANSACTION_FEE".getBytes(); // 1 byte + private static final long DEFAULT_TRANSACTION_FEE = 10L; + public static final String DEFAULT_BANDWIDTH_PRICE_HISTORY = "0:" + DEFAULT_TRANSACTION_FEE; + private static final byte[] ASSET_ISSUE_FEE = "ASSET_ISSUE_FEE".getBytes(); private static final byte[] UPDATE_ACCOUNT_PERMISSION_FEE = "UPDATE_ACCOUNT_PERMISSION_FEE" .getBytes(); @@ -96,6 +104,7 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] STORAGE_EXCHANGE_TAX_RATE = "STORAGE_EXCHANGE_TAX_RATE".getBytes(); private static final String FORK_CONTROLLER = "FORK_CONTROLLER"; private static final String FORK_PREFIX = "FORK_VERSION_"; + private static final byte[] VERSION_NUMBER = "VERSION_NUMBER".getBytes(); //This value is only allowed to be 0, 1, -1 private static final byte[] REMOVE_THE_POWER_OF_THE_GR = "REMOVE_THE_POWER_OF_THE_GR".getBytes(); //This value is only allowed to be 0, 1, -1 @@ -154,7 +163,8 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking private static final byte[] MAX_FEE_LIMIT = "MAX_FEE_LIMIT".getBytes(); private static final byte[] BURN_TRX_AMOUNT = "BURN_TRX_AMOUNT".getBytes(); - private static final byte[] ALLOW_BLACKHOLE_OPTIMIZATION = "ALLOW_BLACKHOLE_OPTIMIZATION".getBytes(); + private static final byte[] ALLOW_BLACKHOLE_OPTIMIZATION = + "ALLOW_BLACKHOLE_OPTIMIZATION".getBytes(); private static final byte[] ALLOW_NEW_RESOURCE_MODEL = "ALLOW_NEW_RESOURCE_MODEL".getBytes(); private static final byte[] ALLOW_TVM_FREEZE = "ALLOW_TVM_FREEZE".getBytes(); private static final byte[] ALLOW_TVM_VOTE = "ALLOW_TVM_VOTE".getBytes(); @@ -165,11 +175,62 @@ public class DynamicPropertiesStore extends TronStoreWithRevoking //This value is only allowed to be 1 private static final byte[] ALLOW_ACCOUNT_ASSET_OPTIMIZATION = "ALLOW_ACCOUNT_ASSET_OPTIMIZATION".getBytes(); + + private static final byte[] ALLOW_ASSET_OPTIMIZATION = + "ALLOW_ASSET_OPTIMIZATION".getBytes(); + + private static final byte[] ENERGY_PRICE_HISTORY = "ENERGY_PRICE_HISTORY".getBytes(); private static final byte[] ENERGY_PRICE_HISTORY_DONE = "ENERGY_PRICE_HISTORY_DONE".getBytes(); + private static final byte[] BANDWIDTH_PRICE_HISTORY = "BANDWIDTH_PRICE_HISTORY".getBytes(); + private static final byte[] BANDWIDTH_PRICE_HISTORY_DONE = + "BANDWIDTH_PRICE_HISTORY_DONE".getBytes(); + private static final byte[] SET_BLACKHOLE_ACCOUNT_PERMISSION = "SET_BLACKHOLE_ACCOUNT_PERMISSION".getBytes(); + private static final byte[] ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX = + "ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX".getBytes(); + + private static final byte[] ALLOW_NEW_REWARD = "ALLOW_NEW_REWARD".getBytes(); + private static final byte[] MEMO_FEE = "MEMO_FEE".getBytes(); + private static final byte[] MEMO_FEE_HISTORY = "MEMO_FEE_HISTORY".getBytes(); + private static final byte[] ALLOW_DELEGATE_OPTIMIZATION = + "ALLOW_DELEGATE_OPTIMIZATION".getBytes(); + private static final byte[] ALLOW_DYNAMIC_ENERGY = + "ALLOW_DYNAMIC_ENERGY".getBytes(); + private static final byte[] DYNAMIC_ENERGY_THRESHOLD = + "DYNAMIC_ENERGY_THRESHOLD".getBytes(); + private static final byte[] DYNAMIC_ENERGY_INCREASE_FACTOR = + "DYNAMIC_ENERGY_INCREASE_FACTOR".getBytes(); + private static final byte[] DYNAMIC_ENERGY_MAX_FACTOR = + "DYNAMIC_ENERGY_MAX_FACTOR".getBytes(); + + private static final byte[] UNFREEZE_DELAY_DAYS = "UNFREEZE_DELAY_DAYS".getBytes(); + + private static final byte[] ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID = + "ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID".getBytes(); + + private static final byte[] ALLOW_TVM_SHANGHAI = "ALLOW_TVM_SHANGHAI".getBytes(); + + private static final byte[] ALLOW_CANCEL_ALL_UNFREEZE_V2 = "ALLOW_CANCEL_ALL_UNFREEZE_V2" + .getBytes(); + + private static final byte[] MAX_DELEGATE_LOCK_PERIOD = + "MAX_DELEGATE_LOCK_PERIOD".getBytes(); + + private static final byte[] ALLOW_OLD_REWARD_OPT = "ALLOW_OLD_REWARD_OPT".getBytes(); + private static final byte[] ALLOW_ENERGY_ADJUSTMENT = "ALLOW_ENERGY_ADJUSTMENT".getBytes(); + + private static final byte[] MAX_CREATE_ACCOUNT_TX_SIZE = "MAX_CREATE_ACCOUNT_TX_SIZE".getBytes(); + private static final byte[] ALLOW_STRICT_MATH = "ALLOW_STRICT_MATH".getBytes(); + + private static final byte[] CONSENSUS_LOGIC_OPTIMIZATION + = "CONSENSUS_LOGIC_OPTIMIZATION".getBytes(); + + private static final byte[] ALLOW_TVM_CANCUN = "ALLOW_TVM_CANCUN".getBytes(); + + private static final byte[] ALLOW_TVM_BLOB = "ALLOW_TVM_BLOB".getBytes(); @Autowired private DynamicPropertiesStore(@Value("properties") String dbName) { @@ -369,7 +430,6 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { this.saveTotalTronPowerWeight(0L); } - try { this.getAllowAdaptiveEnergy(); } catch (IllegalArgumentException e) { @@ -440,7 +500,7 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { try { this.getTransactionFee(); } catch (IllegalArgumentException e) { - this.saveTransactionFee(10L); // 10sun/byte + this.saveTransactionFee(DEFAULT_TRANSACTION_FEE); // 10sun/byte } try { @@ -742,7 +802,8 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { try { this.getAllowBlackHoleOptimization(); } catch (IllegalArgumentException e) { - this.saveAllowBlackHoleOptimization(CommonParameter.getInstance().getAllowBlackHoleOptimization()); + this.saveAllowBlackHoleOptimization( + CommonParameter.getInstance().getAllowBlackHoleOptimization()); } try { @@ -779,11 +840,18 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { this.saveAllowTvmCompatibleEvm(CommonParameter.getInstance().getAllowTvmCompatibleEvm()); } + try { + this.getAllowAssetOptimization(); + } catch (IllegalArgumentException e) { + this.setAllowAssetOptimization(CommonParameter + .getInstance().getAllowAssetOptimization()); + } + try { this.getAllowAccountAssetOptimization(); } catch (IllegalArgumentException e) { this.setAllowAccountAssetOptimization(CommonParameter - .getInstance().getAllowAccountAssetOptimization()); + .getInstance().getAllowAccountAssetOptimization()); } try { @@ -798,11 +866,107 @@ private DynamicPropertiesStore(@Value("properties") String dbName) { this.saveEnergyPriceHistory(DEFAULT_ENERGY_PRICE_HISTORY); } + try { + this.getBandwidthPriceHistoryDone(); + } catch (IllegalArgumentException e) { + this.saveBandwidthPriceHistoryDone(0); + } + + try { + this.getBandwidthPriceHistory(); + } catch (IllegalArgumentException e) { + this.saveBandwidthPriceHistory(DEFAULT_BANDWIDTH_PRICE_HISTORY); + } + try { this.getSetBlackholeAccountPermission(); } catch (IllegalArgumentException e) { this.saveSetBlackholePermission(0); } + + try { + this.getAllowHigherLimitForMaxCpuTimeOfOneTx(); + } catch (IllegalArgumentException e) { + this.saveAllowHigherLimitForMaxCpuTimeOfOneTx( + CommonParameter.getInstance().getAllowHigherLimitForMaxCpuTimeOfOneTx()); + } + + try { + this.getNewRewardAlgorithmEffectiveCycle(); + } catch (IllegalArgumentException e) { + if (CommonParameter.getInstance().getAllowNewRewardAlgorithm() == 1) { + this.put(NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE, + new BytesCapsule(ByteArray.fromLong(getCurrentCycleNumber()))); + } else { + this.put(NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE, + new BytesCapsule(ByteArray.fromLong(Long.MAX_VALUE))); + } + } + + try { + this.getAllowNewReward(); + } catch (IllegalArgumentException e) { + this.saveAllowNewReward(CommonParameter.getInstance().getAllowNewReward()); + if (CommonParameter.getInstance().getAllowNewReward() == 1) { + this.put(NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE, + new BytesCapsule(ByteArray.fromLong(getCurrentCycleNumber()))); + } + } + + try { + this.getMemoFee(); + } catch (IllegalArgumentException e) { + long memoFee = CommonParameter.getInstance().getMemoFee(); + this.saveMemoFee(memoFee); + this.saveMemoFeeHistory("0:" + memoFee); + } + + try { + this.getAllowDelegateOptimization(); + } catch (IllegalArgumentException e) { + this.saveAllowDelegateOptimization( + CommonParameter.getInstance().getAllowDelegateOptimization()); + } + + try { + this.getUnfreezeDelayDays(); + } catch (IllegalArgumentException e) { + this.saveUnfreezeDelayDays( + CommonParameter.getInstance().getUnfreezeDelayDays() + ); + } + + try { + this.getAllowOptimizedReturnValueOfChainId(); + } catch (IllegalArgumentException e) { + this.saveAllowOptimizedReturnValueOfChainId( + CommonParameter.getInstance().getAllowOptimizedReturnValueOfChainId() + ); + } + + try { + this.getAllowDynamicEnergy(); + } catch (IllegalArgumentException e) { + this.saveAllowDynamicEnergy(CommonParameter.getInstance().getAllowDynamicEnergy()); + } + + try { + this.getDynamicEnergyThreshold(); + } catch (IllegalArgumentException e) { + this.saveDynamicEnergyThreshold(CommonParameter.getInstance().getDynamicEnergyThreshold()); + } + + try { + this.getDynamicEnergyIncreaseFactor(); + } catch (IllegalArgumentException e) { + this.saveDynamicEnergyIncreaseFactor(CommonParameter.getInstance().getDynamicEnergyIncreaseFactor()); + } + + try { + this.getDynamicEnergyMaxFactor(); + } catch (IllegalArgumentException e) { + this.saveDynamicEnergyMaxFactor(CommonParameter.getInstance().getDynamicEnergyMaxFactor()); + } } public String intArrayToString(int[] a) { @@ -862,7 +1026,7 @@ public long getAbiMoveDone() { } public void saveBlockFilledSlotsIndex(int blockFilledSlotsIndex) { - logger.debug("blockFilledSlotsIndex:" + blockFilledSlotsIndex); + logger.debug("BlockFilledSlotsIndex: {}.", blockFilledSlotsIndex); this.put(BLOCK_FILLED_SLOTS_INDEX, new BytesCapsule(ByteArray.fromInt(blockFilledSlotsIndex))); } @@ -1893,7 +2057,7 @@ public boolean supportShieldedTRC20Transaction() { } public void saveBlockFilledSlots(int[] blockFilledSlots) { - logger.debug("blockFilledSlots:" + intArrayToString(blockFilledSlots)); + logger.debug("BlockFilledSlots: {}.", intArrayToString(blockFilledSlots)); this.put(BLOCK_FILLED_SLOTS, new BytesCapsule(ByteArray.fromString(intArrayToString(blockFilledSlots)))); } @@ -1983,6 +2147,19 @@ public long getLatestBlockHeaderNumber() { () -> new IllegalArgumentException("not found latest block header number")); } + public long getLatestBlockHeaderNumberFromDB() { + try { + return Optional.ofNullable(getFromRoot(LATEST_BLOCK_HEADER_NUMBER)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found latest block header number")); + } catch (ItemNotFoundException | BadItemException e) { + logger.error("Get header from DB, {}.", e.getMessage()); + } + return -1; + } + public int getStateFlag() { return Optional.ofNullable(getUnchecked(STATE_FLAG)) .map(BytesCapsule::getData) @@ -2005,7 +2182,7 @@ public Sha256Hash getLatestBlockHeaderHash() { * save timestamp of creating global latest block. */ public void saveLatestBlockHeaderTimestamp(long t) { - logger.info("update latest block header timestamp = {}", t); + logger.info("Update latest block header timestamp = {}.", t); this.put(LATEST_BLOCK_HEADER_TIMESTAMP, new BytesCapsule(ByteArray.fromLong(t))); } @@ -2013,7 +2190,7 @@ public void saveLatestBlockHeaderTimestamp(long t) { * save number of global latest block. */ public void saveLatestBlockHeaderNumber(long n) { - logger.info("update latest block header number = {}", n); + logger.info("Update latest block header number = {}.", n); this.put(LATEST_BLOCK_HEADER_NUMBER, new BytesCapsule(ByteArray.fromLong(n))); } @@ -2021,12 +2198,12 @@ public void saveLatestBlockHeaderNumber(long n) { * save id of global latest block. */ public void saveLatestBlockHeaderHash(ByteString h) { - logger.info("update latest block header id = {}", ByteArray.toHexString(h.toByteArray())); + logger.info("Update latest block header id = {}.", ByteArray.toHexString(h.toByteArray())); this.put(LATEST_BLOCK_HEADER_HASH, new BytesCapsule(h.toByteArray())); } public void saveStateFlag(int n) { - logger.info("update state flag = {}", n); + logger.info("Update state flag = {}.", n); this.put(STATE_FLAG, new BytesCapsule(ByteArray.fromInt(n))); } @@ -2039,7 +2216,7 @@ public long getNextMaintenanceTime() { } public long getMaintenanceSkipSlots() { - return Parameter.ChainConstant.MAINTENANCE_SKIP_SLOTS; + return ChainConstant.MAINTENANCE_SKIP_SLOTS; } public void saveNextMaintenanceTime(long nextMaintenanceTime) { @@ -2056,8 +2233,8 @@ public void updateNextMaintenanceTime(long blockTime) { saveNextMaintenanceTime(nextMaintenanceTime); logger.info( - "do update nextMaintenanceTime,currentMaintenanceTime:{}, blockTime:{}," - + "nextMaintenanceTime:{}", + "Do update nextMaintenanceTime, currentMaintenanceTime: {}, blockTime: {}, " + + "nextMaintenanceTime: {}.", new DateTime(currentMaintenanceTime), new DateTime(blockTime), new DateTime(nextMaintenanceTime) ); @@ -2065,22 +2242,40 @@ public void updateNextMaintenanceTime(long blockTime) { //The unit is trx public void addTotalNetWeight(long amount) { + if (amount == 0) { + return; + } long totalNetWeight = getTotalNetWeight(); totalNetWeight += amount; + if (allowNewReward()) { + totalNetWeight = max(0, totalNetWeight, disableJavaLangMath()); + } saveTotalNetWeight(totalNetWeight); } //The unit is trx public void addTotalEnergyWeight(long amount) { + if (amount == 0) { + return; + } long totalEnergyWeight = getTotalEnergyWeight(); totalEnergyWeight += amount; + if (allowNewReward()) { + totalEnergyWeight = max(0, totalEnergyWeight, disableJavaLangMath()); + } saveTotalEnergyWeight(totalEnergyWeight); } //The unit is trx public void addTotalTronPowerWeight(long amount) { + if (amount == 0) { + return; + } long totalWeight = getTotalTronPowerWeight(); totalWeight += amount; + if (allowNewReward()) { + totalWeight = max(0, totalWeight, disableJavaLangMath()); + } saveTotalTronPowerWeight(totalWeight); } @@ -2120,6 +2315,19 @@ public Boolean getForked(int version) { return value == null ? null : Boolean.valueOf(new String(value)); } + public void saveLatestVersion(int version) { + this.put(VERSION_NUMBER, new BytesCapsule(ByteArray.fromInt(version))); + } + + public int getLatestVersion() { + BytesCapsule data = getUnchecked(VERSION_NUMBER); + if (data == null) { + saveLatestVersion(0); + return 0; + } + return ByteArray.toInt(data.getData()); + } + /** * get allow protobuf number. */ @@ -2134,7 +2342,7 @@ public long getAllowProtoFilterNum() { * save allow protobuf number. */ public void saveAllowProtoFilterNum(long num) { - logger.info("update allow protobuf number = {}", num); + logger.info("Update allow protobuf number = {}.", num); this.put(ALLOW_PROTO_FILTER_NUM, new BytesCapsule(ByteArray.fromLong(num))); } @@ -2254,6 +2462,10 @@ public boolean supportAllowAccountAssetOptimization() { return getAllowAccountAssetOptimization() == 1L; } + public boolean supportAllowAssetOptimization() { + return getAllowAssetOptimization() == 1L; + } + public void saveAllowNewResourceModel(long value) { this.put(ALLOW_NEW_RESOURCE_MODEL, new BytesCapsule(ByteArray.fromLong(value))); } @@ -2323,7 +2535,7 @@ public long getAllowTvmCompatibleEvm() { } public boolean useNewRewardAlgorithm() { - return getAllowTvmVote() == 1; + return getNewRewardAlgorithmEffectiveCycle() != Long.MAX_VALUE; } public void saveNewRewardAlgorithmEffectiveCycle() { @@ -2338,21 +2550,50 @@ public long getNewRewardAlgorithmEffectiveCycle() { return Optional.ofNullable(getUnchecked(NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE)) .map(BytesCapsule::getData) .map(ByteArray::toLong) - .orElse(Long.MAX_VALUE); + .orElseThrow( + () -> new IllegalArgumentException("not found NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE")); + } + + public long getAllowAccountAssetOptimizationFromRoot() { + try { + return Optional.ofNullable(getFromRoot(ALLOW_ASSET_OPTIMIZATION)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_ASSET_OPTIMIZATION")); + } catch (Exception e) { + logger.debug("{}", e.getMessage()); + return CommonParameter.getInstance().getAllowAssetOptimization(); + } } // 1: enable public long getAllowAccountAssetOptimization() { return Optional.ofNullable(getUnchecked(ALLOW_ACCOUNT_ASSET_OPTIMIZATION)) - .map(BytesCapsule::getData) - .map(ByteArray::toLong) - .orElseThrow(() -> new IllegalArgumentException("not found ALLOW_ACCOUNT_ASSET_OPTIMIZATION")); + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_ACCOUNT_ASSET_OPTIMIZATION")); } public void setAllowAccountAssetOptimization(long value) { this.put(ALLOW_ACCOUNT_ASSET_OPTIMIZATION, new BytesCapsule(ByteArray.fromLong(value))); } + // 1: enable + public long getAllowAssetOptimization() { + return Optional.ofNullable(getUnchecked(ALLOW_ASSET_OPTIMIZATION)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_ASSET_OPTIMIZATION")); + } + + public void setAllowAssetOptimization(long value) { + this.put(ALLOW_ASSET_OPTIMIZATION, new BytesCapsule(ByteArray.fromLong(value))); + } + + // for energy price history public void saveEnergyPriceHistoryDone(long value) { this.put(ENERGY_PRICE_HISTORY_DONE, new BytesCapsule(ByteArray.fromLong(value))); @@ -2377,6 +2618,31 @@ public void saveEnergyPriceHistory(String value) { this.put(ENERGY_PRICE_HISTORY, new BytesCapsule(ByteArray.fromString(value))); } + // for bandwidth price history + public void saveBandwidthPriceHistoryDone(long value) { + this.put(BANDWIDTH_PRICE_HISTORY_DONE, + new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getBandwidthPriceHistoryDone() { + return Optional.ofNullable(getUnchecked(BANDWIDTH_PRICE_HISTORY_DONE)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found BANDWIDTH_PRICE_HISTORY_DONE")); + } + + public String getBandwidthPriceHistory() { + return Optional.ofNullable(getUnchecked(BANDWIDTH_PRICE_HISTORY)) + .map(BytesCapsule::getData) + .map(ByteArray::toStr) + .orElseThrow(() -> new IllegalArgumentException("not found BANDWIDTH_PRICE_HISTORY")); + } + + public void saveBandwidthPriceHistory(String value) { + this.put(BANDWIDTH_PRICE_HISTORY, new BytesCapsule(ByteArray.fromString(value))); + } + public long getSetBlackholeAccountPermission() { return Optional.of(getUnchecked(SET_BLACKHOLE_ACCOUNT_PERMISSION)) .map(BytesCapsule::getData) @@ -2389,6 +2655,297 @@ public void saveSetBlackholePermission(long value) { this.put(SET_BLACKHOLE_ACCOUNT_PERMISSION, new BytesCapsule(ByteArray.fromLong(value))); } + public void saveAllowHigherLimitForMaxCpuTimeOfOneTx(long value) { + this.put(ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX, + new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getAllowHigherLimitForMaxCpuTimeOfOneTx() { + String msg = "not found ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX"; + return Optional.ofNullable(getUnchecked(ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException(msg)); + } + + public long getMemoFee() { + return Optional.ofNullable(getUnchecked(MEMO_FEE)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow(() -> new IllegalArgumentException("not found MEMO_FEE")); + } + + public void saveMemoFee(long value) { + this.put(MEMO_FEE, new BytesCapsule(ByteArray.fromLong(value))); + } + + public String getMemoFeeHistory() { + return Optional.ofNullable(getUnchecked(MEMO_FEE_HISTORY)) + .map(BytesCapsule::getData) + .map(ByteArray::toStr) + .orElseThrow(() -> new IllegalArgumentException("not found MEMO_FEE_HISTORY")); + } + + public void saveMemoFeeHistory(String value) { + this.put(MEMO_FEE_HISTORY, new BytesCapsule(ByteArray.fromString(value))); + } + + public long getAllowNewReward() { + return Optional.ofNullable(getUnchecked(ALLOW_NEW_REWARD)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow(() -> new IllegalArgumentException("not found AllowNewReward")); + } + + public void saveAllowNewReward(long newReward) { + this.put(ALLOW_NEW_REWARD, new BytesCapsule(ByteArray.fromLong(newReward))); + } + + public long getAllowDelegateOptimization() { + return Optional.ofNullable(getUnchecked(ALLOW_DELEGATE_OPTIMIZATION)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_DELEGATE_OPTIMIZATION")); + } + + public boolean supportAllowDelegateOptimization() { + return getAllowDelegateOptimization() == 1L; + } + + public void saveAllowDelegateOptimization(long value) { + this.put(ALLOW_DELEGATE_OPTIMIZATION, new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getAllowDynamicEnergy() { + return Optional.ofNullable(getUnchecked(ALLOW_DYNAMIC_ENERGY)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found ALLOW_DYNAMIC_ENERGY")); + } + + public boolean supportAllowDynamicEnergy() { + return getAllowDynamicEnergy() == 1L; + } + + public void saveAllowDynamicEnergy(long value) { + this.put(ALLOW_DYNAMIC_ENERGY, new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getDynamicEnergyThreshold() { + return Optional.ofNullable(getUnchecked(DYNAMIC_ENERGY_THRESHOLD)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found DYNAMIC_ENERGY_THRESHOLD")); + } + + public void saveDynamicEnergyThreshold(long value) { + this.put(DYNAMIC_ENERGY_THRESHOLD, new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getDynamicEnergyIncreaseFactor() { + return Optional.ofNullable(getUnchecked(DYNAMIC_ENERGY_INCREASE_FACTOR)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found DYNAMIC_ENERGY_INCREASE_FACTOR")); + } + + public void saveDynamicEnergyIncreaseFactor(long value) { + this.put(DYNAMIC_ENERGY_INCREASE_FACTOR, new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getDynamicEnergyMaxFactor() { + return Optional.ofNullable(getUnchecked(DYNAMIC_ENERGY_MAX_FACTOR)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found DYNAMIC_ENERGY_MAX_FACTOR")); + } + + public void saveDynamicEnergyMaxFactor(long value) { + this.put(DYNAMIC_ENERGY_MAX_FACTOR, new BytesCapsule(ByteArray.fromLong(value))); + } + + public boolean allowNewReward() { + return getAllowNewReward() == 1; + } + + public long getUnfreezeDelayDays() { + return Optional.ofNullable(getUnchecked(UNFREEZE_DELAY_DAYS)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow(() -> new IllegalArgumentException("not found UNFREEZE_DELAY_DAYS")); + } + + public boolean supportUnfreezeDelay() { + return getUnfreezeDelayDays() > 0; + } + + public void saveUnfreezeDelayDays(long value) { + this.put(UNFREEZE_DELAY_DAYS, new BytesCapsule(ByteArray.fromLong(value))); + } + + public void saveAllowOptimizedReturnValueOfChainId(long value) { + this.put(ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID, + new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getAllowOptimizedReturnValueOfChainId() { + String msg = "not found ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID"; + return Optional.ofNullable(getUnchecked(ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException(msg)); + } + + public void saveAllowTvmShangHai(long allowTvmShangHai) { + this.put(DynamicPropertiesStore.ALLOW_TVM_SHANGHAI, + new BytesCapsule(ByteArray.fromLong(allowTvmShangHai))); + } + + public long getAllowTvmShangHai() { + return Optional.ofNullable(getUnchecked(ALLOW_TVM_SHANGHAI)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowTvmShangHai()); + } + + public void saveAllowCancelAllUnfreezeV2(long allowCancelAllUnfreezeV2) { + this.put(DynamicPropertiesStore.ALLOW_CANCEL_ALL_UNFREEZE_V2, + new BytesCapsule(ByteArray.fromLong(allowCancelAllUnfreezeV2))); + } + + public long getAllowCancelAllUnfreezeV2() { + return Optional.ofNullable(getUnchecked(ALLOW_CANCEL_ALL_UNFREEZE_V2)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowCancelAllUnfreezeV2()); + } + + public boolean supportAllowCancelAllUnfreezeV2() { + return getAllowCancelAllUnfreezeV2() == 1L && getUnfreezeDelayDays() > 0; + } + + public void saveMaxDelegateLockPeriod(long maxDelegateLockPeriod) { + this.put(DynamicPropertiesStore.MAX_DELEGATE_LOCK_PERIOD, + new BytesCapsule(ByteArray.fromLong(maxDelegateLockPeriod))); + } + + public long getMaxDelegateLockPeriod() { + return Optional.ofNullable(getUnchecked(MAX_DELEGATE_LOCK_PERIOD)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL); + } + + public boolean supportMaxDelegateLockPeriod() { + return (getMaxDelegateLockPeriod() > DELEGATE_PERIOD / BLOCK_PRODUCED_INTERVAL) && + getUnfreezeDelayDays() > 0; + } + + public void saveAllowOldRewardOpt(long allowOldRewardOpt) { + this.put(ALLOW_OLD_REWARD_OPT, new BytesCapsule(ByteArray.fromLong(allowOldRewardOpt))); + } + + public boolean allowOldRewardOpt() { + return getAllowOldRewardOpt() == 1L; + } + + public long getAllowOldRewardOpt() { + return Optional.ofNullable(getUnchecked(ALLOW_OLD_REWARD_OPT)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowOldRewardOpt()); + } + + public void saveAllowEnergyAdjustment(long allowEnergyAdjustment) { + this.put(ALLOW_ENERGY_ADJUSTMENT, new BytesCapsule(ByteArray.fromLong(allowEnergyAdjustment))); + } + + public long getAllowEnergyAdjustment() { + return Optional.ofNullable(getUnchecked(ALLOW_ENERGY_ADJUSTMENT)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowEnergyAdjustment()); + } + + public void saveMaxCreateAccountTxSize(long maxCreateAccountTxSize) { + this.put(MAX_CREATE_ACCOUNT_TX_SIZE, + new BytesCapsule(ByteArray.fromLong(maxCreateAccountTxSize))); + } + + public long getMaxCreateAccountTxSize() { + return Optional.ofNullable(getUnchecked(MAX_CREATE_ACCOUNT_TX_SIZE)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getMaxCreateAccountTxSize()); + } + public long getAllowStrictMath() { + return Optional.ofNullable(getUnchecked(ALLOW_STRICT_MATH)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowStrictMath()); + } + public void saveAllowStrictMath(long allowStrictMath) { + this.put(ALLOW_STRICT_MATH, new BytesCapsule(ByteArray.fromLong(allowStrictMath))); + } + + public boolean allowStrictMath() { + return getAllowStrictMath() == 1L; + } + + public boolean disableJavaLangMath() { + return this.allowConsensusLogicOptimization(); + } + + public void saveConsensusLogicOptimization(long value) { + this.put(CONSENSUS_LOGIC_OPTIMIZATION, + new BytesCapsule(ByteArray.fromLong(value))); + } + + public long getConsensusLogicOptimization() { + return Optional.ofNullable(getUnchecked(CONSENSUS_LOGIC_OPTIMIZATION)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getConsensusLogicOptimization()); + } + + public boolean allowConsensusLogicOptimization() { + return getConsensusLogicOptimization() == 1L; + } + + public boolean allowWitnessSortOptimization() { + return this.allowConsensusLogicOptimization(); + } + + public void saveAllowTvmCancun(long allowTvmCancun) { + this.put(ALLOW_TVM_CANCUN, + new BytesCapsule(ByteArray.fromLong(allowTvmCancun))); + } + + public long getAllowTvmCancun() { + return Optional.ofNullable(getUnchecked(ALLOW_TVM_CANCUN)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowTvmCancun()); + } + + public void saveAllowTvmBlob(long allowTvmBlob) { + this.put(ALLOW_TVM_BLOB, new BytesCapsule(ByteArray.fromLong(allowTvmBlob))); + } + + public long getAllowTvmBlob() { + return Optional.ofNullable(getUnchecked(ALLOW_TVM_BLOB)) + .map(BytesCapsule::getData) + .map(ByteArray::toLong) + .orElse(CommonParameter.getInstance().getAllowTvmBlob()); + } + private static class DynamicResourceProperties { private static final byte[] ONE_DAY_NET_LIMIT = "ONE_DAY_NET_LIMIT".getBytes(); diff --git a/chainbase/src/main/java/org/tron/core/store/RewardViStore.java b/chainbase/src/main/java/org/tron/core/store/RewardViStore.java new file mode 100755 index 00000000000..f173cecc00f --- /dev/null +++ b/chainbase/src/main/java/org/tron/core/store/RewardViStore.java @@ -0,0 +1,43 @@ +package org.tron.core.store; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; +import org.tron.core.db.TronDatabase; +import org.tron.core.db.common.iterator.DBIterator; + +@Slf4j(topic = "DB") +@Component +public class RewardViStore extends TronDatabase { + + @Autowired + private RewardViStore(@Value("reward-vi") String dbName) { + super(dbName); + } + + @Override + public byte[] get(byte[] key) { + return dbSource.getData(key); + } + + @Override + public void put(byte[] key, byte[] item) { + dbSource.putData(key, item); + } + + @Override + public void delete(byte[] key) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean has(byte[] key) { + return dbSource.getData(key) != null; + } + + @Override + public DBIterator iterator() { + return ((DBIterator) dbSource.iterator()); + } +} diff --git a/chainbase/src/main/java/org/tron/core/store/TransactionRetStore.java b/chainbase/src/main/java/org/tron/core/store/TransactionRetStore.java index 249523de5a4..a22e69e8692 100644 --- a/chainbase/src/main/java/org/tron/core/store/TransactionRetStore.java +++ b/chainbase/src/main/java/org/tron/core/store/TransactionRetStore.java @@ -14,6 +14,7 @@ import org.tron.core.db.TransactionStore; import org.tron.core.db.TronStoreWithRevoking; import org.tron.core.exception.BadItemException; +import org.tron.protos.Protocol; import org.tron.protos.Protocol.TransactionInfo; @Slf4j(topic = "DB") @@ -54,6 +55,17 @@ public TransactionInfoCapsule getTransactionInfo(byte[] key) throws BadItemExcep ByteString id = ByteString.copyFrom(key); for (TransactionInfo transactionResultInfo : result.getInstance().getTransactioninfoList()) { if (transactionResultInfo.getId().equals(id)) { + Protocol.ResourceReceipt receipt = transactionResultInfo.getReceipt(); + // If query a result with dirty origin usage in receipt, we just reset it. + if (receipt.getEnergyUsageTotal() == 0 && receipt.getOriginEnergyUsage() > 0) { + transactionResultInfo = + transactionResultInfo.toBuilder() + .setReceipt( + receipt.toBuilder() + .clearOriginEnergyUsage() + .build()) + .build(); + } return new TransactionInfoCapsule(transactionResultInfo); } } diff --git a/chainbase/src/main/java/org/tron/core/store/TreeBlockIndexStore.java b/chainbase/src/main/java/org/tron/core/store/TreeBlockIndexStore.java index 95ef3a3373c..fbeaecfda40 100644 --- a/chainbase/src/main/java/org/tron/core/store/TreeBlockIndexStore.java +++ b/chainbase/src/main/java/org/tron/core/store/TreeBlockIndexStore.java @@ -28,7 +28,7 @@ public byte[] get(Long num) throws ItemNotFoundException { BytesCapsule value = getUnchecked(ByteArray.fromLong(num)); if (value == null || value.getData() == null) { - throw new ItemNotFoundException("number: " + num + " is not found!"); + throw new ItemNotFoundException(String.format("number: %d is not found!", num)); } return value.getData(); @@ -39,7 +39,8 @@ public BytesCapsule get(byte[] key) throws ItemNotFoundException { byte[] value = revokingDB.getUnchecked(key); if (ArrayUtils.isEmpty(value)) { - throw new ItemNotFoundException("number: " + Arrays.toString(key) + " is not found!"); + throw new ItemNotFoundException(String.format("number: %d is not found!", + ByteArray.toLong(key))); } return new BytesCapsule(value); } diff --git a/chainbase/src/main/java/org/tron/core/store/WitnessScheduleStore.java b/chainbase/src/main/java/org/tron/core/store/WitnessScheduleStore.java index 227b65b6c98..285638c9f49 100644 --- a/chainbase/src/main/java/org/tron/core/store/WitnessScheduleStore.java +++ b/chainbase/src/main/java/org/tron/core/store/WitnessScheduleStore.java @@ -49,11 +49,11 @@ private List getData(byte[] species) { System.arraycopy(ba, i * ADDRESS_BYTE_ARRAY_LENGTH, b, 0, ADDRESS_BYTE_ARRAY_LENGTH); witnessesAddressList.add(ByteString.copyFrom(b)); } - logger.debug("getWitnesses:" + ByteArray.toStr(species) + witnessesAddressList); + logger.debug("GetWitnesses: {}, {}.", ByteArray.toStr(species), witnessesAddressList); return witnessesAddressList; }).orElseThrow( () -> new IllegalArgumentException( - "not found " + ByteArray.toStr(species) + "Witnesses")); + String.format("not found %s Witnesses", ByteArray.toStr(species)))); } public void saveActiveWitnesses(List witnessesAddressList) { diff --git a/chainbase/src/main/java/org/tron/core/store/WitnessStore.java b/chainbase/src/main/java/org/tron/core/store/WitnessStore.java index 22324bca108..9f444d3333d 100644 --- a/chainbase/src/main/java/org/tron/core/store/WitnessStore.java +++ b/chainbase/src/main/java/org/tron/core/store/WitnessStore.java @@ -1,6 +1,9 @@ package org.tron.core.store; import com.google.common.collect.Streams; +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.Comparator; import java.util.List; import java.util.Map.Entry; import java.util.stream.Collectors; @@ -9,7 +12,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; +import org.tron.common.utils.ByteArray; import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.Parameter; import org.tron.core.db.TronStoreWithRevoking; @Slf4j(topic = "DB") @@ -35,4 +40,33 @@ public WitnessCapsule get(byte[] key) { byte[] value = revokingDB.getUnchecked(key); return ArrayUtils.isEmpty(value) ? null : new WitnessCapsule(value); } + + public List getWitnessStandby(boolean isSortOpt) { + List ret; + List all = getAllWitnesses(); + sortWitnesses(all, isSortOpt); + if (all.size() > Parameter.ChainConstant.WITNESS_STANDBY_LENGTH) { + ret = new ArrayList<>(all.subList(0, Parameter.ChainConstant.WITNESS_STANDBY_LENGTH)); + } else { + ret = new ArrayList<>(all); + } + // trim voteCount = 0 + ret.removeIf(w -> w.getVoteCount() < 1); + return ret; + } + + public void sortWitnesses(List witnesses, boolean isSortOpt) { + witnesses.sort(Comparator.comparingLong(WitnessCapsule::getVoteCount).reversed() + .thenComparing(isSortOpt + ? Comparator.comparing(WitnessCapsule::createReadableString).reversed() + : Comparator.comparingInt((WitnessCapsule w) -> w.getAddress().hashCode()).reversed())); + } + + public void sortWitness(List list, boolean isSortOpt) { + list.sort(Comparator.comparingLong((ByteString b) -> get(b.toByteArray()).getVoteCount()) + .reversed().thenComparing(isSortOpt + ? Comparator.comparing( + (ByteString b) -> ByteArray.toHexString(b.toByteArray())).reversed() + : Comparator.comparingInt(ByteString::hashCode).reversed())); + } } diff --git a/checkStyle.sh b/checkStyle.sh deleted file mode 100644 index af3d5e7df1f..00000000000 --- a/checkStyle.sh +++ /dev/null @@ -1,26 +0,0 @@ -./gradlew clean build -x test > build.log 2>&1 -if [ $? != 0 ];then - echo "run ./gradlew build fail, Please check you code, Or just retry this test" - exit 1 -fi -echo "------------------------------ checkStyle check ------------------------------" -#echo $BUILDKITE_PULL_REQUEST_BASE_BRANCH -#if [[ x"$BUILDKITE_PULL_REQUEST_BASE_BRANCH" != x'develop' && x"$BUILDKITE_PULL_REQUEST_BASE_BRANCH" != x'master' ]];then -# echo "BUILDKITE_PULL_REQUEST_BASE_BRANCH isnot develop or master, SKIPED" -# exit 0 -#fi - -grep -v ":checkstyleMain\|:checkstyleTest\|:lint" build.log |grep "ant:checkstyle" > checkStyle.log 2>&1 -checkNum=`cat checkStyle.log | wc -l` -if [ ${checkNum} -gt 0 ];then - echo "please fix checkStyle problem," - echo "run [ ./gradlew clean build -x test ], and you can find checkStyle report in framework/build/reports/checkstyle/" - echo "!!!!! checkStyle Num ${checkNum} !!!!!" - cat checkStyle.log - - echo "checkStyle Failed, please fix checkStyle problem" - touch checkFailTag -else - echo "checkStyle problem zero" -fi -exit 0 diff --git a/codecov.sh b/codecov.sh deleted file mode 100644 index ba83a5a8ee2..00000000000 --- a/codecov.sh +++ /dev/null @@ -1,5 +0,0 @@ -bash <(curl -s https://codecov.io/bash) -t ee5ed39e-1cc4-49d1-bcf9-12bce10e5b3b -s ./common/build/reports/jacoco/test/ -s ./consensus/build/reports/jacoco/test/ -s ./chainbase/build/reports/jacoco/test/ -s ./actuator/build/reports/jacoco/test/ -s ./framework/build/reports/jacoco/test/ - -#bash <(curl -s https://codecov.io/bash) -t ee5ed39e-1cc4-49d1-bcf9-12bce10e5b3b -s ./common/build/reports/jacoco/test/jacocoTestReport.xml -s ./consensus/build/reports/jacoco/test/jacocoTestReport.xml -s ./chainbase/build/reports/jacoco/test/jacocoTestReport.xml -s ./actuator/build/reports/jacoco/test/jacocoTestReport.xml -s ./framework/build/reports/jacoco/test/jacocoTestReport.xml - -#bash <(curl -s https://codecov.io/bash) -t c2f718cbe2e84c62970a892cef614689 diff --git a/common/build.gradle b/common/build.gradle index c66a26f36e1..c6ce8cf44f9 100644 --- a/common/build.gradle +++ b/common/build.gradle @@ -8,7 +8,6 @@ sourceCompatibility = 1.8 // Dependency versions // --------------------------------------- - def leveldbVersion = "1.8" // -------------------------------------- @@ -30,22 +29,39 @@ if (isWindows()) { } } -repositories { - mavenCentral() -} - dependencies { - testCompile group: 'junit', name: 'junit', version: '4.12' - compile group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' - compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.10.3' - compile "com.cedarsoftware:java-util:1.8.0" - compile group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.1' - compile group: 'commons-codec', name: 'commons-codec', version: '1.11' - compile group: 'com.beust', name: 'jcommander', version: '1.72' - compile group: 'com.typesafe', name: 'config', version: '1.3.2' - compile group: leveldbGroup, name: leveldbName, version: leveldbVersion - compile group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' - compile project(":protocol") + api group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.13.4.2' // https://github.com/FasterXML/jackson-databind/issues/3627 + api "com.cedarsoftware:java-util:1.8.0" + api group: 'org.apache.httpcomponents', name: 'httpasyncclient', version: '4.1.1' + api group: 'commons-codec', name: 'commons-codec', version: '1.11' + api group: 'com.beust', name: 'jcommander', version: '1.78' + api group: 'com.typesafe', name: 'config', version: '1.3.2' + api group: leveldbGroup, name: leveldbName, version: leveldbVersion + api group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' + api group: 'io.prometheus', name: 'simpleclient', version: '0.15.0' + api group: 'io.prometheus', name: 'simpleclient_httpserver', version: '0.15.0' + api group: 'io.prometheus', name: 'simpleclient_hotspot', version: '0.15.0' + api 'org.aspectj:aspectjrt:1.8.13' + api 'org.aspectj:aspectjweaver:1.8.13' + api 'org.aspectj:aspectjtools:1.8.13' + api group: 'io.github.tronprotocol', name: 'libp2p', version: '2.2.5',{ + 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(":protocol") } jacocoTestReport { @@ -53,7 +69,7 @@ jacocoTestReport { xml.enabled = true html.enabled = true } - executionData.from = '../framework/build/jacoco/jacocoTest.exec' + getExecutionData().setFrom(fileTree('../framework/build/jacoco').include("**.exec")) afterEvaluate { classDirectories.from = classDirectories.files.collect { fileTree(dir: it,) diff --git a/common/src/main/java/org/tron/common/cache/CacheManager.java b/common/src/main/java/org/tron/common/cache/CacheManager.java new file mode 100644 index 00000000000..fa1fbff193b --- /dev/null +++ b/common/src/main/java/org/tron/common/cache/CacheManager.java @@ -0,0 +1,44 @@ +package org.tron.common.cache; + +import com.google.common.cache.CacheLoader; +import com.google.common.cache.CacheStats; +import com.google.common.collect.Maps; +import java.util.Map; +import java.util.stream.Collectors; +import org.tron.common.parameter.CommonParameter; + +public class CacheManager { + + private static final Map> CACHES = Maps.newConcurrentMap(); + + public static TronCache allocate(CacheType name) { + TronCache cache = new TronCache<>(name, CommonParameter.getInstance() + .getStorage().getCacheStrategy(name)); + CACHES.put(name, cache); + return cache; + } + + public static TronCache allocate(CacheType name, String strategy) { + TronCache cache = new TronCache<>(name, strategy); + CACHES.put(name, cache); + return cache; + } + + public static TronCache allocate(CacheType name, String strategy, + CacheLoader loader) { + TronCache cache = new TronCache<>(name, strategy, loader); + CACHES.put(name, cache); + return cache; + } + + + public static void release(TronCache cache) { + cache.invalidateAll(); + } + + public static Map stats() { + return CACHES.values().stream().collect(Collectors.toMap(c -> c.getName().toString(), + TronCache::stats)); + } + +} diff --git a/common/src/main/java/org/tron/common/cache/CacheStrategies.java b/common/src/main/java/org/tron/common/cache/CacheStrategies.java new file mode 100644 index 00000000000..b282ca1a687 --- /dev/null +++ b/common/src/main/java/org/tron/common/cache/CacheStrategies.java @@ -0,0 +1,70 @@ +package org.tron.common.cache; + +import static org.tron.common.cache.CacheType.abi; +import static org.tron.common.cache.CacheType.account; +import static org.tron.common.cache.CacheType.assetIssueV2; +import static org.tron.common.cache.CacheType.code; +import static org.tron.common.cache.CacheType.contract; +import static org.tron.common.cache.CacheType.delegatedResource; +import static org.tron.common.cache.CacheType.delegatedResourceAccountIndex; +import static org.tron.common.cache.CacheType.delegation; +import static org.tron.common.cache.CacheType.properties; +import static org.tron.common.cache.CacheType.recentBlock; +import static org.tron.common.cache.CacheType.storageRow; +import static org.tron.common.cache.CacheType.votes; +import static org.tron.common.cache.CacheType.witness; +import static org.tron.common.cache.CacheType.witnessSchedule; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class CacheStrategies { + + + public static final String PATTERNS = + "initialCapacity=%d,maximumSize=%d,expireAfterAccess=%s,concurrencyLevel=%d,recordStats"; + public static final List CACHE_BIG_DBS = Collections.singletonList(delegation); + private static final int CPUS = Runtime.getRuntime().availableProcessors(); + public static final String CACHE_STRATEGY_DEFAULT = + String.format(PATTERNS, 1000, 1000, "30s", CPUS); + private static final String CACHE_STRATEGY_SMALL_DEFAULT = + String.format(PATTERNS, 100, 100, "30s", CPUS); + private static final List CACHE_SMALL_DBS = Arrays.asList(recentBlock, witness, + witnessSchedule, delegatedResource, delegatedResourceAccountIndex, + votes, abi); + private static final String CACHE_STRATEGY_NORMAL_DEFAULT = + String.format(PATTERNS, 500, 500, "30s", CPUS); + private static final List CACHE_NORMAL_DBS = Arrays.asList(code, contract, + assetIssueV2, properties); + private static final String CACHE_STRATEGY_BIG_DEFAULT = + String.format(PATTERNS, 10000, 10000, "30s", CPUS); + private static final String CACHE_STRATEGY_HUGE_DEFAULT = + String.format(PATTERNS, 20000, 20000, "30s", CPUS); + private static final List CACHE_HUGE_DBS = Arrays.asList(storageRow, account); + + public static final List CACHE_DBS = Stream.of(CACHE_SMALL_DBS, CACHE_NORMAL_DBS, + CACHE_BIG_DBS, CACHE_HUGE_DBS).flatMap(Collection::stream).map(CacheType::toString) + .collect(Collectors.toList()); + + + public static String getCacheStrategy(CacheType dbName) { + String defaultStrategy = CACHE_STRATEGY_DEFAULT; + if (CACHE_SMALL_DBS.contains(dbName)) { + defaultStrategy = CACHE_STRATEGY_SMALL_DEFAULT; + } + if (CACHE_NORMAL_DBS.contains(dbName)) { + defaultStrategy = CACHE_STRATEGY_NORMAL_DEFAULT; + } + if (CACHE_BIG_DBS.contains(dbName)) { + defaultStrategy = CACHE_STRATEGY_BIG_DEFAULT; + } + if (CACHE_HUGE_DBS.contains(dbName)) { + defaultStrategy = CACHE_STRATEGY_HUGE_DEFAULT; + } + return defaultStrategy; + } +} diff --git a/common/src/main/java/org/tron/common/cache/CacheType.java b/common/src/main/java/org/tron/common/cache/CacheType.java new file mode 100644 index 00000000000..b9b28d0bd7c --- /dev/null +++ b/common/src/main/java/org/tron/common/cache/CacheType.java @@ -0,0 +1,46 @@ +package org.tron.common.cache; + +import java.util.Arrays; + +public enum CacheType { + // for 127 SR + witnessStandby("witnessStandby"), + // for leveldb or rocksdb cache + recentBlock("recent-block"), + witness("witness"), + witnessSchedule("witness_schedule"), + delegatedResource("DelegatedResource"), + delegatedResourceAccountIndex("DelegatedResourceAccountIndex"), + votes("votes"), + abi("abi"), + code("code"), + contract("contract"), + assetIssueV2("asset-issue-v2"), + properties("properties"), + delegation("delegation"), + storageRow("storage-row"), + account("account"); + // for leveldb or rocksdb cache + + public final String type; + + CacheType(String type) { + this.type = type; + } + + public static CacheType findByType(String type) { + return Arrays.stream(CacheType.values()).filter(c -> c.type.equals(type)).findFirst() + .orElseThrow(() -> new IllegalArgumentException(type)); + } + + @Override + public String toString() { + return type; + } + + + + + + +} diff --git a/common/src/main/java/org/tron/common/cache/TronCache.java b/common/src/main/java/org/tron/common/cache/TronCache.java new file mode 100644 index 00000000000..4faf73f864a --- /dev/null +++ b/common/src/main/java/org/tron/common/cache/TronCache.java @@ -0,0 +1,64 @@ +package org.tron.common.cache; + +import com.google.common.base.Objects; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.CacheStats; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import lombok.Getter; + +public class TronCache { + + @Getter + private final CacheType name; + private final Cache cache; + + TronCache(CacheType name, String strategy) { + this.name = name; + this.cache = CacheBuilder.from(strategy).build(); + } + + TronCache(CacheType name, String strategy, CacheLoader loader) { + this.name = name; + this.cache = CacheBuilder.from(strategy).build(loader); + } + + public void put(K k, V v) { + this.cache.put(k, v); + } + + public V getIfPresent(K k) { + return this.cache.getIfPresent(k); + } + + public V get(K k, Callable loader) throws ExecutionException { + return this.cache.get(k, loader); + } + + public CacheStats stats() { + return this.cache.stats(); + } + + public void invalidateAll() { + this.cache.invalidateAll(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TronCache tronCache = (TronCache) o; + return Objects.equal(name, tronCache.name); + } + + @Override + public int hashCode() { + return Objects.hashCode(name); + } +} diff --git a/common/src/main/java/org/tron/common/cron/CronExpression.java b/common/src/main/java/org/tron/common/cron/CronExpression.java new file mode 100644 index 00000000000..0445ec2ce5b --- /dev/null +++ b/common/src/main/java/org/tron/common/cron/CronExpression.java @@ -0,0 +1,1411 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + * Copyright IBM Corp. 2024, 2025 + * + * 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.tron.common.cron; + +import java.io.Serializable; +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.SortedSet; +import java.util.StringTokenizer; +import java.util.TimeZone; +import java.util.TreeSet; + +/** + * Provides a parser and evaluator for unix-like cron expressions. Cron + * expressions provide the ability to specify complex time combinations such as + * "At 8:00am every Monday through Friday" or "At 1:30am every + * last Friday of the month". + *

+ * Cron expressions are comprised of 6 required fields and one optional field + * separated by white space. The fields respectively are described as follows: + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Examples of cron expressions and their meanings.
Field Name Allowed Values Allowed Special Characters
Seconds 0-59 , - * /
Minutes 0-59 , - * /
Hours 0-23 , - * /
Day-of-month 1-31 , - * ? / L W
Month 0-11 or JAN-DEC , - * /
Day-of-Week 1-7 or SUN-SAT , - * ? / L #
Year (Optional) empty, 1970-2199 , - * /
+ *

+ * The '*' character is used to specify all values. For example, "*" + * in the minute field means "every minute". + *

+ *

+ * The '?' character is allowed for the day-of-month and day-of-week fields. It + * is used to specify 'no specific value'. This is useful when you need to + * specify something in one of the two fields, but not the other. + *

+ * The '-' character is used to specify ranges For example "10-12" in + * the hour field means "the hours 10, 11 and 12". + *

+ * The ',' character is used to specify additional values. For example + * "MON,WED,FRI" in the day-of-week field means "the days Monday, + * Wednesday, and Friday". + *

+ *

+ * The '/' character is used to specify increments. For example "0/15" + * in the seconds field means "the seconds 0, 15, 30, and 45". And + * "5/15" in the seconds field means "the seconds 5, 20, 35, and + * 50". Specifying '*' before the '/' is equivalent to specifying 0 is + * the value to start with. Essentially, for each field in the expression, there + * is a set of numbers that can be turned on or off. For seconds and minutes, + * the numbers range from 0 to 59. For hours 0 to 23, for days of the month 0 to + * 31, and for months 0 to 11 (JAN to DEC). The "/" character simply helps you turn + * on every "nth" value in the given set. Thus "7/6" in the + * month field only turns on month "7", it does NOT mean every 6th + * month, please note that subtlety. + *

+ *

+ * The 'L' character is allowed for the day-of-month and day-of-week fields. + * This character is short-hand for "last", but it has different + * meaning in each of the two fields. For example, the value "L" in + * the day-of-month field means "the last day of the month" - day 31 + * for January, day 28 for February on non-leap years. If used in the + * day-of-week field by itself, it simply means "7" or + * "SAT". But if used in the day-of-week field after another value, it + * means "the last xxx day of the month" - for example "6L" + * means "the last friday of the month". You can also specify an offset + * from the last day of the month, such as "L-3" which would mean the third-to-last + * day of the calendar month. When using the 'L' option, it is important not to + * specify lists, or ranges of values, as you'll get confusing/unexpected results. + *

+ *

+ * The 'W' character is allowed for the day-of-month field. This character + * is used to specify the weekday (Monday-Friday) nearest the given day. As an + * example, if you were to specify "15W" as the value for the + * day-of-month field, the meaning is: "the nearest weekday to the 15th of + * the month". So if the 15th is a Saturday, the trigger will fire on + * Friday the 14th. If the 15th is a Sunday, the trigger will fire on Monday the + * 16th. If the 15th is a Tuesday, then it will fire on Tuesday the 15th. + * However if you specify "1W" as the value for day-of-month, and the + * 1st is a Saturday, the trigger will fire on Monday the 3rd, as it will not + * 'jump' over the boundary of a month's days. The 'W' character can only be + * specified when the day-of-month is a single day, not a range or list of days. + *

+ *

+ * The 'L' and 'W' characters can also be combined for the day-of-month + * expression to yield 'LW', which translates to "last weekday of the + * month". + *

+ *

+ * The '#' character is allowed for the day-of-week field. This character is + * used to specify "the nth" XXX day of the month. For example, the + * value of "6#3" in the day-of-week field means the third Friday of + * the month (day 6 = Friday and "#3" = the 3rd one in the month). + * Other examples: "2#1" = the first Monday of the month and + * "4#5" = the fifth Wednesday of the month. Note that if you specify + * "#5" and there is not 5 of the given day-of-week in the month, then + * no firing will occur that month. If the '#' character is used, there can + * only be one expression in the day-of-week field ("3#1,6#3" is + * not valid, since there are two expressions). + *

+ * + *

+ * The legal characters and the names of months and days of the week are not + * case sensitive. + * + *

+ * NOTES: + *

+ *
    + *
  • Support for specifying both a day-of-week and a day-of-month value is + * not complete (you'll need to use the '?' character in one of these fields). + *
  • + *
  • Overflowing ranges is supported - that is, having a larger number on + * the left hand side than the right. You might do 22-2 to catch 10 o'clock + * at night until 2 o'clock in the morning, or you might have NOV-FEB. It is + * very important to note that overuse of overflowing ranges creates ranges + * that don't make sense and no effort has been made to determine which + * interpretation CronExpression chooses. An example would be + * "0 0 14-6 ? * FRI-MON".
  • + *
+ * + * @author Sharada Jambula, James House + * @author Contributions from Mads Henderson + * @author Refactoring from CronTrigger to CronExpression by Aaron Craven + */ +public final class CronExpression implements Serializable { + + public static final int MAX_YEAR = Calendar.getInstance().get(Calendar.YEAR) + 100; + private static final int SECOND = 0; + private static final int MINUTE = 1; + private static final int HOUR = 2; + private static final int DAY_OF_MONTH = 3; + private static final int MONTH = 4; + private static final int DAY_OF_WEEK = 5; + private static final int YEAR = 6; + private static final int ALL_SPEC_INT = 99; // '*' + private static final int NO_SPEC_INT = 98; // '?' + private static final int MAX_LAST_DAY_OFFSET = 30; + private static final int LAST_DAY_OFFSET_START = 32; // "L-30" + private static final int LAST_DAY_OFFSET_END = LAST_DAY_OFFSET_START + MAX_LAST_DAY_OFFSET; // 'L' + private static final Integer ALL_SPEC = ALL_SPEC_INT; + private static final Integer NO_SPEC = NO_SPEC_INT; + private static final Map monthMap = new HashMap<>(20); + private static final Map dayMap = new HashMap<>(60); + private static final long serialVersionUID = 12423409423L; + + static { + monthMap.put("JAN", 0); + monthMap.put("FEB", 1); + monthMap.put("MAR", 2); + monthMap.put("APR", 3); + monthMap.put("MAY", 4); + monthMap.put("JUN", 5); + monthMap.put("JUL", 6); + monthMap.put("AUG", 7); + monthMap.put("SEP", 8); + monthMap.put("OCT", 9); + monthMap.put("NOV", 10); + monthMap.put("DEC", 11); + + dayMap.put("SUN", 1); + dayMap.put("MON", 2); + dayMap.put("TUE", 3); + dayMap.put("WED", 4); + dayMap.put("THU", 5); + dayMap.put("FRI", 6); + dayMap.put("SAT", 7); + } + + private final String cronExpression; + private TimeZone timeZone = null; + private transient TreeSet seconds; + private transient TreeSet minutes; + private transient TreeSet hours; + private transient TreeSet daysOfMonth; + private transient TreeSet nearestWeekdays; + private transient TreeSet months; + private transient TreeSet daysOfWeek; + private transient TreeSet years; + private transient boolean lastDayOfWeek = false; + private transient int nthDayOfWeek = 0; + + /** + * Constructs a new CronExpression based on the specified + * parameter. + * + * @param cronExpression String representation of the cron expression the + * new object should represent + * @throws java.text.ParseException if the string expression cannot be parsed into a valid + * CronExpression + */ + public CronExpression(String cronExpression) throws ParseException { + if (cronExpression == null) { + throw new IllegalArgumentException("cronExpression cannot be null"); + } + + this.cronExpression = cronExpression.toUpperCase(Locale.US); + + buildExpression(this.cronExpression); + } + + /** + * Indicates whether the specified cron expression can be parsed into a + * valid cron expression + * + * @param cronExpression the expression to evaluate + * @return a boolean indicating whether the given expression is a valid cron + * expression + */ + public static boolean isValidExpression(String cronExpression) { + try { + validateExpression(cronExpression); + } catch (ParseException pe) { + return false; + } + return true; + } + + public static void validateExpression(String cronExpression) throws ParseException { + new CronExpression(cronExpression); + } + + /** + * Indicates whether the given date satisfies the cron expression. Note that + * milliseconds are ignored, so two Dates falling on different milliseconds + * of the same second will always have the same result here. + * + * @param date the date to evaluate + * @return a boolean indicating whether the given date satisfies the cron + * expression + */ + public boolean isSatisfiedBy(Date date) { + Calendar testDateCal = Calendar.getInstance(getTimeZone()); + testDateCal.setTime(date); + testDateCal.set(Calendar.MILLISECOND, 0); + Date originalDate = testDateCal.getTime(); + + testDateCal.add(Calendar.SECOND, -1); + + Date timeAfter = getTimeAfter(testDateCal.getTime()); + + return ((timeAfter != null) && (timeAfter.equals(originalDate))); + } + + /** + * Returns the next date/time after the given date/time which + * satisfies the cron expression. + * + * @param date the date/time at which to begin the search for the next valid + * date/time + * @return the next valid date/time + */ + public Date getNextValidTimeAfter(Date date) { + return getTimeAfter(date); + } + + /** + * Returns the time zone for which this CronExpression + * will be resolved. + */ + public TimeZone getTimeZone() { + if (timeZone == null) { + timeZone = TimeZone.getDefault(); + } + + return timeZone; + } + + /** + * Sets the time zone for which this CronExpression + * will be resolved. + */ + public void setTimeZone(TimeZone timeZone) { + this.timeZone = timeZone; + } + + /** + * Returns the string representation of the CronExpression + * + * @return a string representation of the CronExpression + */ + @Override + public String toString() { + return cronExpression; + } + + private void buildExpression(String expression) throws ParseException { + try { + + if (seconds == null) { + seconds = new TreeSet<>(); + } + if (minutes == null) { + minutes = new TreeSet<>(); + } + if (hours == null) { + hours = new TreeSet<>(); + } + if (daysOfMonth == null) { + daysOfMonth = new TreeSet<>(); + } + if (nearestWeekdays == null) { + nearestWeekdays = new TreeSet<>(); + } + if (months == null) { + months = new TreeSet<>(); + } + if (daysOfWeek == null) { + daysOfWeek = new TreeSet<>(); + } + if (years == null) { + years = new TreeSet<>(); + } + + int exprOn = SECOND; + + StringTokenizer exprsTok = new StringTokenizer(expression, " \t", + false); + + if(exprsTok.countTokens() > 7) { + throw new ParseException("Invalid expression has too many terms: " + expression, -1); + } + + while (exprsTok.hasMoreTokens() && exprOn <= YEAR) { + String expr = exprsTok.nextToken().trim(); + + // throw an exception if L is used with other days of the week + if (exprOn == DAY_OF_WEEK && expr.indexOf('L') != -1 && expr.length() > 1 + && expr.contains(",")) { + throw new ParseException("Support for specifying 'L' " + + "with other days of the week is not implemented", -1); + } + if (exprOn == DAY_OF_WEEK && expr.indexOf('#') != -1 + && expr.indexOf('#', expr.indexOf('#') +1) != -1) { + throw new ParseException( + "Support for specifying multiple \"nth\" days is not implemented.", -1); + } + + StringTokenizer vTok = new StringTokenizer(expr, ","); + while (vTok.hasMoreTokens()) { + String v = vTok.nextToken(); + storeExpressionVals(0, v, exprOn); + } + + exprOn++; + } + + if (exprOn <= DAY_OF_WEEK) { + throw new ParseException("Unexpected end of expression.", expression.length()); + } + + if (exprOn <= YEAR) { + storeExpressionVals(0, "*", YEAR); + } + + TreeSet dow = getSet(DAY_OF_WEEK); + TreeSet dom = getSet(DAY_OF_MONTH); + + // Copying the logic from the UnsupportedOperationException below + boolean dayOfMSpec = !dom.contains(NO_SPEC); + boolean dayOfWSpec = !dow.contains(NO_SPEC); + + if ((!dayOfMSpec || dayOfWSpec) && (!dayOfWSpec || dayOfMSpec)) { + throw new ParseException( + "Support for specifying both a day-of-week AND a day-of-month" + + " parameter is not implemented.", 0); + } + } catch (ParseException pe) { + throw pe; + } catch (Exception e) { + throw new ParseException("Illegal cron expression format (" + e + ")", 0); + } + } + + private int storeExpressionVals(int pos, String s, int type) + throws ParseException { + + int incr = 0; + int i = skipWhiteSpace(pos, s); + if (i >= s.length()) { + return i; + } + char c = s.charAt(i); + if ((c >= 'A') && (c <= 'Z') && (!"L".equals(s)) && (!"LW".equals(s)) + && (!s.matches("^L-[0-9]*[W]?"))) { + String sub = s.substring(i, i + 3); + int sval; + int eval = -1; + if (type == MONTH) { + sval = getMonthNumber(sub) + 1; + if (sval <= 0) { + throw new ParseException("Invalid Month value: '" + sub + "'", i); + } + if (s.length() > i + 3) { + c = s.charAt(i + 3); + if (c == '-') { + i += 4; + sub = s.substring(i, i + 3); + eval = getMonthNumber(sub) + 1; + if (eval <= 0) { + throw new ParseException("Invalid Month value: '" + sub + "'", i); + } + } + } + } else if (type == DAY_OF_WEEK) { + sval = getDayOfWeekNumber(sub); + if (sval < 0) { + throw new ParseException("Invalid Day-of-Week value: '" + sub + "'", i); + } + if (s.length() > i + 3) { + c = s.charAt(i + 3); + if (c == '-') { + i += 4; + sub = s.substring(i, i + 3); + eval = getDayOfWeekNumber(sub); + if (eval < 0) { + throw new ParseException("Invalid Day-of-Week value: '" + sub + "'", i); + } + } else if (c == '#') { + try { + i += 4; + nthDayOfWeek = Integer.parseInt(s.substring(i)); + if (nthDayOfWeek < 1 || nthDayOfWeek > 5) { + throw new Exception(); + } + } catch (Exception e) { + throw new ParseException( + "A numeric value between 1 and 5 must follow the '#' option", i); + } + } else if (c == 'L') { + lastDayOfWeek = true; + i++; + } + } + + } else { + throw new ParseException("Illegal characters for this position: '" + sub + "'", i); + } + if (eval != -1) { + incr = 1; + } + addToSet(sval, eval, incr, type); + return (i + 3); + } + + if (c == '?') { + i++; + if ((i + 1) < s.length() + && (s.charAt(i) != ' ' && s.charAt(i + 1) != '\t')) { + throw new ParseException("Illegal character after '?': " + s.charAt(i), i); + } + if (type != DAY_OF_WEEK && type != DAY_OF_MONTH) { + throw new ParseException( + "'?' can only be specified for Day-of-Month or Day-of-Week.", i); + } + if ((type == DAY_OF_WEEK) && (!daysOfMonth.isEmpty() && daysOfMonth.last() == NO_SPEC_INT)) { + throw new ParseException("'?' can only be specified for Day-of-Month -OR- Day-of-Week.", i); + } + + addToSet(NO_SPEC_INT, -1, 0, type); + return i; + } + + if (c == '*' || c == '/') { + if (c == '*' && (i + 1) >= s.length()) { + addToSet(ALL_SPEC_INT, -1, incr, type); + return i + 1; + } else if (c == '/' + && ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s + .charAt(i + 1) == '\t')) { + throw new ParseException("'/' must be followed by an integer.", i); + } else if (c == '*') { + i++; + } + c = s.charAt(i); + if (c == '/') { // is an increment specified? + i++; + if (i >= s.length()) { + throw new ParseException("Unexpected end of string.", i); + } + + incr = getNumericValue(s, i); + + i++; + if (incr > 10) { + i++; + } + checkIncrementRange(incr, type, i); + } else { + incr = 1; + } + + addToSet(ALL_SPEC_INT, -1, incr, type); + return i; + } else if (c == 'L') { + i++; + if (type == DAY_OF_WEEK) { + addToSet(7, 7, 0, type); + } + if (type == DAY_OF_MONTH) { + int dom = LAST_DAY_OFFSET_END; + boolean nearestWeekday = false; + if (s.length() > i) { + c = s.charAt(i); + if (c == '-') { + ValueSet vs = getValue(0, s, i + 1); + int offset = vs.value; + if (offset > MAX_LAST_DAY_OFFSET) { + throw new ParseException( + "Offset from last day must be <= " + MAX_LAST_DAY_OFFSET, i + 1); + } + dom -= offset; + i = vs.pos; + } + if (s.length() > i) { + c = s.charAt(i); + if (c == 'W') { + nearestWeekday = true; + i++; + } + } + } + if (nearestWeekday) { + nearestWeekdays.add(dom); + } else { + daysOfMonth.add(dom); + } + } + return i; + } else if (c >= '0' && c <= '9') { + int val = Integer.parseInt(String.valueOf(c)); + i++; + if (i >= s.length()) { + addToSet(val, -1, -1, type); + } else { + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(val, s, i); + val = vs.value; + i = vs.pos; + } + i = checkNext(i, s, val, type); + return i; + } + } else { + throw new ParseException("Unexpected character: " + c, i); + } + + return i; + } + + private void checkIncrementRange(int incr, int type, int idxPos) throws ParseException { + if (incr > 59 && (type == SECOND || type == MINUTE)) { + throw new ParseException("Increment > 60 : " + incr, idxPos); + } else if (incr > 23 && (type == HOUR)) { + throw new ParseException("Increment > 24 : " + incr, idxPos); + } else if (incr > 31 && (type == DAY_OF_MONTH)) { + throw new ParseException("Increment > 31 : " + incr, idxPos); + } else if (incr > 7 && (type == DAY_OF_WEEK)) { + throw new ParseException("Increment > 7 : " + incr, idxPos); + } else if (incr > 12 && (type == MONTH)) { + throw new ParseException("Increment > 12 : " + incr, idxPos); + } + } + + private int checkNext(int pos, String s, int val, int type) + throws ParseException { + + int end = -1; + int i = pos; + + if (i >= s.length()) { + addToSet(val, end, -1, type); + return i; + } + + char c = s.charAt(pos); + + if (c == 'L') { + if (type == DAY_OF_WEEK) { + if(val < 1 || val > 7) + throw new ParseException("Day-of-Week values must be between 1 and 7", -1); + lastDayOfWeek = true; + } else { + throw new ParseException("'L' option is not valid here. (pos=" + i + ")", i); + } + TreeSet set = getSet(type); + set.add(val); + i++; + return i; + } + + if (c == 'W') { + if (type != DAY_OF_MONTH) { + throw new ParseException("'W' option is not valid here. (pos=" + i + ")", i); + } + if (val > 31) { + throw new ParseException("The 'W' option does not make sense with values larger than" + + " 31 (max number of days in a month)", i); + } + + nearestWeekdays.add(val); + i++; + return i; + } + + if (c == '#') { + if (type != DAY_OF_WEEK) { + throw new ParseException("'#' option is not valid here. (pos=" + i + ")", i); + } + i++; + try { + nthDayOfWeek = Integer.parseInt(s.substring(i)); + if (nthDayOfWeek < 1 || nthDayOfWeek > 5) { + throw new Exception(); + } + } catch (Exception e) { + throw new ParseException( + "A numeric value between 1 and 5 must follow the '#' option", + i); + } + + TreeSet set = getSet(type); + set.add(val); + i++; + return i; + } + + if (c == '-') { + i++; + c = s.charAt(i); + int v = Integer.parseInt(String.valueOf(c)); + end = v; + i++; + if (i >= s.length()) { + addToSet(val, end, 1, type); + return i; + } + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(v, s, i); + end = vs.value; + i = vs.pos; + } + if (i < s.length() && (s.charAt(i) == '/')) { + i++; + c = s.charAt(i); + int v2 = Integer.parseInt(String.valueOf(c)); + i++; + if (i >= s.length()) { + addToSet(val, end, v2, type); + return i; + } + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(v2, s, i); + int v3 = vs.value; + addToSet(val, end, v3, type); + i = vs.pos; + return i; + } else { + addToSet(val, end, v2, type); + return i; + } + } else { + addToSet(val, end, 1, type); + return i; + } + } + + if (c == '/') { + if ((i + 1) >= s.length() || s.charAt(i + 1) == ' ' || s.charAt(i + 1) == '\t') { + throw new ParseException("'/' must be followed by an integer.", i); + } + + i++; + c = s.charAt(i); + int v2 = Integer.parseInt(String.valueOf(c)); + i++; + if (i >= s.length()) { + checkIncrementRange(v2, type, i); + addToSet(val, end, v2, type); + return i; + } + c = s.charAt(i); + if (c >= '0' && c <= '9') { + ValueSet vs = getValue(v2, s, i); + int v3 = vs.value; + checkIncrementRange(v3, type, i); + addToSet(val, end, v3, type); + i = vs.pos; + return i; + } else { + throw new ParseException("Unexpected character '" + c + "' after '/'", i); + } + } + + addToSet(val, end, 0, type); + i++; + return i; + } + + public String getCronExpression() { + return cronExpression; + } + + private int skipWhiteSpace(int i, String s) { + for (; i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i++) { + } + + return i; + } + + private int findNextWhiteSpace(int i, String s) { + for (; i < s.length() && (s.charAt(i) != ' ' || s.charAt(i) != '\t'); i++) { + } + + return i; + } + + private void addToSet(int val, int end, int incr, int type) + throws ParseException { + + TreeSet set = getSet(type); + + if (type == SECOND || type == MINUTE) { + if ((val < 0 || val > 59 || end > 59) && (val != ALL_SPEC_INT)) { + throw new ParseException("Minute and Second values must be between 0 and 59", -1); + } + } else if (type == HOUR) { + if ((val < 0 || val > 23 || end > 23) && (val != ALL_SPEC_INT)) { + throw new ParseException("Hour values must be between 0 and 23", -1); + } + } else if (type == DAY_OF_MONTH) { + if ((val < 1 || val > 31 || end > 31) && (val != ALL_SPEC_INT) + && (val != NO_SPEC_INT)) { + throw new ParseException("Day of month values must be between 1 and 31", -1); + } + } else if (type == MONTH) { + if ((val < 1 || val > 12 || end > 12) && (val != ALL_SPEC_INT)) { + throw new ParseException("Month values must be between 1 and 12", -1); + } + } else if (type == DAY_OF_WEEK && ((val == 0 || val > 7 || end > 7) && (val != ALL_SPEC_INT) + && (val != NO_SPEC_INT))) { + throw new ParseException("Day-of-Week values must be between 1 and 7", -1); + } + + if ((incr == 0 || incr == -1) && val != ALL_SPEC_INT) { + if (val != -1) { + set.add(val); + } else { + set.add(NO_SPEC); + } + + return; + } + + int startAt = val; + int stopAt = end; + + if (val == ALL_SPEC_INT && incr <= 0) { + incr = 1; + set.add(ALL_SPEC); // put in a marker, but also fill values + } + + if (type == SECOND || type == MINUTE) { + if (stopAt == -1) { + stopAt = 59; + } + if (startAt == -1 || startAt == ALL_SPEC_INT) { + startAt = 0; + } + } else if (type == HOUR) { + if (stopAt == -1) { + stopAt = 23; + } + if (startAt == -1 || startAt == ALL_SPEC_INT) { + startAt = 0; + } + } else if (type == DAY_OF_MONTH) { + if (stopAt == -1) { + stopAt = 31; + } + if (startAt == -1 || startAt == ALL_SPEC_INT) { + startAt = 1; + } + } else if (type == MONTH) { + if (stopAt == -1) { + stopAt = 12; + } + if (startAt == -1 || startAt == ALL_SPEC_INT) { + startAt = 1; + } + } else if (type == DAY_OF_WEEK) { + if (stopAt == -1) { + stopAt = 7; + } + if (startAt == -1 || startAt == ALL_SPEC_INT) { + startAt = 1; + } + } else if (type == YEAR) { + if (stopAt == -1) { + stopAt = MAX_YEAR; + } + if (startAt == -1 || startAt == ALL_SPEC_INT) { + startAt = 1970; + } + } + + // if the end of the range is before the start, then we need to overflow into + // the next day, month etc. This is done by adding the maximum amount for that + // type, and using modulus max to determine the value being added. + int max = -1; + if (stopAt < startAt) { + switch (type) { + case SECOND: + case MINUTE: + max = 60; + break; + case HOUR: + max = 24; + break; + case MONTH: + max = 12; + break; + case DAY_OF_WEEK: + max = 7; + break; + case DAY_OF_MONTH: + max = 31; + break; + case YEAR: + throw new IllegalArgumentException("Start year must be less than stop year"); + default: + throw new IllegalArgumentException("Unexpected type encountered"); + } + stopAt += max; + } + + for (int i = startAt; i <= stopAt; i += incr) { + if (max == -1) { + // ie: there's no max to overflow over + set.add(i); + } else { + // take the modulus to get the real value + int i2 = i % max; + + // 1-indexed ranges should not include 0, and should include their max + if (i2 == 0 && (type == MONTH || type == DAY_OF_WEEK || type == DAY_OF_MONTH)) { + i2 = max; + } + + set.add(i2); + } + } + } + + TreeSet getSet(int type) { + switch (type) { + case SECOND: + return seconds; + case MINUTE: + return minutes; + case HOUR: + return hours; + case DAY_OF_MONTH: + return daysOfMonth; + case MONTH: + return months; + case DAY_OF_WEEK: + return daysOfWeek; + case YEAR: + return years; + default: + throw new IllegalArgumentException("Invalid type encountered: " + type); + } + } + + private ValueSet getValue(int v, String s, int i) { + char c = s.charAt(i); + StringBuilder s1 = new StringBuilder(String.valueOf(v)); + while (c >= '0' && c <= '9') { + s1.append(c); + i++; + if (i >= s.length()) { + break; + } + c = s.charAt(i); + } + ValueSet val = new ValueSet(); + + val.pos = (i < s.length()) ? i : i + 1; + val.value = Integer.parseInt(s1.toString()); + return val; + } + + private int getNumericValue(String s, int i) { + int endOfVal = findNextWhiteSpace(i, s); + String val = s.substring(i, endOfVal); + return Integer.parseInt(val); + } + + private int getMonthNumber(String s) { + Integer integer = monthMap.get(s); + + if (integer == null) { + return -1; + } + + return integer; + } + + private int getDayOfWeekNumber(String s) { + Integer integer = dayMap.get(s); + + if (integer == null) { + return -1; + } + + return integer; + } + + + public Date getTimeAfter(Date afterTime) { + + // Computation is based on Gregorian year only. + Calendar cl = new java.util.GregorianCalendar(getTimeZone()); + + // move ahead one second, since we're computing the time *after* the + // given time + afterTime = new Date(afterTime.getTime() + 1000); + // CronTrigger does not deal with milliseconds + cl.setTime(afterTime); + cl.set(Calendar.MILLISECOND, 0); + + boolean gotOne = false; + // loop until we've computed the next time, or we've past the endTime + while (!gotOne) { + + + if(cl.get(Calendar.YEAR) > 2999) { // prevent endless loop... + return null; + } + + + int sec = cl.get(Calendar.SECOND); + int min = cl.get(Calendar.MINUTE); + + // get second................................................. + SortedSet st = seconds.tailSet(sec); + if (!st.isEmpty()) { + sec = st.first(); + } else { + sec = seconds.first(); + min++; + cl.set(Calendar.MINUTE, min); + } + cl.set(Calendar.SECOND, sec); + + min = cl.get(Calendar.MINUTE); + int hr = cl.get(Calendar.HOUR_OF_DAY); + int t = -1; + + // get minute................................................. + st = minutes.tailSet(min); + if (!st.isEmpty()) { + t = min; + min = st.first(); + } else { + min = minutes.first(); + hr++; + } + if (min != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, min); + setCalendarHour(cl, hr); + continue; + } + cl.set(Calendar.MINUTE, min); + + hr = cl.get(Calendar.HOUR_OF_DAY); + int day = cl.get(Calendar.DAY_OF_MONTH); + t = -1; + + // get hour................................................... + st = hours.tailSet(hr); + if (!st.isEmpty()) { + t = hr; + hr = st.first(); + } else { + hr = hours.first(); + day++; + } + if (hr != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + setCalendarHour(cl, hr); + continue; + } + cl.set(Calendar.HOUR_OF_DAY, hr); + + day = cl.get(Calendar.DAY_OF_MONTH); + int mon = cl.get(Calendar.MONTH) + 1; + // '+ 1' because calendar is 0-based for this field, and we are + // 1-based + int tmon = mon; + + // get day................................................... + boolean dayOfMSpec = !daysOfMonth.contains(NO_SPEC); + boolean dayOfWSpec = !daysOfWeek.contains(NO_SPEC); + if (dayOfMSpec && !dayOfWSpec) { // get day by day of month rule + final Optional smallestDay = findSmallestDay(day, mon, cl.get(Calendar.YEAR), + daysOfMonth); + Optional smallestDayForWeekday = findSmallestDay(day, mon, cl.get(Calendar.YEAR), + nearestWeekdays); + t = day; + day = -1; + if (smallestDayForWeekday.isPresent()) { + day = smallestDayForWeekday.get(); + + java.util.Calendar tcal = java.util.Calendar.getInstance(getTimeZone()); + tcal.set(Calendar.SECOND, 0); + tcal.set(Calendar.MINUTE, 0); + tcal.set(Calendar.HOUR_OF_DAY, 0); + tcal.set(Calendar.DAY_OF_MONTH, day); + tcal.set(Calendar.MONTH, mon - 1); + tcal.set(Calendar.YEAR, cl.get(Calendar.YEAR)); + + int ldom = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + int dow = tcal.get(Calendar.DAY_OF_WEEK); + + if (dow == Calendar.SATURDAY && day == 1) { + day += 2; + } else if (dow == Calendar.SATURDAY) { + day -= 1; + } else if (dow == Calendar.SUNDAY && day == ldom) { + day -= 2; + } else if (dow == Calendar.SUNDAY) { + day += 1; + } + + + tcal.set(Calendar.SECOND, sec); + tcal.set(Calendar.MINUTE, min); + tcal.set(Calendar.HOUR_OF_DAY, hr); + tcal.set(Calendar.DAY_OF_MONTH, day); + tcal.set(Calendar.MONTH, mon - 1); + Date nTime = tcal.getTime(); + if (nTime.before(afterTime)) { + day = -1; + } + } + if (smallestDay.isPresent()) { + if (day == -1 || smallestDay.get() < day) { + day = smallestDay.get(); + } + } else if (day == -1) { + day = 1; + mon++; + } + if (day != t || mon != tmon) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, and we + // are 1-based + continue; + } + } else if (dayOfWSpec && !dayOfMSpec) { // get day by day of week rule + if (lastDayOfWeek) { // are we looking for the last XXX day of + // the month? + int dow = daysOfWeek.first(); // desired + // d-o-w + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int daysToAdd = 0; + if (cDow < dow) { + daysToAdd = dow - cDow; + } + if (cDow > dow) { + daysToAdd = dow + (7 - cDow); + } + + int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + + if (day + daysToAdd > lDay) { // did we already miss the + // last one? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); + // no '- 1' here because we are promoting the month + continue; + } + + // find date of last occurrence of this day in this month... + while ((day + daysToAdd + 7) <= lDay) { + daysToAdd += 7; + } + + day += daysToAdd; + + if (daysToAdd > 0) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' here because we are not promoting the month + continue; + } + + } else if (nthDayOfWeek != 0) { + // are we looking for the Nth XXX day in the month? + int dow = daysOfWeek.first(); // desired + // d-o-w + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int daysToAdd = 0; + if (cDow < dow) { + daysToAdd = dow - cDow; + } else if (cDow > dow) { + daysToAdd = dow + (7 - cDow); + } + + final boolean dayShifted = daysToAdd > 0; + + day += daysToAdd; + int weekOfMonth = day / 7; + if (day % 7 > 0) { + weekOfMonth++; + } + + daysToAdd = (nthDayOfWeek - weekOfMonth) * 7; + day += daysToAdd; + if (daysToAdd < 0 + || day > getLastDayOfMonth(mon, cl + .get(Calendar.YEAR))) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); + // no '- 1' here because we are promoting the month + continue; + } else if (daysToAdd > 0 || dayShifted) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' here because we are NOT promoting the month + continue; + } + } else { + int cDow = cl.get(Calendar.DAY_OF_WEEK); // current d-o-w + int dow = daysOfWeek.first(); // desired + // d-o-w + st = daysOfWeek.tailSet(cDow); + if (!st.isEmpty()) { + dow = st.first(); + } + + int daysToAdd = 0; + if (cDow < dow) { + daysToAdd = dow - cDow; + } + if (cDow > dow) { + daysToAdd = dow + (7 - cDow); + } + + int lDay = getLastDayOfMonth(mon, cl.get(Calendar.YEAR)); + + if (day + daysToAdd > lDay) { // will we pass the end of + // the month? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon); + // no '- 1' here because we are promoting the month + continue; + } else if (daysToAdd > 0) { // are we switching days? + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, day + daysToAdd); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, + // and we are 1-based + continue; + } + } + } else { // dayOfWSpec && !dayOfMSpec + throw new UnsupportedOperationException( + "Support for specifying both a day-of-week" + + " AND a day-of-month parameter is not implemented."); + } + cl.set(Calendar.DAY_OF_MONTH, day); + + mon = cl.get(Calendar.MONTH) + 1; + // '+ 1' because calendar is 0-based for this field, and we are + // 1-based + int year = cl.get(Calendar.YEAR); + t = -1; + + // test for expressions that never generate a valid fire date, + // but keep looping... + if (year > MAX_YEAR) { + return null; + } + + // get month................................................... + st = months.tailSet(mon); + if (!st.isEmpty()) { + t = mon; + mon = st.first(); + } else { + mon = months.first(); + year++; + } + if (mon != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, and we are + // 1-based + cl.set(Calendar.YEAR, year); + continue; + } + cl.set(Calendar.MONTH, mon - 1); + // '- 1' because calendar is 0-based for this field, and we are + // 1-based + + year = cl.get(Calendar.YEAR); + + // get year................................................... + st = years.tailSet(year); + if (!st.isEmpty()) { + t = year; + year = st.first(); + } else { + return null; // ran out of years... + } + + if (year != t) { + cl.set(Calendar.SECOND, 0); + cl.set(Calendar.MINUTE, 0); + cl.set(Calendar.HOUR_OF_DAY, 0); + cl.set(Calendar.DAY_OF_MONTH, 1); + cl.set(Calendar.MONTH, 0); + // '- 1' because calendar is 0-based for this field, and we are + // 1-based + cl.set(Calendar.YEAR, year); + continue; + } + cl.set(Calendar.YEAR, year); + + gotOne = true; + } + + return cl.getTime(); + } + + /** + * Advance the calendar to the particular hour paying particular attention + * to daylight saving problems. + * + * @param cal the calendar to operate on + * @param hour the hour to set + */ + private void setCalendarHour(Calendar cal, int hour) { + cal.set(java.util.Calendar.HOUR_OF_DAY, hour); + if (cal.get(java.util.Calendar.HOUR_OF_DAY) != hour && hour != 24) { + cal.set(java.util.Calendar.HOUR_OF_DAY, hour + 1); + } + } + + private boolean isLeapYear(int year) { + return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); + } + + private int getLastDayOfMonth(int monthNum, int year) { + switch (monthNum) { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + return 31; + case 2: + return (isLeapYear(year)) ? 29 : 28; + case 4: + case 6: + case 9: + case 11: + return 30; + default: + throw new IllegalArgumentException("Illegal month number: " + + monthNum); + } + } + + + private Optional findSmallestDay(int day, int mon, int year, TreeSet set) { + if (set.isEmpty()) { + return Optional.empty(); + } + + final int lastDay = getLastDayOfMonth(mon, year); + // For "L", "L-1", etc. + int smallestDay = Optional.ofNullable(set.ceiling(LAST_DAY_OFFSET_END - (lastDay - day))) + .map(d -> d - LAST_DAY_OFFSET_START + 1) + .orElse(Integer.MAX_VALUE); + + // For "1", "2", etc. + SortedSet st = set.subSet(day, LAST_DAY_OFFSET_START); + // make sure we don't over-run a short month, such as february + if (!st.isEmpty() && st.first() < smallestDay && st.first() <= lastDay) { + smallestDay = st.first(); + } + + return smallestDay == Integer.MAX_VALUE ? Optional.empty() : Optional.of(smallestDay); + } + } diff --git a/common/src/main/java/org/tron/common/cron/ValueSet.java b/common/src/main/java/org/tron/common/cron/ValueSet.java new file mode 100644 index 00000000000..e8ffa73b1e2 --- /dev/null +++ b/common/src/main/java/org/tron/common/cron/ValueSet.java @@ -0,0 +1,7 @@ +package org.tron.common.cron; + +class ValueSet { + protected int value; + + protected int pos; +} diff --git a/common/src/main/java/org/tron/common/es/ExecutorServiceManager.java b/common/src/main/java/org/tron/common/es/ExecutorServiceManager.java new file mode 100644 index 00000000000..779a8edf75d --- /dev/null +++ b/common/src/main/java/org/tron/common/es/ExecutorServiceManager.java @@ -0,0 +1,112 @@ +package org.tron.common.es; + +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.exit.ExitManager; + +@Slf4j(topic = "common-executor") +public class ExecutorServiceManager { + + public static ExecutorService newSingleThreadExecutor(String name) { + return newSingleThreadExecutor(name, false); + } + + public static ExecutorService newSingleThreadExecutor(String name, boolean isDaemon) { + return Executors.newSingleThreadExecutor( + new ThreadFactoryBuilder().setNameFormat(name).setDaemon(isDaemon).build()); + } + + + public static ScheduledExecutorService newSingleThreadScheduledExecutor(String name) { + return newSingleThreadScheduledExecutor(name, false); + } + + public static ScheduledExecutorService newSingleThreadScheduledExecutor(String name, + boolean isDaemon) { + return Executors.newSingleThreadScheduledExecutor( + new ThreadFactoryBuilder().setNameFormat(name).setDaemon(isDaemon).build()); + } + + public static ExecutorService newFixedThreadPool(String name, int fixThreads) { + return newFixedThreadPool(name, fixThreads, false); + } + + public static ExecutorService newFixedThreadPool(String name, int fixThreads, boolean isDaemon) { + return Executors.newFixedThreadPool(fixThreads, + new ThreadFactoryBuilder().setNameFormat(name + "-%d").setDaemon(isDaemon).build()); + } + + public static ExecutorService newThreadPoolExecutor(int corePoolSize, int maximumPoolSize, + long keepAliveTime, TimeUnit unit, + BlockingQueue workQueue, + String name) { + return newThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, + name, false); + } + + public static ExecutorService newThreadPoolExecutor(int corePoolSize, int maximumPoolSize, + long keepAliveTime, TimeUnit unit, + BlockingQueue workQueue, + String name, boolean isDaemon) { + return new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, + new ThreadFactoryBuilder().setNameFormat(name + "-%d").setDaemon(isDaemon).build()); + } + + public static void shutdownAndAwaitTermination(ExecutorService pool, String name) { + if (pool == null) { + return; + } + logger.info("Pool {} shutdown...", name); + pool.shutdown(); // Disable new tasks from being submitted + try { + // Wait a while for existing tasks to terminate + if (!pool.awaitTermination(60, java.util.concurrent.TimeUnit.SECONDS)) { + pool.shutdownNow(); // Cancel currently executing tasks + // Wait a while for tasks to respond to being cancelled + if (!pool.awaitTermination(60, java.util.concurrent.TimeUnit.SECONDS)) { + logger.warn("Pool {} did not terminate", name); + } + } + } catch (InterruptedException ie) { + // (Re-)Cancel if current thread also interrupted + pool.shutdownNow(); + // Preserve interrupt status + Thread.currentThread().interrupt(); + } + logger.info("Pool {} shutdown done", name); + } + + public static Future submit(ExecutorService es, Runnable task) { + return es.submit(() -> { + try { + task.run(); + } catch (Throwable e) { + ExitManager.findTronError(e).ifPresent(ExitManager::logAndExit); + throw e; + } + }); + } + + public static ScheduledFuture scheduleWithFixedDelay(ScheduledExecutorService es, + Runnable command, + long initialDelay, + long delay, + TimeUnit unit) { + return es.scheduleWithFixedDelay(() -> { + try { + command.run(); + } catch (Throwable e) { + ExitManager.findTronError(e).ifPresent(ExitManager::logAndExit); + throw e; + } + }, initialDelay, delay, unit); + } +} diff --git a/common/src/main/java/org/tron/common/exit/ExitManager.java b/common/src/main/java/org/tron/common/exit/ExitManager.java new file mode 100644 index 00000000000..d80b7838c08 --- /dev/null +++ b/common/src/main/java/org/tron/common/exit/ExitManager.java @@ -0,0 +1,53 @@ +package org.tron.common.exit; + +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.ThreadFactory; +import lombok.extern.slf4j.Slf4j; +import org.tron.core.exception.TronError; + +@Slf4j(topic = "Exit") +public class ExitManager { + + private static final ThreadFactory exitThreadFactory = r -> { + Thread thread = new Thread(r, "System-Exit-Thread"); + thread.setDaemon(true); + return thread; + }; + + private ExitManager() { + + } + + public static void initExceptionHandler() { + Thread.setDefaultUncaughtExceptionHandler((t, e) -> { + findTronError(e).ifPresent(ExitManager::logAndExit); + logger.error("Uncaught exception", e); + }); + } + + public static Optional findTronError(Throwable e) { + if (e == null) { + return Optional.empty(); + } + + Set seen = new HashSet<>(); + + while (e != null && !seen.contains(e)) { + if (e instanceof TronError) { + return Optional.of((TronError) e); + } + seen.add(e); + e = e.getCause(); + } + return Optional.empty(); + } + + public static void logAndExit(TronError exit) { + final int code = exit.getErrCode().getCode(); + logger.error("Shutting down with code: {}.", exit.getErrCode(), exit); + Thread exitThread = exitThreadFactory.newThread(() -> System.exit(code)); + exitThread.start(); + } +} \ No newline at end of file diff --git a/common/src/main/java/org/tron/common/log/LogService.java b/common/src/main/java/org/tron/common/log/LogService.java new file mode 100644 index 00000000000..801e13f54f7 --- /dev/null +++ b/common/src/main/java/org/tron/common/log/LogService.java @@ -0,0 +1,26 @@ +package org.tron.common.log; + +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.joran.JoranConfigurator; +import java.io.File; +import org.slf4j.LoggerFactory; +import org.tron.core.exception.TronError; + +public class LogService { + + public static void load(String path) { + try { + File file = new File(path); + if (!file.exists() || !file.isFile() || !file.canRead()) { + return; + } + LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); + JoranConfigurator configurator = new JoranConfigurator(); + configurator.setContext(lc); + lc.reset(); + configurator.doConfigure(file); + } catch (Exception e) { + throw new TronError(e, TronError.ErrCode.LOG_LOAD); + } + } +} diff --git a/common/src/main/java/org/tron/common/log/layout/DesensitizedConverter.java b/common/src/main/java/org/tron/common/log/layout/DesensitizedConverter.java new file mode 100644 index 00000000000..2777d6ba283 --- /dev/null +++ b/common/src/main/java/org/tron/common/log/layout/DesensitizedConverter.java @@ -0,0 +1,49 @@ +package org.tron.common.log.layout; + +import ch.qos.logback.classic.pattern.ClassicConverter; +import ch.qos.logback.classic.spi.ILoggingEvent; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.parameter.CommonParameter; + +@Slf4j(topic = "Parser") +public class DesensitizedConverter extends ClassicConverter { + + private static final int SENSITIVE_WORD_SIZE = 1_000; + + private static final Pattern pattern = Pattern.compile( + "(((25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(25[0-5]|2[0-4]\\d|((1\\d{2})|" + + "([1-9]?\\d))))"); + + private static final Cache sensitiveCache = CacheBuilder.newBuilder() + .maximumSize(SENSITIVE_WORD_SIZE) + .recordStats().build(); + + public static void addSensitive(String key, String value) { + sensitiveCache.put(key, value); + } + + private String desensitization(String content) { + Matcher matcher = pattern.matcher(content); + while (matcher.find()) { + String key = matcher.group(); + String value = sensitiveCache.getIfPresent(key); + if (value != null) { + content = content.replaceAll(key, value); + } else { + content = content.replaceAll(key, "IP"); + } + } + + return content; + } + + @Override + public String convert(ILoggingEvent iLoggingEvent) { + String source = iLoggingEvent.getFormattedMessage(); + return CommonParameter.getInstance().isFastForward() ? desensitization(source) : source; + } +} diff --git a/common/src/main/java/org/tron/common/log/layout/MultiLayoutPattern.java b/common/src/main/java/org/tron/common/log/layout/MultiLayoutPattern.java new file mode 100644 index 00000000000..9fde78c1a7b --- /dev/null +++ b/common/src/main/java/org/tron/common/log/layout/MultiLayoutPattern.java @@ -0,0 +1,106 @@ +package org.tron.common.log.layout; + +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.encoder.PatternLayoutEncoder; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.Context; +import ch.qos.logback.core.Layout; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class MultiLayoutPattern extends PatternLayoutEncoder { + private List rules = new ArrayList<>(); + private Map> layoutMap = new HashMap<>(); + + public void addRule(Rule rule) { + this.rules.add(rule); + rule.start(context); + } + + public byte[] encode(ILoggingEvent event) { + Layout layout = getLayout(event.getLoggerName()); + String txt = layout.doLayout(event); + return convertToBytes(txt); + } + + private byte[] convertToBytes(String s) { + Charset charset = getCharset(); + if (charset == null) { + return s.getBytes(); + } else { + return s.getBytes(charset); + } + } + + private Layout getLayout(final String name) { + if (name == null) { + throw new IllegalArgumentException("name cannot be null"); + } + if (Logger.ROOT_LOGGER_NAME.equalsIgnoreCase(name)) { + return this.getLayout(); + } + if (layoutMap.containsKey(name)) { + return layoutMap.get(name); + } + Layout layout = getLayout(); + for (Rule rule : rules) { + if (rule.logger.equals(name)) { + layout = rule.getPatternLayoutEncoder().getLayout(); + break; + } + } + layoutMap.put(name, layout); + return layout; + } + + @Override + public void start() { + super.start(); + } + + public static class Rule { + private String logger; + private String pattern; + private PatternLayoutEncoder patternLayoutEncoder; + private boolean outputPatternAsHeader = false; + + public String getLogger() { + return logger; + } + + public void setLogger(String logger) { + this.logger = logger; + } + + public String getPattern() { + return pattern; + } + + public void setPattern(String pattern) { + this.pattern = pattern; + } + + public boolean isOutputPatternAsHeader() { + return outputPatternAsHeader; + } + + public void setOutputPatternAsHeader(boolean outputPatternAsHeader) { + this.outputPatternAsHeader = outputPatternAsHeader; + } + + public PatternLayoutEncoder getPatternLayoutEncoder() { + return patternLayoutEncoder; + } + + public void start(Context context) { + patternLayoutEncoder = new PatternLayoutEncoder(); + patternLayoutEncoder.setPattern(pattern); + patternLayoutEncoder.setContext(context); + patternLayoutEncoder.setOutputPatternAsHeader(outputPatternAsHeader); + patternLayoutEncoder.start(); + } + } +} \ No newline at end of file diff --git a/common/src/main/java/org/tron/common/logsfilter/EventPluginConfig.java b/common/src/main/java/org/tron/common/logsfilter/EventPluginConfig.java index 050499b6123..e2aa0950d72 100644 --- a/common/src/main/java/org/tron/common/logsfilter/EventPluginConfig.java +++ b/common/src/main/java/org/tron/common/logsfilter/EventPluginConfig.java @@ -15,6 +15,14 @@ public class EventPluginConfig { public static final String SOLIDITY_EVENT_NAME = "solidityevent"; public static final String SOLIDITY_LOG_NAME = "soliditylog"; + @Getter + @Setter + private int version; + + @Getter + @Setter + private long startSyncBlockNum; + @Getter @Setter private String pluginPath; diff --git a/common/src/main/java/org/tron/common/logsfilter/trigger/BlockLogTrigger.java b/common/src/main/java/org/tron/common/logsfilter/trigger/BlockLogTrigger.java index 5e64c5a1050..b878597045d 100644 --- a/common/src/main/java/org/tron/common/logsfilter/trigger/BlockLogTrigger.java +++ b/common/src/main/java/org/tron/common/logsfilter/trigger/BlockLogTrigger.java @@ -34,7 +34,7 @@ public BlockLogTrigger() { @Override public String toString() { return new StringBuilder().append("triggerName: ").append(getTriggerName()) - .append("timestamp: ") + .append(", timestamp: ") .append(timeStamp) .append(", blockNumber: ") .append(blockNumber) diff --git a/common/src/main/java/org/tron/common/logsfilter/trigger/SolidityTrigger.java b/common/src/main/java/org/tron/common/logsfilter/trigger/SolidityTrigger.java index d9745f4724a..230544a91ff 100644 --- a/common/src/main/java/org/tron/common/logsfilter/trigger/SolidityTrigger.java +++ b/common/src/main/java/org/tron/common/logsfilter/trigger/SolidityTrigger.java @@ -16,7 +16,7 @@ public SolidityTrigger() { @Override public String toString() { return new StringBuilder().append("triggerName: ").append(getTriggerName()) - .append("timestamp: ") + .append(", timestamp: ") .append(timeStamp) .append(", latestSolidifiedBlockNumber: ") .append(latestSolidifiedBlockNumber).toString(); diff --git a/common/src/main/java/org/tron/common/logsfilter/trigger/TransactionLogTrigger.java b/common/src/main/java/org/tron/common/logsfilter/trigger/TransactionLogTrigger.java index dec4170efb8..a4fb1fddb79 100644 --- a/common/src/main/java/org/tron/common/logsfilter/trigger/TransactionLogTrigger.java +++ b/common/src/main/java/org/tron/common/logsfilter/trigger/TransactionLogTrigger.java @@ -1,6 +1,8 @@ package org.tron.common.logsfilter.trigger; import java.util.List; +import java.util.Map; + import lombok.Getter; import lombok.Setter; @@ -91,6 +93,10 @@ public class TransactionLogTrigger extends Trigger { @Setter private long energyUnitPrice; + @Getter + @Setter + private Map extMap; + public TransactionLogTrigger() { setTriggerName(Trigger.TRANSACTION_TRIGGER_NAME); } diff --git a/common/src/main/java/org/tron/common/math/MathWrapper.java b/common/src/main/java/org/tron/common/math/MathWrapper.java new file mode 100644 index 00000000000..758a0f18370 --- /dev/null +++ b/common/src/main/java/org/tron/common/math/MathWrapper.java @@ -0,0 +1,78 @@ +package org.tron.common.math; + +/** + * This class is deprecated and should not be used in new code, + * for cross-platform consistency, please use {@link StrictMathWrapper} instead, + * especially for floating-point calculations. + */ +@Deprecated +public class MathWrapper { + + public static double pow(double a, double b) { + return Math.pow(a, b); + } + + public static long addExact(long x, long y) { + return Math.addExact(x, y); + } + + public static int addExact(int x, int y) { + return Math.addExact(x, y); + } + + public static long floorDiv(long x, long y) { + return Math.floorDiv(x, y); + } + + public static int multiplyExact(int x, int y) { + return Math.multiplyExact(x, y); + } + + public static long multiplyExact(long x, long y) { + return Math.multiplyExact(x, y); + } + + public static long subtractExact(long x, long y) { + return Math.subtractExact(x, y); + } + + public static int min(int a, int b) { + return Math.min(a, b); + } + + public static long min(long a, long b) { + return Math.min(a, b); + } + + public static int max(int a, int b) { + return Math.max(a, b); + } + + public static long max(long a, long b) { + return Math.max(a, b); + } + + public static int round(float a) { + return Math.round(a); + } + + public static long round(double a) { + return Math.round(a); + } + + public static double ceil(double a) { + return Math.ceil(a); + } + + public static double signum(double a) { + return Math.signum(a); + } + + public static double random() { + return Math.random(); + } + + public static long abs(long a) { + return Math.abs(a); + } +} diff --git a/common/src/main/java/org/tron/common/math/Maths.java b/common/src/main/java/org/tron/common/math/Maths.java new file mode 100644 index 00000000000..f0503cee2e4 --- /dev/null +++ b/common/src/main/java/org/tron/common/math/Maths.java @@ -0,0 +1,92 @@ +package org.tron.common.math; + +/** + * This class is deprecated and should not be used in new code, + * for cross-platform consistency, please use {@link StrictMathWrapper} instead, + * especially for floating-point calculations. + */ +@Deprecated +public class Maths { + + /** + * Returns the value of the first argument raised to the power of the second argument. + * @param a the base. + * @param b the exponent. + * @return the value {@code a}{@code b}. + */ + public static double pow(double a, double b, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.pow(a, b) : MathWrapper.pow(a, b); + } + + /** + * Adds two integers together, checking for overflow. + * @param x the first value. + * @param y the second value. + * @return the sum of {@code x} and {@code y}. + * @throws ArithmeticException if the result overflows an int. + */ + public static long addExact(long x, long y, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.addExact(x, y) : MathWrapper.addExact(x, y); + } + + public static int addExact(int x, int y, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.addExact(x, y) : MathWrapper.addExact(x, y); + } + + public static long floorDiv(long x, long y, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.floorDiv(x, y) : MathWrapper.floorDiv(x, y); + } + + public static int multiplyExact(int x, int y, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.multiplyExact(x, y) : MathWrapper.multiplyExact(x, y); + } + + public static long multiplyExact(long x, long y, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.multiplyExact(x, y) : MathWrapper.multiplyExact(x, y); + } + + public static long subtractExact(long x, long y, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.subtractExact(x, y) : MathWrapper.subtractExact(x, y); + } + + public static int min(int a, int b, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.min(a, b) : MathWrapper.min(a, b); + } + + public static long min(long a, long b, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.min(a, b) : MathWrapper.min(a, b); + } + + public static int max(int a, int b, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.max(a, b) : MathWrapper.max(a, b); + } + + public static long max(long a, long b, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.max(a, b) : MathWrapper.max(a, b); + } + + public static int round(float a, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.round(a) : MathWrapper.round(a); + } + + public static long round(double a, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.round(a) : MathWrapper.round(a); + } + + public static double ceil(double a, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.ceil(a) : MathWrapper.ceil(a); + } + + public static double signum(double a, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.signum(a) : MathWrapper.signum(a); + } + + public static double random(boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.random() : MathWrapper.random(); + } + + public static long abs(long a, boolean useStrictMath) { + return useStrictMath ? StrictMathWrapper.abs(a) : MathWrapper.abs(a); + } + +} diff --git a/common/src/main/java/org/tron/common/math/StrictMathWrapper.java b/common/src/main/java/org/tron/common/math/StrictMathWrapper.java new file mode 100644 index 00000000000..6a4d9c4e1a6 --- /dev/null +++ b/common/src/main/java/org/tron/common/math/StrictMathWrapper.java @@ -0,0 +1,144 @@ +package org.tron.common.math; + +public class StrictMathWrapper { + + public static double pow(double a, double b) { + return StrictMath.pow(a, b); + } + + /** + * *** methods are same as {@link java.lang.Math} methods, guaranteed by the call start *** + */ + + /** + * finally calls {@link java.lang.Math#addExact(long, long)} + */ + + public static long addExact(long x, long y) { + return StrictMath.addExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#addExact(int, int)} + */ + + public static int addExact(int x, int y) { + return StrictMath.addExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#subtractExact(long, long)} + */ + + public static long subtractExact(long x, long y) { + return StrictMath.subtractExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#floorMod(long, long)} + */ + public static long multiplyExact(long x, long y) { + return StrictMath.multiplyExact(x, y); + } + + public static long multiplyExact(long x, int y) { + return multiplyExact(x, (long) y); + } + + public static int multiplyExact(int x, int y) { + return StrictMath.multiplyExact(x, y); + } + + /** + * finally calls {@link java.lang.Math#floorDiv(long, long)} + */ + public static long floorDiv(long x, long y) { + return StrictMath.floorDiv(x, y); + } + + public static long floorDiv(long x, int y) { + return floorDiv(x, (long) y); + } + + /** + * finally calls {@link java.lang.Math#min(int, int)} + */ + public static int min(int a, int b) { + return StrictMath.min(a, b); + } + + /** + * finally calls {@link java.lang.Math#min(long, long)} + */ + public static long min(long a, long b) { + return StrictMath.min(a, b); + } + + /** + * finally calls {@link java.lang.Math#max(int, int)} + */ + public static int max(int a, int b) { + return StrictMath.max(a, b); + } + + /** + * finally calls {@link java.lang.Math#max(long, long)} + */ + public static long max(long a, long b) { + return StrictMath.max(a, b); + } + + /** + * finally calls {@link java.lang.Math#round(float)} + */ + public static int round(float a) { + return StrictMath.round(a); + } + + /** + * finally calls {@link java.lang.Math#round(double)} + */ + public static long round(double a) { + return StrictMath.round(a); + } + + /** + * finally calls {@link java.lang.Math#signum(double)} + */ + public static double signum(double d) { + return StrictMath.signum(d); + } + + /** + * finally calls {@link java.lang.Math#signum(float)} + */ + public static long abs(long a) { + return StrictMath.abs(a); + } + + /** + * *** methods are same as {@link java.lang.Math} methods, guaranteed by the call end *** + */ + + /** + * *** methods are same as {@link java.lang.Math} methods by mathematical algorithms*** + * / + + + /** + * mathematical integer: ceil(i) = floor(i) = i + * @return the smallest (closest to negative infinity) double value that is greater + * than or equal to the argument and is equal to a mathematical integer. + */ + public static double ceil(double a) { + return StrictMath.ceil(a); + } + + /** + * *** methods are no matters *** + */ + public static double random() { + return StrictMath.random(); + } + +} diff --git a/common/src/main/java/org/tron/common/overlay/discover/node/Node.java b/common/src/main/java/org/tron/common/overlay/discover/node/Node.java deleted file mode 100644 index 9115b9c9414..00000000000 --- a/common/src/main/java/org/tron/common/overlay/discover/node/Node.java +++ /dev/null @@ -1,135 +0,0 @@ -package org.tron.common.overlay.discover.node; - -import java.io.Serializable; -import java.util.Random; -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.common.utils.ByteArray; -import org.tron.common.utils.Utils; - -@Slf4j(topic = "discover") -public class Node implements Serializable { - - private static final long serialVersionUID = -4267600517925770636L; - - private byte[] id; - - private String host; - - private int port; - - @Getter - private int bindPort; - - @Setter - private int p2pVersion; - - private boolean isFakeNodeId = false; - - public Node(byte[] id, String host, int port) { - this.id = id; - this.host = host; - this.port = port; - this.isFakeNodeId = true; - } - - public Node(byte[] id, String host, int port, int bindPort) { - this.id = id; - this.host = host; - this.port = port; - this.bindPort = bindPort; - } - - public static Node instanceOf(String hostPort) { - try { - String[] sz = hostPort.split(":"); - int port = Integer.parseInt(sz[1]); - return new Node(Node.getNodeId(), sz[0], port); - } catch (Exception e) { - logger.error("Parse node failed, {}", hostPort); - throw e; - } - } - - public static byte[] getNodeId() { - int NODE_ID_LENGTH = 64; - Random gen = new Random(); - byte[] id = new byte[NODE_ID_LENGTH]; - gen.nextBytes(id); - return id; - } - - public boolean isConnectible(int argsP2PVersion) { - return port == bindPort && p2pVersion == argsP2PVersion; - } - - public String getHexId() { - return Hex.toHexString(id); - } - - public String getHexIdShort() { - return Utils.getIdShort(getHexId()); - } - - public boolean isDiscoveryNode() { - return isFakeNodeId; - } - - public byte[] getId() { - return id; - } - - public void setId(byte[] id) { - this.id = id; - } - - public String getHost() { - return host; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public String getIdString() { - if (id == null) { - return null; - } - return new String(id); - } - - @Override - public String toString() { - return "Node{" + " host='" + host + '\'' + ", port=" + port - + ", id=" + ByteArray.toHexString(id) + '}'; - } - - @Override - public int hashCode() { - return this.toString().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; - } -} 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 f105eb6402d..45893970fb0 100644 --- a/common/src/main/java/org/tron/common/parameter/CommonParameter.java +++ b/common/src/main/java/org/tron/common/parameter/CommonParameter.java @@ -1,6 +1,8 @@ package org.tron.common.parameter; import com.beust.jcommander.Parameter; +import java.net.InetAddress; +import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -8,14 +10,16 @@ import lombok.Setter; import org.tron.common.args.GenesisBlock; import org.tron.common.config.DbBackupConfig; +import org.tron.common.cron.CronExpression; import org.tron.common.logsfilter.EventPluginConfig; import org.tron.common.logsfilter.FilterQuery; -import org.tron.common.overlay.discover.node.Node; import org.tron.common.setting.RocksDbSettings; import org.tron.core.Constant; import org.tron.core.config.args.Overlay; import org.tron.core.config.args.SeedNode; import org.tron.core.config.args.Storage; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.dns.update.PublishConfig; public class CommonParameter { @@ -24,53 +28,83 @@ public class CommonParameter { public static CommonParameter PARAMETER = new CommonParameter(); @Setter public static boolean ENERGY_LIMIT_HARD_FORK = false; - @Parameter(names = {"-c", "--config"}, description = "Config File") + @Getter + @Parameter(names = {"-c", "--config"}, description = "Config file (default:config.conf)") public String shellConfFileName = ""; @Getter - @Parameter(names = {"-d", "--output-directory"}, description = "Directory") + @Parameter(names = {"-d", "--output-directory"}, + description = "Data directory for the databases (default:output-directory)") public String outputDirectory = "output-directory"; @Getter - @Parameter(names = {"--log-config"}) + @Parameter(names = {"--log-config"}, description = "Logback config file") public String logbackPath = ""; @Getter - @Parameter(names = {"-h", "--help"}, help = true, description = "HELP message") + @Parameter(names = {"-h", "--help"}, help = true, description = "Show help message") public boolean help = false; @Getter @Setter - @Parameter(names = {"-w", "--witness"}) + @Parameter(names = {"-w", "--witness"}, description = "Is witness node") public boolean witness = false; @Getter @Setter - @Parameter(names = {"--support-constant"}) + @Parameter(names = {"--support-constant"}, description = "Support constant calling for TVM. " + + "(defalut: false)") public boolean supportConstant = false; @Getter @Setter - @Parameter(names = {"--max-energy-limit-for-constant"}) + @Parameter(names = {"--max-energy-limit-for-constant"}, description = "Max energy limit for " + + "constant calling. (default: 100,000,000)") public long maxEnergyLimitForConstant = 100_000_000L; @Getter @Setter - @Parameter(names = {"--debug"}) + @Parameter(names = {"--lru-cache-size"}, description = "Max LRU size for caching bytecode and " + + "result of JUMPDEST analysis. (default: 500)") + public int lruCacheSize = 500; + @Getter + @Setter + @Parameter(names = {"--debug"}, description = "Switch for TVM debug mode. In debug model, TVM " + + "will not check for timeout. (default: false)") public boolean debug = false; @Getter @Setter - @Parameter(names = {"--min-time-ratio"}) + @Parameter(names = {"--min-time-ratio"}, description = "Maximum CPU tolerance when executing " + + "timeout transactions while synchronizing blocks. (default: 0.0)") public double minTimeRatio = 0.0; @Getter @Setter - @Parameter(names = {"--max-time-ratio"}) + @Parameter(names = {"--max-time-ratio"}, description = "Maximum CPU tolerance when executing " + + "non-timeout transactions while synchronizing blocks. (default: 5.0)") public double maxTimeRatio = calcMaxTimeRatio(); @Getter @Setter + @Parameter(names = {"--save-internaltx"}, description = "Save internal transactions generated " + + "during TVM execution, such as create, call and suicide. (default: false)") + public boolean saveInternalTx; + @Getter + @Setter + @Parameter(names = {"--save-featured-internaltx"}, description = "Save featured internal " + + "transactions generated during TVM execution, such as freeze, vote and so on. " + + "(default: false)") + public boolean saveFeaturedInternalTx; + @Getter + @Setter + @Parameter(names = {"--save-cancel-all-unfreeze-v2-details"}, description = "Record the details of the internal " + + "transactions generated by the CANCELALLUNFREEZEV2 opcode, such as bandwidth/energy/tronpower cancel amount. " + + "(default: false)") + public boolean saveCancelAllUnfreezeV2Details; + @Getter + @Setter @Parameter(names = {"--long-running-time"}) public int longRunningTime = 10; @Getter @Setter - @Parameter(names = {"--max-connect-number"}) + @Parameter(names = {"--max-connect-number"}, description = "Http server max connect number " + + "(default:50)") public int maxHttpConnectNumber = 50; @Getter @Parameter(description = "--seed-nodes") public List seedNodes = new ArrayList<>(); - @Parameter(names = {"-p", "--private-key"}, description = "private-key") + @Parameter(names = {"-p", "--private-key"}, description = "Witness private key") public String privateKey = ""; @Parameter(names = {"--witness-address"}, description = "witness-address") public String witnessAddress = ""; @@ -78,8 +112,6 @@ public class CommonParameter { public String password; @Parameter(names = {"--storage-db-directory"}, description = "Storage db directory") public String storageDbDirectory = ""; - @Parameter(names = {"--storage-db-version"}, description = "Storage db version.(1 or 2)") - public String storageDbVersion = ""; @Parameter(names = { "--storage-db-engine"}, description = "Storage db engine.(leveldb or rocksdb)") public String storageDbEngine = ""; @@ -87,8 +119,8 @@ public class CommonParameter { "--storage-db-synchronous"}, description = "Storage db is synchronous or not.(true or false)") public String storageDbSynchronous = ""; - @Parameter(names = {"--contract-parse-enable"}, - description = "enable contract parses in java-tron or not.(true or false)") + @Parameter(names = {"--contract-parse-enable"}, description = "Switch for contract parses in " + + "java-tron. (default: true)") public String contractParseEnable = ""; @Parameter(names = {"--storage-index-directory"}, description = "Storage index directory") @@ -115,47 +147,61 @@ public class CommonParameter { public boolean nodeDiscoveryPersist; @Getter @Setter + public boolean nodeEffectiveCheckEnable; + @Getter + @Setter public int nodeConnectionTimeout; @Getter @Setter + public int fetchBlockTimeout; + @Getter + @Setter public int nodeChannelReadTimeout; @Getter @Setter - public int nodeMaxActiveNodes; + public int maxConnections; + @Getter + @Setter + public int minConnections; @Getter @Setter - public int nodeMaxActiveNodesWithSameIp; + public int minActiveConnections; + @Getter + @Setter + public int maxConnectionsWithSameIp; + @Getter + @Setter + public int maxTps; @Getter @Setter public int minParticipationRate; @Getter + public P2pConfig p2pConfig; + @Getter @Setter public int nodeListenPort; @Getter @Setter - public String nodeDiscoveryBindIp; + public String nodeLanIp; @Getter @Setter public String nodeExternalIp; @Getter @Setter - public boolean nodeDiscoveryPublicHomeNode; + public int nodeP2pVersion; @Getter @Setter - public long nodeDiscoveryPingTimeout; + public boolean nodeEnableIpv6 = false; @Getter @Setter - public long nodeP2pPingInterval; + public List dnsTreeUrls; @Getter @Setter - @Parameter(names = {"--save-internaltx"}) - public boolean saveInternalTx; - @Getter - @Setter - public int nodeP2pVersion; + public PublishConfig dnsPublishConfig; @Getter @Setter - public String p2pNodeId; + public long syncFetchBatchNum; + //If you are running a solidity node for java tron, this flag is set to true @Getter @Setter @@ -215,6 +261,9 @@ public class CommonParameter { public int maxHeaderListSize; @Getter @Setter + public boolean isRpcReflectionServiceEnable; + @Getter + @Setter @Parameter(names = {"--validate-sign-thread"}, description = "Num of validate thread") public int validateSignThreadNum; @Getter @@ -266,34 +315,34 @@ public class CommonParameter { public boolean walletExtensionApi; @Getter @Setter - public int backupPriority; + public boolean estimateEnergy; @Getter @Setter - public int backupPort; + public int estimateEnergyMaxRetry; @Getter @Setter - public int keepAliveInterval; + public int backupPriority; @Getter @Setter - public List backupMembers; + public int backupPort; @Getter @Setter - public double connectFactor; + public int keepAliveInterval; @Getter @Setter - public double activeConnectFactor; + public List backupMembers; @Getter @Setter - public double disconnectNumberFactor; + public long receiveTcpMinDataLength; @Getter @Setter - public double maxConnectNumberFactor; + public boolean isOpenFullTcpDisconnect; @Getter @Setter - public long receiveTcpMinDataLength; + public int inactiveThreshold; @Getter @Setter - public boolean isOpenFullTcpDisconnect; + public boolean nodeDetectEnable; @Getter @Setter public int allowMultiSign; @@ -340,12 +389,12 @@ public class CommonParameter { public long blockNumForEnergyLimit; @Getter @Setter - @Parameter(names = {"--es"}) + @Parameter(names = {"--es"}, description = "Start event subscribe server") public boolean eventSubscribe = false; @Getter @Setter public long trxExpirationTimeInMilliseconds; // (ms) - @Parameter(names = {"-v", "--version"}, description = "output code version", help = true) + @Parameter(names = {"-v", "--version"}, description = "Output code version", help = true) public boolean version; @Getter @Setter @@ -372,6 +421,14 @@ public class CommonParameter { @Setter public RateLimiterInitialization rateLimiterInitialization; @Getter + @Setter + public int rateLimiterGlobalQps; + @Getter + @Setter + public int rateLimiterGlobalIpQps; + @Getter + public int rateLimiterGlobalApiQps; + @Getter public DbBackupConfig dbBackupConfig; @Getter public RocksDbSettings rocksDBCustomSettings; @@ -379,12 +436,19 @@ public class CommonParameter { public GenesisBlock genesisBlock; @Getter @Setter - public List activeNodes; + @Parameter(names = {"--p2p-disable"}, description = "Switch for p2p module initialization. " + + "(defalut: false)", arity = 1) + public boolean p2pDisable = false; @Getter @Setter - public List passiveNodes; + public List activeNodes; @Getter - public List fastForwardNodes; + @Setter + public List passiveNodes; + @Getter + public List fastForwardNodes; + @Getter + public int maxFastForwardNum; @Getter public Storage storage; @Getter @@ -398,12 +462,30 @@ public class CommonParameter { @Getter @Setter public String cryptoEngine = Constant.ECKey_ENGINE; + + @Getter + @Setter + public boolean rpcEnable = true; + + @Getter + @Setter + public boolean rpcSolidityEnable = true; + + @Getter + @Setter + public boolean rpcPBFTEnable = true; + @Getter @Setter public boolean fullNodeHttpEnable = true; @Getter @Setter public boolean solidityNodeHttpEnable = true; + + @Getter + @Setter + public boolean pBFTHttpEnable = true; + @Getter @Setter public boolean jsonRpcHttpFullNodeEnable = false; @@ -413,6 +495,13 @@ public class CommonParameter { @Getter @Setter public boolean jsonRpcHttpPBFTNodeEnable = false; + @Getter + @Setter + public int jsonRpcMaxBlockRange = 5000; + @Getter + @Setter + public int jsonRpcMaxSubTopics = 1000; + @Getter @Setter public int maxTransactionPendingSize; @@ -443,6 +532,14 @@ public class CommonParameter { @Setter public int metricsReportInterval = 10; + @Getter + @Setter + public boolean metricsPrometheusEnable = false; + + @Getter + @Setter + public int metricsPrometheusPort; + @Getter @Setter public int agreeNodeCount; @@ -458,6 +555,9 @@ public class CommonParameter { public int pBFTHttpPort; @Getter @Setter + public long pBFTExpireNum; + @Getter + @Setter public long oldSolidityBlockNum = -1; @Getter/**/ @@ -486,11 +586,11 @@ public class CommonParameter { @Getter @Setter - public boolean openHistoryQueryWhenLiteFN = false; + public long allowHigherLimitForMaxCpuTimeOfOneTx; @Getter @Setter - public boolean isLiteFullNode = false; + public boolean openHistoryQueryWhenLiteFN = false; @Getter @Setter @@ -508,10 +608,122 @@ public class CommonParameter { @Setter public long allowAccountAssetOptimization; + @Getter + @Setter + public long allowAssetOptimization; + @Getter @Setter public List disabledApiList; + @Getter + @Setter + public CronExpression shutdownBlockTime = null; + + @Getter + @Setter + public long shutdownBlockHeight = -1; + + @Getter + @Setter + public long shutdownBlockCount = -1; + + @Getter + @Setter + public long blockCacheTimeout = 60; + + @Getter + @Setter + public long allowNewRewardAlgorithm; + + @Getter + @Setter + public long allowNewReward = 0L; + + @Getter + @Setter + public long memoFee = 0L; + + @Getter + @Setter + public long allowDelegateOptimization = 0L; + + @Getter + @Setter + public long unfreezeDelayDays = 0L; + + @Getter + @Setter + public long allowOptimizedReturnValueOfChainId = 0L; + + @Getter + @Setter + public long allowDynamicEnergy = 0L; + + @Getter + @Setter + public long dynamicEnergyThreshold = 0L; + + @Getter + @Setter + public long dynamicEnergyIncreaseFactor = 0L; + + @Getter + @Setter + public long dynamicEnergyMaxFactor = 0L; + + @Getter + @Setter + public boolean dynamicConfigEnable; + + @Getter + @Setter + public long dynamicConfigCheckInterval; + + @Getter + @Setter + public long allowTvmShangHai; + + @Getter + @Setter + public long allowCancelAllUnfreezeV2; + + @Getter + @Setter + public boolean unsolidifiedBlockCheck; + + @Getter + @Setter + public int maxUnsolidifiedBlocks; + + @Getter + @Setter + public long allowOldRewardOpt; + + @Getter + @Setter + public long allowEnergyAdjustment; + + @Getter + @Setter + public long maxCreateAccountTxSize = 1000L; + + @Getter + @Setter + public long allowStrictMath; + + @Getter + @Setter + public long consensusLogicOptimization; + + @Getter + @Setter + public long allowTvmCancun; + + @Getter + @Setter + public long allowTvmBlob; + private static double calcMaxTimeRatio() { //return max(2.0, min(5.0, 5 * 4.0 / max(Runtime.getRuntime().availableProcessors(), 1))); return 5.0; @@ -529,4 +741,8 @@ public boolean isECKeyCryptoEngine() { public boolean isJsonRpcFilterEnabled() { return jsonRpcHttpFullNodeEnable || jsonRpcHttpSolidityNodeEnable; } + + public int getSafeLruCacheSize() { + return lruCacheSize < 1 ? 500 : lruCacheSize; + } } diff --git a/common/src/main/java/org/tron/common/prometheus/GuavaCacheExports.java b/common/src/main/java/org/tron/common/prometheus/GuavaCacheExports.java new file mode 100644 index 00000000000..e8e39d5b3ad --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/GuavaCacheExports.java @@ -0,0 +1,89 @@ +package org.tron.common.prometheus; + +import static io.prometheus.client.SampleNameFilter.ALLOW_ALL; + +import io.prometheus.client.Collector; +import io.prometheus.client.GaugeMetricFamily; +import io.prometheus.client.Predicate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.tron.common.cache.CacheManager; + +/** + * Exports metrics about for guava cache. + *

+ * Example usage: + *

+ * {@code
+ *   new GuavaCacheExports().register();
+ * }
+ * 
+ * Example metrics being exported: + *
+ *   tron:guava_cache_hit_rate{type="account"} 0.135679
+ *   tron:guava_cache_request{type="account"} 3000
+ * 
+ */ +public class GuavaCacheExports extends Collector { + + private static final String TRON_GUAVA_CACHE_HIT_RATE = "tron:guava_cache_hit_rate"; + private static final String TRON_GUAVA_CACHE_REQUEST = "tron:guava_cache_request"; + private static final String TRON_GUAVA_CACHE_EVICTION_COUNT = "tron:guava_cache_eviction_count"; + + + public GuavaCacheExports() { + } + + + void addHitRateMetrics(List sampleFamilies, Predicate nameFilter) { + if (nameFilter.test(TRON_GUAVA_CACHE_HIT_RATE)) { + GaugeMetricFamily hitRate = new GaugeMetricFamily( + TRON_GUAVA_CACHE_HIT_RATE, + "Hit rate of a guava cache.", + Collections.singletonList("type")); + CacheManager.stats().forEach((k, v) -> hitRate + .addMetric(Collections.singletonList(k), v.hitRate())); + sampleFamilies.add(hitRate); + } + } + + void addRequestMetrics(List sampleFamilies, Predicate nameFilter) { + if (nameFilter.test(TRON_GUAVA_CACHE_REQUEST)) { + GaugeMetricFamily request = new GaugeMetricFamily( + TRON_GUAVA_CACHE_REQUEST, + "Request of a guava cache.", + Collections.singletonList("type")); + CacheManager.stats().forEach((k, v) -> request + .addMetric(Collections.singletonList(k), v.requestCount())); + sampleFamilies.add(request); + } + } + + void addEvictionCountMetrics(List sampleFamilies, + Predicate nameFilter) { + if (nameFilter.test(TRON_GUAVA_CACHE_EVICTION_COUNT)) { + GaugeMetricFamily request = new GaugeMetricFamily( + TRON_GUAVA_CACHE_EVICTION_COUNT, + "Eviction count of a guava cache.", + Collections.singletonList("type")); + CacheManager.stats().forEach((k, v) -> request + .addMetric(Collections.singletonList(k), v.evictionCount())); + sampleFamilies.add(request); + } + } + + @Override + public List collect() { + return collect(null); + } + + @Override + public List collect(Predicate nameFilter) { + List mfs = new ArrayList<>(); + addHitRateMetrics(mfs, nameFilter == null ? ALLOW_ALL : nameFilter); + addRequestMetrics(mfs, nameFilter == null ? ALLOW_ALL : nameFilter); + addEvictionCountMetrics(mfs, nameFilter == null ? ALLOW_ALL : nameFilter); + return mfs; + } +} diff --git a/common/src/main/java/org/tron/common/prometheus/InstrumentedAppender.java b/common/src/main/java/org/tron/common/prometheus/InstrumentedAppender.java new file mode 100644 index 00000000000..7b9972ebebe --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/InstrumentedAppender.java @@ -0,0 +1,30 @@ +package org.tron.common.prometheus; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.UnsynchronizedAppenderBase; +import io.prometheus.client.Counter; + +/** + * a new instrumented appender using the default registry. + */ +public class InstrumentedAppender extends UnsynchronizedAppenderBase { + public static final String COUNTER_NAME = "tron:error_info"; + + private static final Counter defaultCounter = Counter.build().name(COUNTER_NAME) + .help("tron log statements at error type levels") + .labelNames("topic", "type") + .register(); + + @Override + protected void append(ILoggingEvent event) { + if (Metrics.enabled() && event.getLevel().toInt() == Level.ERROR_INT) { + String type = MetricLabels.UNDEFINED; + if (event.getThrowableProxy() != null) { + type = event.getThrowableProxy().getClassName(); + type = type.substring(type.lastIndexOf(".") + 1); + } + defaultCounter.labels(event.getLoggerName(), type).inc(); + } + } +} diff --git a/common/src/main/java/org/tron/common/prometheus/MetricAspect.java b/common/src/main/java/org/tron/common/prometheus/MetricAspect.java new file mode 100644 index 00000000000..c6f7a08f95c --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricAspect.java @@ -0,0 +1,55 @@ +package org.tron.common.prometheus; + +import io.prometheus.client.Histogram; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.stereotype.Component; + +@Aspect +@Component +public class MetricAspect { + + @Around("@annotation(metricTime)") + public Object aroundAdviceMetricTime(ProceedingJoinPoint pjp, MetricTime metricTime) + throws Throwable { + Object result; + Histogram.Timer requestTimer = Metrics.histogramStartTimer( + MetricKeys.Histogram.INTERNAL_SERVICE_LATENCY, + pjp.getSignature().getDeclaringType().getSimpleName(), + metricTime.value().isEmpty() ? pjp.getSignature().getName() : metricTime.value()); + try { + result = pjp.proceed(); + } catch (Throwable throwable) { + Metrics.counterInc( + MetricKeys.Counter.INTERNAL_SERVICE_FAIL, 1, + pjp.getSignature().getDeclaringType().getSimpleName(), + metricTime.value().isEmpty() ? pjp.getSignature().getName() : metricTime.value()); + throw throwable; + } finally { + Metrics.histogramObserve(requestTimer); + } + return result; + } + + @Around("execution(public * org.tron.core.Wallet.*(..))") + public Object walletAroundAdvice(ProceedingJoinPoint pjp) throws Throwable { + Object result; + Histogram.Timer requestTimer = Metrics.histogramStartTimer( + MetricKeys.Histogram.INTERNAL_SERVICE_LATENCY, + pjp.getSignature().getDeclaringType().getSimpleName(), + pjp.getSignature().getName()); + try { + result = pjp.proceed(); + } catch (Throwable throwable) { + Metrics.counterInc( + MetricKeys.Counter.INTERNAL_SERVICE_FAIL, 1, + pjp.getSignature().getDeclaringType().getSimpleName(), + pjp.getSignature().getName()); + throw throwable; + } finally { + Metrics.histogramObserve(requestTimer); + } + return result; + } +} \ No newline at end of file diff --git a/common/src/main/java/org/tron/common/prometheus/MetricKeys.java b/common/src/main/java/org/tron/common/prometheus/MetricKeys.java new file mode 100644 index 00000000000..87ab6fae0a3 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricKeys.java @@ -0,0 +1,72 @@ +package org.tron.common.prometheus; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j(topic = "metrics") +public class MetricKeys { + + private MetricKeys() { + throw new IllegalStateException("MetricsKey"); + } + + // Counter + public static class Counter { + public static final String TXS = "tron:txs"; + public static final String MINER = "tron:miner"; + public static final String BLOCK_FORK = "tron:block_fork"; + public static final String P2P_ERROR = "tron:p2p_error"; + public static final String P2P_DISCONNECT = "tron:p2p_disconnect"; + public static final String INTERNAL_SERVICE_FAIL = "tron:internal_service_fail"; + + private Counter() { + throw new IllegalStateException("Counter"); + } + + } + + // Gauge + public static class Gauge { + public static final String HEADER_HEIGHT = "tron:header_height"; + public static final String HEADER_TIME = "tron:header_time"; + public static final String PEERS = "tron:peers"; + public static final String DB_SIZE_BYTES = "tron:db_size_bytes"; + public static final String DB_SST_LEVEL = "tron:db_sst_level"; + public static final String MANAGER_QUEUE = "tron:manager_queue_size"; + public static final String TX_CACHE = "tron:tx_cache"; + + private Gauge() { + throw new IllegalStateException("Gauge"); + } + + } + + // Histogram + public static class Histogram { + public static final String HTTP_SERVICE_LATENCY = "tron:http_service_latency_seconds"; + public static final String GRPC_SERVICE_LATENCY = "tron:grpc_service_latency_seconds"; + public static final String JSONRPC_SERVICE_LATENCY = "tron:jsonrpc_service_latency_seconds"; + public static final String MINER_LATENCY = "tron:miner_latency_seconds"; + public static final String PING_PONG_LATENCY = "tron:ping_pong_latency_seconds"; + public static final String VERIFY_SIGN_LATENCY = "tron:verify_sign_latency_seconds"; + public static final String LOCK_ACQUIRE_LATENCY = "tron:lock_acquire_latency_seconds"; + public static final String BLOCK_PROCESS_LATENCY = "tron:block_process_latency_seconds"; + public static final String BLOCK_PUSH_LATENCY = "tron:block_push_latency_seconds"; + public static final String BLOCK_GENERATE_LATENCY = "tron:block_generate_latency_seconds"; + public static final String PROCESS_TRANSACTION_LATENCY = + "tron:process_transaction_latency_seconds"; + public static final String MINER_DELAY = "tron:miner_delay_seconds"; + public static final String UDP_BYTES = "tron:udp_bytes"; + public static final String TCP_BYTES = "tron:tcp_bytes"; + public static final String HTTP_BYTES = "tron:http_bytes"; + public static final String INTERNAL_SERVICE_LATENCY = "tron:internal_service_latency_seconds"; + public static final String MESSAGE_PROCESS_LATENCY = "tron:message_process_latency_seconds"; + public static final String BLOCK_FETCH_LATENCY = "tron:block_fetch_latency_seconds"; + public static final String BLOCK_RECEIVE_DELAY = "tron:block_receive_delay_seconds"; + + private Histogram() { + throw new IllegalStateException("Histogram"); + } + + } + +} diff --git a/common/src/main/java/org/tron/common/prometheus/MetricLabels.java b/common/src/main/java/org/tron/common/prometheus/MetricLabels.java new file mode 100644 index 00000000000..2aa3c1e3378 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricLabels.java @@ -0,0 +1,78 @@ +package org.tron.common.prometheus; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j(topic = "metrics") +public class MetricLabels { + + public static final String SUCCESS = "success"; + public static final String FAIL = "fail"; + public static final String ALL = "all"; + public static final String UNDEFINED = "undefined"; + public static final String BLOCK = "block"; + public static final String TRX = "trx"; + + private MetricLabels() { + throw new IllegalStateException("MetricsLabels"); + } + + // Counter + public static class Counter { + + public static final String MINE_SUCCESS = SUCCESS; + public static final String MINE_MISS = "miss"; + public static final String MINE_DUP = "dup"; + public static final String TXS_SUCCESS = SUCCESS; + public static final String TXS_FAIL = FAIL; + public static final String TXS_FAIL_ERROR = "error"; + public static final String TXS_FAIL_BIG = "big"; + public static final String TXS_FAIL_EXPIRED = "expired"; + public static final String TXS_FAIL_TIMEOUT = "timeout"; + public static final String TXS_FAIL_SIG = "sig"; + public static final String TXS_FAIL_TAPOS = "tapos"; + public static final String TXS_FAIL_DUP = "dup"; + + private Counter() { + throw new IllegalStateException("Counter"); + } + + + } + + // Gauge + public static class Gauge { + public static final String QUEUE_PENDING = "pending"; + + public static final String QUEUE_REPUSH = "repush"; + + public static final String QUEUE_POPPED = "popped"; + + public static final String QUEUE_QUEUED = "queued"; + + public static final String PEERS_ACTIVE = "active"; + + public static final String PEERS_PASSIVE = "passive"; + + public static final String PEERS_ALL = "all"; + + public static final String PEERS_VALID = "valid"; + + private Gauge() { + throw new IllegalStateException("Gauge"); + } + + + } + + // Histogram + public static class Histogram { + public static final String TRAFFIC_IN = "in"; + public static final String TRAFFIC_OUT = "out"; + + private Histogram() { + throw new IllegalStateException("Histogram"); + } + + } + +} diff --git a/common/src/main/java/org/tron/common/prometheus/MetricTime.java b/common/src/main/java/org/tron/common/prometheus/MetricTime.java new file mode 100644 index 00000000000..47a66d194e8 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricTime.java @@ -0,0 +1,13 @@ +package org.tron.common.prometheus; + +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Target(METHOD) +@Retention(RUNTIME) +public @interface MetricTime { + String value() default ""; +} diff --git a/common/src/main/java/org/tron/common/prometheus/Metrics.java b/common/src/main/java/org/tron/common/prometheus/Metrics.java new file mode 100644 index 00000000000..6774dd7c315 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/Metrics.java @@ -0,0 +1,68 @@ +package org.tron.common.prometheus; + +import io.prometheus.client.Collector; +import io.prometheus.client.CollectorRegistry; +import io.prometheus.client.Histogram; +import io.prometheus.client.exporter.HTTPServer; +import io.prometheus.client.hotspot.DefaultExports; +import lombok.extern.slf4j.Slf4j; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.exception.TronError; + +@Slf4j(topic = "metrics") +public class Metrics { + + public static final double MILLISECONDS_PER_SECOND = Collector.MILLISECONDS_PER_SECOND; + private static volatile boolean initialized = false; + + private Metrics() { + throw new IllegalStateException("Metrics"); + } + + public static synchronized void init() { + if(initialized) { + return; + } + if (CommonParameter.getInstance().isMetricsPrometheusEnable()) { + try { + DefaultExports.initialize(); + new OperatingSystemExports().register(CollectorRegistry.defaultRegistry); + new GuavaCacheExports().register(CollectorRegistry.defaultRegistry); + int port = CommonParameter.getInstance().getMetricsPrometheusPort(); + new HTTPServer.Builder().withPort(port).build(); + logger.info("prometheus exposed on port : {}", port); + initialized = true; + } catch (Exception e) { + throw new TronError(e, TronError.ErrCode.PROMETHEUS_INIT); + } + } + } + + public static boolean enabled() { + return CommonParameter.getInstance().isMetricsPrometheusEnable(); + } + + public static void counterInc(String key, double amt, String... labels) { + MetricsCounter.inc(key, amt, labels); + } + + public static void gaugeInc(String key, double amt, String... labels) { + MetricsGauge.inc(key, amt, labels); + } + + public static void gaugeSet(String key, double amt, String... labels) { + MetricsGauge.set(key, amt, labels); + } + + public static Histogram.Timer histogramStartTimer(String key, String... labels) { + return MetricsHistogram.startTimer(key, labels); + } + + public static void histogramObserve(Histogram.Timer startTimer) { + MetricsHistogram.observeDuration(startTimer); + } + + public static void histogramObserve(String key, double amt, String... labels) { + MetricsHistogram.observe(key, amt, labels); + } +} diff --git a/common/src/main/java/org/tron/common/prometheus/MetricsCounter.java b/common/src/main/java/org/tron/common/prometheus/MetricsCounter.java new file mode 100644 index 00000000000..6acdf23b3bc --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricsCounter.java @@ -0,0 +1,46 @@ +package org.tron.common.prometheus; + +import io.prometheus.client.Counter; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.extern.slf4j.Slf4j; + +@Slf4j(topic = "metrics") +class MetricsCounter { + + private static final Map container = new ConcurrentHashMap<>(); + + static { + init(MetricKeys.Counter.TXS, "tron txs info .", "type", "detail"); + init(MetricKeys.Counter.MINER, "tron miner info .", "miner", "type"); + init(MetricKeys.Counter.BLOCK_FORK, "tron block fork info .", "type"); + init(MetricKeys.Counter.P2P_ERROR, "tron p2p error info .", "type"); + init(MetricKeys.Counter.P2P_DISCONNECT, "tron p2p disconnect .", "type"); + init(MetricKeys.Counter.INTERNAL_SERVICE_FAIL, "internal Service fail.", + "class", "method"); + } + + private MetricsCounter() { + throw new IllegalStateException("MetricsCounter"); + } + + private static void init(String name, String help, String... labels) { + container.put(name, Counter.build() + .name(name) + .help(help) + .labelNames(labels) + .register()); + } + + static void inc(String key, double amt, String... labels) { + if (Metrics.enabled()) { + Counter counter = container.get(key); + if (counter == null) { + logger.info("{} not exist", key); + return; + } + counter.labels(labels).inc(amt); + } + } +} + diff --git a/common/src/main/java/org/tron/common/prometheus/MetricsGauge.java b/common/src/main/java/org/tron/common/prometheus/MetricsGauge.java new file mode 100644 index 00000000000..dc1e5447540 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricsGauge.java @@ -0,0 +1,60 @@ +package org.tron.common.prometheus; + +import io.prometheus.client.Gauge; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.extern.slf4j.Slf4j; + +@Slf4j(topic = "metrics") +class MetricsGauge { + + + private static final Map container = new ConcurrentHashMap<>(); + + static { + init(MetricKeys.Gauge.MANAGER_QUEUE, "tron manager.queue.size .", "type"); + init(MetricKeys.Gauge.HEADER_HEIGHT, "header height ."); + init(MetricKeys.Gauge.HEADER_TIME, "header time ."); + init(MetricKeys.Gauge.PEERS, "tron peers.size .", "type"); + init(MetricKeys.Gauge.DB_SIZE_BYTES, "tron db size .", "type", "db", "level"); + init(MetricKeys.Gauge.DB_SST_LEVEL, "tron db files .", "type", "db", "level"); + init(MetricKeys.Gauge.TX_CACHE, "tron tx cache info.", "type"); + } + + private MetricsGauge() { + throw new IllegalStateException("MetricsGauge"); + } + + private static void init(String name, String help, String... labels) { + container.put(name, Gauge.build() + .name(name) + .help(help) + .labelNames(labels) + .register()); + } + + + static void inc(String key, double delta, String... labels) { + if (Metrics.enabled()) { + Gauge gauge = container.get(key); + if (gauge == null) { + logger.info("{} not exist", key); + return; + } + gauge.labels(labels).inc(delta); + } + } + + static void set(String key, double v, String... labels) { + if (Metrics.enabled()) { + Gauge gauge = container.get(key); + if (gauge == null) { + logger.info("{} not exist", key); + return; + } + gauge.labels(labels).set(v); + } + } + +} + diff --git a/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java b/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java new file mode 100644 index 00000000000..556db10feb5 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/MetricsHistogram.java @@ -0,0 +1,96 @@ +package org.tron.common.prometheus; + +import io.prometheus.client.Histogram; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import lombok.extern.slf4j.Slf4j; + +@Slf4j(topic = "metrics") +public class MetricsHistogram { + + private static final Map container = new ConcurrentHashMap<>(); + + static { + init(MetricKeys.Histogram.INTERNAL_SERVICE_LATENCY, "Internal Service latency.", + "class", "method"); + init(MetricKeys.Histogram.HTTP_SERVICE_LATENCY, "Http Service latency.", + "url"); + init(MetricKeys.Histogram.GRPC_SERVICE_LATENCY, "Grpc Service latency.", + "endpoint"); + init(MetricKeys.Histogram.JSONRPC_SERVICE_LATENCY, "JsonRpc Service latency.", + "method"); + init(MetricKeys.Histogram.MINER_LATENCY, "miner latency.", + "miner"); + init(MetricKeys.Histogram.PING_PONG_LATENCY, "node ping pong latency."); + init(MetricKeys.Histogram.VERIFY_SIGN_LATENCY, "verify sign latency for trx , block.", + "type"); + init(MetricKeys.Histogram.LOCK_ACQUIRE_LATENCY, "lock acquire latency.", + "type"); + init(MetricKeys.Histogram.BLOCK_PROCESS_LATENCY, + "process block latency for TronNetDelegate.", + "sync"); + init(MetricKeys.Histogram.BLOCK_PUSH_LATENCY, "push block latency for Manager."); + init(MetricKeys.Histogram.BLOCK_GENERATE_LATENCY, "generate block latency.", + "address"); + + init(MetricKeys.Histogram.PROCESS_TRANSACTION_LATENCY, "process transaction latency.", + "type", "contract"); + init(MetricKeys.Histogram.MINER_DELAY, "miner delay time, actualTime - planTime.", + "miner"); + init(MetricKeys.Histogram.UDP_BYTES, "udp_bytes traffic.", + "type"); + init(MetricKeys.Histogram.TCP_BYTES, "tcp_bytes traffic.", + "type"); + init(MetricKeys.Histogram.HTTP_BYTES, "http_bytes traffic.", + "url", "status"); + init(MetricKeys.Histogram.MESSAGE_PROCESS_LATENCY, "process message latency.", + "type"); + init(MetricKeys.Histogram.BLOCK_FETCH_LATENCY, "fetch block latency."); + init(MetricKeys.Histogram.BLOCK_RECEIVE_DELAY, + "receive block delay time, receiveTime - blockTime."); + } + + private MetricsHistogram() { + throw new IllegalStateException("MetricsHistogram"); + } + + private static void init(String name, String help, String... labels) { + container.put(name, Histogram.build() + .name(name) + .help(help) + .labelNames(labels) + .register()); + } + + static Histogram.Timer startTimer(String key, String... labels) { + if (Metrics.enabled()) { + Histogram histogram = container.get(key); + if (histogram == null) { + logger.info("{} not exist", key); + return null; + } + return histogram.labels(labels).startTimer(); + } + return null; + } + + static void observeDuration(Histogram.Timer startTimer) { + if (startTimer != null) { + startTimer.observeDuration(); + } + } + + + static void observe(String key, double amt, String... labels) { + if (Metrics.enabled()) { + Histogram histogram = container.get(key); + if (histogram == null) { + logger.info("{} not exist", key); + return; + } + histogram.labels(labels).observe(amt); + } + } + +} + diff --git a/common/src/main/java/org/tron/common/prometheus/OperatingSystemExports.java b/common/src/main/java/org/tron/common/prometheus/OperatingSystemExports.java new file mode 100644 index 00000000000..45cdad344b8 --- /dev/null +++ b/common/src/main/java/org/tron/common/prometheus/OperatingSystemExports.java @@ -0,0 +1,131 @@ +package org.tron.common.prometheus; + +import static io.prometheus.client.SampleNameFilter.ALLOW_ALL; + +import com.sun.management.OperatingSystemMXBean; +import io.prometheus.client.Collector; +import io.prometheus.client.GaugeMetricFamily; +import io.prometheus.client.Predicate; +import java.lang.management.ManagementFactory; +import java.util.ArrayList; +import java.util.List; + +/** + * Exports metrics about Operating System. + *

+ * Example usage: + *

+ * {@code
+ *  new OperatingSystemExports().register(CollectorRegistry.defaultRegistry);
+ * }
+ * 
+ * Example metrics being exported: + *
+ *   system_available_cpus 12.0
+ *   process_cpu_load{} 200
+ *   system_cpu_load 0.3876289375889973
+ *   system_free_physical_memory_bytes 1.96481024E8
+ * 
+ */ +public class OperatingSystemExports extends Collector { + + private static final String SYSTEM_AVAILABLE_CPUS = "system_available_cpus"; + private static final String PROCESS_CPU_LOAD = "process_cpu_load"; + private static final String SYSTEM_CPU_LOAD = "system_cpu_load"; + private static final String SYSTEM_LOAD_AVERAGE = "system_load_average"; + private static final String SYSTEM_TOTAL_PHYSICAL_MEMORY_BYTES = + "system_total_physical_memory_bytes"; + private static final String SYSTEM_FREE_PHYSICAL_MEMORY_BYTES = + "system_free_physical_memory_bytes"; + private static final String SYSTEM_TOTAL_SWAP_SPACES_BYTES = "system_total_swap_spaces_bytes"; + private static final String SYSTEM_FREE_SWAP_SPACES_BYTES = "system_free_swap_spaces_bytes"; + + + private final OperatingSystemMXBean operatingSystemMXBean; + + public OperatingSystemExports() { + this((OperatingSystemMXBean) ManagementFactory + .getOperatingSystemMXBean()); + } + + public OperatingSystemExports(OperatingSystemMXBean operatingSystemMXBean) { + this.operatingSystemMXBean = operatingSystemMXBean; + } + + void addOperatingSystemMetrics(List sampleFamilies, + Predicate nameFilter) { + if (nameFilter.test(SYSTEM_AVAILABLE_CPUS)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_AVAILABLE_CPUS, + "System available cpus", + operatingSystemMXBean.getAvailableProcessors())); + } + + if (nameFilter.test(PROCESS_CPU_LOAD)) { + sampleFamilies.add( + new GaugeMetricFamily( + PROCESS_CPU_LOAD, + "Process cpu load", + operatingSystemMXBean.getProcessCpuLoad())); + } + + if (nameFilter.test(SYSTEM_CPU_LOAD)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_CPU_LOAD, + "System cpu load", + operatingSystemMXBean.getSystemCpuLoad())); + } + + if (nameFilter.test(SYSTEM_LOAD_AVERAGE)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_LOAD_AVERAGE, + "System cpu load average", + operatingSystemMXBean.getSystemLoadAverage())); + } + + if (nameFilter.test(SYSTEM_TOTAL_PHYSICAL_MEMORY_BYTES)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_TOTAL_PHYSICAL_MEMORY_BYTES, + "System total physical memory bytes", + operatingSystemMXBean.getTotalPhysicalMemorySize())); + } + + if (nameFilter.test(SYSTEM_FREE_PHYSICAL_MEMORY_BYTES)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_FREE_PHYSICAL_MEMORY_BYTES, + "System free physical memory bytes", + operatingSystemMXBean.getFreePhysicalMemorySize())); + } + if (nameFilter.test(SYSTEM_TOTAL_SWAP_SPACES_BYTES)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_TOTAL_SWAP_SPACES_BYTES, + "System free swap spaces bytes", + operatingSystemMXBean.getTotalSwapSpaceSize())); + } + if (nameFilter.test(SYSTEM_FREE_SWAP_SPACES_BYTES)) { + sampleFamilies.add( + new GaugeMetricFamily( + SYSTEM_FREE_SWAP_SPACES_BYTES, + "System free swap spaces", + operatingSystemMXBean.getFreeSwapSpaceSize())); + } + } + + @Override + public List collect() { + return collect(null); + } + + @Override + public List collect(Predicate nameFilter) { + List mfs = new ArrayList(); + addOperatingSystemMetrics(mfs, nameFilter == null ? ALLOW_ALL : nameFilter); + return mfs; + } +} \ No newline at end of file diff --git a/common/src/main/java/org/tron/common/runtime/vm/DataWord.java b/common/src/main/java/org/tron/common/runtime/vm/DataWord.java index 0eb0487a534..faeae45782e 100644 --- a/common/src/main/java/org/tron/common/runtime/vm/DataWord.java +++ b/common/src/main/java/org/tron/common/runtime/vm/DataWord.java @@ -17,6 +17,9 @@ */ package org.tron.common.runtime.vm; +import static org.tron.common.math.Maths.min; +import static org.tron.common.math.Maths.signum; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigInteger; @@ -28,6 +31,7 @@ import org.tron.common.utils.DecodeUtil; import org.tron.common.utils.FastByteComparisons; import org.tron.core.db.ByteArrayWrapper; +import org.tron.core.vm.config.VMConfig; /** * DataWord is the 32-byte array representation of a 256-bit number Calculations can be done on this @@ -165,7 +169,7 @@ public byte[] getClonedData() { byte[] ret = ByteUtil.EMPTY_BYTE_ARRAY; if (data != null) { ret = new byte[WORD_SIZE]; - int dataSize = Math.min(data.length, WORD_SIZE); + int dataSize = min(data.length, WORD_SIZE, VMConfig.disableJavaLangMath()); System.arraycopy(data, 0, ret, 0, dataSize); } return ret; @@ -484,7 +488,7 @@ public int compareTo(DataWord o) { data, 0, data.length, o.getData(), 0, o.getData().length); // Convert result into -1, 0 or 1 as is the convention - return (int) Math.signum(result); + return (int) signum(result, VMConfig.disableJavaLangMath()); } public void signExtend(byte k) { diff --git a/common/src/main/java/org/tron/common/utils/ByteUtil.java b/common/src/main/java/org/tron/common/utils/ByteUtil.java index 54d637d3f01..a7f7abd8fa8 100644 --- a/common/src/main/java/org/tron/common/utils/ByteUtil.java +++ b/common/src/main/java/org/tron/common/utils/ByteUtil.java @@ -18,6 +18,8 @@ package org.tron.common.utils; +import static org.tron.common.math.Maths.min; + import com.google.common.base.Preconditions; import com.google.common.primitives.UnsignedBytes; import java.io.ByteArrayOutputStream; @@ -70,7 +72,7 @@ public static byte[] bigIntegerToBytes(BigInteger b, int numBytes) { byte[] bytes = new byte[numBytes]; byte[] biBytes = b.toByteArray(); int start = (biBytes.length == numBytes + 1) ? 1 : 0; - int length = Math.min(biBytes.length, numBytes); + int length = min(biBytes.length, numBytes, true); System.arraycopy(biBytes, start, bytes, numBytes - length, length); return bytes; } @@ -346,7 +348,7 @@ public static byte[] parseBytes(byte[] input, int offset, int len) { } byte[] bytes = new byte[len]; - System.arraycopy(input, offset, bytes, 0, Math.min(input.length - offset, len)); + System.arraycopy(input, offset, bytes, 0, min(input.length - offset, len, true)); return bytes; } @@ -477,40 +479,41 @@ public static byte[] setBit(byte[] data, int pos, int val) { public static byte[] compress(byte[] data) throws EventBloomException { Deflater deflater = new Deflater(); - deflater.setInput(data); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length)) { + deflater.setInput(data); + deflater.finish(); + byte[] buffer = new byte[1024]; - deflater.finish(); - byte[] buffer = new byte[1024]; - while (!deflater.finished()) { - int count = deflater.deflate(buffer); // returns the generated code... index - outputStream.write(buffer, 0, count); - } - try { - outputStream.close(); + while (!deflater.finished()) { + int count = deflater.deflate(buffer); // returns the generated code... index + outputStream.write(buffer, 0, count); + } + + return outputStream.toByteArray(); } catch (IOException e) { throw new EventBloomException("compress data failed"); + } finally { + deflater.end(); } - byte[] output = outputStream.toByteArray(); - - return output; } public static byte[] decompress(byte[] data) throws IOException, DataFormatException { Inflater inflater = new Inflater(); - inflater.setInput(data); - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); - byte[] buffer = new byte[1024]; - while (!inflater.finished()) { - int count = inflater.inflate(buffer); - outputStream.write(buffer, 0, count); - } - outputStream.close(); - byte[] output = outputStream.toByteArray(); + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length)) { + inflater.setInput(data); + byte[] buffer = new byte[1024]; + + while (!inflater.finished()) { + int count = inflater.inflate(buffer); + outputStream.write(buffer, 0, count); + } - return output; + return outputStream.toByteArray(); + } finally { + inflater.end(); + } } } diff --git a/common/src/main/java/org/tron/common/utils/DbOptionalsUtils.java b/common/src/main/java/org/tron/common/utils/DbOptionalsUtils.java index 69965bf39ab..ac743ebc7b7 100644 --- a/common/src/main/java/org/tron/common/utils/DbOptionalsUtils.java +++ b/common/src/main/java/org/tron/common/utils/DbOptionalsUtils.java @@ -12,7 +12,6 @@ public class DbOptionalsUtils { public static final int DEFAULT_BLOCK_SIZE = 4 * 1024; public static final int DEFAULT_WRITE_BUFFER_SIZE = 16 * 1024 * 1024; public static final int DEFAULT_WRITE_BUFFER_SIZE_M = 64 * 1024 * 1024; - public static final int DEFAULT_WRITE_BUFFER_SIZE_L = 256 * 1024 * 1024; public static final long DEFAULT_CACHE_SIZE = 32 * 1024 * 1024L; public static final int DEFAULT_MAX_OPEN_FILES = 100; /** @@ -30,13 +29,10 @@ public class DbOptionalsUtils { */ public static final int DEFAULT_MAX_OPEN_FILES_L = 100; // Read a lot - public static final List DB_M = Arrays.asList( "code", "contract"); + public static final List DB_M = Arrays.asList("code", "contract"); // Read frequently public static final List DB_L = Arrays.asList("account", "delegation", "storage-row"); - // Write frequently - public static final List DB_WRITE_L = Arrays.asList("block", "account", - "transactionRetStore", "storage-row", "trans"); private DbOptionalsUtils() { throw new IllegalStateException("DbOptionalsUtils class"); @@ -80,10 +76,6 @@ public static Options newDefaultDbOptions(String name ,Options defaultOptions) { adjustDefaultDbOptionsForL(dbOptions); } - if (DB_WRITE_L.contains(name)) { - adjustDefaultDbOptionsForWriteL(dbOptions); - } - return dbOptions; } @@ -97,8 +89,4 @@ private static void adjustDefaultDbOptionsForL(Options defaultOptions) { defaultOptions.writeBufferSize(DEFAULT_WRITE_BUFFER_SIZE_M); } - private static void adjustDefaultDbOptionsForWriteL(Options defaultOptions) { - - defaultOptions.writeBufferSize(DEFAULT_WRITE_BUFFER_SIZE_L); - } } diff --git a/common/src/main/java/org/tron/common/utils/MerkleRoot.java b/common/src/main/java/org/tron/common/utils/MerkleRoot.java new file mode 100644 index 00000000000..ccd8905b6c5 --- /dev/null +++ b/common/src/main/java/org/tron/common/utils/MerkleRoot.java @@ -0,0 +1,68 @@ +package org.tron.common.utils; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import lombok.Getter; + +public class MerkleRoot { + + private MerkleRoot() { + + } + + public static Sha256Hash root(List hashList) { + List leaves = createLeaves(hashList); + while (leaves.size() > 1) { + leaves = createParentLeaves(leaves); + } + return leaves.isEmpty() ? Sha256Hash.ZERO_HASH : leaves.get(0).hash; + } + + private static List createParentLeaves(List leaves) { + int step = 2; + int len = leaves.size(); + return IntStream.iterate(0, i -> i + step) + .limit(len) + .filter(i -> i < len) + .mapToObj(i -> { + Leaf right = i + 1 < len ? leaves.get(i + 1) : null; + return createLeaf(leaves.get(i), right); + }).collect(Collectors.toList()); + } + + private static List createLeaves(List hashList) { + int step = 2; + int len = hashList.size(); + return IntStream.iterate(0, i -> i + step) + .limit(len) + .filter(i -> i < len) + .mapToObj(i -> { + Leaf right = i + 1 < len ? createLeaf(hashList.get(i + 1)) : null; + return createLeaf(createLeaf(hashList.get(i)), right); + }).collect(Collectors.toList()); + } + + private static Leaf createLeaf(Leaf left, Leaf right) { + Leaf leaf = new Leaf(); + leaf.hash = right == null ? left.hash : computeHash(left.hash, right.hash); + return leaf; + } + + private static Leaf createLeaf(Sha256Hash hash) { + Leaf leaf = new Leaf(); + leaf.hash = hash; + return leaf; + } + + private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { + return Sha256Hash.of(true, + leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); + } + + @Getter + private static class Leaf { + + private Sha256Hash hash; + } +} diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index e542a12491e..c5a8a02fb4e 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -18,9 +18,16 @@ public class Constant { public static final String ADD_PRE_FIX_STRING_MAINNET = "41"; public static final byte ADD_PRE_FIX_BYTE_TESTNET = (byte) 0xa0; //a0 + address public static final String ADD_PRE_FIX_STRING_TESTNET = "a0"; + public static final int STANDARD_ADDRESS_SIZE = 20; + public static final int TRON_ADDRESS_SIZE = 21; + + public static final int NODE_TYPE_FULL_NODE = 0; + public static final int NODE_TYPE_LIGHT_NODE = 1; // config for transaction public static final long TRANSACTION_MAX_BYTE_SIZE = 500 * 1_024L; + public static final int CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE = 500; + public static final int CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE = 10000; public static final long MAXIMUM_TIME_UNTIL_EXPIRATION = 24 * 60 * 60 * 1_000L; //one day public static final long TRANSACTION_DEFAULT_EXPIRATION_TIME = 60 * 1_000L; //60 seconds public static final long TRANSACTION_FEE_POOL_PERIOD = 1; //1 blocks @@ -28,6 +35,8 @@ public class Constant { public static final long SUN_PER_ENERGY = 100; // 1 us = 100 SUN = 100 * 10^-6 TRX public static final long ENERGY_LIMIT_IN_CONSTANT_TX = 3_000_000L; // ref: 1 us = 1 energy public static final long MAX_RESULT_SIZE_IN_TX = 64; // max 8 * 8 items in result + public static final long PER_SIGN_LENGTH = 65L; + public static final long MAX_CONTRACT_RESULT_SIZE = 2L; public static final long PB_DEFAULT_ENERGY_LIMIT = 0L; public static final long CREATOR_DEFAULT_ENERGY_LIMIT = 1000 * 10_000L; @@ -61,9 +70,13 @@ public class Constant { public static final String LOCAL_WITNESS_KEYSTORE = "localwitnesskeystore"; public static final String VM_SUPPORT_CONSTANT = "vm.supportConstant"; public static final String VM_MAX_ENERGY_LIMIT_FOR_CONSTANT = "vm.maxEnergyLimitForConstant"; + public static final String VM_LRU_CACHE_SIZE = "vm.lruCacheSize"; public static final String VM_MIN_TIME_RATIO = "vm.minTimeRatio"; public static final String VM_MAX_TIME_RATIO = "vm.maxTimeRatio"; public static final String VM_LONG_RUNNING_TIME = "vm.longRunningTime"; + public static final String VM_ESTIMATE_ENERGY = "vm.estimateEnergy"; + + public static final String VM_ESTIMATE_ENERGY_MAX_RETRY = "vm.estimateEnergyMaxRetry"; public static final String ROCKSDB = "ROCKSDB"; @@ -76,32 +89,64 @@ public class Constant { public static final String BLOCK_NEED_SYNC_CHECK = "block.needSyncCheck"; public static final String NODE_DISCOVERY_ENABLE = "node.discovery.enable"; public static final String NODE_DISCOVERY_PERSIST = "node.discovery.persist"; + public static final String NODE_EFFECTIVE_CHECK_ENABLE = "node.effectiveCheckEnable"; public static final String NODE_CONNECTION_TIMEOUT = "node.connection.timeout"; + public static final String NODE_FETCH_BLOCK_TIMEOUT = "node.fetchBlock.timeout"; public static final String NODE_CHANNEL_READ_TIMEOUT = "node.channel.read.timeout"; + public static final String NODE_MAX_CONNECTIONS = "node.maxConnections"; + public static final String NODE_MIN_CONNECTIONS = "node.minConnections"; + public static final String NODE_MIN_ACTIVE_CONNECTIONS = "node.minActiveConnections"; + public static final String NODE_SYNC_FETCH_BATCH_NUM = "node.syncFetchBatchNum"; + public static final String NODE_MAX_ACTIVE_NODES = "node.maxActiveNodes"; - public static final String NODE_MAX_ACTIVE_NODES_WITH_SAMEIP = "node.maxActiveNodesWithSameIp"; + public static final String NODE_MAX_ACTIVE_NODES_WITH_SAME_IP = "node.maxActiveNodesWithSameIp"; + public static final String NODE_MAX_TPS = "node.maxTps"; + public static final String NODE_CONNECT_FACTOR = "node.connectFactor"; + public static final String NODE_ACTIVE_CONNECT_FACTOR = "node.activeConnectFactor"; + + public static final String NODE_MAX_CONNECTIONS_WITH_SAME_IP = "node.maxConnectionsWithSameIp"; public static final String NODE_MIN_PARTICIPATION_RATE = "node.minParticipationRate"; public static final String NODE_LISTEN_PORT = "node.listen.port"; - public static final String NODE_DISCOVERY_PUBLIC_HOME_NODE = "node.discovery.public.home.node"; - public static final String NODE_DISCOVERY_PING_TIMEOUT = "node.discovery.ping.timeout"; - - public static final String NODE_P2P_PING_INTERVAL = "node.p2p.pingInterval"; public static final String NODE_P2P_VERSION = "node.p2p.version"; + public static final String NODE_ENABLE_IPV6 = "node.enableIpv6"; + public static final String NODE_DNS_TREE_URLS = "node.dns.treeUrls"; + public static final String NODE_DNS_PUBLISH = "node.dns.publish"; + public static final String NODE_DNS_DOMAIN = "node.dns.dnsDomain"; + public static final String NODE_DNS_CHANGE_THRESHOLD = "node.dns.changeThreshold"; + public static final String NODE_DNS_MAX_MERGE_SIZE = "node.dns.maxMergeSize"; + public static final String NODE_DNS_PRIVATE = "node.dns.dnsPrivate"; + public static final String NODE_DNS_KNOWN_URLS = "node.dns.knownUrls"; + public static final String NODE_DNS_STATIC_NODES = "node.dns.staticNodes"; + public static final String NODE_DNS_SERVER_TYPE = "node.dns.serverType"; + public static final String NODE_DNS_ACCESS_KEY_ID = "node.dns.accessKeyId"; + public static final String NODE_DNS_ACCESS_KEY_SECRET = "node.dns.accessKeySecret"; + public static final String NODE_DNS_ALIYUN_ENDPOINT = "node.dns.aliyunDnsEndpoint"; + public static final String NODE_DNS_AWS_REGION = "node.dns.awsRegion"; + public static final String NODE_DNS_AWS_HOST_ZONE_ID = "node.dns.awsHostZoneId"; + + // config for rpc public static final String NODE_RPC_PORT = "node.rpc.port"; public static final String NODE_RPC_SOLIDITY_PORT = "node.rpc.solidityPort"; public static final String NODE_RPC_PBFT_PORT = "node.rpc.PBFTPort"; + public static final String NODE_RPC_ENABLE = "node.rpc.enable"; + public static final String NODE_RPC_SOLIDITY_ENABLE = "node.rpc.solidityEnable"; + public static final String NODE_RPC_PBFT_ENABLE = "node.rpc.PBFTEnable"; + // config for http public static final String NODE_HTTP_FULLNODE_PORT = "node.http.fullNodePort"; public static final String NODE_HTTP_SOLIDITY_PORT = "node.http.solidityPort"; public static final String NODE_HTTP_FULLNODE_ENABLE = "node.http.fullNodeEnable"; public static final String NODE_HTTP_SOLIDITY_ENABLE = "node.http.solidityEnable"; + public static final String NODE_HTTP_PBFT_ENABLE = "node.http.PBFTEnable"; public static final String NODE_HTTP_PBFT_PORT = "node.http.PBFTPort"; - + // config for jsonrpc public static final String NODE_JSONRPC_HTTP_FULLNODE_ENABLE = "node.jsonrpc.httpFullNodeEnable"; public static final String NODE_JSONRPC_HTTP_FULLNODE_PORT = "node.jsonrpc.httpFullNodePort"; public static final String NODE_JSONRPC_HTTP_SOLIDITY_ENABLE = "node.jsonrpc.httpSolidityEnable"; public static final String NODE_JSONRPC_HTTP_SOLIDITY_PORT = "node.jsonrpc.httpSolidityPort"; public static final String NODE_JSONRPC_HTTP_PBFT_ENABLE = "node.jsonrpc.httpPBFTEnable"; public static final String NODE_JSONRPC_HTTP_PBFT_PORT = "node.jsonrpc.httpPBFTPort"; + public static final String NODE_JSONRPC_MAX_BLOCK_RANGE = "node.jsonrpc.maxBlockRange"; + public static final String NODE_JSONRPC_MAX_SUB_TOPICS = "node.jsonrpc.maxSubTopics"; public static final String NODE_DISABLED_API_LIST = "node.disabledApi"; @@ -120,6 +165,8 @@ public class Constant { public static final String NODE_RPC_MAX_HEADER_LIST_SIZE = "node.rpc.maxHeaderListSize"; + public static final String NODE_RPC_REFLECTION_SERVICE = "node.rpc.reflectionService"; + public static final String NODE_OPEN_HISTORY_QUERY_WHEN_LITEFN = "node.openHistoryQueryWhenLiteFN"; public static final String BLOCK_MAINTENANCE_TIME_INTERVAL = "block.maintenanceTimeInterval"; @@ -155,18 +202,14 @@ public class Constant { public static final String NODE_WALLET_EXTENSION_API = "node.walletExtensionApi"; - public static final String NODE_CONNECT_FACTOR = "node.connectFactor"; - - public static final String NODE_ACTIVE_CONNECT_FACTOR = "node.activeConnectFactor"; - - public static final String NODE_DISCONNECT_NUMBER_FACTOR = "node.disconnectNumberFactor"; - - public static final String NODE_MAX_CONNECT_NUMBER_FACTOR = "node.maxConnectNumberFactor"; - public static final String NODE_RECEIVE_TCP_MIN_DATA_LENGTH = "node.receiveTcpMinDataLength"; public static final String NODE_IS_OPEN_FULL_TCP_DISCONNECT = "node.isOpenFullTcpDisconnect"; + public static final String NODE_INACTIVE_THRESHOLD = "node.inactiveThreshold"; + + public static final String NODE_DETECT_ENABLE = "node.nodeDetectEnable"; + public static final String NODE_MAX_TRANSACTION_PENDING_SIZE = "node.maxTransactionPendingSize"; public static final String NODE_PENDING_TRANSACTION_TIMEOUT = "node.pendingTransactionTimeout"; @@ -187,6 +230,9 @@ public class Constant { public static final String VM_SAVE_INTERNAL_TX = "vm.saveInternalTx"; + public static final String VM_SAVE_FEATURED_INTERNAL_TX = "vm.saveFeaturedInternalTx"; + public static final String VM_SAVE_CANCEL_ALL_UNFREEZE_V2_DETAILS = "vm.saveCancelAllUnfreezeV2Details"; + // public static final String COMMITTEE_ALLOW_SHIELDED_TRANSACTION = "committee.allowShieldedTransaction"; public static final String COMMITTEE_ALLOW_SHIELDED_TRC20_TRANSACTION = "committee" @@ -219,10 +265,18 @@ public class Constant { public static final String NODE_FAST_FORWARD = "node.fastForward"; + public static final String NODE_MAX_FAST_FORWARD_NUM = "node.maxFastForwardNum"; + public static final String NODE_SHIELDED_TRANS_IN_PENDING_MAX_COUNTS = "node.shieldedTransInPendingMaxCounts"; public static final String RATE_LIMITER = "rate.limiter"; + public static final String RATE_LIMITER_GLOBAL_QPS = "rate.limiter.global.qps"; + + public static final String RATE_LIMITER_GLOBAL_IP_QPS = "rate.limiter.global.ip.qps"; + + public static final String RATE_LIMITER_GLOBAL_API_QPS = "rate.limiter.global.api.qps"; + public static final String COMMITTEE_CHANGED_DELEGATION = "committee.changedDelegation"; public static final String CRYPTO_ENGINE = "crypto.engine"; @@ -235,6 +289,8 @@ public class Constant { public static final String NATIVE_QUEUE_SEND_LENGTH = "event.subscribe.native.sendqueuelength"; + public static final String EVENT_SUBSCRIBE_VERSION = "event.subscribe.version"; + public static final String EVENT_SUBSCRIBE_START_SYNC_BLOCK_NUM = "event.subscribe.startSyncBlockNum"; public static final String EVENT_SUBSCRIBE_PATH = "event.subscribe.path"; public static final String EVENT_SUBSCRIBE_SERVER = "event.subscribe.server"; public static final String EVENT_SUBSCRIBE_DB_CONFIG = "event.subscribe.dbconfig"; @@ -244,10 +300,7 @@ public class Constant { public static final String EVENT_SUBSCRIBE_CONTRACT_ADDRESS = "event.subscribe.filter.contractAddress"; public static final String EVENT_SUBSCRIBE_CONTRACT_TOPIC = "event.subscribe.filter.contractTopic"; - public static final String NODE_DISCOVERY_BIND_IP = "node.discovery.bind.ip"; - public static final String NODE_DISCOVERY_EXTERNAL_IP = "node.discovery.external.ip"; - public static final String AMAZONAWS_URL = "http://checkip.amazonaws.com/"; public static final String NODE_BACKUP_PRIORITY = "node.backup.priority"; public static final String NODE_BACKUP_PORT = "node.backup.port"; @@ -269,6 +322,7 @@ public class Constant { public static final String SEED_NODE_IP_LIST = "seed.node.ip.list"; public static final String NODE_METRICS_ENABLE = "node.metricsEnable"; public static final String COMMITTEE_ALLOW_PBFT = "committee.allowPBFT"; + public static final String COMMITTEE_PBFT_EXPIRE_NUM = "committee.pBFTExpireNum"; public static final String NODE_AGREE_NODE_COUNT = "node.agreeNodeCount"; public static final String COMMITTEE_ALLOW_TRANSACTION_FEE_POOL = "committee.allowTransactionFeePool"; @@ -278,21 +332,77 @@ public class Constant { public static final String COMMITTEE_ALLOW_TVM_FREEZE = "committee.allowTvmFreeze"; public static final String COMMITTEE_ALLOW_TVM_VOTE = "committee.allowTvmVote"; + public static final String COMMITTEE_UNFREEZE_DELAY_DAYS = "committee.unfreezeDelayDays"; public static final String COMMITTEE_ALLOW_TVM_LONDON = "committee.allowTvmLondon"; public static final String COMMITTEE_ALLOW_TVM_COMPATIBLE_EVM = "committee.allowTvmCompatibleEvm"; + public static final String COMMITTEE_ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX = + "committee.allowHigherLimitForMaxCpuTimeOfOneTx"; + public static final String COMMITTEE_ALLOW_NEW_REWARD_ALGORITHM = "committee.allowNewRewardAlgorithm"; + public static final String COMMITTEE_ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID = + "committee.allowOptimizedReturnValueOfChainId"; + public static final String METRICS_STORAGE_ENABLE = "node.metrics.storageEnable"; public static final String METRICS_INFLUXDB_IP = "node.metrics.influxdb.ip"; public static final String METRICS_INFLUXDB_PORT = "node.metrics.influxdb.port"; public static final String METRICS_INFLUXDB_DATABASE = "node.metrics.influxdb.database"; public static final String METRICS_REPORT_INTERVAL = "node.metrics.influxdb.metricsReportInterval"; + public static final String METRICS_PROMETHEUS_ENABLE = "node.metrics.prometheus.enable"; + public static final String METRICS_PROMETHEUS_PORT = "node.metrics.prometheus.port"; public static final String HISTORY_BALANCE_LOOKUP = "storage.balance.history.lookup"; public static final String OPEN_PRINT_LOG = "node.openPrintLog"; public static final String OPEN_TRANSACTION_SORT = "node.openTransactionSort"; - public static final String ALLOW_ACCOUNT_ASSET_OPTIMIZATION = "committee.allowAccountAssetOptimization"; + public static final String ALLOW_ACCOUNT_ASSET_OPTIMIZATION = "committee.allowAccountAssetOptimization"; + public static final String ALLOW_ASSET_OPTIMIZATION = "committee.allowAssetOptimization"; + public static final String ALLOW_NEW_REWARD = "committee.allowNewReward"; + public static final String MEMO_FEE = "committee.memoFee"; + public static final String ALLOW_DELEGATE_OPTIMIZATION = "committee.allowDelegateOptimization"; + + public static final String ALLOW_DYNAMIC_ENERGY = "committee.allowDynamicEnergy"; + + public static final String DYNAMIC_ENERGY_THRESHOLD = "committee.dynamicEnergyThreshold"; + + public static final String DYNAMIC_ENERGY_INCREASE_FACTOR + = "committee.dynamicEnergyIncreaseFactor"; + + public static final String DYNAMIC_ENERGY_MAX_FACTOR = "committee.dynamicEnergyMaxFactor"; + + public static final long DYNAMIC_ENERGY_FACTOR_DECIMAL = 10_000L; + + public static final long DYNAMIC_ENERGY_INCREASE_FACTOR_RANGE = 10_000L; + + public static final long DYNAMIC_ENERGY_MAX_FACTOR_RANGE = 100_000L; + + public static final int DYNAMIC_ENERGY_DECREASE_DIVISION = 4; public static final String LOCAL_HOST = "127.0.0.1"; + + public static final String NODE_SHUTDOWN_BLOCK_TIME = "node.shutdown.BlockTime"; + public static final String NODE_SHUTDOWN_BLOCK_HEIGHT = "node.shutdown.BlockHeight"; + public static final String NODE_SHUTDOWN_BLOCK_COUNT = "node.shutdown.BlockCount"; + + public static final String BLOCK_CACHE_TIMEOUT = "node.blockCacheTimeout"; + + public static final String DYNAMIC_CONFIG_ENABLE = "node.dynamicConfig.enable"; + public static final String DYNAMIC_CONFIG_CHECK_INTERVAL = "node.dynamicConfig.checkInterval"; + + public static final String COMMITTEE_ALLOW_TVM_SHANGHAI = "committee.allowTvmShangHai"; + + public static final String UNSOLIDIFIED_BLOCK_CHECK = "node.unsolidifiedBlockCheck"; + + public static final String MAX_UNSOLIDIFIED_BLOCKS = "node.maxUnsolidifiedBlocks"; + public static final String COMMITTEE_ALLOW_OLD_REWARD_OPT = "committee.allowOldRewardOpt"; + + public static final String COMMITTEE_ALLOW_ENERGY_ADJUSTMENT = "committee.allowEnergyAdjustment"; + public static final String COMMITTEE_ALLOW_STRICT_MATH = "committee.allowStrictMath"; + + public static final String COMMITTEE_CONSENSUS_LOGIC_OPTIMIZATION + = "committee.consensusLogicOptimization"; + + public static final String COMMITTEE_ALLOW_TVM_CANCUN = "committee.allowTvmCancun"; + + public static final String COMMITTEE_ALLOW_TVM_BLOB = "committee.allowTvmBlob"; } 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 386289436f7..a71dc58e8bd 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -17,7 +17,17 @@ public enum ForkBlockVersionEnum { VERSION_4_1_2(20, 1596780000000L, 80), VERSION_4_2(21, 1596780000000L, 80), VERSION_4_3(22, 1596780000000L, 80), - VERSION_4_4(23, 1596780000000L, 80); + VERSION_4_4(23, 1596780000000L, 80), + VERSION_4_5(24, 1596780000000L, 80), + VERSION_4_6(25, 1596780000000L, 80), + VERSION_4_7(26, 1596780000000L, 80), + VERSION_4_7_1(27, 1596780000000L, 80), + VERSION_4_7_2(28, 1596780000000L, 80), + VERSION_4_7_4(29, 1596780000000L, 80), + VERSION_4_7_5(30, 1596780000000L, 80), + VERSION_4_7_7(31, 1596780000000L, 80), + VERSION_4_8_0(32, 1596780000000L, 80); + // if add a version, modify BLOCK_VERSION simultaneously @Getter private int value; @@ -65,9 +75,13 @@ 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 = 23; + public static final int BLOCK_VERSION = 32; 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; + public static final long DELEGATE_COST_BASE_SIZE = 275L; + public static final long WINDOW_SIZE_PRECISION = 1000L; + public static final long ONE_YEAR_BLOCK_NUMBERS = 10512000L; } public class NodeConstant { diff --git a/common/src/main/java/org/tron/core/config/args/SeedNode.java b/common/src/main/java/org/tron/core/config/args/SeedNode.java index 6597110074d..9420d969789 100644 --- a/common/src/main/java/org/tron/core/config/args/SeedNode.java +++ b/common/src/main/java/org/tron/core/config/args/SeedNode.java @@ -1,5 +1,6 @@ package org.tron.core.config.args; +import java.net.InetSocketAddress; import java.util.List; import lombok.Getter; import lombok.Setter; @@ -8,5 +9,5 @@ public class SeedNode { @Getter @Setter - private List ipList; + private List addressList; } diff --git a/common/src/main/java/org/tron/core/config/args/Storage.java b/common/src/main/java/org/tron/core/config/args/Storage.java index 021accb808a..9cf6eb6bab1 100644 --- a/common/src/main/java/org/tron/core/config/args/Storage.java +++ b/common/src/main/java/org/tron/core/config/args/Storage.java @@ -15,9 +15,12 @@ package org.tron.core.config.args; +import com.google.common.collect.Maps; +import com.google.protobuf.ByteString; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; import java.io.File; +import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.Getter; @@ -25,9 +28,12 @@ import org.apache.commons.lang3.StringUtils; import org.iq80.leveldb.CompressionType; import org.iq80.leveldb.Options; +import org.tron.common.cache.CacheStrategies; +import org.tron.common.cache.CacheType; import org.tron.common.utils.DbOptionalsUtils; import org.tron.common.utils.FileUtil; import org.tron.common.utils.Property; +import org.tron.common.utils.Sha256Hash; /** * Custom storage configurations @@ -42,12 +48,14 @@ public class Storage { * Keys (names) of database config */ private static final String DB_DIRECTORY_CONFIG_KEY = "storage.db.directory"; - private static final String DB_VERSION_CONFIG_KEY = "storage.db.version"; private static final String DB_ENGINE_CONFIG_KEY = "storage.db.engine"; private static final String DB_SYNC_CONFIG_KEY = "storage.db.sync"; private static final String INDEX_DIRECTORY_CONFIG_KEY = "storage.index.directory"; private static final String INDEX_SWITCH_CONFIG_KEY = "storage.index.switch"; private static final String TRANSACTIONHISTORY_SWITCH_CONFIG_KEY = "storage.transHistory.switch"; + private static final String ESTIMATED_TRANSACTIONS_CONFIG_KEY = + "storage.txCache.estimatedTransactions"; + private static final String SNAPSHOT_MAX_FLUSH_COUNT_CONFIG_KEY = "storage.snapshot.maxFlushCount"; private static final String PROPERTIES_CONFIG_KEY = "storage.properties"; private static final String PROPERTIES_CONFIG_DB_KEY = "storage"; private static final String PROPERTIES_CONFIG_DEFAULT_KEY = "default"; @@ -67,16 +75,27 @@ public class Storage { private static final String MAX_OPEN_FILES_CONFIG_KEY = "maxOpenFiles"; private static final String EVENT_SUBSCRIBE_CONTRACT_PARSE = "event.subscribe.contractParse"; + private static final String CHECKPOINT_VERSION_KEY = "storage.checkpoint.version"; + private static final String CHECKPOINT_SYNC_KEY = "storage.checkpoint.sync"; + + private static final String CACHE_STRATEGIES = "storage.cache.strategies"; + public static final String TX_CACHE_INIT_OPTIMIZATION = "storage.txCache.initOptimization"; + + private static final String MERKLE_ROOT = "storage.merkleRoot"; + /** * Default values of directory */ - private static final int DEFAULT_DB_VERSION = 2; private static final String DEFAULT_DB_ENGINE = "LEVELDB"; private static final boolean DEFAULT_DB_SYNC = false; private static final boolean DEFAULT_EVENT_SUBSCRIBE_CONTRACT_PARSE = true; private static final String DEFAULT_DB_DIRECTORY = "database"; private static final String DEFAULT_INDEX_DIRECTORY = "index"; private static final String DEFAULT_INDEX_SWITCH = "on"; + private static final int DEFAULT_CHECKPOINT_VERSION = 1; + private static final boolean DEFAULT_CHECKPOINT_SYNC = true; + private static final int DEFAULT_ESTIMATED_TRANSACTIONS = 1000; + private static final int DEFAULT_SNAPSHOT_MAX_FLUSH_COUNT = 1; private Config storage; /** @@ -88,15 +107,15 @@ public class Storage { @Getter @Setter - private int dbVersion; + private String dbEngine; @Getter @Setter - private String dbEngine; + private boolean dbSync; @Getter @Setter - private boolean dbSync; + private int maxFlushCount; /** * Index storage directory: /path/to/{indexDirectory} @@ -117,18 +136,39 @@ public class Storage { @Setter private String transactionHistorySwitch; + @Getter + @Setter + private int checkpointVersion; + + @Getter + @Setter + private boolean checkpointSync; + private Options defaultDbOptions; + @Getter + @Setter + private int estimatedBlockTransactions; + + @Getter + @Setter + private boolean txCacheInitOptimization = false; + + // second cache + private final Map cacheStrategies = Maps.newConcurrentMap(); + + @Getter + private final List cacheDbs = CacheStrategies.CACHE_DBS; + // second cache + /** * Key: dbName, Value: Property object of that database */ @Getter private Map propertyMap; - public static int getDbVersionFromConfig(final Config config) { - return config.hasPath(DB_VERSION_CONFIG_KEY) - ? config.getInt(DB_VERSION_CONFIG_KEY) : DEFAULT_DB_VERSION; - } + // db root + private final Map dbRoots = Maps.newConcurrentMap(); public static String getDbEngineFromConfig(final Config config) { return config.hasPath(DB_ENGINE_CONFIG_KEY) @@ -140,6 +180,20 @@ public static Boolean getDbVersionSyncFromConfig(final Config config) { ? config.getBoolean(DB_SYNC_CONFIG_KEY) : DEFAULT_DB_SYNC; } + public static int getSnapshotMaxFlushCountFromConfig(final Config config) { + if (!config.hasPath(SNAPSHOT_MAX_FLUSH_COUNT_CONFIG_KEY)) { + return DEFAULT_SNAPSHOT_MAX_FLUSH_COUNT; + } + int maxFlushCountConfig = config.getInt(SNAPSHOT_MAX_FLUSH_COUNT_CONFIG_KEY); + if (maxFlushCountConfig <= 0) { + throw new IllegalArgumentException("MaxFlushCount value can not be negative or zero!"); + } + if (maxFlushCountConfig > 500) { + throw new IllegalArgumentException("MaxFlushCount value must not exceed 500!"); + } + return maxFlushCountConfig; + } + public static Boolean getContractParseSwitchFromConfig(final Config config) { return config.hasPath(EVENT_SUBSCRIBE_CONTRACT_PARSE) ? config.getBoolean(EVENT_SUBSCRIBE_CONTRACT_PARSE) @@ -168,6 +222,61 @@ public static String getTransactionHistorySwitchFromConfig(final Config config) : DEFAULT_TRANSACTIONHISTORY_SWITCH; } + public static int getCheckpointVersionFromConfig(final Config config) { + return config.hasPath(CHECKPOINT_VERSION_KEY) + ? config.getInt(CHECKPOINT_VERSION_KEY) + : DEFAULT_CHECKPOINT_VERSION; + } + + public static boolean getCheckpointSyncFromConfig(final Config config) { + return config.hasPath(CHECKPOINT_SYNC_KEY) + ? config.getBoolean(CHECKPOINT_SYNC_KEY) + : DEFAULT_CHECKPOINT_SYNC; + } + + public static int getEstimatedTransactionsFromConfig(final Config config) { + if (!config.hasPath(ESTIMATED_TRANSACTIONS_CONFIG_KEY)) { + return DEFAULT_ESTIMATED_TRANSACTIONS; + } + int estimatedTransactions = config.getInt(ESTIMATED_TRANSACTIONS_CONFIG_KEY); + if (estimatedTransactions > 10000) { + estimatedTransactions = 10000; + } else if (estimatedTransactions < 100) { + estimatedTransactions = 100; + } + return estimatedTransactions; + } + + public static boolean getTxCacheInitOptimizationFromConfig(final Config config) { + return config.hasPath(TX_CACHE_INIT_OPTIMIZATION) + && config.getBoolean(TX_CACHE_INIT_OPTIMIZATION); + } + + + public void setCacheStrategies(Config config) { + if (config.hasPath(CACHE_STRATEGIES)) { + config.getConfig(CACHE_STRATEGIES).resolve().entrySet().forEach(c -> + this.cacheStrategies.put(CacheType.valueOf(c.getKey()), + c.getValue().unwrapped().toString())); + } + } + + public String getCacheStrategy(CacheType dbName) { + return this.cacheStrategies.getOrDefault(dbName, CacheStrategies.getCacheStrategy(dbName)); + } + + public Sha256Hash getDbRoot(String dbName, Sha256Hash defaultV) { + return this.dbRoots.getOrDefault(dbName, defaultV); + } + + public void setDbRoots(Config config) { + if (config.hasPath(MERKLE_ROOT)) { + config.getConfig(MERKLE_ROOT).resolve().entrySet().forEach(c -> + this.dbRoots.put(c.getKey(), Sha256Hash.wrap( + ByteString.fromHex(c.getValue().unwrapped().toString())))); + } + } + private Property createProperty(final ConfigObject conf) { Property property = new Property(); @@ -185,12 +294,12 @@ private Property createProperty(final ConfigObject conf) { File file = new File(path); if (!file.exists() && !file.mkdirs()) { throw new IllegalArgumentException( - "[storage.properties] can not create storage path: " + path); + String.format("[storage.properties] can not create storage path: %s", path)); } if (!file.canWrite()) { throw new IllegalArgumentException( - "[storage.properties] permission denied to write to: " + path); + String.format("[storage.properties] permission denied to write to: %s ", path)); } property.setPath(path); @@ -231,71 +340,58 @@ private static void setIfNeeded(ConfigObject conf, Options dbOptions) { } if (conf.containsKey(COMPRESSION_TYPE_CONFIG_KEY)) { + String param = conf.get(COMPRESSION_TYPE_CONFIG_KEY).unwrapped().toString(); try { dbOptions.compressionType( - CompressionType.getCompressionTypeByPersistentId( - Integer.parseInt( - conf.get(COMPRESSION_TYPE_CONFIG_KEY).unwrapped().toString() - ) - ) - ); + CompressionType.getCompressionTypeByPersistentId(Integer.parseInt(param))); } catch (NumberFormatException e) { - throw new IllegalArgumentException( - "[storage.properties] compressionType must be Integer type."); + throwIllegalArgumentException(COMPRESSION_TYPE_CONFIG_KEY, Integer.class, param); } } if (conf.containsKey(BLOCK_SIZE_CONFIG_KEY)) { + String param = conf.get(BLOCK_SIZE_CONFIG_KEY).unwrapped().toString(); try { - dbOptions.blockSize( - Integer.parseInt( - conf.get(BLOCK_SIZE_CONFIG_KEY).unwrapped().toString() - ) - ); + dbOptions.blockSize(Integer.parseInt(param)); } catch (NumberFormatException e) { - throw new IllegalArgumentException("[storage.properties] blockSize must be Integer type."); + throwIllegalArgumentException(BLOCK_SIZE_CONFIG_KEY, Integer.class, param); } } if (conf.containsKey(WRITE_BUFFER_SIZE_CONFIG_KEY)) { + String param = conf.get(WRITE_BUFFER_SIZE_CONFIG_KEY).unwrapped().toString(); try { - dbOptions.writeBufferSize( - Integer.parseInt( - conf.get(WRITE_BUFFER_SIZE_CONFIG_KEY).unwrapped().toString() - ) - ); + dbOptions.writeBufferSize(Integer.parseInt(param)); } catch (NumberFormatException e) { - throw new IllegalArgumentException( - "[storage.properties] writeBufferSize must be Integer type."); + throwIllegalArgumentException(WRITE_BUFFER_SIZE_CONFIG_KEY, Integer.class, param); } } if (conf.containsKey(CACHE_SIZE_CONFIG_KEY)) { + String param = conf.get(CACHE_SIZE_CONFIG_KEY).unwrapped().toString(); try { - dbOptions.cacheSize( - Long.parseLong( - conf.get(CACHE_SIZE_CONFIG_KEY).unwrapped().toString() - ) - ); + dbOptions.cacheSize(Long.parseLong(param)); } catch (NumberFormatException e) { - throw new IllegalArgumentException("[storage.properties] cacheSize must be Long type."); + throwIllegalArgumentException(CACHE_SIZE_CONFIG_KEY, Long.class, param); } } if (conf.containsKey(MAX_OPEN_FILES_CONFIG_KEY)) { + String param = conf.get(MAX_OPEN_FILES_CONFIG_KEY).unwrapped().toString(); try { - dbOptions.maxOpenFiles( - Integer.parseInt( - conf.get(MAX_OPEN_FILES_CONFIG_KEY).unwrapped().toString() - ) - ); + dbOptions.maxOpenFiles(Integer.parseInt(param)); } catch (NumberFormatException e) { - throw new IllegalArgumentException( - "[storage.properties] maxOpenFiles must be Integer type."); + throwIllegalArgumentException(MAX_OPEN_FILES_CONFIG_KEY, Integer.class, param); } } } + private static void throwIllegalArgumentException(String param, Class type, String actual) { + throw new IllegalArgumentException( + String.format("[storage.properties] %s must be %s type, actual: %s.", + param, type.getSimpleName(), actual)); + } + /** * Set propertyMap of Storage object from Config * diff --git a/common/src/main/java/org/tron/core/exception/AccountResourceInsufficientException.java b/common/src/main/java/org/tron/core/exception/AccountResourceInsufficientException.java index 1318680d463..ba2807e10ab 100644 --- a/common/src/main/java/org/tron/core/exception/AccountResourceInsufficientException.java +++ b/common/src/main/java/org/tron/core/exception/AccountResourceInsufficientException.java @@ -2,10 +2,6 @@ public class AccountResourceInsufficientException extends TronException { - public AccountResourceInsufficientException() { - super("Insufficient bandwidth and balance to create new account"); - } - public AccountResourceInsufficientException(String message) { super(message); } diff --git a/common/src/main/java/org/tron/core/exception/BadBlockException.java b/common/src/main/java/org/tron/core/exception/BadBlockException.java index e3308819d22..224ffc253ee 100644 --- a/common/src/main/java/org/tron/core/exception/BadBlockException.java +++ b/common/src/main/java/org/tron/core/exception/BadBlockException.java @@ -2,6 +2,8 @@ public class BadBlockException extends TronException { + private TypeEnum type = TypeEnum.DEFAULT; + public BadBlockException() { super(); } @@ -9,4 +11,28 @@ public BadBlockException() { public BadBlockException(String message) { super(message); } + + public BadBlockException(TypeEnum type, String message) { + super(message); + this.type = type; + } + + public TypeEnum getType() { + return type; + } + + public enum TypeEnum { + CALC_MERKLE_ROOT_FAILED(1), + DEFAULT(100); + + private Integer value; + + TypeEnum(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + } } diff --git a/common/src/main/java/org/tron/core/exception/DupTransactionException.java b/common/src/main/java/org/tron/core/exception/DupTransactionException.java index 639025ebe81..295500e011f 100644 --- a/common/src/main/java/org/tron/core/exception/DupTransactionException.java +++ b/common/src/main/java/org/tron/core/exception/DupTransactionException.java @@ -1,5 +1,9 @@ package org.tron.core.exception; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.prometheus.Metrics; + public class DupTransactionException extends TronException { public DupTransactionException() { @@ -9,4 +13,10 @@ public DupTransactionException() { public DupTransactionException(String message) { super(message); } + + protected void report() { + Metrics.counterInc(MetricKeys.Counter.TXS, 1, + MetricLabels.Counter.TXS_FAIL, MetricLabels.Counter.TXS_FAIL_DUP); + } + } diff --git a/common/src/main/java/org/tron/core/exception/P2pException.java b/common/src/main/java/org/tron/core/exception/P2pException.java index 8931af3a179..00d82e9fbf7 100644 --- a/common/src/main/java/org/tron/core/exception/P2pException.java +++ b/common/src/main/java/org/tron/core/exception/P2pException.java @@ -1,5 +1,9 @@ package org.tron.core.exception; +import java.util.Locale; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.Metrics; + public class P2pException extends Exception { private TypeEnum type; @@ -7,16 +11,24 @@ public class P2pException extends Exception { public P2pException(TypeEnum type, String errMsg) { super(errMsg); this.type = type; + report(); } public P2pException(TypeEnum type, Throwable throwable) { super(throwable); this.type = type; + report(); } public P2pException(TypeEnum type, String errMsg, Throwable throwable) { super(errMsg, throwable); this.type = type; + report(); + } + + private void report () { + Metrics.counterInc(MetricKeys.Counter.P2P_ERROR, 1, + type.name().toLowerCase(Locale.ROOT)); } public TypeEnum getType() { @@ -38,6 +50,8 @@ public enum TypeEnum { TRX_EXE_FAILED(12, "trx exe failed"), DB_ITEM_NOT_FOUND(13, "DB item not found"), PROTOBUF_ERROR(14, "protobuf inconsistent"), + BLOCK_SIGN_ERROR(15, "block sign error"), + BLOCK_MERKLE_ERROR(16, "block merkle error"), DEFAULT(100, "default exception"); diff --git a/common/src/main/java/org/tron/core/exception/RevokingStoreIllegalStateException.java b/common/src/main/java/org/tron/core/exception/RevokingStoreIllegalStateException.java index fc0b2d56f23..480f850c111 100755 --- a/common/src/main/java/org/tron/core/exception/RevokingStoreIllegalStateException.java +++ b/common/src/main/java/org/tron/core/exception/RevokingStoreIllegalStateException.java @@ -51,4 +51,9 @@ public RevokingStoreIllegalStateException(String message, Throwable cause) { public RevokingStoreIllegalStateException(Throwable cause) { super("", cause); } + + public RevokingStoreIllegalStateException(int activeSession) { + this(String.format("activeSession %d has to be greater than 0", activeSession)); + } + } diff --git a/common/src/main/java/org/tron/core/exception/TaposException.java b/common/src/main/java/org/tron/core/exception/TaposException.java index 222e9c7e83e..234981a9484 100644 --- a/common/src/main/java/org/tron/core/exception/TaposException.java +++ b/common/src/main/java/org/tron/core/exception/TaposException.java @@ -1,6 +1,10 @@ package org.tron.core.exception; -public class TaposException extends Exception { +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.prometheus.Metrics; + +public class TaposException extends TronException { public TaposException() { super(); @@ -14,4 +18,9 @@ public TaposException(String message, Throwable cause) { super(message, cause); } + protected void report() { + Metrics.counterInc(MetricKeys.Counter.TXS, 1, + MetricLabels.Counter.TXS_FAIL, MetricLabels.Counter.TXS_FAIL_TAPOS); + } + } diff --git a/common/src/main/java/org/tron/core/exception/TooBigTransactionException.java b/common/src/main/java/org/tron/core/exception/TooBigTransactionException.java index fa8e3988cf5..cbbb00d7d2c 100644 --- a/common/src/main/java/org/tron/core/exception/TooBigTransactionException.java +++ b/common/src/main/java/org/tron/core/exception/TooBigTransactionException.java @@ -1,5 +1,9 @@ package org.tron.core.exception; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.prometheus.Metrics; + public class TooBigTransactionException extends TronException { public TooBigTransactionException() { @@ -9,4 +13,10 @@ public TooBigTransactionException() { public TooBigTransactionException(String message) { super(message); } + + protected void report() { + Metrics.counterInc(MetricKeys.Counter.TXS, 1, + MetricLabels.Counter.TXS_FAIL, MetricLabels.Counter.TXS_FAIL_BIG); + } + } diff --git a/common/src/main/java/org/tron/core/exception/TransactionExpirationException.java b/common/src/main/java/org/tron/core/exception/TransactionExpirationException.java index e8282a41f80..cac2cd7412b 100644 --- a/common/src/main/java/org/tron/core/exception/TransactionExpirationException.java +++ b/common/src/main/java/org/tron/core/exception/TransactionExpirationException.java @@ -1,5 +1,9 @@ package org.tron.core.exception; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.prometheus.Metrics; + public class TransactionExpirationException extends TronException { public TransactionExpirationException() { @@ -10,4 +14,10 @@ public TransactionExpirationException(String message) { super(message); } + protected void report() { + Metrics.counterInc(MetricKeys.Counter.TXS, 1, + MetricLabels.Counter.TXS_FAIL, MetricLabels.Counter.TXS_FAIL_EXPIRED); + + } + } \ No newline at end of file diff --git a/common/src/main/java/org/tron/core/exception/TronError.java b/common/src/main/java/org/tron/core/exception/TronError.java new file mode 100644 index 00000000000..9d11d249476 --- /dev/null +++ b/common/src/main/java/org/tron/core/exception/TronError.java @@ -0,0 +1,63 @@ +package org.tron.core.exception; + +import lombok.Getter; + +/** + * If a {@link TronError} is thrown, the service will trigger {@link System#exit(int)} by + * {@link Thread#setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler)}. + * NOTE: Do not attempt to catch {@link TronError}. + */ +@Getter +public class TronError extends Error { + + private final ErrCode errCode; + + public TronError(String message, ErrCode exitCode) { + super(message); + this.errCode = exitCode; + } + + public TronError(String message, Throwable cause, ErrCode exitCode) { + super(message, cause); + this.errCode = exitCode; + } + + public TronError(Throwable cause, ErrCode exitCode) { + super(cause); + this.errCode = exitCode; + } + + @Getter + public enum ErrCode { + WITNESS_KEYSTORE_LOAD(-1), + CHECKPOINT_VERSION(-1), + LEVELDB_INIT(1), + ROCKSDB_INIT(1), + DB_FLUSH(1), + REWARD_VI_CALCULATOR(1), + KHAOS_DB_INIT(1), + GENESIS_BLOCK_INIT(1), + EVENT_SUBSCRIBE_ERROR(1), + AUTO_STOP_PARAMS(1), + API_SERVER_INIT(1), + EVENT_SUBSCRIBE_INIT(1), + PROMETHEUS_INIT(1), + TRON_NET_SERVICE_INIT(1), + ZCASH_INIT(1), + LOG_LOAD(1), + WITNESS_INIT(1), + RATE_LIMITER_INIT(1), + SOLID_NODE_INIT(0); + + private final int code; + + ErrCode(int code) { + this.code = code; + } + + @Override + public String toString() { + return name() + "(" + code + ")"; + } + } +} diff --git a/common/src/main/java/org/tron/core/exception/TronException.java b/common/src/main/java/org/tron/core/exception/TronException.java index 686d979b5ca..0447b28969e 100644 --- a/common/src/main/java/org/tron/core/exception/TronException.java +++ b/common/src/main/java/org/tron/core/exception/TronException.java @@ -4,14 +4,21 @@ public class TronException extends Exception { public TronException() { super(); + report(); } public TronException(String message) { super(message); + report(); } public TronException(String message, Throwable cause) { super(message, cause); + report(); + } + + protected void report(){ + } } diff --git a/common/src/main/java/org/tron/core/exception/ValidateSignatureException.java b/common/src/main/java/org/tron/core/exception/ValidateSignatureException.java index 9c85a5f8e3b..b146b7f3398 100644 --- a/common/src/main/java/org/tron/core/exception/ValidateSignatureException.java +++ b/common/src/main/java/org/tron/core/exception/ValidateSignatureException.java @@ -1,5 +1,9 @@ package org.tron.core.exception; +import org.tron.common.prometheus.MetricKeys; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.prometheus.Metrics; + public class ValidateSignatureException extends TronException { public ValidateSignatureException() { @@ -10,4 +14,9 @@ public ValidateSignatureException(String message) { super(message); } + protected void report() { + Metrics.counterInc(MetricKeys.Counter.TXS, 1, + MetricLabels.Counter.TXS_FAIL, MetricLabels.Counter.TXS_FAIL_SIG); + } + } 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 new file mode 100644 index 00000000000..2bdbeb78b92 --- /dev/null +++ b/common/src/main/java/org/tron/core/vm/config/VMConfig.java @@ -0,0 +1,264 @@ +package org.tron.core.vm.config; + +import lombok.Setter; +import org.tron.common.parameter.CommonParameter; + +/** + * For developer only + */ +public class VMConfig { + + private static boolean vmTraceCompressed = false; + + @Setter + private static boolean vmTrace = false; + + private static boolean ALLOW_TVM_TRANSFER_TRC10 = false; + + private static boolean ALLOW_TVM_CONSTANTINOPLE = false; + + private static boolean ALLOW_MULTI_SIGN = false; + + private static boolean ALLOW_TVM_SOLIDITY_059 = false; + + private static boolean ALLOW_SHIELDED_TRC20_TRANSACTION = false; + + private static boolean ALLOW_TVM_ISTANBUL = false; + + private static boolean ALLOW_TVM_FREEZE = false; + + private static boolean ALLOW_TVM_VOTE = false; + + private static boolean ALLOW_TVM_LONDON = false; + + private static boolean ALLOW_TVM_COMPATIBLE_EVM = false; + + private static boolean ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX = false; + + private static boolean ALLOW_TVM_FREEZE_V2 = false; + + private static boolean ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID = false; + + private static boolean ALLOW_DYNAMIC_ENERGY = false; + + private static long DYNAMIC_ENERGY_THRESHOLD = 0L; + + private static long DYNAMIC_ENERGY_INCREASE_FACTOR = 0L; + + private static long DYNAMIC_ENERGY_MAX_FACTOR = 0L; + + private static boolean ALLOW_TVM_SHANGHAI = false; + + private static boolean ALLOW_ENERGY_ADJUSTMENT = false; + + private static boolean ALLOW_STRICT_MATH = false; + + private static boolean ALLOW_TVM_CANCUN = false; + + private static Boolean DISABLE_JAVA_LANG_MATH = false; + + private static boolean ALLOW_TVM_BLOB = false; + + private VMConfig() { + } + + public static boolean vmTrace() { + return vmTrace; + } + + public static boolean vmTraceCompressed() { + return vmTraceCompressed; + } + + public static void initVmHardFork(boolean pass) { + CommonParameter.ENERGY_LIMIT_HARD_FORK = pass; + } + + public static void initAllowMultiSign(long allow) { + ALLOW_MULTI_SIGN = allow == 1; + } + + public static void initAllowTvmTransferTrc10(long allow) { + ALLOW_TVM_TRANSFER_TRC10 = allow == 1; + } + + public static void initAllowTvmConstantinople(long allow) { + ALLOW_TVM_CONSTANTINOPLE = allow == 1; + } + + public static void initAllowTvmSolidity059(long allow) { + ALLOW_TVM_SOLIDITY_059 = allow == 1; + } + + public static void initAllowShieldedTRC20Transaction(long allow) { + ALLOW_SHIELDED_TRC20_TRANSACTION = allow == 1; + } + + public static void initAllowTvmIstanbul(long allow) { + ALLOW_TVM_ISTANBUL = allow == 1; + } + + public static void initAllowTvmFreeze(long allow) { + ALLOW_TVM_FREEZE = allow == 1; + } + + public static void initAllowTvmVote(long allow) { + ALLOW_TVM_VOTE = allow == 1; + } + + public static void initAllowTvmLondon(long allow) { + ALLOW_TVM_LONDON = allow == 1; + } + + public static void initAllowTvmCompatibleEvm(long allow) { + ALLOW_TVM_COMPATIBLE_EVM = allow == 1; + } + + public static void initAllowHigherLimitForMaxCpuTimeOfOneTx(long allow) { + ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX = allow == 1; + } + + public static void initAllowTvmFreezeV2(long allow) { + ALLOW_TVM_FREEZE_V2 = allow == 1; + } + + public static void initAllowOptimizedReturnValueOfChainId(long allow) { + ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID = allow == 1; + } + + public static void initAllowDynamicEnergy(long allow) { + ALLOW_DYNAMIC_ENERGY = allow == 1; + } + + public static void initDynamicEnergyThreshold(long threshold) { + DYNAMIC_ENERGY_THRESHOLD = threshold; + } + + public static void initDynamicEnergyIncreaseFactor(long increaseFactor) { + DYNAMIC_ENERGY_INCREASE_FACTOR = increaseFactor; + } + + public static void initDynamicEnergyMaxFactor(long maxFactor) { + DYNAMIC_ENERGY_MAX_FACTOR = maxFactor; + } + + public static void initAllowTvmShangHai(long allow) { + ALLOW_TVM_SHANGHAI = allow == 1; + } + + public static void initAllowEnergyAdjustment(long allow) { + ALLOW_ENERGY_ADJUSTMENT = allow == 1; + } + + public static void initAllowStrictMath(long allow) { + ALLOW_STRICT_MATH = allow == 1; + } + + public static void initAllowTvmCancun(long allow) { + ALLOW_TVM_CANCUN = allow == 1; + } + + public static void initDisableJavaLangMath(long allow) { + DISABLE_JAVA_LANG_MATH = allow == 1; + } + + public static void initAllowTvmBlob(long allow) { + ALLOW_TVM_BLOB = allow == 1; + } + + public static boolean getEnergyLimitHardFork() { + return CommonParameter.ENERGY_LIMIT_HARD_FORK; + } + + public static boolean allowTvmTransferTrc10() { + return ALLOW_TVM_TRANSFER_TRC10; + } + + public static boolean allowTvmConstantinople() { + return ALLOW_TVM_CONSTANTINOPLE; + } + + public static boolean allowMultiSign() { + return ALLOW_MULTI_SIGN; + } + + public static boolean allowTvmSolidity059() { + return ALLOW_TVM_SOLIDITY_059; + } + + public static boolean allowShieldedTRC20Transaction() { + return ALLOW_SHIELDED_TRC20_TRANSACTION; + } + + public static boolean allowTvmIstanbul() { + return ALLOW_TVM_ISTANBUL; + } + + public static boolean allowTvmFreeze() { + return ALLOW_TVM_FREEZE; + } + + public static boolean allowTvmVote() { + return ALLOW_TVM_VOTE; + } + + public static boolean allowTvmLondon() { + return ALLOW_TVM_LONDON; + } + + public static boolean allowTvmCompatibleEvm() { + return ALLOW_TVM_COMPATIBLE_EVM; + } + + public static boolean allowHigherLimitForMaxCpuTimeOfOneTx() { + return ALLOW_HIGHER_LIMIT_FOR_MAX_CPU_TIME_OF_ONE_TX; + } + + public static boolean allowTvmFreezeV2() { + return ALLOW_TVM_FREEZE_V2; + } + + public static boolean allowOptimizedReturnValueOfChainId() { + return ALLOW_OPTIMIZED_RETURN_VALUE_OF_CHAIN_ID; + } + + public static boolean allowDynamicEnergy() { + return ALLOW_DYNAMIC_ENERGY; + } + + public static long getDynamicEnergyThreshold() { + return DYNAMIC_ENERGY_THRESHOLD; + } + + public static long getDynamicEnergyIncreaseFactor() { + return DYNAMIC_ENERGY_INCREASE_FACTOR; + } + + public static long getDynamicEnergyMaxFactor() { + return DYNAMIC_ENERGY_MAX_FACTOR; + } + + public static boolean allowTvmShanghai() { + return ALLOW_TVM_SHANGHAI; + } + + public static boolean allowEnergyAdjustment() { + return ALLOW_ENERGY_ADJUSTMENT; + } + + public static boolean allowStrictMath() { + return ALLOW_STRICT_MATH; + } + + public static boolean allowTvmCancun() { + return ALLOW_TVM_CANCUN; + } + + public static boolean disableJavaLangMath() { + return DISABLE_JAVA_LANG_MATH; + } + + public static boolean allowTvmBlob() { + return ALLOW_TVM_BLOB; + } +} diff --git a/config/checkstyle/checkStyle.xml b/config/checkstyle/checkStyle.xml index 16fda0fdc4f..9d09ca11bee 100644 --- a/config/checkstyle/checkStyle.xml +++ b/config/checkstyle/checkStyle.xml @@ -1,7 +1,7 @@ + "https://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd"> + @@ -34,6 +36,23 @@ + + ./logs/db/db.log + + ./logs/db/db-%d{yyyy-MM-dd}.%i.log.gz + 500MB + 7 + 50GB + + + %d{HH:mm:ss.SSS} %m%n + UTF-8 + + + TRACE + + + 0 @@ -50,6 +69,13 @@ + + + + + + + @@ -62,7 +88,12 @@ - + + + + + + diff --git a/framework/src/test/java/org/tron/common/BaseTest.java b/framework/src/test/java/org/tron/common/BaseTest.java new file mode 100644 index 00000000000..552808b842c --- /dev/null +++ b/framework/src/test/java/org/tron/common/BaseTest.java @@ -0,0 +1,114 @@ +package org.tron.common; + +import com.google.protobuf.ByteString; +import java.io.IOException; +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.tron.common.application.Application; +import org.tron.common.crypto.ECKey; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.Commons; +import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.base.Param; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.Manager; +import org.tron.core.exception.BalanceInsufficientException; +import org.tron.core.store.AccountStore; +import org.tron.protos.Protocol; + +@Slf4j +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(classes = {DefaultConfig.class}) +@DirtiesContext +public abstract class BaseTest { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Resource + protected Manager dbManager; + @Resource + protected ChainBaseManager chainBaseManager; + + @Resource + protected Application appT; + + private static Application appT1; + + + @PostConstruct + private void prepare() { + appT1 = appT; + } + + public static String dbPath() { + try { + return temporaryFolder.newFolder().toString(); + } catch (IOException e) { + Assert.fail("create temp folder failed"); + } + return null; + } + + @AfterClass + public static void destroy() { + appT1.shutdown(); + Args.clearParam(); + } + + public Protocol.Block getSignedBlock(ByteString witness, long time, byte[] privateKey) { + long blockTime = System.currentTimeMillis() / 3000 * 3000; + if (time != 0) { + blockTime = time; + } else { + if (chainBaseManager.getHeadBlockId().getNum() != 0) { + blockTime = chainBaseManager.getHeadBlockTimeStamp() + 3000; + } + } + Param param = Param.getInstance(); + Param.Miner miner = param.new Miner(privateKey, witness, witness); + BlockCapsule blockCapsule = dbManager + .generateBlock(miner, time, System.currentTimeMillis() + 1000); + Protocol.Block block = blockCapsule.getInstance(); + + Protocol.BlockHeader.raw raw = block.getBlockHeader().getRawData().toBuilder() + .setParentHash(ByteString + .copyFrom(chainBaseManager.getDynamicPropertiesStore() + .getLatestBlockHeaderHash().getBytes())) + .setNumber(chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1) + .setTimestamp(blockTime) + .setWitnessAddress(witness) + .build(); + + ECKey ecKey = ECKey.fromPrivate(privateKey); + assert ecKey != null; + ECKey.ECDSASignature signature = ecKey.sign(Sha256Hash.of(CommonParameter + .getInstance().isECKeyCryptoEngine(), raw.toByteArray()).getBytes()); + ByteString sign = ByteString.copyFrom(signature.toByteArray()); + + Protocol.BlockHeader blockHeader = block.getBlockHeader().toBuilder() + .setRawData(raw) + .setWitnessSignature(sign) + .build(); + + return block.toBuilder().setBlockHeader(blockHeader).build(); + } + + public void adjustBalance(AccountStore accountStore, byte[] accountAddress, long amount) + throws BalanceInsufficientException { + Commons.adjustBalance(accountStore, accountAddress, amount, + chainBaseManager.getDynamicPropertiesStore().disableJavaLangMath()); + } +} diff --git a/framework/src/test/java/org/tron/common/ComparatorTest.java b/framework/src/test/java/org/tron/common/ComparatorTest.java index 51ae5c2d6d6..fec38624364 100644 --- a/framework/src/test/java/org/tron/common/ComparatorTest.java +++ b/framework/src/test/java/org/tron/common/ComparatorTest.java @@ -1,6 +1,7 @@ package org.tron.common; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; import java.util.Comparator; import java.util.List; import lombok.AllArgsConstructor; @@ -8,7 +9,6 @@ import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; -import org.testng.collections.Lists; @Slf4j diff --git a/framework/src/test/java/org/tron/common/EntityTest.java b/framework/src/test/java/org/tron/common/EntityTest.java new file mode 100644 index 00000000000..483475a453b --- /dev/null +++ b/framework/src/test/java/org/tron/common/EntityTest.java @@ -0,0 +1,67 @@ +package org.tron.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Lists; +import java.util.HashMap; +import org.apache.commons.collections4.CollectionUtils; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.entity.NodeInfo; +import org.tron.common.entity.NodeInfo.MachineInfo; +import org.tron.common.entity.NodeInfo.MachineInfo.DeadLockThreadInfo; + +public class EntityTest { + + private final MachineInfo machineInfo = new MachineInfo(); + private final DeadLockThreadInfo deadLockThreadInfo = new DeadLockThreadInfo(); + + @Before + public void setup() { + deadLockThreadInfo.setName("name"); + deadLockThreadInfo.setLockName("lockName"); + deadLockThreadInfo.setLockOwner("lockOwner"); + deadLockThreadInfo.setState("state"); + deadLockThreadInfo.setStackTrace("stackTrace"); + deadLockThreadInfo.setWaitTime(0L); + deadLockThreadInfo.setBlockTime(0L); + machineInfo.setDeadLockThreadInfoList(Lists.newArrayList(deadLockThreadInfo)); + machineInfo.setJavaVersion("1.8"); + machineInfo.setOsName("linux"); + } + + @Test + public void testMachineInfo() { + machineInfo.setDeadLockThreadCount(3); + assertTrue(CollectionUtils.isNotEmpty(machineInfo.getDeadLockThreadInfoList())); + assertEquals(3, machineInfo.getDeadLockThreadCount()); + + } + + @Test + public void testDeadLockThreadInfo() { + assertEquals("name", deadLockThreadInfo.getName()); + assertEquals("lockName", deadLockThreadInfo.getLockName()); + assertEquals("lockOwner", deadLockThreadInfo.getLockOwner()); + assertEquals("state", deadLockThreadInfo.getState()); + assertEquals("stackTrace", deadLockThreadInfo.getStackTrace()); + assertEquals(0, deadLockThreadInfo.getBlockTime()); + assertEquals(0, deadLockThreadInfo.getWaitTime()); + + } + + @Test + public void testNodeInfo() { + NodeInfo nodeInfo = new NodeInfo(); + nodeInfo.setTotalFlow(1L); + nodeInfo.setCheatWitnessInfoMap(new HashMap<>()); + assertEquals(1, nodeInfo.getTotalFlow()); + assertNotNull(nodeInfo.getCheatWitnessInfoMap()); + nodeInfo.setMachineInfo(machineInfo); + nodeInfo.setBlock("block"); + nodeInfo.setSolidityBlock("solidityBlock"); + nodeInfo.transferToProtoEntity(); + } +} diff --git a/framework/src/test/java/org/tron/common/MultiLayoutPatternTest.java b/framework/src/test/java/org/tron/common/MultiLayoutPatternTest.java new file mode 100644 index 00000000000..87223757e8e --- /dev/null +++ b/framework/src/test/java/org/tron/common/MultiLayoutPatternTest.java @@ -0,0 +1,72 @@ +package org.tron.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.LoggerContext; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.LoggingEvent; +import org.junit.Before; +import org.junit.Test; +import org.slf4j.LoggerFactory; +import org.tron.common.log.layout.MultiLayoutPattern; + +public class MultiLayoutPatternTest { + + private MultiLayoutPattern multiLayoutPattern; + private LoggerContext context; + + @Before + public void setUp() { + context = new LoggerContext(); + multiLayoutPattern = new MultiLayoutPattern(); + multiLayoutPattern.setContext(context); + + MultiLayoutPattern.Rule rule1 = new MultiLayoutPattern.Rule(); + rule1.setLogger("com.example.app1"); + assertNotNull(rule1.getLogger()); + rule1.setPattern("%date [%thread] %-5level %logger{36} - %msg%n"); + assertNotNull(rule1.getPattern()); + rule1.setOutputPatternAsHeader(true); + assertTrue(rule1.isOutputPatternAsHeader()); + multiLayoutPattern.addRule(rule1); + + MultiLayoutPattern.Rule rule2 = new MultiLayoutPattern.Rule(); + rule2.setLogger("com.example.app2"); + rule2.setPattern("%msg%n"); + multiLayoutPattern.addRule(rule2); + + multiLayoutPattern.start(); + } + + @Test + public void testEncodeForSpecificLogger() { + ILoggingEvent event1 = createLoggingEvent("com.example.app1", "Test message 1"); + byte[] encoded1 = multiLayoutPattern.encode(event1); + String result1 = new String(encoded1); + assertTrue(result1.contains("Test message 1")); + + ILoggingEvent event2 = createLoggingEvent("com.example.app2", "Test message 2"); + byte[] encoded2 = multiLayoutPattern.encode(event2); + String result2 = new String(encoded2); + assertEquals("Test message 2\n", result2); + } + + @Test + public void testEncodeForRootLogger() { + ILoggingEvent event = createLoggingEvent(Logger.ROOT_LOGGER_NAME, "Root logger message"); + byte[] encoded = multiLayoutPattern.encode(event); + String result = new String(encoded); + assertFalse(result.contains("Root logger message")); + } + + private ILoggingEvent createLoggingEvent(String loggerName, String message) { + Logger logger = (Logger) LoggerFactory.getLogger(loggerName); + return new LoggingEvent(loggerName, logger, Level.INFO, message, null, null); + } + +} diff --git a/framework/src/test/java/org/tron/common/ParameterTest.java b/framework/src/test/java/org/tron/common/ParameterTest.java new file mode 100644 index 00000000000..b16be405f61 --- /dev/null +++ b/framework/src/test/java/org/tron/common/ParameterTest.java @@ -0,0 +1,320 @@ +package org.tron.common; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.tron.common.parameter.RateLimiterInitialization.createHttpItem; +import static org.tron.common.parameter.RateLimiterInitialization.createRpcItem; +import static org.tron.core.Constant.ECKey_ENGINE; + +import com.google.common.collect.Lists; +import com.typesafe.config.ConfigFactory; +import com.typesafe.config.ConfigObject; +import java.util.ArrayList; +import java.util.HashSet; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.parameter.RateLimiterInitialization; +import org.tron.common.parameter.RateLimiterInitialization.HttpRateLimiterItem; +import org.tron.common.parameter.RateLimiterInitialization.RpcRateLimiterItem; +import org.tron.p2p.dns.update.PublishConfig; + +public class ParameterTest { + @Test + public void testConstructor_ValidConfig() { + String configStr = "{\"component\":\"testComponent\",\"strategy\":\"testStrategy\"," + + "\"paramString\":\"testParams\"}"; + ConfigObject config = ConfigFactory.parseString(configStr).root().toConfig().root(); + RpcRateLimiterItem item = new RpcRateLimiterItem(config); + HttpRateLimiterItem item1 = new HttpRateLimiterItem(config); + + assertEquals("testComponent", item.getComponent()); + assertEquals("testComponent", item1.getComponent()); + assertEquals("testStrategy", item.getStrategy()); + assertEquals("testParams", item.getParams()); + assertNull(createRpcItem(null)); + assertNull(createHttpItem(null)); + assertNotNull(createRpcItem(config)); + RateLimiterInitialization rateLimiterInitialization = new RateLimiterInitialization(); + rateLimiterInitialization.setRpcMap(Lists.newArrayList(item)); + assertFalse(rateLimiterInitialization.isHttpFlag()); + assertTrue(rateLimiterInitialization.isRpcFlag()); + } + + @Test + public void testCommonParameter() { + CommonParameter parameter = new CommonParameter(); + parameter.setWitness(false); + parameter.setSupportConstant(false); + parameter.setMaxEnergyLimitForConstant(1000000L); + parameter.setLruCacheSize(5); + parameter.setMinTimeRatio(0); + parameter.setMaxTimeRatio(20); + parameter.setSaveInternalTx(false); + parameter.setSaveFeaturedInternalTx(false); + parameter.setLongRunningTime(60); + parameter.setMaxHttpConnectNumber(5); + + assertEquals(StringUtils.EMPTY, parameter.getLogbackPath()); + assertEquals(1000000L, parameter.getMaxEnergyLimitForConstant()); + assertEquals(5, parameter.getLruCacheSize()); + assertEquals(60, parameter.getLongRunningTime()); + assertFalse(parameter.isHelp()); + assertFalse(parameter.isSaveFeaturedInternalTx()); + assertFalse(parameter.isSaveInternalTx()); + CollectionUtils.isEmpty(parameter.getSeedNodes()); + parameter.setChainId("123"); + assertEquals("123", parameter.getChainId()); + parameter.setNeedSyncCheck(false); + assertFalse(parameter.isNeedSyncCheck()); + parameter.setNodeDiscoveryEnable(false); + assertFalse(parameter.isNodeDiscoveryEnable()); + parameter.setNodeDiscoveryPersist(false); + assertFalse(parameter.isNodeDiscoveryPersist()); + parameter.setNodeEffectiveCheckEnable(false); + assertFalse(parameter.isNodeEffectiveCheckEnable()); + parameter.setNodeConnectionTimeout(500); + assertEquals(500, parameter.getNodeConnectionTimeout()); + parameter.setFetchBlockTimeout(500); + assertEquals(500, parameter.getFetchBlockTimeout()); + parameter.setNodeChannelReadTimeout(500); + assertEquals(500, parameter.getNodeChannelReadTimeout()); + parameter.setMaxConnections(500); + assertEquals(500, parameter.getMaxConnections()); + parameter.setMinConnections(500); + assertEquals(500, parameter.getMinConnections()); + parameter.setMinActiveConnections(500); + assertEquals(500, parameter.getMinActiveConnections()); + parameter.setMaxConnectionsWithSameIp(500); + assertEquals(500, parameter.getMaxConnectionsWithSameIp()); + parameter.setMaxTps(500); + assertEquals(500, parameter.getMaxTps()); + parameter.setMinParticipationRate(500); + assertEquals(500, parameter.getMinParticipationRate()); + parameter.setMaxConnectionsWithSameIp(500); + assertEquals(500, parameter.getMaxConnectionsWithSameIp()); + assertNull(parameter.getP2pConfig()); + parameter.setNodeLanIp("500"); + assertEquals("500", parameter.getNodeLanIp()); + parameter.setNodeP2pVersion(5); + assertEquals(5, parameter.getNodeP2pVersion()); + parameter.setNodeEnableIpv6(false); + assertFalse(parameter.isNodeEnableIpv6()); + parameter.setDnsTreeUrls(new ArrayList<>()); + assertTrue(CollectionUtils.isEmpty(parameter.getDnsTreeUrls())); + parameter.setDnsPublishConfig(new PublishConfig()); + parameter.setSyncFetchBatchNum(500); + assertEquals(500, parameter.getSyncFetchBatchNum()); + parameter.setDebug(false); + assertFalse(parameter.isDebug()); + parameter.setFullNodeHttpPort(80); + assertEquals(80, parameter.getFullNodeHttpPort()); + parameter.setSolidityHttpPort(80); + assertEquals(80, parameter.getSolidityHttpPort()); + parameter.setJsonRpcHttpFullNodePort(80); + assertEquals(80, parameter.getJsonRpcHttpFullNodePort()); + parameter.setJsonRpcHttpSolidityPort(80); + assertEquals(80, parameter.getJsonRpcHttpSolidityPort()); + parameter.setJsonRpcHttpPBFTPort(80); + assertEquals(80, parameter.getJsonRpcHttpPBFTPort()); + parameter.setRpcThreadNum(10); + assertEquals(10, parameter.getRpcThreadNum()); + parameter.setSolidityThreads(5); + assertEquals(5, parameter.getSolidityThreads()); + parameter.setMaxConcurrentCallsPerConnection(10); + assertEquals(10, parameter.getMaxConcurrentCallsPerConnection()); + parameter.setFlowControlWindow(20); + assertEquals(20, parameter.getFlowControlWindow()); + parameter.setMaxConnectionIdleInMillis(1000); + assertEquals(1000, parameter.getMaxConnectionIdleInMillis()); + parameter.setBlockProducedTimeOut(500); + assertEquals(500, parameter.getBlockProducedTimeOut()); + parameter.setNetMaxTrxPerSecond(15); + assertEquals(15, parameter.getNetMaxTrxPerSecond()); + parameter.setMaxConnectionAgeInMillis(1500); + assertEquals(1500, parameter.getMaxConnectionAgeInMillis()); + parameter.setMaxMessageSize(200); + assertEquals(200, parameter.getMaxMessageSize()); + parameter.setMaxHeaderListSize(100); + assertEquals(100, parameter.getMaxHeaderListSize()); + parameter.setRpcReflectionServiceEnable(false); + assertFalse(parameter.isRpcReflectionServiceEnable); + parameter.setValidateSignThreadNum(5); + assertEquals(5, parameter.getValidateSignThreadNum()); + parameter.setMaintenanceTimeInterval(200); + assertEquals(200, parameter.getMaintenanceTimeInterval()); + parameter.setProposalExpireTime(1000); + assertEquals(1000, parameter.getProposalExpireTime()); + parameter.setAllowCreationOfContracts(1); + assertEquals(1, parameter.getAllowCreationOfContracts()); + parameter.setAllowAdaptiveEnergy(1); + assertEquals(1, parameter.getAllowAdaptiveEnergy()); + parameter.setAllowDelegateResource(1); + assertEquals(1, parameter.getAllowDelegateResource()); + parameter.setAllowSameTokenName(1); + assertEquals(1, parameter.getAllowSameTokenName()); + parameter.setAllowTvmTransferTrc10(1); + assertEquals(1, parameter.getAllowTvmTransferTrc10()); + parameter.setAllowTvmConstantinople(1); + assertEquals(1, parameter.getAllowTvmConstantinople()); + parameter.setAllowTvmSolidity059(1); + assertEquals(1, parameter.getAllowTvmSolidity059()); + parameter.setForbidTransferToContract(1); + assertEquals(1, parameter.getForbidTransferToContract()); + parameter.setTcpNettyWorkThreadNum(5); + assertEquals(5, parameter.getTcpNettyWorkThreadNum()); + parameter.setUdpNettyWorkThreadNum(5); + assertEquals(5, parameter.getUdpNettyWorkThreadNum()); + parameter.setTrustNodeAddr("address"); + assertEquals("address", parameter.getTrustNodeAddr()); + parameter.setWalletExtensionApi(false); + assertFalse(parameter.isWalletExtensionApi()); + parameter.setEstimateEnergy(false); + assertFalse(parameter.isEstimateEnergy()); + parameter.setEstimateEnergyMaxRetry(2); + assertEquals(2, parameter.getEstimateEnergyMaxRetry()); + parameter.setKeepAliveInterval(1000); + assertEquals(1000, parameter.getKeepAliveInterval()); + parameter.setReceiveTcpMinDataLength(10); + assertEquals(10, parameter.getReceiveTcpMinDataLength()); + parameter.setOpenFullTcpDisconnect(false); + assertFalse(parameter.isOpenFullTcpDisconnect()); + parameter.setNodeDetectEnable(false); + assertFalse(parameter.isNodeDetectEnable()); + parameter.setAllowMultiSign(1); + assertEquals(1, parameter.getAllowMultiSign()); + parameter.setVmTrace(false); + assertFalse(parameter.isVmTrace()); + parameter.setNeedToUpdateAsset(false); + assertFalse(parameter.isNeedToUpdateAsset()); + parameter.setTrxReferenceBlock("test"); + assertEquals("test", parameter.getTrxReferenceBlock()); + parameter.setTrxCacheEnable(false); + assertFalse(parameter.isTrxCacheEnable()); + parameter.setAllowMarketTransaction(1); + assertEquals(1, parameter.getAllowMarketTransaction()); + parameter.setAllowTransactionFeePool(1); + assertEquals(1, parameter.getAllowTransactionFeePool()); + parameter.setAllowBlackHoleOptimization(1); + assertEquals(1, parameter.getAllowBlackHoleOptimization()); + parameter.setAllowNewResourceModel(1); + assertEquals(1, parameter.getAllowNewResourceModel()); + parameter.setEventSubscribe(false); + assertFalse(parameter.isEventSubscribe()); + parameter.setTrxExpirationTimeInMilliseconds(100); + assertEquals(100, parameter.getTrxExpirationTimeInMilliseconds()); + parameter.setAllowProtoFilterNum(10); + assertEquals(10, parameter.getAllowProtoFilterNum()); + parameter.setShieldedTransInPendingMaxCounts(1); + assertEquals(1, parameter.getShieldedTransInPendingMaxCounts()); + parameter.setChangedDelegation(1); + assertEquals(1, parameter.getChangedDelegation()); + parameter.setActuatorSet(new HashSet<>()); + assertTrue(CollectionUtils.isEmpty(parameter.getActuatorSet())); + parameter.setRateLimiterInitialization(new RateLimiterInitialization()); + assertNotNull(parameter.getRateLimiterInitialization()); + parameter.setRateLimiterGlobalQps(1000); + assertEquals(1000, parameter.getRateLimiterGlobalQps()); + parameter.setRateLimiterGlobalIpQps(100); + assertEquals(100, parameter.getRateLimiterGlobalIpQps()); + assertNull(parameter.getOverlay()); + assertNull(parameter.getEventPluginConfig()); + assertNull(parameter.getEventFilter()); + parameter.setCryptoEngine(ECKey_ENGINE); + assertEquals(ECKey_ENGINE, parameter.getCryptoEngine()); + parameter.setFullNodeHttpEnable(false); + assertFalse(parameter.isFullNodeHttpEnable()); + parameter.setSolidityNodeHttpEnable(false); + assertFalse(parameter.isSolidityNodeHttpEnable()); + parameter.setMaxTransactionPendingSize(500); + assertEquals(500, parameter.getMaxTransactionPendingSize()); + parameter.setPendingTransactionTimeout(500); + assertEquals(500, parameter.getPendingTransactionTimeout()); + parameter.setNodeMetricsEnable(false); + assertFalse(parameter.isNodeMetricsEnable()); + parameter.setMetricsStorageEnable(false); + assertFalse(parameter.isMetricsStorageEnable()); + parameter.setInfluxDbIp("127.0.0.1"); + assertEquals("127.0.0.1", parameter.getInfluxDbIp()); + parameter.setInfluxDbPort(90); + assertEquals(90, parameter.getInfluxDbPort()); + parameter.setInfluxDbDatabase("InfluxDb"); + assertEquals("InfluxDb", parameter.getInfluxDbDatabase()); + parameter.setMetricsReportInterval(100); + assertEquals(100, parameter.getMetricsReportInterval()); + parameter.setMetricsPrometheusPort(3000); + assertEquals(3000, parameter.getMetricsPrometheusPort()); + parameter.setAgreeNodeCount(10); + assertEquals(10, parameter.getAgreeNodeCount()); + parameter.setAllowPBFT(1); + assertEquals(1, parameter.getAllowPBFT()); + parameter.setPBFTHttpPort(70); + assertEquals(70, parameter.getPBFTHttpPort()); + parameter.setPBFTExpireNum(100); + assertEquals(100, parameter.getPBFTExpireNum()); + parameter.setAllowShieldedTRC20Transaction(10); + assertEquals(10, parameter.getAllowShieldedTRC20Transaction()); + parameter.setAllowTvmIstanbul(1); + assertEquals(1, parameter.getAllowTvmIstanbul()); + parameter.setAllowTvmVote(1); + assertEquals(1, parameter.getAllowTvmVote()); + parameter.setAllowTvmLondon(1); + assertEquals(1, parameter.getAllowTvmLondon()); + parameter.setAllowTvmCompatibleEvm(1); + assertEquals(1, parameter.getAllowTvmCompatibleEvm()); + parameter.setAllowHigherLimitForMaxCpuTimeOfOneTx(1); + assertEquals(1, parameter.getAllowHigherLimitForMaxCpuTimeOfOneTx()); + parameter.setHistoryBalanceLookup(false); + assertFalse(parameter.isHistoryBalanceLookup()); + parameter.setOpenPrintLog(false); + assertFalse(parameter.isOpenPrintLog()); + parameter.setOpenTransactionSort(false); + assertFalse(parameter.isOpenTransactionSort()); + parameter.setAllowAssetOptimization(1); + assertEquals(1, parameter.getAllowAssetOptimization()); + parameter.setAllowAccountAssetOptimization(1); + assertEquals(1, parameter.getAllowAccountAssetOptimization()); + parameter.setBlockCacheTimeout(60); + assertEquals(60, parameter.getBlockCacheTimeout()); + parameter.setAllowNewReward(1); + assertEquals(1, parameter.getAllowNewReward()); + parameter.setAllowNewRewardAlgorithm(1); + assertEquals(1, parameter.getAllowNewRewardAlgorithm()); + parameter.setMemoFee(100); + assertEquals(100, parameter.getMemoFee()); + parameter.setAllowDelegateOptimization(1); + assertEquals(1, parameter.getAllowDelegateOptimization()); + parameter.setUnfreezeDelayDays(10); + assertEquals(10, parameter.getUnfreezeDelayDays()); + parameter.setAllowOptimizedReturnValueOfChainId(1); + assertEquals(1, parameter.getAllowOptimizedReturnValueOfChainId()); + parameter.setAllowDynamicEnergy(1); + assertEquals(1, parameter.getAllowDynamicEnergy()); + parameter.setDynamicEnergyThreshold(1); + assertEquals(1, parameter.getDynamicEnergyThreshold()); + parameter.setDynamicEnergyIncreaseFactor(1); + assertEquals(1, parameter.getDynamicEnergyIncreaseFactor()); + parameter.setDynamicEnergyMaxFactor(1); + assertEquals(1, parameter.getDynamicEnergyMaxFactor()); + parameter.setDynamicConfigEnable(false); + assertFalse(parameter.isDynamicConfigEnable()); + parameter.setDynamicConfigCheckInterval(10); + assertEquals(10, parameter.getDynamicConfigCheckInterval()); + parameter.setAllowTvmShangHai(1); + assertEquals(1, parameter.getAllowTvmShangHai()); + parameter.setAllowCancelAllUnfreezeV2(1); + assertEquals(1, parameter.getAllowCancelAllUnfreezeV2()); + parameter.setMaxUnsolidifiedBlocks(100); + assertEquals(100, parameter.getMaxUnsolidifiedBlocks()); + parameter.setAllowOldRewardOpt(1); + assertEquals(1, parameter.getAllowOldRewardOpt()); + parameter.setAllowEnergyAdjustment(1); + assertEquals(1, parameter.getAllowEnergyAdjustment()); + parameter.setMaxCreateAccountTxSize(1000); + assertEquals(1000, parameter.getMaxCreateAccountTxSize()); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java b/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java new file mode 100644 index 00000000000..9ace8f5b601 --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/BackupManagerTest.java @@ -0,0 +1,142 @@ +package org.tron.common.backup; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.backup.BackupManager.BackupStatusEnum; +import org.tron.common.backup.message.KeepAliveMessage; +import org.tron.common.backup.socket.BackupServer; +import org.tron.common.backup.socket.UdpEvent; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.PublicMethod; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class BackupManagerTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + private BackupManager manager; + private BackupServer backupServer; + + @Before + public void setUp() throws Exception { + Args.setParam(new String[] {"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + CommonParameter.getInstance().setBackupPort(PublicMethod.chooseRandomPort()); + manager = new BackupManager(); + backupServer = new BackupServer(manager); + } + + @After + public void tearDown() { + Args.clearParam(); + } + + @Test + public void test() throws Exception { + CommonParameter.getInstance().setBackupPriority(8); + List members = new ArrayList<>(); + members.add("127.0.0.2"); + CommonParameter.getInstance().setBackupMembers(members); + + Field field = manager.getClass().getDeclaredField("localIp"); + field.setAccessible(true); + field.set(manager, "127.0.0.1"); + + Assert.assertEquals(BackupManager.BackupStatusEnum.MASTER, manager.getStatus()); + + field = manager.getClass().getDeclaredField("executorService"); + field.setAccessible(true); + ScheduledExecutorService executorService = (ScheduledExecutorService) field.get(manager); + manager.init(); + executorService.shutdown(); + Assert.assertEquals(BackupManager.BackupStatusEnum.INIT, manager.getStatus()); + + /* ip not in the members */ + manager.setStatus(BackupManager.BackupStatusEnum.INIT); + KeepAliveMessage message = new KeepAliveMessage(false, 6); + InetSocketAddress address = new InetSocketAddress("127.0.0.3", 1000); + UdpEvent event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupManager.BackupStatusEnum.INIT, manager.getStatus()); + + /* ip not the member */ + address = new InetSocketAddress("127.0.0.3", 1000); + message = new KeepAliveMessage(false, 6); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupManager.BackupStatusEnum.INIT, manager.getStatus()); + + /* keepAliveMessage.getFlag() || peerPriority > priority */ + address = new InetSocketAddress("127.0.0.2", 1000); + message = new KeepAliveMessage(false, 6); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupStatusEnum.SLAVER, manager.getStatus()); + + /* keepAliveMessage.getFlag() || peerPriority > priority */ + message = new KeepAliveMessage(false, 10); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupManager.BackupStatusEnum.SLAVER, manager.getStatus()); + + /* keepAliveMessage.getFlag() || peerPriority > priority */ + manager.setStatus(BackupManager.BackupStatusEnum.INIT); + message = new KeepAliveMessage(true, 6); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupManager.BackupStatusEnum.SLAVER, manager.getStatus()); + + manager.setStatus(BackupManager.BackupStatusEnum.MASTER); + message = new KeepAliveMessage(false, 10); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupManager.BackupStatusEnum.MASTER, manager.getStatus()); + + message = new KeepAliveMessage(true, 10); + event = new UdpEvent(message, address); + manager.handleEvent(event); + Assert.assertEquals(BackupManager.BackupStatusEnum.SLAVER, manager.getStatus()); + + } + + @Test + public void testSendKeepAliveMessage() throws Exception { + CommonParameter parameter = CommonParameter.getInstance(); + parameter.setBackupPriority(8); + List members = new ArrayList<>(); + members.add("127.0.0.2"); + parameter.setBackupMembers(members); + + Field field = manager.getClass().getDeclaredField("localIp"); + field.setAccessible(true); + field.set(manager, "127.0.0.1"); + + Assert.assertEquals(manager.getStatus(), BackupManager.BackupStatusEnum.MASTER); + backupServer.initServer(); + 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(); + + Assert.assertEquals(BackupManager.BackupStatusEnum.INIT, manager.getStatus()); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/BackupServerTest.java b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java new file mode 100644 index 00000000000..c40aca7e17a --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/BackupServerTest.java @@ -0,0 +1,50 @@ +package org.tron.common.backup; + +import java.util.ArrayList; +import java.util.List; +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.rules.Timeout; +import org.tron.common.backup.socket.BackupServer; +import org.tron.common.parameter.CommonParameter; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + + +public class BackupServerTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Rule + public Timeout globalTimeout = Timeout.seconds(60); + private BackupServer backupServer; + + @Before + public void setUp() throws Exception { + Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + CommonParameter.getInstance().setBackupPort(80); + List members = new ArrayList<>(); + members.add("127.0.0.2"); + CommonParameter.getInstance().setBackupMembers(members); + BackupManager backupManager = new BackupManager(); + backupManager.init(); + backupServer = new BackupServer(backupManager); + } + + @After + public void tearDown() { + backupServer.close(); + Args.clearParam(); + } + + @Test(timeout = 60_000) + public void test() throws InterruptedException { + backupServer.initServer(); + // wait for the server to start + Thread.sleep(1000); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/KeepAliveMessageTest.java b/framework/src/test/java/org/tron/common/backup/KeepAliveMessageTest.java new file mode 100644 index 00000000000..67658331913 --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/KeepAliveMessageTest.java @@ -0,0 +1,32 @@ +package org.tron.common.backup; + +import static org.tron.common.backup.message.UdpMessageTypeEnum.BACKUP_KEEP_ALIVE; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.backup.message.KeepAliveMessage; +import org.tron.protos.Discover; + +public class KeepAliveMessageTest { + + @Test + public void test() throws Exception { + KeepAliveMessage m1 = new KeepAliveMessage(true, 10); + Assert.assertTrue(m1.getFlag()); + Assert.assertEquals(m1.getPriority(), 10); + Assert.assertEquals(m1.getType(), BACKUP_KEEP_ALIVE); + Assert.assertNull(m1.getFrom()); + Assert.assertEquals(m1.getTimestamp(), 0); + Assert.assertEquals(m1.getData().length + 1, m1.getSendData().length); + + + Discover.BackupMessage backupMessage = Discover.BackupMessage.newBuilder() + .setFlag(true).setPriority(10).build(); + KeepAliveMessage m2 = new KeepAliveMessage(backupMessage.toByteArray()); + Assert.assertTrue(m2.getFlag()); + Assert.assertEquals(m2.getPriority(), 10); + Assert.assertEquals(m2.getType(), BACKUP_KEEP_ALIVE); + + Assert.assertArrayEquals(m2.getMessageId().getBytes(), m1.getMessageId().getBytes()); + } +} diff --git a/framework/src/test/java/org/tron/common/backup/UdpMessageTypeEnumTest.java b/framework/src/test/java/org/tron/common/backup/UdpMessageTypeEnumTest.java new file mode 100644 index 00000000000..72253fa710e --- /dev/null +++ b/framework/src/test/java/org/tron/common/backup/UdpMessageTypeEnumTest.java @@ -0,0 +1,23 @@ +package org.tron.common.backup; + +import static org.tron.common.backup.message.UdpMessageTypeEnum.BACKUP_KEEP_ALIVE; +import static org.tron.common.backup.message.UdpMessageTypeEnum.UNKNOWN; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.backup.message.UdpMessageTypeEnum; + +public class UdpMessageTypeEnumTest { + + @Test + public void test() { + UdpMessageTypeEnum type = UdpMessageTypeEnum.fromByte((byte) 5); + Assert.assertEquals(type.getType(), (byte) 0x05); + Assert.assertEquals(type, BACKUP_KEEP_ALIVE); + + + type = UdpMessageTypeEnum.fromByte((byte) 1); + Assert.assertEquals(type.getType(), (byte) 0xFF); + Assert.assertEquals(type, UNKNOWN); + } +} diff --git a/framework/src/test/java/org/tron/common/cache/TronCacheTest.java b/framework/src/test/java/org/tron/common/cache/TronCacheTest.java new file mode 100644 index 00000000000..422bd1de881 --- /dev/null +++ b/framework/src/test/java/org/tron/common/cache/TronCacheTest.java @@ -0,0 +1,100 @@ +package org.tron.common.cache; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.tron.common.cache.CacheManager.allocate; +import static org.tron.common.cache.CacheStrategies.CACHE_STRATEGY_DEFAULT; +import static org.tron.common.cache.CacheType.findByType; +import static org.tron.common.cache.CacheType.witness; +import static org.tron.common.cache.CacheType.witnessStandby; + +import com.google.common.cache.CacheLoader; +import java.util.concurrent.ExecutionException; +import javax.annotation.ParametersAreNonnullByDefault; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; + +@Slf4j +public class TronCacheTest { + + private TronCache cacheWithLoader; + private TronCache cacheWithoutLoader; + CacheLoader loader = new CacheLoader() { + @Override + @ParametersAreNonnullByDefault + public String load(String key) { + return "Loaded: " + key; + } + }; + + @Before + public void setUp() { + + cacheWithLoader = new TronCache<>(witness, CACHE_STRATEGY_DEFAULT, loader); + + cacheWithoutLoader = new TronCache<>(witnessStandby, CACHE_STRATEGY_DEFAULT); + } + + @Test + public void testGetIfPresent() { + cacheWithoutLoader.put("key1", "value1"); + assertEquals("value1", cacheWithoutLoader.getIfPresent("key1")); + assertNull(cacheWithoutLoader.getIfPresent("key2")); + } + + @Test + public void testGetWithLoader() throws ExecutionException { + String value = cacheWithLoader.get("key1", () -> "Fallback value"); + assertEquals("Fallback value", value); + } + + @Test + public void testPutAndGet() { + cacheWithoutLoader.put("key2", "value2"); + assertEquals("value2", cacheWithoutLoader.getIfPresent("key2")); + assertEquals(witnessStandby, cacheWithoutLoader.getName()); + logger.info("hash code: {}", cacheWithoutLoader.hashCode()); + } + + @Test + public void testStats() { + cacheWithoutLoader.put("key3", "value3"); + assertNotNull(cacheWithoutLoader.stats()); + assertEquals(0, cacheWithoutLoader.stats().hitCount()); + cacheWithoutLoader.getIfPresent("key3"); + assertTrue(cacheWithoutLoader.stats().hitCount() > 0); + } + + @Test + public void testInvalidateAll() { + cacheWithoutLoader.put("key4", "value4"); + assertEquals("value4", cacheWithoutLoader.getIfPresent("key4")); + cacheWithoutLoader.invalidateAll(); + assertNull(cacheWithoutLoader.getIfPresent("key4")); + } + + @Test + public void testEquals() { + TronCache tmpCache = cacheWithoutLoader; + assertEquals(cacheWithoutLoader, tmpCache); + assertNotEquals(cacheWithoutLoader, new Object()); + assertNotEquals(cacheWithoutLoader, cacheWithLoader); + tmpCache = new TronCache<>(witnessStandby, CACHE_STRATEGY_DEFAULT); + assertEquals(cacheWithoutLoader, tmpCache); + } + + @Test + public void testCacheManager() { + TronCache allocate = allocate(witness, CACHE_STRATEGY_DEFAULT); + TronCache allocate1 = allocate(witness, CACHE_STRATEGY_DEFAULT, loader); + assertNotNull(allocate); + assertNotNull(allocate1); + assertThrows(IllegalArgumentException.class, () -> findByType("test")); + } + +} diff --git a/framework/src/test/java/org/tron/common/config/args/ArgsTest.java b/framework/src/test/java/org/tron/common/config/args/ArgsTest.java index 0578b76136f..01a49f6df40 100644 --- a/framework/src/test/java/org/tron/common/config/args/ArgsTest.java +++ b/framework/src/test/java/org/tron/common/config/args/ArgsTest.java @@ -1,32 +1,67 @@ package org.tron.common.config.args; -import java.io.File; +import com.beust.jcommander.JCommander; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import org.tron.common.utils.FileUtil; +import org.junit.rules.TemporaryFolder; +import org.tron.common.parameter.RateLimiterInitialization; import org.tron.core.Constant; import org.tron.core.config.args.Args; public class ArgsTest { + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Before - public void init() { - Args.setParam(new String[]{"--output-directory", "output-directory", "--debug"}, - Constant.TEST_CONF); + public void init() throws IOException { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString(), "--p2p-disable", "true", + "--debug"}, Constant.TEST_CONF); } @After public void destroy() { Args.clearParam(); - FileUtil.deleteDir(new File("output-directory")); } @Test public void testConfig() { + Args.logConfig(); Assert.assertEquals(Args.getInstance().getMaxTransactionPendingSize(), 2000); Assert.assertEquals(Args.getInstance().getPendingTransactionTimeout(), 60_000); - Assert.assertEquals(Args.getInstance().getNodeDiscoveryPingTimeout(), 15_000); + Assert.assertEquals(Args.getInstance().getMaxFastForwardNum(), 4); + Assert.assertEquals(Args.getInstance().getBlockCacheTimeout(), 60); + Assert.assertEquals(Args.getInstance().isNodeDetectEnable(), false); + Assert.assertFalse(Args.getInstance().isNodeEffectiveCheckEnable()); + Assert.assertEquals(Args.getInstance().getRateLimiterGlobalQps(), 1000); + Assert.assertEquals(Args.getInstance().getRateLimiterGlobalIpQps(), 1000); + Assert.assertEquals(Args.getInstance().getRateLimiterGlobalApiQps(), 100); + Assert.assertEquals(Args.getInstance().p2pDisable, true); + Assert.assertEquals(Args.getInstance().getMaxTps(), 1000); + RateLimiterInitialization rateLimiter = Args.getInstance().getRateLimiterInitialization(); + Assert.assertEquals(rateLimiter.getHttpMap().size(), 1); + Assert.assertEquals(rateLimiter.getRpcMap().size(), 0); + Assert.assertTrue(Args.getInstance().isRpcReflectionServiceEnable()); + } + + @Test + public void testHelpMessage() { + JCommander jCommander = JCommander.newBuilder().addObject(Args.PARAMETER).build(); + Method method; + try { + method = Args.class.getDeclaredMethod("printVersion"); + method.setAccessible(true); + method.invoke(Args.class); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + Assert.fail(); + } + Args.printHelp(jCommander); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/org/tron/common/cron/CronExpressionTest.java b/framework/src/test/java/org/tron/common/cron/CronExpressionTest.java new file mode 100644 index 00000000000..5e41670763c --- /dev/null +++ b/framework/src/test/java/org/tron/common/cron/CronExpressionTest.java @@ -0,0 +1,450 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + * Copyright IBM Corp. 2024, 2025 + * + * 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.tron.common.cron; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.fail; + +import java.text.ParseException; +import java.util.Calendar; +import java.util.Date; +import org.junit.Test; + +public class CronExpressionTest { + + private static void assertTrue(boolean condition, String message) { + if (!condition) { + fail(message); + } + } + + private static void assertTrue(boolean condition) { + if (!condition) { + fail(); + } + } + + @Test + public void testTooManyTokens() { + try { + new CronExpression("0 15 10 * * ? 2005 *"); // too many tokens/terms in expression + fail("Expected ParseException did not occur for invalid expression"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().contains("too many"), + "Incorrect ParseException thrown"); + } + + } + + @Test + public void testIsSatisfiedBy() throws Exception { + CronExpression cronExpression = new CronExpression("0 15 10 * * ? 2005"); + + Calendar cal = Calendar.getInstance(); + + cal.set(2005, Calendar.JUNE, 1, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cal.set(Calendar.YEAR, 2006); + assertFalse(cronExpression.isSatisfiedBy(cal.getTime())); + + cal = Calendar.getInstance(); + cal.set(2005, Calendar.JUNE, 1, 10, 16, 0); + assertFalse(cronExpression.isSatisfiedBy(cal.getTime())); + + cal = Calendar.getInstance(); + cal.set(2005, Calendar.JUNE, 1, 10, 14, 0); + assertFalse(cronExpression.isSatisfiedBy(cal.getTime())); + } + + @Test + public void testIsValidExpression() { + assertTrue(CronExpression.isValidExpression("0 0 0 L-2 * ? *")); + assertTrue(CronExpression.isValidExpression("0 0 0 LW * ? *")); + assertFalse(CronExpression.isValidExpression("0 0 0 Foo * ? *")); + assertFalse(CronExpression.isValidExpression("61 15 10 L-2 * ? 2010")); + assertFalse(CronExpression.isValidExpression("0 61 10 L-2 * ? 2010")); + assertFalse(CronExpression.isValidExpression("0 15 25 L-2 * ? 2010")); + assertTrue(CronExpression.isValidExpression("0/5 * * * * ?")); + assertTrue(CronExpression.isValidExpression("0 0 2 * * ?")); + assertTrue(CronExpression.isValidExpression("0 15 8 ? * MON-FRI")); + assertTrue(CronExpression.isValidExpression("0 45 15 1,15 * ? 2005")); + assertTrue(CronExpression.isValidExpression("0 10 * * * ?")); + assertTrue(CronExpression.isValidExpression("0 0 12 L 3,6,9,12 ?")); + assertTrue(CronExpression.isValidExpression("0 0 6 ? DEC,JAN SUN,SAT")); + assertTrue(CronExpression.isValidExpression("0 0 12 1/5 * ?")); + assertTrue(CronExpression.isValidExpression("0 0 8-18 ? * MON,WED,FRI")); + assertTrue(CronExpression.isValidExpression("0 10,44 14 ? 3 WED 2022/2")); + assertTrue(CronExpression.isValidExpression("0 0/30 9-17 * * ? 2022-2025")); + assertTrue(CronExpression.isValidExpression("0 15 10 ? * 6#3 2022,2023")); + assertTrue(CronExpression.isValidExpression("0 10,44 14 ? 3 WED 2022/2")); + assertTrue(CronExpression.isValidExpression("0 0/5 14,18 * * ?")); + assertTrue(CronExpression.isValidExpression("0 15 10 ? * 6#3")); + assertFalse(CronExpression.isValidExpression(" 0 15 10 ? * 6#3 2014-2012")); + assertTrue(CronExpression.isValidExpression("0 0 20-18 ? * MON,WED,FRI")); + assertTrue(CronExpression.isValidExpression("0 0/30 17-9 * 10-9 ? 2022")); + + } + + @Test + public void testLastDayOffset() throws Exception { + CronExpression cronExpression = new CronExpression("0 15 10 L-2 * ? 2010"); + cronExpression.setTimeZone(Calendar.getInstance().getTimeZone()); + + Calendar cal = Calendar.getInstance(); + // last day - 2 + cal.set(2010, Calendar.OCTOBER, 29, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cal.set(2010, Calendar.OCTOBER, 28, 10, 15, 0); + assertFalse(cronExpression.isSatisfiedBy(cal.getTime())); + + cronExpression = new CronExpression("0 15 10 L-5W * ? 2010"); + // last day - 5 + cal.set(2010, Calendar.OCTOBER, 26, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cronExpression = new CronExpression("0 15 10 L-1 * ? 2010"); + // last day - 1 + cal.set(2010, Calendar.OCTOBER, 30, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cronExpression = new CronExpression("0 15 10 L-1W * ? 2010"); + // nearest weekday to last day - 1 (29th is a friday in 2010) + cal.set(2010, Calendar.OCTOBER, 29, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cronExpression = new CronExpression("0 15 10 1,L * ? 2010"); + + cal.set(2010, Calendar.OCTOBER, 1, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cal.set(2010, Calendar.OCTOBER, 31, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cal.set(2010, Calendar.OCTOBER, 30, 10, 15, 0); + assertFalse(cronExpression.isSatisfiedBy(cal.getTime())); + + cronExpression = new CronExpression("0 15 10 L-1W,L-1 * ? 2010"); + // nearest weekday to last day - 1 (29th is a friday in 2010) + cal.set(2010, Calendar.OCTOBER, 29, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + // last day - 1 + cal.set(2010, Calendar.OCTOBER, 30, 10, 15, 0); + + cronExpression = new CronExpression("0 15 10 2W,16 * ? 2010"); + // nearest weekday to the 2nd of the month (1st is a friday in 2010) + cal.set(2010, Calendar.OCTOBER, 1, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + cal.set(2010, Calendar.OCTOBER, 2, 10, 15, 0); + assertFalse(cronExpression.isSatisfiedBy(cal.getTime())); + + cal.set(2010, Calendar.OCTOBER, 16, 10, 15, 0); + assertTrue(cronExpression.isSatisfiedBy(cal.getTime())); + + } + + @Test + public void testQuartz() throws Exception { + CronExpression cronExpression = new CronExpression("19 15 10 4 Apr ? "); + assertEquals("19 15 10 4 Apr ? ".toUpperCase(), cronExpression.getCronExpression()); + assertEquals("19 15 10 4 Apr ? ".toUpperCase(), cronExpression.toString()); + + // if broken, this will throw an exception + cronExpression.getNextValidTimeAfter(new Date()); + + try { + new CronExpression(null); + fail("Expected ParseException did not fire for null "); + } catch (IllegalArgumentException e) { + assertTrue(e.getMessage().equals("cronExpression cannot be null"), + "Incorrect ParseException thrown"); + } + + try { + new CronExpression("* * * * Foo ? "); + fail("Expected ParseException did not fire for nonexistent month"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith("Invalid Month value:"), + "Incorrect ParseException thrown"); + } + + try { + new CronExpression("* * * * Jan-Foo ? "); + fail("Expected ParseException did not fire for nonexistent month"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith("Invalid Month value:"), + "Incorrect ParseException thrown"); + } + + try { + new CronExpression("0 0 * * * *"); + fail("Expected ParseException did not fire for wildcard day-of-month and day-of-week"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith( + "Support for specifying both a day-of-week AND" + + " a day-of-month parameter is not implemented."), + "Incorrect ParseException thrown"); + } + try { + new CronExpression("0 0 * 4 * *"); + fail("Expected ParseException did not fire for specified day-of-month and" + + " wildcard day-of-week"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith( + "Support for specifying both a day-of-week AND a day-of-month" + + " parameter is not implemented."), "Incorrect ParseException thrown"); + } + try { + new CronExpression("0 0 * * * 4"); + fail("Expected ParseException did not fire for wildcard day-of-month" + + " and specified day-of-week"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith( + "Support for specifying both a day-of-week AND a day-of-month" + + " parameter is not implemented."), "Incorrect ParseException thrown"); + } + + try { + new CronExpression("0 43 9 ? * SAT,SUN,L"); + fail("Expected ParseException did not fire for L combined with other days of the week"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith( + "Support for specifying 'L' with other days of the week is not implemented"), + "Incorrect ParseException thrown"); + } + try { + new CronExpression("0 43 9 ? * 6,7,L"); + fail("Expected ParseException did not fire for L combined with other days of the week"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith( + "Support for specifying 'L' with other days of the week is not implemented"), + "Incorrect ParseException thrown"); + } + try { + new CronExpression("0 43 9 ? * 5L"); + } catch (ParseException pe) { + fail("Unexpected ParseException thrown for supported '5L' expression."); + } + } + + @Test + public void testQtz96() throws ParseException { + try { + new CronExpression("0/5 * * 32W 1 ?"); + fail("Expected ParseException did not fire for W with value larger than 31"); + } catch (ParseException pe) { + assertTrue(pe.getMessage().startsWith( + "The 'W' option does not make sense with values larger than"), + "Incorrect ParseException thrown"); + } + + // Test case 1 + try { + new CronExpression("/120 0 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in '_blank/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 60 : 120", e.getMessage()); + } + + // Test case 2 + try { + new CronExpression("0/120 0 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in in '0/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 60 : 120", e.getMessage()); + } + + // Test case 3 + try { + new CronExpression("/ 0 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in '_blank/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 4 + try { + new CronExpression("0/ 0 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in '0/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 1 + try { + new CronExpression("0 /120 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in '_blank/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 60 : 120", e.getMessage()); + } + + // Test case 2 + try { + new CronExpression("0 0/120 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in in '0/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 60 : 120", e.getMessage()); + } + + // Test case 3 + try { + new CronExpression("0 / 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in '_blank/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 4 + try { + new CronExpression("0 0/ 8-18 ? * 2-6"); + fail("Cron did not validate bad range interval in '0/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 1 + try { + new CronExpression("0 0 /120 ? * 2-6"); + fail("Cron did not validate bad range interval in '_blank/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 24 : 120", e.getMessage()); + } + + // Test case 2 + try { + new CronExpression("0 0 0/120 ? * 2-6"); + fail("Cron did not validate bad range interval in in '0/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 24 : 120", e.getMessage()); + } + + // Test case 3 + try { + new CronExpression("0 0 / ? * 2-6"); + fail("Cron did not validate bad range interval in '_blank/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 4 + try { + new CronExpression("0 0 0/ ? * 2-6"); + fail("Cron did not validate bad range interval in '0/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 1 + try { + new CronExpression("0 0 0 /120 * 2-6"); + fail("Cron did not validate bad range interval in '_blank/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 31 : 120", e.getMessage()); + } + + // Test case 2 + try { + new CronExpression("0 0 0 0/120 * 2-6"); + fail("Cron did not validate bad range interval in in '0/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 31 : 120", e.getMessage()); + } + + // Test case 3 + try { + new CronExpression("0 0 0 / * 2-6"); + fail("Cron did not validate bad range interval in '_blank/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 4 + try { + new CronExpression("0 0 0 0/ * 2-6"); + fail("Cron did not validate bad range interval in '0/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + // Test case 1 + try { + new CronExpression("0 0 0 ? /120 2-6"); + fail("Cron did not validate bad range interval in '_blank/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 12 : 120", e.getMessage()); + } + + // Test case 2 + try { + new CronExpression("0 0 0 ? 0/120 2-6"); + fail("Cron did not validate bad range interval in in '0/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 12 : 120", e.getMessage()); + } + + // Test case 3 + try { + new CronExpression("0 0 0 ? / 2-6"); + fail("Cron did not validate bad range interval in '_blank/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 4 + try { + new CronExpression("0 0 0 ? 0/ 2-6"); + fail("Cron did not validate bad range interval in '0/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + // Test case 1 + try { + new CronExpression("0 0 0 ? * /120"); + fail("Cron did not validate bad range interval in '_blank/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 7 : 120", e.getMessage()); + } + + // Test case 2 + try { + new CronExpression("0 0 0 ? * 0/120"); + fail("Cron did not validate bad range interval in in '0/xxx' form"); + } catch (ParseException e) { + assertEquals("Increment > 7 : 120", e.getMessage()); + } + + // Test case 3 + try { + new CronExpression("0 0 0 ? * /"); + fail("Cron did not validate bad range interval in '_blank/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + + // Test case 4 + try { + new CronExpression("0 0 0 ? * 0/"); + fail("Cron did not validate bad range interval in '0/_blank'"); + } catch (ParseException e) { + assertEquals("'/' must be followed by an integer.", e.getMessage()); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java index ebb12f25284..ab6b2832c12 100644 --- a/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java +++ b/framework/src/test/java/org/tron/common/crypto/BouncyCastleTest.java @@ -2,24 +2,32 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.tron.common.utils.client.utils.AbiUtil.generateOccupationConstantPrivateKey; import java.math.BigInteger; import java.security.SignatureException; import java.util.Arrays; import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; import org.tron.common.crypto.sm2.SM2; import org.tron.common.utils.Sha256Hash; +/** + * The reason the test case uses the private key plaintext is to ensure that, + * after the ECkey tool or algorithm is upgraded, + * the upgraded differences can be verified. + */ public class BouncyCastleTest { - private String privString = "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"; - private BigInteger privateKey = new BigInteger(privString, 16); + // For safety reasons, test with a placeholder private key + private final String privString = generateOccupationConstantPrivateKey(); + private final BigInteger privateKey = new BigInteger(privString, 16); @Test public void testHex() { - String spongyAddress = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + String spongyAddress = "2e988a386a799f506693793c6a5af6b54dfaabfb"; ECKey key = ECKey.fromPrivate(privateKey); byte[] address = key.getAddress(); assertEquals(spongyAddress, @@ -49,10 +57,9 @@ public void testSha3Hash() { @Test public void testECKeyAddress() { - String spongyPubkey = - "040947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f698ccc8ad75" - + "aa17564ae80a20bb044ee7a6d903e8e8df624b089c95d66a0570f051e5a05b"; - String spongyAddress = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + String spongyPubkey = "04e90c7d3640a1568839c31b70a893ab6714ef8415b9de90cedfc1c8f353a6983e625529" + + "392df7fa514bdd65a2003f6619567d79bee89830e63e932dbd42362d34"; + String spongyAddress = "2e988a386a799f506693793c6a5af6b54dfaabfb"; ECKey key = ECKey.fromPrivate(privateKey); byte[] pubkey = key.getPubKey(); assertEquals(spongyPubkey, Hex.toHexString(pubkey)); @@ -65,7 +72,7 @@ public void testECKeyAddress() { public void testECKeySignature() throws SignatureException { SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString), true); String msg = "transaction raw data"; - String spongyAddress = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + String spongyAddress = "2e988a386a799f506693793c6a5af6b54dfaabfb"; byte[] hash = Sha256Hash.hash(true, msg.getBytes()); String sig = sign.signHash(hash); byte[] address = SignUtils.signatureToAddress(hash, sig, true); @@ -96,9 +103,9 @@ public void testSM3Hash() { @Test public void testSM2Address() { - String spongyPublickey = "04f9539070c135be6183cbff4539f8298755df5981022769cd16cfdcb917fa7e32" - + "4e83b50f0bdbb34acd6ccbb78d45a8a383403f26bbd03805a178c43407dfdeae"; - String spongyAddress = "7dc44d739a5226c0d3037bb7919f653eb2f938b9"; + String spongyPublickey = "04dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c6824058ac" + + "35ddecb12f3a8bbc3104a2b91a2b7d04851d773d9b4ab8d5e0359243c8628"; + String spongyAddress = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; SM2 key = SM2.fromPrivate(privateKey); assertEquals(spongyPublickey, Hex.toHexString(key.getPubKey())); byte[] address = key.getAddress(); @@ -109,7 +116,7 @@ public void testSM2Address() { public void testSM2Signature() throws SignatureException { SignInterface sign = SignUtils.fromPrivate(Hex.decode(privString), false); String msg = "transaction raw data"; - String spongyAddress = "7dc44d739a5226c0d3037bb7919f653eb2f938b9"; + String spongyAddress = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; byte[] hash = Sha256Hash.hash(false, msg.getBytes()); String sig = sign.signHash(hash); byte[] address = SignUtils.signatureToAddress(hash, sig, false); @@ -126,4 +133,21 @@ public void testSM2SpongySignature() throws SignatureException { byte[] address = SignUtils.signatureToAddress(hash, spongySig, false); assertEquals(spongyAddress, Hex.toHexString(Arrays.copyOfRange(address, 1, 21))); } + + @Test + public void testSignToAddress() { + String messageHash = "818e0e76976123b9b78b6076cc2b5d53e61b49ff9cf78304de688a860ce7cb95"; + String base64Sign = "G1y76mVO6TRpFwp3qOiLVzHA8uFsrDiOL7hbC2uN9qTHHiLypaW4vnQkfkoUygjo5qBd" + + "+NlYQ/mAPVWKu6K00co="; + try { + SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign, Boolean.TRUE); + } catch (Exception e) { + Assert.assertTrue(e instanceof SignatureException); + } + try { + SignUtils.signatureToAddress(Hex.decode(messageHash), base64Sign, Boolean.FALSE); + } catch (Exception e) { + Assert.assertTrue(e instanceof SignatureException); + } + } } diff --git a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java index facdcaccccc..4e7d45ee8d7 100644 --- a/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/ECKeyTest.java @@ -7,6 +7,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.AbiUtil.generateOccupationConstantPrivateKey; import java.math.BigInteger; import java.security.KeyPairGenerator; @@ -19,19 +20,25 @@ import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.core.Wallet; +/** + * The reason the test case uses the private key plaintext is to ensure that, + * after the ECkey tool or algorithm is upgraded, + * the upgraded differences can be verified. + */ @Slf4j public class ECKeyTest { - private String privString = "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"; + // For safety reasons, test with a placeholder private key + private String privString = generateOccupationConstantPrivateKey(); private BigInteger privateKey = new BigInteger(privString, 16); - private String pubString = "040947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f698ccc" - + "8ad75aa17564ae80a20bb044ee7a6d903e8e8df624b089c95d66a0570f051e5a05b"; + private String pubString = "04e90c7d3640a1568839c31b70a893ab6714ef8415b9de90cedfc1c8f353a6983e62" + + "5529392df7fa514bdd65a2003f6619567d79bee89830e63e932dbd42362d34"; private String compressedPubString = - "030947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f6" + "98ccc8ad"; + "02e90c7d3640a1568839c31b70a893ab6714ef8415b9de90cedfc1c8f353a6983e"; private byte[] pubKey = Hex.decode(pubString); private byte[] compressedPubKey = Hex.decode(compressedPubString); - private String address = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + private String address = "2e988a386a799f506693793c6a5af6b54dfaabfb"; String eventSign = "eventBytesL(address,bytes,bytes32,uint256,string)"; @Test @@ -41,7 +48,7 @@ public void testSha3() { @Test public void testHashCode() { - assertEquals(-351262686, ECKey.fromPrivate(privateKey).hashCode()); + assertEquals(-827927068, ECKey.fromPrivate(privateKey).hashCode()); } @Test diff --git a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java b/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java index 80d355eb2cf..b84026d2085 100644 --- a/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java +++ b/framework/src/test/java/org/tron/common/crypto/SM2KeyTest.java @@ -6,6 +6,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.AbiUtil.generateOccupationConstantPrivateKey; import java.math.BigInteger; import java.security.KeyPairGenerator; @@ -19,25 +20,31 @@ import org.tron.common.crypto.sm2.SM2Signer; import org.tron.core.Wallet; +/** + * The reason the test case uses the private key plaintext is to ensure that, + * after the ECkey tool or algorithm is upgraded, + * the upgraded differences can be verified. + */ @Slf4j public class SM2KeyTest { //private String IDa = "ALICE123@YAHOO.COM"; private static BigInteger SM2_N = new BigInteger("FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6" + "B21C6052B53BBF40939D54123", 16); - private String privString = "128B2FA8BD433C6C068C8D803DFF79792A519A55171B1B650C23661D15897263"; + // For safety reasons, test with a placeholder private key + private String privString = generateOccupationConstantPrivateKey(); private BigInteger privateKey = new BigInteger(privString, 16); - private String pubString = "04d5548c7825cbb56150a3506cd57464af8a1ae0519dfaf3c58221dc810caf28d" - + "d921073768fe3d59ce54e79a49445cf73fed23086537027264d168946d479533e"; + private String pubString = "04dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c6824058ac" + + "35ddecb12f3a8bbc3104a2b91a2b7d04851d773d9b4ab8d5e0359243c8628"; private String compressedPubString = - "02d5548c7825cbb56150a3506cd57464af8a1ae0519dfaf3c58221dc810caf28dd"; + "02dc3547dbbc4c90a9cde599848e26cb145e805b3d11daaf9daae0680d9c682405"; private byte[] pubKey = Hex.decode(pubString); private byte[] compressedPubKey = Hex.decode(compressedPubString); - private String address = "62e49e4c2f4e3c0653a02f8859c1e6991b759e87"; + private String address = "6cb22f88564bdd61eb4cdb36215add53bc702ff1"; @Test public void testHashCode() { - assertEquals(1126288006, SM2.fromPrivate(privateKey).hashCode()); + assertEquals(578690511, SM2.fromPrivate(privateKey).hashCode()); } @Test @@ -109,7 +116,7 @@ public void testSM3Hash() { SM2Signer signer = key.getSM2SignerForHash(); String message = "message digest"; byte[] hash = signer.generateSM3Hash(message.getBytes()); - assertEquals("299C7DDB0D8DD2A85381BACBB92F738F390210A493A144C78E18C67B430DA882", + assertEquals("2A723761EAE35429DF643648FD69FB7787E7FC32F321BFAF7E294390F529BAF4", Hex.toHexString(hash).toUpperCase()); } diff --git a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java index bed38852ef3..b413127db53 100644 --- a/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java +++ b/framework/src/test/java/org/tron/common/crypto/SignatureInterfaceTest.java @@ -8,35 +8,26 @@ import org.bouncycastle.util.encoders.Hex; import org.junit.Test; import org.tron.common.crypto.sm2.SM2; +import org.tron.common.utils.PublicMethod; @Slf4j public class SignatureInterfaceTest { - private String SM2_privString = "128B2FA8BD433C6C068C8D803DFF79792A519A5517" - + "1B1B650C23661D15897263"; + private String SM2_privString = PublicMethod.getSM2RandomPrivateKey(); private byte[] SM2_privateKey = Hex.decode(SM2_privString); - private String SM2_pubString = "04d5548c7825cbb56150a3506cd57464af8a1ae0519" - + "dfaf3c58221dc810caf28dd921073768fe3d59ce54e79a49445cf73fed23086537" - + "027264d168946d479533e"; - private String SM2_compressedPubString = - "02d5548c7825cbb56150a3506cd57464af8a1ae0519dfaf3c58221dc810caf28dd"; + private String SM2_pubString = PublicMethod.getSM2PublicByPrivateKey(SM2_privString); private byte[] SM2_pubKey = Hex.decode(SM2_pubString); - private byte[] SM2_compressedPubKey = Hex.decode(SM2_compressedPubString); - private String SM2_address = "62e49e4c2f4e3c0653a02f8859c1e6991b759e87"; + private String SM2_address = PublicMethod.getSM2AddressByPrivateKey(SM2_privString); - - private String EC_privString = "c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4"; + private String EC_privString = PublicMethod.getRandomPrivateKey(); private byte[] EC_privateKey = Hex.decode(EC_privString); - private String EC_pubString = "040947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f698ccc" - + "8ad75aa17564ae80a20bb044ee7a6d903e8e8df624b089c95d66a0570f051e5a05b"; - private String EC_compressedPubString = - "030947751e3022ecf3016be03ec77ab0ce3c2662b4843898cb068d74f6" + "98ccc8ad"; + private String EC_pubString = PublicMethod.getPublicByPrivateKey(EC_privString); private byte[] EC_pubKey = Hex.decode(EC_pubString); - private byte[] EC_compressedPubKey = Hex.decode(EC_compressedPubString); - private String EC_address = "cd2a3d9f938e13cd947ec05abc7fe734df8dd826"; + private String EC_address = PublicMethod.getHexAddressByPrivateKey(EC_privString); + @Test @@ -83,11 +74,12 @@ public void testAddress() { SignInterface sign = new SM2(SM2_pubKey, false); byte[] prefix_address = sign.getAddress(); byte[] address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); - assertEquals(SM2_address, Hex.toHexString(address)); - + byte[] addressTmp = Arrays.copyOfRange(Hex.decode(SM2_address), 1, prefix_address.length); + assertEquals(Hex.toHexString(addressTmp), Hex.toHexString(address)); sign = new ECKey(EC_pubKey, false); prefix_address = sign.getAddress(); address = Arrays.copyOfRange(prefix_address, 1, prefix_address.length); - assertEquals(EC_address, Hex.toHexString(address)); + byte[] ecAddressTmp = Arrays.copyOfRange(Hex.decode(EC_address), 1, prefix_address.length); + assertEquals(Hex.toHexString(ecAddressTmp), Hex.toHexString(address)); } } diff --git a/framework/src/test/java/org/tron/common/jetty/JettyServerTest.java b/framework/src/test/java/org/tron/common/jetty/JettyServerTest.java new file mode 100644 index 00000000000..fbb2721f502 --- /dev/null +++ b/framework/src/test/java/org/tron/common/jetty/JettyServerTest.java @@ -0,0 +1,64 @@ +package org.tron.common.jetty; + +import java.net.URI; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.impl.client.DefaultHttpClient; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.DefaultServlet; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.common.utils.PublicMethod; + +@Slf4j +public class JettyServerTest { + private static Server server; + private static URI serverUri; + + @BeforeClass + public static void startJetty() throws Exception { + server = new Server(); + ServerConnector connector = new ServerConnector(server); + connector.setPort(PublicMethod.chooseRandomPort()); + server.addConnector(connector); + + ServletContextHandler context = new ServletContextHandler(); + ServletHolder defaultServ = new ServletHolder("default", DefaultServlet.class); + context.addServlet(defaultServ, "/"); + server.setHandler(context); + server.start(); + String host = connector.getHost(); + if (host == null) { + host = "localhost"; + } + int port = connector.getLocalPort(); + serverUri = new URI(String.format("http://%s:%d/", host, port)); + } + + @AfterClass + public static void stopJetty() { + try { + server.stop(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Test + public void testGet() throws Exception { + HttpClient client = new DefaultHttpClient(); + HttpGet request = new HttpGet(serverUri.resolve("/")); + request.setHeader("Content-Length", "+450"); + HttpResponse mockResponse = client.execute(request); + Assert.assertTrue(mockResponse.getStatusLine().toString().contains( + "400 Invalid Content-Length Value")); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/DesensitizedConverterTest.java b/framework/src/test/java/org/tron/common/logsfilter/DesensitizedConverterTest.java new file mode 100644 index 00000000000..abdc0eccdfd --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/DesensitizedConverterTest.java @@ -0,0 +1,32 @@ +package org.tron.common.logsfilter; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.log.layout.DesensitizedConverter; + +public class DesensitizedConverterTest { + + @Test + public void testReplace() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + DesensitizedConverter converter = new DesensitizedConverter(); + DesensitizedConverter.addSensitive("192.168.1.10", "address1"); + DesensitizedConverter.addSensitive("197.168.1.10", "address2"); + + Method method = converter.getClass().getDeclaredMethod( + "desensitization", String.class); + method.setAccessible(true); + + String logStr1 = "This is test log /192.168.1.10:100, /197.168.1.10:200, /197.168.1.10:100"; + String result1 = (String) method.invoke(converter, logStr1); + Assert.assertEquals("This is test log /address1:100, /address2:200, /address2:100", + result1); + + String logStr2 = "This is test log /192.168.1.100:100, /197.168.1.10:200, /197.168.1.10:100"; + String result2 = (String) method.invoke(converter, logStr2); + Assert.assertEquals("This is test log /IP:100, /address2:200, /address2:100", + result2); + } +} 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 c2bf24ba383..1e5268ddeb6 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventLoaderTest.java @@ -1,9 +1,15 @@ package org.tron.common.logsfilter; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; +import org.tron.common.logsfilter.trigger.BlockLogTrigger; +import org.tron.common.logsfilter.trigger.TransactionLogTrigger; public class EventLoaderTest { @@ -13,19 +19,81 @@ public void launchNativeQueue() { config.setSendQueueLength(1000); config.setBindPort(5555); config.setUseNativeQueue(true); + config.setPluginPath("pluginPath"); + config.setServerAddress("serverAddress"); + config.setDbConfig("dbConfig"); + assertEquals("pluginPath", config.getPluginPath()); + assertEquals("serverAddress", config.getServerAddress()); + assertEquals("dbConfig", config.getDbConfig()); List triggerConfigList = new ArrayList<>(); - TriggerConfig blockTriggerConfig = new TriggerConfig(); - blockTriggerConfig.setTriggerName("block"); - blockTriggerConfig.setEnabled(true); - blockTriggerConfig.setTopic("block"); - triggerConfigList.add(blockTriggerConfig); + TriggerConfig triggerConfig = new TriggerConfig(); + triggerConfig.setTriggerName("block"); + triggerConfig.setEnabled(true); + triggerConfig.setTopic("topic"); + triggerConfig.setRedundancy(false); + triggerConfig.setEthCompatible(false); + triggerConfig.setSolidified(false); + assertFalse(triggerConfig.isRedundancy()); + assertFalse(triggerConfig.isEthCompatible()); + assertFalse(triggerConfig.isSolidified()); + assertEquals("topic", triggerConfig.getTopic()); + triggerConfigList.add(triggerConfig); config.setTriggerConfigList(triggerConfigList); - Assert.assertEquals(true, EventPluginLoader.getInstance().start(config)); + assertTrue(EventPluginLoader.getInstance().start(config)); EventPluginLoader.getInstance().stopPlugin(); } + + @Test + public void testBlockLogTrigger() { + BlockLogTrigger blt = new BlockLogTrigger(); + blt.setBlockHash(blt.getBlockHash()); + blt.setBlockNumber(blt.getBlockNumber()); + blt.setTransactionSize(blt.getTransactionSize()); + blt.setLatestSolidifiedBlockNumber(blt.getLatestSolidifiedBlockNumber()); + blt.setTriggerName(blt.getTriggerName()); + blt.setTimeStamp(blt.getTimeStamp()); + blt.setTransactionList(blt.getTransactionList()); + Assert.assertNotNull(blt.toString()); + } + + @Test + public void testTransactionLogTrigger() { + TransactionLogTrigger tlt = new TransactionLogTrigger(); + tlt.setBlockHash(tlt.getBlockHash()); + tlt.setBlockNumber(tlt.getBlockNumber()); + tlt.setTransactionId(tlt.getTransactionId()); + tlt.setLatestSolidifiedBlockNumber(tlt.getLatestSolidifiedBlockNumber()); + tlt.setTriggerName(tlt.getTriggerName()); + tlt.setTimeStamp(tlt.getTimeStamp()); + tlt.setEnergyFee(tlt.getEnergyFee()); + tlt.setNetFee(tlt.getNetFee()); + tlt.setEnergyUsage(tlt.getEnergyUsage()); + tlt.setAssetAmount(tlt.getAssetAmount()); + tlt.setContractAddress(tlt.getContractAddress()); + tlt.setResult(tlt.getResult()); + tlt.setContractResult(tlt.getContractResult()); + tlt.setContractType(tlt.getContractType()); + tlt.setContractCallValue(tlt.getContractCallValue()); + tlt.setFromAddress(tlt.getFromAddress()); + tlt.setToAddress(tlt.getToAddress()); + tlt.setTransactionIndex(tlt.getTransactionIndex()); + tlt.setFeeLimit(tlt.getFeeLimit()); + tlt.setCumulativeEnergyUsed(tlt.getCumulativeEnergyUsed()); + tlt.setData(tlt.getData()); + tlt.setOriginEnergyUsage(tlt.getOriginEnergyUsage()); + tlt.setEnergyUsageTotal(tlt.getEnergyUsageTotal()); + tlt.setNetUsage(tlt.getNetUsage()); + tlt.setAssetName(tlt.getAssetName()); + tlt.setInternalTransactionList(tlt.getInternalTransactionList()); + tlt.setPreCumulativeLogCount(tlt.getPreCumulativeLogCount()); + tlt.setLogList(tlt.getLogList()); + tlt.setEnergyUnitPrice(tlt.getEnergyUnitPrice()); + tlt.setTimeStamp(1L); + Assert.assertNotNull(tlt.toString()); + } } diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java index 33ab712e52b..34a8e82c424 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventParserJsonTest.java @@ -7,8 +7,8 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.crypto.Hash; import org.tron.common.utils.ByteArray; import org.tron.core.Wallet; diff --git a/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java b/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java index 5745102156b..eff644b9cd9 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/EventParserTest.java @@ -5,11 +5,13 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; +import org.bouncycastle.util.Arrays; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.crypto.Hash; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.WalletUtil; import org.tron.core.Wallet; import org.tron.core.vm.LogInfoTriggerParser; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; @@ -56,6 +58,8 @@ public synchronized void testEventParser() { + "000000000"; ABI abi = TvmTestUtils.jsonStr2Abi(abiStr); + Assert.assertFalse(WalletUtil.isConstant(abi, new byte[3])); + byte[] data = ByteArray.fromHexString(dataStr); List topicList = new LinkedList<>(); topicList.add(Hash.sha3(eventSign.getBytes())); @@ -72,7 +76,7 @@ public synchronized void testEventParser() { } Assert.assertEquals(LogInfoTriggerParser.getEntrySignature(entry), eventSign); - Assert.assertEquals(Hash.sha3(LogInfoTriggerParser.getEntrySignature(entry).getBytes()), + Assert.assertArrayEquals(Hash.sha3(LogInfoTriggerParser.getEntrySignature(entry).getBytes()), topicList.get(0)); Assert.assertNotNull(entry); Map dataMap = ContractEventParserAbi.parseEventData(data, topicList, entry); @@ -96,4 +100,18 @@ public synchronized void testEventParser() { Assert.assertEquals(dataMap.get("str"), "abcdefg123"); } + + @Test + public void testParseRevert() { + String dataHex = "08c379a0" + + "0000000000000000000000000000000000000000000000000000000000000020" + + "0000000000000000000000000000000000000000000000000000000000000016" + + "6e6f7420656e6f75676820696e7075742076616c756500000000000000000000"; + + byte[] data = ByteArray.fromHexString(dataHex); + String msg = ContractEventParser.parseDataBytes(Arrays.copyOfRange(data, 4, data.length), + "string", 0); + Assert.assertEquals(msg, "not enough input value"); + + } } diff --git a/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java b/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java index 601cf72b294..5ee32d98ee6 100644 --- a/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java +++ b/framework/src/test/java/org/tron/common/logsfilter/FilterQueryTest.java @@ -1,6 +1,13 @@ package org.tron.common.logsfilter; +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.tron.common.logsfilter.EventPluginLoader.matchFilter; +import static org.tron.common.logsfilter.FilterQuery.EARLIEST_BLOCK_NUM; +import static org.tron.common.logsfilter.FilterQuery.LATEST_BLOCK_NUM; import static org.tron.common.logsfilter.FilterQuery.parseFromBlockNumber; import static org.tron.common.logsfilter.FilterQuery.parseToBlockNumber; @@ -9,54 +16,57 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Test; import org.tron.common.logsfilter.capsule.ContractEventTriggerCapsule; +import org.tron.common.logsfilter.capsule.FilterTriggerCapsule; +import org.tron.common.logsfilter.capsule.TriggerCapsule; import org.tron.common.runtime.LogEventWrapper; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI.Entry; +@Slf4j public class FilterQueryTest { @Test public synchronized void testParseFilterQueryBlockNumber() { - { - String blockNum = ""; - Assert.assertEquals(FilterQuery.LATEST_BLOCK_NUM, parseToBlockNumber(blockNum)); - } + assertEquals(LATEST_BLOCK_NUM, parseToBlockNumber(EMPTY)); + assertEquals(13245, parseToBlockNumber("13245")); - { - String blockNum = "earliest"; - Assert.assertEquals(FilterQuery.EARLIEST_BLOCK_NUM, parseFromBlockNumber(blockNum)); - } + assertEquals(EARLIEST_BLOCK_NUM, parseFromBlockNumber("earliest")); + assertEquals(13245, parseFromBlockNumber("13245")); + assertThrows(Exception.class, () -> parseFromBlockNumber("test")); + assertThrows(Exception.class, () -> parseToBlockNumber("test")); - { - String blockNum = "13245"; - Assert.assertEquals(13245, parseToBlockNumber(blockNum)); - } } @Test public synchronized void testMatchFilter() { - String[] addrList = {"address1", "address2"}; + String[] adrList = {"address1", "address2"}; String[] topList = {"top1", "top2"}; - Map topMap = new HashMap(); + Map topMap = new HashMap<>(); List addressList = new ArrayList<>(); - addressList.add(addrList[0].getBytes()); - addressList.add(addrList[1].getBytes()); + addressList.add(adrList[0].getBytes()); + addressList.add(adrList[1].getBytes()); topMap.put("1", topList[0]); topMap.put("2", topList[1]); LogEventWrapper event = new LogEventWrapper(); - ((LogEventWrapper) event).setTopicList(addressList); - ((LogEventWrapper) event).setData(new byte[]{}); - ((LogEventWrapper) event).setEventSignature(""); - ((LogEventWrapper) event).setAbiEntry(Entry.newBuilder().setName("testABI").build()); - event.setBlockNumber(new Long(123)); + event.setTopicList(addressList); + event.setData(new byte[]{}); + event.setEventSignature(""); + event.setAbiEntry(Entry.newBuilder().setName("testABI").build()); + event.setBlockNumber(123L); ContractEventTriggerCapsule capsule = new ContractEventTriggerCapsule(event); + capsule.setContractEventTrigger(capsule.getContractEventTrigger()); capsule.getContractEventTrigger().setContractAddress("address1"); + capsule.setLatestSolidifiedBlockNumber(0L); + capsule.setData(capsule.getData()); + capsule.setTopicList(capsule.getTopicList()); + capsule.setAbiEntry(capsule.getAbiEntry()); capsule.getContractEventTrigger().setTopicMap(topMap); { - Assert.assertEquals(true, matchFilter(capsule.getContractEventTrigger())); + Assert.assertTrue(matchFilter(capsule.getContractEventTrigger())); } { @@ -64,7 +74,7 @@ public synchronized void testMatchFilter() { filterQuery.setFromBlock(1); filterQuery.setToBlock(100); EventPluginLoader.getInstance().setFilterQuery(filterQuery); - Assert.assertEquals(false, matchFilter(capsule.getContractEventTrigger())); + Assert.assertFalse(matchFilter(capsule.getContractEventTrigger())); } { @@ -72,17 +82,33 @@ public synchronized void testMatchFilter() { filterQuery.setFromBlock(133); filterQuery.setToBlock(190); EventPluginLoader.getInstance().setFilterQuery(filterQuery); - Assert.assertEquals(false, matchFilter(capsule.getContractEventTrigger())); + Assert.assertFalse(matchFilter(capsule.getContractEventTrigger())); } { FilterQuery filterQuery = new FilterQuery(); filterQuery.setFromBlock(100); filterQuery.setToBlock(190); - filterQuery.setContractAddressList(Arrays.asList(addrList)); + filterQuery.setContractAddressList(Arrays.asList(adrList)); filterQuery.setContractTopicList(Arrays.asList(topList)); EventPluginLoader.getInstance().setFilterQuery(filterQuery); - Assert.assertEquals(true, matchFilter(capsule.getContractEventTrigger())); + Assert.assertTrue(matchFilter(capsule.getContractEventTrigger())); + capsule.processTrigger(); + assertNotNull(filterQuery.toString()); + } + + FilterTriggerCapsule filterTriggerCapsule = new FilterTriggerCapsule(); + try { + filterTriggerCapsule.processFilterTrigger(); + } catch (Exception e) { + logger.info(e.getMessage()); + } + + TriggerCapsule triggerCapsule = new TriggerCapsule(); + try { + triggerCapsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof UnsupportedOperationException); } } } diff --git a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java new file mode 100644 index 00000000000..975d41a9051 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleMockTest.java @@ -0,0 +1,128 @@ +package org.tron.common.logsfilter; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.protobuf.ByteString; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; +import org.tron.common.logsfilter.trigger.InternalTransactionPojo; +import org.tron.common.runtime.InternalTransaction; +import org.tron.common.runtime.ProgramResult; +import org.tron.common.runtime.RuntimeImpl; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.ReceiptCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.db.TransactionTrace; +import org.tron.p2p.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + + + + +public class TransactionLogTriggerCapsuleMockTest { + + private static final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + private static final String RECEIVER_ADDRESS = "41abd4b9367799eaa3197fecb144eb71de1e049150"; + private static final String CONTRACT_ADDRESS = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; + + private TransactionCapsule transactionCapsule; + private BlockCapsule blockCapsule; + + @Before + public void setup() { + blockCapsule = new BlockCapsule(1, + Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), + Sha256Hash.ZERO_HASH.getByteString() + ); + } + + @After + public void clearMocks() { + + } + + + @Test + public void testConstructorWithTransactionTrace() { + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = spy(new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract)); + + TransactionTrace trace = mock(TransactionTrace.class); + ReceiptCapsule receiptCapsule = new ReceiptCapsule(Sha256Hash.ZERO_HASH); + RuntimeImpl runtime = mock(RuntimeImpl.class); + List logs = new ArrayList<>(); + logs.add(Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom("address".getBytes())) + .setData(ByteString.copyFrom("data".getBytes())) + .addTopics(ByteString.copyFrom("topic".getBytes())) + .build()); + + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder() + .addAllLog(logs); + + ProgramResult programResult = ProgramResult.createEmpty(); + programResult.setHReturn("hreturn".getBytes()); + programResult.setContractAddress(CONTRACT_ADDRESS.getBytes()); + + when(transactionCapsule.getTrxTrace()).thenReturn(trace); + when(trace.getReceipt()).thenReturn(receiptCapsule); + when(trace.getRuntime()).thenReturn(runtime); + when(runtime.getResult()).thenReturn(programResult); + + transactionCapsule.setTrxTrace(trace); + + TransactionLogTriggerCapsule triggerCapsule = new TransactionLogTriggerCapsule( + transactionCapsule, blockCapsule,0,0,0, + builder.build(),0); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger()); + } + + @Test + public void testGetInternalTransactionList() throws Exception { + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract); + InternalTransaction internalTransaction = new InternalTransaction( + "parentHash".getBytes(), 10, 0, + "sendAddress".getBytes(), + "transferToAddress".getBytes(), + 100L, "data".getBytes(), "note", + 0L, new HashMap<>() + ); + List internalTransactionList = new ArrayList<>(); + internalTransactionList.add(internalTransaction); + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Method privateMethod = TransactionLogTriggerCapsule.class.getDeclaredMethod( + "getInternalTransactionList", List.class); + privateMethod.setAccessible(true); + List pojoList = (List) + privateMethod.invoke(triggerCapsule, internalTransactionList); + + Assert.assertNotNull(pojoList); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java new file mode 100644 index 00000000000..ce0f63ef7a4 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/TransactionLogTriggerCapsuleTest.java @@ -0,0 +1,289 @@ +package org.tron.common.logsfilter; + +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; + +import com.google.protobuf.ByteString; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.StringUtil; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.p2p.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.Common; +import org.tron.protos.contract.SmartContractOuterClass; + +public class TransactionLogTriggerCapsuleTest { + + private static final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + private static final String RECEIVER_ADDRESS = "41abd4b9367799eaa3197fecb144eb71de1e049150"; + private static final String CONTRACT_ADDRESS = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; + + public TransactionCapsule transactionCapsule; + public BlockCapsule blockCapsule; + + @Before + public void setup() { + blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + } + + @Test + public void testConstructorWithUnfreezeBalanceTrxCapsule() { + BalanceContract.UnfreezeBalanceContract.Builder builder2 = + BalanceContract.UnfreezeBalanceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.UnfreezeBalanceContract); + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder(); + builder.setUnfreezeAmount(TRX_PRECISION + 1000); + + + TransactionLogTriggerCapsule triggerCapsule = new TransactionLogTriggerCapsule( + transactionCapsule, blockCapsule,0,0,0, + builder.build(),0); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + Assert.assertEquals(TRX_PRECISION + 1000, + triggerCapsule.getTransactionLogTrigger().getAssetAmount()); + } + + + @Test + public void testConstructorWithFreezeBalanceV2TrxCapsule() { + BalanceContract.FreezeBalanceV2Contract.Builder builder2 = + BalanceContract.FreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setFrozenBalance(TRX_PRECISION + 100000) + .setResource(Common.ResourceCode.BANDWIDTH); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.FreezeBalanceV2Contract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertEquals("trx", triggerCapsule.getTransactionLogTrigger().getAssetName()); + Assert.assertEquals(TRX_PRECISION + 100000, + triggerCapsule.getTransactionLogTrigger().getAssetAmount()); + } + + @Test + public void testConstructorWithUnfreezeBalanceV2TrxCapsule() { + BalanceContract.UnfreezeBalanceV2Contract.Builder builder2 = + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setUnfreezeBalance(TRX_PRECISION + 4000) + .setResource(Common.ResourceCode.BANDWIDTH); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.UnfreezeBalanceV2Contract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertEquals("trx", triggerCapsule.getTransactionLogTrigger().getAssetName()); + Assert.assertEquals(TRX_PRECISION + 4000, + triggerCapsule.getTransactionLogTrigger().getAssetAmount()); + } + + + @Test + public void testConstructorWithWithdrawExpireTrxCapsule() { + BalanceContract.WithdrawExpireUnfreezeContract.Builder builder2 = + BalanceContract.WithdrawExpireUnfreezeContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.WithdrawExpireUnfreezeContract); + + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder(); + builder.setWithdrawExpireAmount(TRX_PRECISION + 1000); + + TransactionLogTriggerCapsule triggerCapsule = new TransactionLogTriggerCapsule( + transactionCapsule, blockCapsule,0,0,0, + builder.build(),0); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertEquals("trx", triggerCapsule.getTransactionLogTrigger().getAssetName()); + Assert.assertEquals(TRX_PRECISION + 1000, + triggerCapsule.getTransactionLogTrigger().getAssetAmount()); + } + + + @Test + public void testConstructorWithDelegateResourceTrxCapsule() { + BalanceContract.DelegateResourceContract.Builder builder2 = + BalanceContract.DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(TRX_PRECISION + 2000); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.DelegateResourceContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + Assert.assertEquals("trx", triggerCapsule.getTransactionLogTrigger().getAssetName()); + Assert.assertEquals(TRX_PRECISION + 2000, + triggerCapsule.getTransactionLogTrigger().getAssetAmount()); + } + + @Test + public void testConstructorWithUnDelegateResourceTrxCapsule() { + BalanceContract.UnDelegateResourceContract.Builder builder2 = + BalanceContract.UnDelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(TRX_PRECISION + 10000); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.UnDelegateResourceContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + Assert.assertEquals("trx", triggerCapsule.getTransactionLogTrigger().getAssetName()); + Assert.assertEquals(TRX_PRECISION + 10000, + triggerCapsule.getTransactionLogTrigger().getAssetAmount()); + } + + @Test + public void testConstructorWithCancelAllUnfreezeTrxCapsule() { + BalanceContract.CancelAllUnfreezeV2Contract.Builder builder2 = + BalanceContract.CancelAllUnfreezeV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.CancelAllUnfreezeV2Contract); + + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder(); + builder.clearCancelUnfreezeV2Amount().putCancelUnfreezeV2Amount( + BANDWIDTH.name(), TRX_PRECISION + 2000); + + TransactionLogTriggerCapsule triggerCapsule = new TransactionLogTriggerCapsule( + transactionCapsule, blockCapsule,0,0,0, + builder.build(),0); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertEquals(TRX_PRECISION + 2000, + triggerCapsule.getTransactionLogTrigger().getExtMap().get(BANDWIDTH.name()).longValue()); + } + + + @Test + public void testConstructorWithTransferCapsule() { + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + } + + @Test + public void testConstructorWithTransferAssetCapsule() { + AssetIssueContractOuterClass.TransferAssetContract.Builder builder2 = + AssetIssueContractOuterClass.TransferAssetContract.newBuilder() + .setAssetName(ByteString.copyFrom("AssetName".getBytes())) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferAssetContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + } + + @Test + public void testConstructorWithTriggerSmartContract() { + SmartContractOuterClass.TriggerSmartContract.Builder builder2 = + SmartContractOuterClass.TriggerSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(CONTRACT_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TriggerSmartContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getToAddress()); + } + + @Test + public void testConstructorWithCreateSmartContract() { + SmartContractOuterClass.CreateSmartContract.Builder builder2 = + SmartContractOuterClass.CreateSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.CreateSmartContract); + + TransactionLogTriggerCapsule triggerCapsule = + new TransactionLogTriggerCapsule(transactionCapsule, blockCapsule); + + Assert.assertNotNull(triggerCapsule.getTransactionLogTrigger().getFromAddress()); + } + + @Test + public void testConstructorWithCreateTransactionInfo() { + Protocol.TransactionInfo.Builder infoBuild = Protocol.TransactionInfo.newBuilder(); + + Protocol.ResourceReceipt.Builder resourceBuild = Protocol.ResourceReceipt.newBuilder(); + resourceBuild.setEnergyFee(1); + resourceBuild.setEnergyUsageTotal(2); + resourceBuild.setEnergyUsage(3); + resourceBuild.setOriginEnergyUsage(4); + resourceBuild.setNetFee(5); + resourceBuild.setNetUsage(6); + + infoBuild + .setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(CONTRACT_ADDRESS))) + .addContractResult(ByteString.copyFrom(ByteArray.fromHexString("112233"))) + .setReceipt(resourceBuild.build()); + + SmartContractOuterClass.CreateSmartContract.Builder builder2 = + SmartContractOuterClass.CreateSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + TransactionCapsule tc = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.CreateSmartContract); + + BlockCapsule bc = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + + + TransactionLogTriggerCapsule trigger = + new TransactionLogTriggerCapsule(tc, bc, infoBuild.build()); + + Assert.assertEquals(1, trigger.getTransactionLogTrigger().getEnergyFee()); + Assert.assertEquals(2, trigger.getTransactionLogTrigger().getEnergyUsageTotal()); + Assert.assertEquals(3, trigger.getTransactionLogTrigger().getEnergyUsage()); + Assert.assertEquals(4, trigger.getTransactionLogTrigger().getOriginEnergyUsage()); + Assert.assertEquals(5, trigger.getTransactionLogTrigger().getNetFee()); + Assert.assertEquals(6, trigger.getTransactionLogTrigger().getNetUsage()); + + Assert.assertEquals(StringUtil.encode58Check(Hex.decode(CONTRACT_ADDRESS)), + trigger.getTransactionLogTrigger().getContractAddress()); + Assert.assertEquals("112233", trigger.getTransactionLogTrigger().getContractResult()); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java new file mode 100644 index 00000000000..5381c6ab2de --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockFilterCapsuleTest.java @@ -0,0 +1,38 @@ +package org.tron.common.logsfilter.capsule; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; + +public class BlockFilterCapsuleTest { + + private BlockFilterCapsule blockFilterCapsule; + + @Before + public void setUp() { + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + blockFilterCapsule = new BlockFilterCapsule(blockCapsule, false); + } + + @Test + public void testSetAndGetBlockHash() { + blockFilterCapsule + .setBlockHash("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f"); + System.out.println(blockFilterCapsule); + Assert.assertEquals("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", + blockFilterCapsule.getBlockHash()); + } + + @Test + public void testSetAndIsSolidified() { + blockFilterCapsule = new BlockFilterCapsule( + "e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", false); + blockFilterCapsule.setSolidified(true); + blockFilterCapsule.processFilterTrigger(); + Assert.assertTrue(blockFilterCapsule.isSolidified()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockLogTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockLogTriggerCapsuleTest.java new file mode 100644 index 00000000000..f77869b8650 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/BlockLogTriggerCapsuleTest.java @@ -0,0 +1,35 @@ +package org.tron.common.logsfilter.capsule; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; + +public class BlockLogTriggerCapsuleTest { + + private BlockLogTriggerCapsule blockLogTriggerCapsule; + + @Before + public void setUp() { + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + blockLogTriggerCapsule = new BlockLogTriggerCapsule(blockCapsule); + } + + @Test + public void testSetAndGetBlockLogTrigger() { + blockLogTriggerCapsule + .setBlockLogTrigger(blockLogTriggerCapsule.getBlockLogTrigger()); + Assert.assertEquals(1, + blockLogTriggerCapsule.getBlockLogTrigger().getBlockNumber()); + } + + @Test + public void testSetLatestSolidifiedBlockNumber() { + blockLogTriggerCapsule.setLatestSolidifiedBlockNumber(100); + Assert.assertEquals(100, + blockLogTriggerCapsule.getBlockLogTrigger().getLatestSolidifiedBlockNumber()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractLogTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractLogTriggerCapsuleTest.java new file mode 100644 index 00000000000..3d45eb026ea --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractLogTriggerCapsuleTest.java @@ -0,0 +1,36 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.tron.common.logsfilter.trigger.Trigger.CONTRACTLOG_TRIGGER_NAME; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractLogTrigger; + +@Slf4j +public class ContractLogTriggerCapsuleTest { + + private ContractLogTriggerCapsule capsule; + + @Before + public void setUp() { + ContractLogTrigger contractLogTrigger = new ContractLogTrigger(); + contractLogTrigger.setBlockNumber(0L); + capsule = new ContractLogTriggerCapsule(contractLogTrigger); + capsule.setLatestSolidifiedBlockNumber(0); + } + + @Test + public void testSetAndGetContractLogTrigger() { + capsule.setContractLogTrigger(capsule.getContractLogTrigger()); + assertEquals(CONTRACTLOG_TRIGGER_NAME, capsule.getContractLogTrigger().getTriggerName()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsuleTest.java new file mode 100644 index 00000000000..898447b3a75 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/ContractTriggerCapsuleTest.java @@ -0,0 +1,70 @@ +package org.tron.common.logsfilter.capsule; + +import static com.google.common.collect.Lists.newArrayList; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import com.beust.jcommander.internal.Lists; +import java.util.ArrayList; +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractTrigger; +import org.tron.common.runtime.vm.DataWord; +import org.tron.common.runtime.vm.LogInfo; + +@Slf4j +public class ContractTriggerCapsuleTest { + + private ContractTriggerCapsule capsule; + + private LogInfo logInfo; + + @Before + public void setUp() { + ContractTrigger contractTrigger = new ContractTrigger(); + contractTrigger.setBlockNumber(0L); + contractTrigger.setRemoved(false); + logInfo = new LogInfo(bytesToAddress(new byte[] {0x11}), + newArrayList(new DataWord()), new byte[0]); + contractTrigger.setLogInfo(logInfo); + contractTrigger.setRawData(new RawData(null, null, null)); + contractTrigger.setAbi(contractTrigger.getAbi()); + capsule = new ContractTriggerCapsule(contractTrigger); + + } + + private byte[] bytesToAddress(byte[] address) { + byte[] data = new byte[20]; + System.arraycopy(address, 0, data, 20 - address.length, address.length); + return data; + } + + @Test + public void testSetAndGetContractTrigger() { + capsule.setContractTrigger(capsule.getContractTrigger()); + capsule.setBlockHash("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f"); + capsule.setLatestSolidifiedBlockNumber(0); + assertEquals(0, capsule.getContractTrigger().getLatestSolidifiedBlockNumber()); + assertEquals("e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", + capsule.getContractTrigger().getBlockHash()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + + @Test + public void testLogInfo() { + logger.info("log info to string: {}, ", logInfo.toString()); + logger.info("log clone data: {}, ", logInfo.getClonedData()); + CollectionUtils.isNotEmpty(logInfo.getClonedTopics()); + CollectionUtils.isNotEmpty(logInfo.getHexTopics()); + new LogInfo(null, null, null); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/LogsFilterCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/LogsFilterCapsuleTest.java new file mode 100644 index 00000000000..691a3106b49 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/LogsFilterCapsuleTest.java @@ -0,0 +1,33 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.bloom.Bloom; + +public class LogsFilterCapsuleTest { + + private LogsFilterCapsule capsule; + + @Before + public void setUp() { + capsule = new LogsFilterCapsule(0, + "e58f33f9baf9305dc6f82b9f1934ea8f0ade2defb951258d50167028c780351f", + new Bloom(), new ArrayList<>(), true, false); + } + + @Test + public void testSetAndGetLogsFilterCapsule() { + capsule.setBlockNumber(capsule.getBlockNumber()); + capsule.setBlockHash(capsule.getBlockHash()); + capsule.setSolidified(capsule.isSolidified()); + capsule.setBloom(capsule.getBloom()); + capsule.setRemoved(capsule.isRemoved()); + capsule.setTxInfoList(capsule.getTxInfoList()); + assertNotNull(capsule.toString()); + capsule.processFilterTrigger(); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/RawDataTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/RawDataTest.java new file mode 100644 index 00000000000..c14afcd903b --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/RawDataTest.java @@ -0,0 +1,33 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.List; +import org.junit.Test; +import org.tron.common.runtime.vm.DataWord; + +public class RawDataTest { + @Test + public void testRawDataConstructor() { + byte[] addressBytes = {0x01, 0x02, 0x03, 0x04}; + byte[] dataBytes = {0x10, 0x20, 0x30, 0x40}; + List topics = Arrays.asList( + new DataWord("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), + new DataWord("0000000000000000000000000000000000000000000000000000000000000001")); + + RawData rawData = new RawData(addressBytes, topics, dataBytes); + + assertEquals("01020304", rawData.getAddress()); + assertEquals(topics, rawData.getTopics()); + assertEquals("10203040", rawData.getData()); + + rawData = new RawData(null, null, null); + assertEquals("", rawData.getAddress()); + assertTrue(rawData.getTopics().isEmpty()); + assertEquals("", rawData.getData()); + assertNotNull(rawData.toString()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityEventCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityEventCapsuleTest.java new file mode 100644 index 00000000000..9259ca3ea97 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityEventCapsuleTest.java @@ -0,0 +1,32 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertTrue; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractEventTrigger; + +@Slf4j +public class SolidityEventCapsuleTest { + + private SolidityEventCapsule capsule; + + @Before + public void setUp() { + ContractEventTrigger contractEventTrigger = new ContractEventTrigger(); + capsule = new SolidityEventCapsule(contractEventTrigger); + } + + @Test + public void testSetAndGetSolidityEventCapsule() { + capsule.setSolidityEventTrigger(capsule.getSolidityEventTrigger()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityLogCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityLogCapsuleTest.java new file mode 100644 index 00000000000..4e663930530 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityLogCapsuleTest.java @@ -0,0 +1,31 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertTrue; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.ContractLogTrigger; + +@Slf4j +public class SolidityLogCapsuleTest { + + private SolidityLogCapsule capsule; + + @Before + public void setUp() { + ContractLogTrigger trigger = new ContractLogTrigger(); + capsule = new SolidityLogCapsule(trigger); + } + + @Test + public void testSetAndGetSolidityLogCapsule() { + capsule.setSolidityLogTrigger(capsule.getSolidityLogTrigger()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityTriggerCapsuleTest.java b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityTriggerCapsuleTest.java new file mode 100644 index 00000000000..849803c1f04 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/capsule/SolidityTriggerCapsuleTest.java @@ -0,0 +1,37 @@ +package org.tron.common.logsfilter.capsule; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.trigger.SolidityTrigger; + +@Slf4j +public class SolidityTriggerCapsuleTest { + + private SolidityTriggerCapsule capsule; + + @Before + public void setUp() { + capsule = new SolidityTriggerCapsule(0); + SolidityTrigger trigger = new SolidityTrigger(); + assertNotNull(trigger.toString()); + capsule.setSolidityTrigger(trigger); + capsule.setTimeStamp(System.currentTimeMillis()); + } + + @Test + public void testSetAndGetSolidityLogCapsule() { + capsule.setSolidityTrigger(capsule.getSolidityTrigger()); + capsule.setTimeStamp(capsule.getSolidityTrigger().getTimeStamp()); + try { + capsule.processTrigger(); + } catch (Exception e) { + assertTrue(e instanceof NullPointerException); + } + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/trigger/ContractLogTriggerTest.java b/framework/src/test/java/org/tron/common/logsfilter/trigger/ContractLogTriggerTest.java new file mode 100644 index 00000000000..8d6e044c134 --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/trigger/ContractLogTriggerTest.java @@ -0,0 +1,82 @@ +package org.tron.common.logsfilter.trigger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.Arrays; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.logsfilter.capsule.RawData; +import org.tron.common.runtime.vm.DataWord; + +public class ContractLogTriggerTest { + private ContractEventTrigger mockEventTrigger; + + @Before + public void setUp() { + mockEventTrigger = new ContractEventTrigger(); + byte[] addressBytes = {0x01, 0x02, 0x03, 0x04}; + byte[] dataBytes = {0x10, 0x20, 0x30, 0x40}; + List topics = Arrays.asList( + new DataWord("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), + new DataWord("0000000000000000000000000000000000000000000000000000000000000001")); + + RawData rawData = new RawData(addressBytes, topics, dataBytes); + mockEventTrigger.setRawData(rawData); + mockEventTrigger.setLatestSolidifiedBlockNumber(12345L); + mockEventTrigger.setRemoved(false); + mockEventTrigger.setUniqueId("unique-id"); + mockEventTrigger.setTransactionId("tx-id"); + mockEventTrigger.setContractAddress("contract-addr"); + mockEventTrigger.setOriginAddress("origin-addr"); + mockEventTrigger.setCreatorAddress("creator-addr"); + mockEventTrigger.setBlockNumber(67890L); + mockEventTrigger.setTimeStamp(1622547200L); + mockEventTrigger.setBlockHash("block-hash"); + } + + @Test + public void testDefaultConstructor() { + ContractLogTrigger trigger = new ContractLogTrigger(); + assertEquals(Trigger.CONTRACTLOG_TRIGGER_NAME, trigger.getTriggerName()); + assertNull(trigger.getTopicList()); + assertNull(trigger.getData()); + } + + @Test + public void testConstructorWithEventTrigger() { + ContractLogTrigger trigger = new ContractLogTrigger(mockEventTrigger); + assertEquals(Trigger.CONTRACTLOG_TRIGGER_NAME, trigger.getTriggerName()); + assertEquals(mockEventTrigger.getRawData(), trigger.getRawData()); + assertEquals(mockEventTrigger.getLatestSolidifiedBlockNumber(), + trigger.getLatestSolidifiedBlockNumber()); + assertEquals(mockEventTrigger.isRemoved(), trigger.isRemoved()); + assertEquals(mockEventTrigger.getUniqueId(), trigger.getUniqueId()); + assertEquals(mockEventTrigger.getTransactionId(), trigger.getTransactionId()); + assertEquals(mockEventTrigger.getContractAddress(), trigger.getContractAddress()); + assertEquals(mockEventTrigger.getOriginAddress(), trigger.getOriginAddress()); + assertEquals("", trigger.getCallerAddress()); // Explicitly set to empty string + assertEquals(mockEventTrigger.getCreatorAddress(), trigger.getCreatorAddress()); + assertEquals(mockEventTrigger.getBlockNumber(), trigger.getBlockNumber()); + assertEquals(mockEventTrigger.getTimeStamp(), trigger.getTimeStamp()); + assertEquals(mockEventTrigger.getBlockHash(), trigger.getBlockHash()); + } + + @Test + public void testSetAndGetTopicList() { + ContractLogTrigger trigger = new ContractLogTrigger(); + List topics = Arrays.asList("topic1", "topic2"); + trigger.setTopicList(topics); + assertEquals(topics, trigger.getTopicList()); + } + + @Test + public void testSetAndGetData() { + ContractLogTrigger trigger = new ContractLogTrigger(); + String testData = "log data"; + trigger.setData(testData); + assertEquals(testData, trigger.getData()); + } + +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/trigger/InternalTransactionPojoTest.java b/framework/src/test/java/org/tron/common/logsfilter/trigger/InternalTransactionPojoTest.java new file mode 100644 index 00000000000..9948c5535af --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/trigger/InternalTransactionPojoTest.java @@ -0,0 +1,87 @@ +package org.tron.common.logsfilter.trigger; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.HashMap; +import java.util.Map; +import org.junit.Before; +import org.junit.Test; + +public class InternalTransactionPojoTest { + private InternalTransactionPojo internalTransactionPojo; + + @Before + public void setUp() { + internalTransactionPojo = new InternalTransactionPojo(); + } + + @Test + public void testHash() { + String testHash = "0x123456789abcdef0123456789abcdef0"; + internalTransactionPojo.setHash(testHash); + assertEquals(testHash, internalTransactionPojo.getHash()); + } + + @Test + public void testCallValue() { + long testCallValue = 123456789L; + internalTransactionPojo.setCallValue(testCallValue); + assertEquals(testCallValue, internalTransactionPojo.getCallValue()); + } + + @Test + public void testTokenInfo() { + Map testTokenInfo = new HashMap<>(); + testTokenInfo.put("token1", 100L); + testTokenInfo.put("token2", 200L); + internalTransactionPojo.setTokenInfo(testTokenInfo); + assertEquals(testTokenInfo, internalTransactionPojo.getTokenInfo()); + } + + @Test + public void testTransferToAddress() { + String testAddress = "0x0000000000000000000000000000000000000001"; + internalTransactionPojo.setTransferTo_address(testAddress); + assertEquals(testAddress, internalTransactionPojo.getTransferTo_address()); + } + + @Test + public void testData() { + String testData = "0x6060604052341561000f57600080fd5b5b6040516020806101158339810160405280805" + + "19060200190929190505050"; + internalTransactionPojo.setData(testData); + assertEquals(testData, internalTransactionPojo.getData()); + } + + @Test + public void testCallerAddress() { + String testCallerAddress = "0x0000000000000000000000000000000000000002"; + internalTransactionPojo.setCaller_address(testCallerAddress); + assertEquals(testCallerAddress, internalTransactionPojo.getCaller_address()); + } + + @Test + public void testRejected() { + internalTransactionPojo.setRejected(true); + assertTrue(internalTransactionPojo.isRejected()); + + internalTransactionPojo.setRejected(false); + assertFalse(internalTransactionPojo.isRejected()); + } + + @Test + public void testNote() { + String testNote = "This is a test note"; + internalTransactionPojo.setNote(testNote); + assertEquals(testNote, internalTransactionPojo.getNote()); + } + + @Test + public void testExtra() { + String testExtra = "extra_data_for_vote_witness"; + internalTransactionPojo.setExtra(testExtra); + assertEquals(testExtra, internalTransactionPojo.getExtra()); + } +} diff --git a/framework/src/test/java/org/tron/common/logsfilter/trigger/LogPojoTest.java b/framework/src/test/java/org/tron/common/logsfilter/trigger/LogPojoTest.java new file mode 100644 index 00000000000..7c94ec4f7ad --- /dev/null +++ b/framework/src/test/java/org/tron/common/logsfilter/trigger/LogPojoTest.java @@ -0,0 +1,74 @@ +package org.tron.common.logsfilter.trigger; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import java.util.List; +import org.junit.Before; +import org.junit.Test; + +public class LogPojoTest { + + private LogPojo logPojo; + + @Before + public void setUp() { + logPojo = new LogPojo(); + } + + @Test + public void testAddress() { + String testAddress = "123 Test Address"; + logPojo.setAddress(testAddress); + assertEquals(testAddress, logPojo.getAddress()); + } + + @Test + public void testBlockHash() { + String testBlockHash = "abcdef1234567890abcdef1234567890abcdef12"; + logPojo.setBlockHash(testBlockHash); + assertEquals(testBlockHash, logPojo.getBlockHash()); + } + + @Test + public void testBlockNumber() { + long testBlockNumber = 1234567L; + logPojo.setBlockNumber(testBlockNumber); + assertEquals(testBlockNumber, logPojo.getBlockNumber()); + } + + @Test + public void testData() { + String testData = "Some data here"; + logPojo.setData(testData); + assertEquals(testData, logPojo.getData()); + } + + @Test + public void testLogIndex() { + long testLogIndex = 5L; + logPojo.setLogIndex(testLogIndex); + assertEquals(testLogIndex, logPojo.getLogIndex()); + } + + @Test + public void testTopicList() { + List testTopicList = Arrays.asList("topic1", "topic2", "topic3"); + logPojo.setTopicList(testTopicList); + assertEquals(testTopicList, logPojo.getTopicList()); + } + + @Test + public void testTransactionHash() { + String testTransactionHash = "abcdef1234567890abcdef1234567890abcdef12"; + logPojo.setTransactionHash(testTransactionHash); + assertEquals(testTransactionHash, logPojo.getTransactionHash()); + } + + @Test + public void testTransactionIndex() { + long testTransactionIndex = 3L; + logPojo.setTransactionIndex(testTransactionIndex); + assertEquals(testTransactionIndex, logPojo.getTransactionIndex()); + } +} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeHandlerTest.java b/framework/src/test/java/org/tron/common/overlay/discover/node/NodeHandlerTest.java deleted file mode 100644 index dfe24f8e644..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeHandlerTest.java +++ /dev/null @@ -1,100 +0,0 @@ -package org.tron.common.overlay.discover.node; - -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; -import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; - - -public class NodeHandlerTest { - - private static final Logger logger = LoggerFactory.getLogger("Test"); - // private static Manager dbManager; - private static TronApplicationContext context; - // private Application appTest; - // private CommonParameter argsTest; - private static Node currNode; - private static Node oldNode; - private static Node replaceNode; - private static NodeHandler currHandler; - private static NodeHandler oldHandler; - private static NodeHandler replaceHandler; - private static NodeManager nodeManager; - private static String dbPath = "NodeHandlerTest"; - - static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - /** - * init the application. - */ - @BeforeClass - public static void init() { - initNodes(); - } - - /** - * destroy the context. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - /** - * init nodes. - */ - public static void initNodes() { - // dbManager = context.getBean(Manager.class); - nodeManager = new NodeManager(context.getBean(ChainBaseManager.class)); - String currNodeId = "74c11ffad1d59d7b1a56691a0b84a53f0791c92361357364f1d2537" - + "898407ef0249bbbf5a4ce8cff9e34e2fdf8bac883540e026d1e5d6ebf536414bdde81198e"; - String oldNodeId = "74c11ffad1d59d7b2c56691a0b84a53f0791c92361357364f1d2537898407e" - + "f0249bbbf5a4ce8cff9e34e2fdf8bac883540e026d1e5d6ebf536414bdde81198e"; - String replaceNodeId = "74c11ffad1d59d7b1a56691a0b84a53f0791c92361357364f1d2537" - + "837407ef0249bbbf5a4ce8cff9e34e2fdf8bac883540e026d1e5d6ebf536414bdde81198e"; - currNode = new Node(currNodeId.getBytes(), "47.95.206.44", 18885, 18888); - oldNode = new Node(oldNodeId.getBytes(), "36.95.165.44", 18885, 18888); - replaceNode = new Node(replaceNodeId.getBytes(), "47.29.177.44", 18885, 18888); - currHandler = new NodeHandler(currNode, nodeManager); - oldHandler = new NodeHandler(oldNode, nodeManager); - replaceHandler = new NodeHandler(replaceNode, nodeManager); - } - - @Test - public void stateNonActiveTest() throws Exception { - Class clazz = NodeHandler.class; - Constructor cn = clazz.getDeclaredConstructor(Node.class, NodeManager.class); - NodeHandler nh = cn.newInstance(oldNode, nodeManager); - Field declaredField = clazz.getDeclaredField("replaceCandidate"); - declaredField.setAccessible(true); - declaredField.set(nh, replaceHandler); - - nodeManager.getTable().addNode(oldNode); - nh.changeState(NodeHandler.State.EVICTCANDIDATE); - nh.changeState(NodeHandler.State.NONACTIVE); - replaceHandler.changeState(NodeHandler.State.ALIVE); - - Assert.assertFalse(nodeManager.getTable().contains(oldNode)); - Assert.assertTrue(nodeManager.getTable().contains(replaceNode)); - } -} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeManagerTest.java b/framework/src/test/java/org/tron/common/overlay/discover/node/NodeManagerTest.java deleted file mode 100644 index f5b870bacdf..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeManagerTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package org.tron.common.overlay.discover.node; - -import java.io.File; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.common.application.Application; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; -import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; - - -public class NodeManagerTest { - - private static final Logger logger = LoggerFactory.getLogger("Test"); - private static Manager manager; - private static NodeManager nodeManager; - private static TronApplicationContext context; - private static CommonParameter argsTest; - private static Application appTest; - private static Class nodeManagerClazz; - private static String dbPath = "NodeManagerTest"; - - static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - /** - * start the application. - */ - @BeforeClass - public static void init() { - // argsTest = Args.getInstance(); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // Constant.TEST_CONF); - // context = new TronApplicationContext(DefaultConfig.class); - // appTest = ApplicationFactory.create(context); - // appTest.initServices(argsTest); - // appTest.startServices(); - // appTest.startup(); - try { - initManager(); - } catch (Exception e) { - logger.error("init failed {}", e.getMessage()); - } - } - - /** - * destroy the context. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - /** - * init the managers. - */ - // @Before - public static void initManager() throws Exception { - nodeManagerClazz = NodeManager.class; - // Constructor handlerConstructor - // = nodeManagerClazz.getConstructor(ChainBaseManager.class); - manager = context.getBean(Manager.class); - // nodeManager = handlerConstructor.newInstance(context.getBean(ChainBaseManager.class)); - nodeManager = new NodeManager(context.getBean(ChainBaseManager.class)); - } - - @Test - public void isNodeAliveTest() { - Node node = new Node(new byte[64], "128.0.0.1", 18889, 18889); - nodeManager.getTable().addNode(node); - NodeHandler nodeHandler = new NodeHandler(node, nodeManager); - nodeHandler.changeState(NodeHandler.State.ACTIVE); - Assert.assertTrue(nodeManager.isNodeAlive(nodeHandler)); - nodeHandler.changeState(NodeHandler.State.ALIVE); - Assert.assertTrue(nodeManager.isNodeAlive(nodeHandler)); - nodeHandler.changeState(NodeHandler.State.EVICTCANDIDATE); - Assert.assertTrue(nodeManager.isNodeAlive(nodeHandler)); - } - - @Test - public void trimTableTest_removeByReputation() throws Exception { - //insert 3001 nodes(isConnectible = true) with threshold = 3000 - final int totalNodes = insertValues(3002); - Assert.assertEquals(calculateTrimNodes(totalNodes, 0), getHandlerMapSize()); - - clearNodeManager(); - } - - @Test - public void trimTableTest_removeNotConnectibleNodes() throws Exception { - final int totalNodes = insertValues(3000); - insertNotConnectibleNodes(); - Method method = nodeManagerClazz.getDeclaredMethod("trimTable"); - method.setAccessible(true); - method.invoke(nodeManager); - Assert.assertEquals(calculateTrimNodes(totalNodes, 2), getHandlerMapSize()); - - clearNodeManager(); - } - - private void clearNodeManager() { - nodeManager.clearNodeHandlerMap(); - } - - /** - * calculate nodes number after table trim. - * - * @param totalNodes total nodes inserted - * @param wrongNodes isConnectable = false - * @return nodes count after trimTable() - */ - public int calculateTrimNodes(int totalNodes, int wrongNodes) { - if (totalNodes + wrongNodes > 3000) { - if (totalNodes <= 3000) { - return totalNodes; - } else { - int result = 2000 + ((totalNodes + wrongNodes) % 2000 - 1001); - return result; - } - } - return totalNodes + wrongNodes; - } - - /** - * insert valid nodes in map. - * - * @param totalNodes total nodes to be inserted. - * @return total nodes inserted. - */ - public int insertValues(int totalNodes) throws Exception { - //put 3001 nodes in nodeHandlerMap - int ipPart3 = 1; - int ipPart4 = 1; - for (int i = 0; i < totalNodes; i++) { - StringBuilder stringBuilder = new StringBuilder("128.0."); - byte[] bytes = new byte[64]; - bytes[0] = (byte) (i + 1); - stringBuilder.append(ipPart3); - stringBuilder.append("."); - stringBuilder.append(ipPart4); - ipPart4++; - if (ipPart4 == 256) { - ipPart3++; - ipPart4 = 1; - } - Class nodeClazz = Node.class; - Constructor nodeConstructor - = nodeClazz.getConstructor(byte[].class, String.class, int.class, int.class); - Node node = nodeConstructor.newInstance(bytes, stringBuilder.toString(), 18889, 18889); - Field isConnectableField = nodeClazz.getDeclaredField("p2pVersion"); - isConnectableField.setAccessible(true); - isConnectableField.set(node, Args.getInstance().getNodeP2pVersion()); - nodeManager.getNodeHandler(node); - } - return totalNodes; - } - - /** - * insert nodes with illegal p2p version. - */ - public void insertNotConnectibleNodes() throws Exception { - Class nodeClazz = Node.class; - Constructor nodeConstructor - = nodeClazz.getConstructor(byte[].class, String.class, int.class, int.class); - Node wrongNode1 = nodeConstructor.newInstance(new byte[64], "128.0.0.1", 1111, 18889); - byte[] id = new byte[64]; - id[63] = 1; - Node wrongNode2 = nodeConstructor.newInstance(id, "128.0.0.2", 1111, 18889); - Field isConnectableField = nodeClazz.getDeclaredField("p2pVersion"); - isConnectableField.setAccessible(true); - isConnectableField.set(wrongNode1, 999); - isConnectableField.set(wrongNode2, 999); - nodeManager.getNodeHandler(wrongNode1); - nodeManager.getNodeHandler(wrongNode2); - } - - - /** - * get the size of nodeHandlerMap. - * - * @return NodeManager.nodeHandlerMap - */ - public int getHandlerMapSize() throws Exception { - Field mapField = nodeManagerClazz.getDeclaredField("nodeHandlerMap"); - mapField.setAccessible(true); - Map nodeHandlerMap = (ConcurrentHashMap) mapField.get(nodeManager); - return nodeHandlerMap.size(); - } - - @Test - public void dumpActiveNodesTest() { - Node node1 = new Node(new byte[64], "128.0.0.1", 18889, 18889); - Node node2 = new Node(new byte[64], "128.0.0.2", 18889, 18889); - Node node3 = new Node(new byte[64], "128.0.0.3", 18889, 18889); - NodeHandler nodeHandler1 = nodeManager.getNodeHandler(node1); - NodeHandler nodeHandler2 = nodeManager.getNodeHandler(node2); - NodeHandler nodeHandler3 = nodeManager.getNodeHandler(node3); - nodeHandler1.changeState(NodeHandler.State.ALIVE); - nodeHandler2.changeState(NodeHandler.State.ACTIVE); - nodeHandler3.changeState(NodeHandler.State.NONACTIVE); - int activeNodes = nodeManager.dumpActiveNodes().size(); - Assert.assertEquals(2, activeNodes); - } -} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java b/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java deleted file mode 100644 index 157c31e26a3..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/node/NodeStatisticsTest.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.tron.common.overlay.discover.node; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.LinkedList; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.tron.common.net.udp.message.UdpMessageTypeEnum; -import org.tron.common.overlay.discover.node.statistics.MessageStatistics; -import org.tron.common.overlay.discover.node.statistics.NodeStatistics; -import org.tron.common.overlay.message.DisconnectMessage; -import org.tron.common.overlay.message.PongMessage; -import org.tron.common.utils.Sha256Hash; -import org.tron.core.capsule.BlockCapsule; -import org.tron.core.net.message.BlockMessage; -import org.tron.core.net.message.ChainInventoryMessage; -import org.tron.core.net.message.FetchInvDataMessage; -import org.tron.core.net.message.InventoryMessage; -import org.tron.core.net.message.MessageTypes; -import org.tron.core.net.message.SyncBlockChainMessage; -import org.tron.core.net.message.TransactionsMessage; -import org.tron.protos.Protocol; - -public class NodeStatisticsTest { - - private NodeStatistics nodeStatistics; - - @Before - public void init() { - this.nodeStatistics = new NodeStatistics(); - } - - @Test - public void testNode() throws NoSuchFieldException, IllegalAccessException { - Protocol.ReasonCode reasonCode = this.nodeStatistics.getDisconnectReason(); - Assert.assertEquals(Protocol.ReasonCode.UNKNOWN, reasonCode); - - boolean isReputationPenalized = this.nodeStatistics.isReputationPenalized(); - Assert.assertFalse(isReputationPenalized); - - this.nodeStatistics.setPredefined(true); - Assert.assertTrue(this.nodeStatistics.isPredefined()); - - this.nodeStatistics.setPersistedReputation(10000); - this.nodeStatistics.nodeDisconnectedRemote(Protocol.ReasonCode.INCOMPATIBLE_VERSION); - isReputationPenalized = this.nodeStatistics.isReputationPenalized(); - Assert.assertTrue(isReputationPenalized); - - Field field = this.nodeStatistics.getClass().getDeclaredField("firstDisconnectedTime"); - field.setAccessible(true); - field.set(this.nodeStatistics, System.currentTimeMillis() - 60 * 60 * 1000L - 1); - isReputationPenalized = this.nodeStatistics.isReputationPenalized(); - Assert.assertFalse(isReputationPenalized); - reasonCode = this.nodeStatistics.getDisconnectReason(); - Assert.assertEquals(Protocol.ReasonCode.UNKNOWN, reasonCode); - - String str = this.nodeStatistics.toString(); - //System.out.println(str); - Assert.assertNotNull(str); - - this.nodeStatistics.nodeIsHaveDataTransfer(); - this.nodeStatistics.resetTcpFlow(); - this.nodeStatistics.discoverMessageLatency.add(10); - this.nodeStatistics.discoverMessageLatency.add(20); - long avg = this.nodeStatistics.discoverMessageLatency.getAvg(); - Assert.assertEquals(15, avg); - - } - - @Test - public void testMessage() { - MessageStatistics statistics = this.nodeStatistics.messageStatistics; - statistics.addUdpInMessage(UdpMessageTypeEnum.DISCOVER_FIND_NODE); - statistics.addUdpOutMessage(UdpMessageTypeEnum.DISCOVER_NEIGHBORS); - statistics.addUdpInMessage(UdpMessageTypeEnum.DISCOVER_NEIGHBORS); - statistics.addUdpOutMessage(UdpMessageTypeEnum.DISCOVER_FIND_NODE); - Assert.assertEquals(1, statistics.discoverInFindNode.getTotalCount()); - long inFindNodeCount = statistics.discoverInFindNode.getTotalCount(); - long outNeighbours = statistics.discoverOutNeighbours.getTotalCount(); - Assert.assertEquals(inFindNodeCount, outNeighbours); - - PongMessage pongMessage = new PongMessage(MessageTypes.P2P_PONG.asByte(), Hex.decode("C0")); - pongMessage.getData(); - String pongStr = pongMessage.toString(); - Assert.assertNotNull(pongStr); - statistics.addTcpInMessage(pongMessage); - statistics.addTcpOutMessage(pongMessage); - Assert.assertEquals(1, statistics.p2pInPong.getTotalCount()); - - DisconnectMessage disconnectMessage = new DisconnectMessage(Protocol.ReasonCode.TOO_MANY_PEERS); - Assert.assertEquals(Protocol.ReasonCode.TOO_MANY_PEERS, disconnectMessage.getReasonCode()); - statistics.addTcpInMessage(disconnectMessage); - statistics.addTcpOutMessage(disconnectMessage); - Assert.assertEquals(1, statistics.p2pOutDisconnect.getTotalCount()); - - SyncBlockChainMessage syncBlockChainMessage = new SyncBlockChainMessage(new ArrayList<>()); - String syncBlockChainStr = syncBlockChainMessage.toString(); - Assert.assertNotNull(syncBlockChainStr); - statistics.addTcpInMessage(syncBlockChainMessage); - statistics.addTcpOutMessage(syncBlockChainMessage); - Assert.assertEquals(1, statistics.tronInSyncBlockChain.getTotalCount()); - - ChainInventoryMessage chainInventoryMessage = new ChainInventoryMessage(new ArrayList<>(), 0L); - String chainInventoryMessageStr = chainInventoryMessage.toString(); - Assert.assertNotNull(chainInventoryMessageStr); - statistics.addTcpInMessage(chainInventoryMessage); - statistics.addTcpOutMessage(chainInventoryMessage); - Assert.assertEquals(1, statistics.tronOutBlockChainInventory.getTotalCount()); - - InventoryMessage invMsgTrx = - new InventoryMessage(new ArrayList<>(), Protocol.Inventory.InventoryType.TRX); - String inventoryMessageStr = invMsgTrx.toString(); - Assert.assertNotNull(inventoryMessageStr); - statistics.addTcpInMessage(invMsgTrx); - statistics.addTcpOutMessage(invMsgTrx); - InventoryMessage invMsgBlock = - new InventoryMessage(new ArrayList<>(), Protocol.Inventory.InventoryType.BLOCK); - MessageTypes invType = invMsgBlock.getInvMessageType(); - Assert.assertEquals(MessageTypes.BLOCK, invType); - statistics.addTcpInMessage(invMsgBlock); - statistics.addTcpOutMessage(invMsgBlock); - Assert.assertEquals(1, statistics.tronInBlockInventory.getTotalCount()); - - FetchInvDataMessage fetchInvDataTrx = - new FetchInvDataMessage(new ArrayList<>(), Protocol.Inventory.InventoryType.TRX); - statistics.addTcpInMessage(fetchInvDataTrx); - statistics.addTcpOutMessage(fetchInvDataTrx); - FetchInvDataMessage fetchInvDataBlock = - new FetchInvDataMessage(new ArrayList<>(), Protocol.Inventory.InventoryType.BLOCK); - statistics.addTcpInMessage(fetchInvDataBlock); - statistics.addTcpOutMessage(fetchInvDataBlock); - Assert.assertEquals(1, statistics.tronInTrxFetchInvData.getTotalCount()); - - TransactionsMessage transactionsMessage = - new TransactionsMessage(new LinkedList<>()); - statistics.addTcpInMessage(transactionsMessage); - statistics.addTcpOutMessage(transactionsMessage); - Assert.assertEquals(1, statistics.tronInTrxs.getTotalCount()); - - BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, - System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); - BlockMessage blockMessage = new BlockMessage(blockCapsule); - statistics.addTcpInMessage(blockMessage); - statistics.addTcpOutMessage(blockMessage); - long inBlockCount = statistics.tronInBlock.getTotalCount(); - Assert.assertEquals(1, inBlockCount); - } -} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/node/statistics/ReputationTest.java b/framework/src/test/java/org/tron/common/overlay/discover/node/statistics/ReputationTest.java deleted file mode 100644 index cee5d1d76dd..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/node/statistics/ReputationTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.tron.common.overlay.discover.node.statistics; - -import org.junit.Assert; -import org.junit.Test; - -public class ReputationTest { - - NodeStatistics nodeStatistics = new NodeStatistics(); - Reputation reputation = new Reputation(nodeStatistics); - - @Test - public void testGetScore() { - Assert.assertEquals(0, reputation.getScore()); - - nodeStatistics.messageStatistics.discoverInPong.add(3); - Assert.assertEquals(100, reputation.getScore()); - - nodeStatistics.messageStatistics.discoverOutPing.add(3); - Assert.assertEquals(200, reputation.getScore()); - - nodeStatistics.messageStatistics.discoverOutPing.add(1); - Assert.assertEquals(150, reputation.getScore()); - - nodeStatistics.tcpFlow.add(10240 * 5); - Assert.assertEquals(155, reputation.getScore()); - - nodeStatistics.discoverMessageLatency.add(100); - Assert.assertEquals(165, reputation.getScore()); - - nodeStatistics.notifyDisconnect(); - Assert.assertEquals(155, reputation.getScore()); - } -} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/table/NodeEntryTest.java b/framework/src/test/java/org/tron/common/overlay/discover/table/NodeEntryTest.java deleted file mode 100644 index 76d2baae9bc..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/table/NodeEntryTest.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.tron.common.overlay.discover.table; - -import org.junit.Assert; -import org.junit.Test; -import org.tron.common.overlay.discover.node.Node; - -public class NodeEntryTest { - - @Test - public void test() throws InterruptedException { - Node node1 = Node.instanceOf("127.0.0.1:10001"); - NodeEntry nodeEntry = new NodeEntry(node1); - int distance = nodeEntry.getDistance(); - Assert.assertEquals(-256, distance); - - long lastModified = nodeEntry.getModified(); - //System.out.println(lastModified); - Thread.sleep(1); - nodeEntry.touch(); - long nowModified = nodeEntry.getModified(); - //System.out.println(nowModified); - Assert.assertNotEquals(lastModified, nowModified); - - Node node2 = Node.instanceOf("127.0.0.1:10002"); - NodeEntry nodeEntry2 = new NodeEntry(node2); - boolean isDif = nodeEntry.equals(nodeEntry2); - Assert.assertTrue(isDif); - } - -} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/table/NodeTableTest.java b/framework/src/test/java/org/tron/common/overlay/discover/table/NodeTableTest.java deleted file mode 100644 index ab0062f5d82..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/table/NodeTableTest.java +++ /dev/null @@ -1,203 +0,0 @@ -package org.tron.common.overlay.discover.table; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.Before; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.tron.common.overlay.discover.node.Node; - - -public class NodeTableTest { - - private static final Logger logger = LoggerFactory.getLogger("Test"); - private Node homeNode; - private NodeTable nodeTable; - private String[] ips; - private List ids; - - @Test - public void test() { - Node node1 = Node.instanceOf("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 = Node.instanceOf("127.0.0.1:10003"); - Node node3 = Node.instanceOf("127.0.0.2: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 = Node.getNodeId(); - List nodeList = table.getClosestNodes(targetId); - Assert.assertTrue(nodeList.isEmpty()); - //Assert.assertTrue(true); - } - - /** - * init nodes for test. - */ - @Before - public void init() { - 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", 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], 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], 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], 18888, 18888)); - } - Node lastSeen = nodeTable.addNode(new Node(ids.get(16), ips[16], 18888, 18888)); - Assert.assertTrue(null != lastSeen); - Assert.assertEquals(ips[15], lastSeen.getHost()); - } - - public void addNode(Node n) { - nodeTable.addNode(n); - } - - @Test - public void dropNodeTest() { - Node node = new Node(ids.get(0), ips[0], 18888, 18888); - nodeTable.addNode(node); - Assert.assertTrue(nodeTable.contains(node)); - nodeTable.dropNode(node); - Assert.assertTrue(!nodeTable.contains(node)); - } - - @Test - public void getBucketsCountTest() { - Assert.assertEquals(0, nodeTable.getBucketsCount()); - Node node = new Node(ids.get(0), ips[0], 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], 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], 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], 18888, 18888); //id: 11100...000 - nodeTable.addNode(node); - NodeEntry nodeEntry = new NodeEntry(homeNode.getId(), node); - Assert.assertEquals(252, nodeTable.getBucketId(nodeEntry)); - } - - @Test - public void getClosestNodes_nodesMoreThanBucketCapacity() throws Exception { - byte[] bytes = new byte[64]; - bytes[0] = 15; - Node nearNode = new Node(bytes, "127.0.0.19", 18888, 18888); - bytes[0] = 70; - Node farNode = new Node(bytes, "127.0.0.20", 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], 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.assertTrue(closest.contains(nearNode)); - //the farest node should be excluded - } - - @Test - public void getClosestNodes_isDiscoverNode() { - Node node = new Node(ids.get(0), ips[0], 18888); - //This constructor builds a node with isFakeNodeId = true - nodeTable.addNode(node); - List closest = nodeTable.getClosestNodes(homeNode.getId()); - Assert.assertTrue(closest.isEmpty()); - } - -} diff --git a/framework/src/test/java/org/tron/common/overlay/discover/table/TimeComparatorTest.java b/framework/src/test/java/org/tron/common/overlay/discover/table/TimeComparatorTest.java deleted file mode 100644 index 616ec29b772..00000000000 --- a/framework/src/test/java/org/tron/common/overlay/discover/table/TimeComparatorTest.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.tron.common.overlay.discover.table; - -import org.junit.Assert; -import org.junit.Test; -import org.tron.common.overlay.discover.node.Node; - -public class TimeComparatorTest { - - @Test - public void test() throws InterruptedException { - Node node1 = Node.instanceOf("127.0.0.1:10001"); - NodeEntry ne1 = new NodeEntry(node1); - Thread.sleep(1); - Node node2 = Node.instanceOf("127.0.0.1:10002"); - NodeEntry ne2 = new NodeEntry(node2); - TimeComparator tc = new TimeComparator(); - int result = tc.compare(ne1, ne2); - Assert.assertEquals(1, result); - - } -} diff --git a/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java b/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java index 386c53a4294..4b57bc880d7 100644 --- a/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java +++ b/framework/src/test/java/org/tron/common/runtime/InheritanceTest.java @@ -1,77 +1,52 @@ package org.tron.common.runtime; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j -public class InheritanceTest { +public class InheritanceTest extends BaseTest { - private static final String dbPath = "output_InheritanceTest"; private static final String OWNER_ADDRESS; - private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; + private RepositoryImpl repository; + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); + @Before + public void init() { + if (init) { + return; } + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); + init = true; } /** * pragma solidity ^0.4.19; - * * contract foo { uint256 public id=10; function getNumber() returns (uint256){return 100;} * function getName() returns (string){ return "foo"; } } - * * contract bar is foo { function getName() returns (string) { return "bar"; } function getId() * returns(uint256){return id;} } */ @@ -113,14 +88,14 @@ public void inheritanceTest() byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, callerAddress, ABI, code, - value, fee, consumeUserResourcePercent, null, deposit, null); + value, fee, consumeUserResourcePercent, null, repository, null); /* ========================== CALL getName() return child value ============================= */ byte[] triggerData1 = TvmTestUtils.parseAbi("getName()", ""); - runtime = TvmTestUtils + Runtime runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(callerAddress, contractAddress, - triggerData1, 0, 1000000, deposit, null); + triggerData1, 0, 1000000, repository, null); //0x20 => pointer position, 0x3 => size, 626172 => "bar" Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), @@ -132,7 +107,7 @@ public void inheritanceTest() byte[] triggerData2 = TvmTestUtils.parseAbi("getNumber()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(callerAddress, contractAddress, - triggerData2, 0, 1000000, deposit, null); + triggerData2, 0, 1000000, repository, null); //0x64 =>100 Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), @@ -142,7 +117,7 @@ public void inheritanceTest() byte[] triggerData3 = TvmTestUtils.parseAbi("getId()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(callerAddress, contractAddress, - triggerData3, 0, 1000000, deposit, null); + triggerData3, 0, 1000000, repository, null); //0x64 =>100 Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), diff --git a/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java b/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java index 281968b1122..172ef40afa7 100644 --- a/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java +++ b/framework/src/test/java/org/tron/common/runtime/InternalTransactionComplexTest.java @@ -1,79 +1,55 @@ package org.tron.common.runtime; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j -public class InternalTransactionComplexTest { +public class InternalTransactionComplexTest extends BaseTest { - private static final String dbPath = "output_InternalTransactionComplexTest"; private static final String OWNER_ADDRESS; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; + private static RepositoryImpl repository; + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug", "--support-constant"}, + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug", "--support-constant"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); + @Before + public void init() { + if (init) { + return; } + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); + init = true; } /** * pragma solidity 0.4.24; - * * // this is to test wither the TVM is returning vars from one contract calling another // * contract's functions. - * * contract callerContract { // lets set up our instance of the new contract calledContract * CALLED_INSTANCE; // lets set the contract instance address in the constructor * constructor(address _addr) public { CALLED_INSTANCE = calledContract(_addr); } // lets create a @@ -84,7 +60,6 @@ public static void destroy() { * in to temp vars (bool _bool, uint256 _uint, bytes32 _bytes32) = CALLED_INSTANCE.testReturns(); * // lets write those temp vars to state testCallbackReturns_.someBool = _bool; * testCallbackReturns_.someUint = _uint; testCallbackReturns_.someBytes32 = _bytes32; } } - * * contract calledContract { function testReturns() external pure returns(bool, uint256, bytes32) * { return(true, 314159, 0x123456); } } */ @@ -99,13 +74,13 @@ public void internalTransactionAsInstanceTest() byte[] triggerData1 = TvmTestUtils.parseAbi("makeTheCall()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - callerContractAddress, triggerData1, 0, 100000000, deposit, null); + callerContractAddress, triggerData1, 0, 100000000, repository, null); /* =============== CALL testCallbackReturns_ to check data ====================== */ byte[] triggerData2 = TvmTestUtils.parseAbi("testCallbackReturns_()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - callerContractAddress, triggerData2, 0, 100000000, deposit, null); + callerContractAddress, triggerData2, 0, 100000000, repository, null); // bool true => 0000000000000000000000000000000000000000000000000000000000000001, // uint256 314159 =>000000000000000000000000000000000000000000000000000000000004cb2f, @@ -144,7 +119,7 @@ private byte[] deployCalledContractandGetItsAddress() return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } // Just for the caller/called example above @@ -192,7 +167,7 @@ private byte[] deployCallerContractAndGetItsAddress(byte[] calledContractAddress return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } } diff --git a/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java b/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java index 61b1024bc66..a2e53dd8711 100644 --- a/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java +++ b/framework/src/test/java/org/tron/common/runtime/ProgramResultTest.java @@ -3,36 +3,31 @@ import static org.tron.core.capsule.utils.TransactionUtil.buildTransactionInfoInstance; import static org.tron.core.utils.TransactionUtil.generateContractAddress; -import java.io.File; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionInfoCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; @@ -40,22 +35,17 @@ @Slf4j -public class ProgramResultTest { +public class ProgramResultTest extends BaseTest { - private static final String dbPath = "output_InternalTransactionComplexTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; + private static RepositoryImpl repository; + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug", "--support-constant"}, + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug", "--support-constant"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } @@ -63,29 +53,18 @@ public class ProgramResultTest { /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); - deposit.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); - deposit.addBalance(Hex.decode(TRANSFER_TO), 0); - deposit.commit(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); + @Before + public void init() { + if (init) { + return; } + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); + repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); + repository.addBalance(Hex.decode(TRANSFER_TO), 0); + repository.commit(); + init = true; } /** @@ -116,7 +95,7 @@ public void uniqueInternalTransactionHashTest() byte[] triggerData1 = TvmTestUtils.parseAbi("create()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData1, 0, 100000000, deposit, null); + contractAAddress, triggerData1, 0, 100000000, repository, null); List internalTransactionsList = runtime.getResult() .getInternalTransactions(); // 15 internalTransactions in total @@ -126,8 +105,8 @@ public void uniqueInternalTransactionHashTest() internalTransaction -> hashList.add(Hex.toHexString(internalTransaction.getHash()))); // No dup List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)).entrySet().stream() - .filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) + .collect(Collectors.toMap(e -> e, e -> 1, Integer::sum)).entrySet().stream() + .filter(entry -> entry.getValue() > 1).map(Map.Entry::getKey) .collect(Collectors.toList()); Assert.assertEquals(dupHash.size(), 0); } @@ -153,7 +132,7 @@ private byte[] deployCalledContractAndGetItsAddress() return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } private byte[] deployContractAAndGetItsAddress(byte[] calledContractAddress) @@ -262,7 +241,7 @@ private byte[] deployContractAAndGetItsAddress(byte[] calledContractAddress) return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } /** @@ -295,38 +274,39 @@ public void successAndFailResultTest() .generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), aContract, triggerData1, 0, 100000000); TransactionTrace traceSuccess = TvmTestUtils - .processTransactionAndReturnTrace(trx1, deposit, null); + .processTransactionAndReturnTrace(trx1, repository, null); runtime = traceSuccess.getRuntime(); byte[] bContract = runtime.getResult().getHReturn(); List internalTransactionsList = runtime.getResult() .getInternalTransactions(); Assert.assertEquals(internalTransactionsList.get(0).getValue(), 10); - Assert.assertEquals(internalTransactionsList.get(0).getSender(), aContract); - Assert.assertEquals( + Assert.assertArrayEquals(internalTransactionsList.get(0).getSender(), aContract); + Assert.assertArrayEquals( new DataWord(internalTransactionsList.get(0).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(0).getNote(), "create"); - Assert.assertEquals(internalTransactionsList.get(0).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(0).isRejected()); Assert.assertEquals(internalTransactionsList.get(1).getValue(), 5); - Assert.assertEquals(internalTransactionsList.get(1).getSender(), aContract); - Assert.assertEquals( + Assert.assertArrayEquals(internalTransactionsList.get(1).getSender(), aContract); + Assert.assertArrayEquals( new DataWord(internalTransactionsList.get(1).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(1).getNote(), "call"); - Assert.assertEquals(internalTransactionsList.get(1).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(1).isRejected()); Assert.assertEquals(internalTransactionsList.get(2).getValue(), 0); - Assert.assertEquals(internalTransactionsList.get(2).getSender(), aContract); - Assert.assertEquals( + Assert.assertArrayEquals(internalTransactionsList.get(2).getSender(), aContract); + Assert.assertArrayEquals( new DataWord(internalTransactionsList.get(2).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); Assert.assertEquals(internalTransactionsList.get(2).getNote(), "call"); - Assert.assertEquals(internalTransactionsList.get(2).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(2).isRejected()); Assert.assertEquals(internalTransactionsList.get(3).getValue(), 1); - Assert.assertEquals(new DataWord(internalTransactionsList.get(3).getSender()).getLast20Bytes(), + Assert.assertArrayEquals( + new DataWord(internalTransactionsList.get(3).getSender()).getLast20Bytes(), new DataWord(bContract).getLast20Bytes()); - Assert.assertEquals(internalTransactionsList.get(3).getTransferToAddress(), cContract); + Assert.assertArrayEquals(internalTransactionsList.get(3).getTransferToAddress(), cContract); Assert.assertEquals(internalTransactionsList.get(3).getNote(), "call"); - Assert.assertEquals(internalTransactionsList.get(3).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(3).isRejected()); checkTransactionInfo(traceSuccess, trx1, null, internalTransactionsList); // ======================================= Test Fail ======================================= @@ -338,7 +318,7 @@ public void successAndFailResultTest() .generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), aContract, triggerData2, 0, 100000000); TransactionTrace traceFailed = TvmTestUtils - .processTransactionAndReturnTrace(trx2, deposit, null); + .processTransactionAndReturnTrace(trx2, repository, null); runtime = traceFailed.getRuntime(); byte[] bContract2 = @@ -346,33 +326,33 @@ public void successAndFailResultTest() List internalTransactionsListFail = runtime.getResult() .getInternalTransactions(); Assert.assertEquals(internalTransactionsListFail.get(0).getValue(), 10); - Assert.assertEquals(internalTransactionsListFail.get(0).getSender(), aContract); - Assert.assertEquals( + Assert.assertArrayEquals(internalTransactionsListFail.get(0).getSender(), aContract); + Assert.assertArrayEquals( new DataWord(internalTransactionsListFail.get(0).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(0).getNote(), "create"); - Assert.assertEquals(internalTransactionsListFail.get(0).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(0).isRejected()); Assert.assertEquals(internalTransactionsListFail.get(1).getValue(), 5); - Assert.assertEquals(internalTransactionsListFail.get(1).getSender(), aContract); - Assert.assertEquals( + Assert.assertArrayEquals(internalTransactionsListFail.get(1).getSender(), aContract); + Assert.assertArrayEquals( new DataWord(internalTransactionsListFail.get(1).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(1).getNote(), "call"); - Assert.assertEquals(internalTransactionsListFail.get(1).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(1).isRejected()); Assert.assertEquals(internalTransactionsListFail.get(2).getValue(), 0); - Assert.assertEquals(internalTransactionsListFail.get(2).getSender(), aContract); - Assert.assertEquals( + Assert.assertArrayEquals(internalTransactionsListFail.get(2).getSender(), aContract); + Assert.assertArrayEquals( new DataWord(internalTransactionsListFail.get(2).getTransferToAddress()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); Assert.assertEquals(internalTransactionsListFail.get(2).getNote(), "call"); - Assert.assertEquals(internalTransactionsListFail.get(2).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(2).isRejected()); Assert.assertEquals(internalTransactionsListFail.get(3).getValue(), 1); - Assert.assertEquals( + Assert.assertArrayEquals( new DataWord(internalTransactionsListFail.get(3).getSender()).getLast20Bytes(), new DataWord(bContract2).getLast20Bytes()); - Assert.assertEquals(internalTransactionsListFail.get(3).getTransferToAddress(), cContract); + Assert.assertArrayEquals(internalTransactionsListFail.get(3).getTransferToAddress(), cContract); Assert.assertEquals(internalTransactionsListFail.get(3).getNote(), "call"); - Assert.assertEquals(internalTransactionsListFail.get(3).isRejected(), true); + Assert.assertTrue(internalTransactionsListFail.get(3).isRejected()); checkTransactionInfo(traceFailed, trx2, null, internalTransactionsListFail); } @@ -393,7 +373,7 @@ public void timeOutFeeTest() .generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), aContract, triggerData1, 0, 100000000); TransactionTrace traceSuccess = TvmTestUtils - .processTransactionAndReturnTrace(trx1, deposit, null); + .processTransactionAndReturnTrace(trx1, repository, null); Assert.assertEquals(traceSuccess.getReceipt().getEnergyFee(), 12705900L); @@ -438,7 +418,7 @@ private byte[] deployC(String contractName) return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } private byte[] deployA(String contractName) @@ -490,7 +470,7 @@ private byte[] deployA(String contractName) return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } /** @@ -504,7 +484,7 @@ public void suicideResultTest() throws ContractExeException, ReceiptCheckErrException, VMIllegalException, ContractValidateException { byte[] suicideContract = deploySuicide(); - Assert.assertEquals(deposit.getAccount(suicideContract).getBalance(), 1000); + Assert.assertEquals(repository.getAccount(suicideContract).getBalance(), 1000); String params = Hex .toHexString(new DataWord(new DataWord(TRANSFER_TO).getLast20Bytes()).getData()); @@ -513,20 +493,21 @@ public void suicideResultTest() Transaction trx = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(Hex.decode(OWNER_ADDRESS), suicideContract, triggerData1, 0, 100000000); - TransactionTrace trace = TvmTestUtils.processTransactionAndReturnTrace(trx, deposit, null); + TransactionTrace trace = TvmTestUtils.processTransactionAndReturnTrace(trx, repository, null); runtime = trace.getRuntime(); List internalTransactionsList = runtime.getResult() .getInternalTransactions(); Assert .assertEquals(dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getBalance(), 1000); - Assert.assertEquals(dbManager.getAccountStore().get(suicideContract), null); + Assert.assertNull(dbManager.getAccountStore().get(suicideContract)); Assert.assertEquals(internalTransactionsList.get(0).getValue(), 1000); - Assert.assertEquals(new DataWord(internalTransactionsList.get(0).getSender()).getLast20Bytes(), + Assert.assertArrayEquals(new DataWord( + internalTransactionsList.get(0).getSender()).getLast20Bytes(), new DataWord(suicideContract).getLast20Bytes()); - Assert.assertEquals(internalTransactionsList.get(0).getTransferToAddress(), + Assert.assertArrayEquals(internalTransactionsList.get(0).getTransferToAddress(), Hex.decode(TRANSFER_TO)); Assert.assertEquals(internalTransactionsList.get(0).getNote(), "suicide"); - Assert.assertEquals(internalTransactionsList.get(0).isRejected(), false); + Assert.assertFalse(internalTransactionsList.get(0).isRejected()); checkTransactionInfo(trace, trx, null, internalTransactionsList); } @@ -554,7 +535,7 @@ private byte[] deploySuicide() return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); } public void checkTransactionInfo(TransactionTrace trace, Transaction trx, BlockCapsule block, @@ -566,15 +547,16 @@ public void checkTransactionInfo(TransactionTrace trace, Transaction trx, BlockC for (int i = 0; i < internalTransactionListFromProtocol.size(); i++) { Assert.assertEquals(internalTransactionListFromProtocol.get(i).getRejected(), internalTransactionsList.get(i).isRejected()); - Assert - .assertEquals(internalTransactionListFromProtocol.get(i).getCallerAddress().toByteArray(), + Assert.assertArrayEquals( + internalTransactionListFromProtocol.get(i).getCallerAddress().toByteArray(), internalTransactionsList.get(i).getSender()); - Assert.assertEquals(internalTransactionListFromProtocol.get(i).getHash().toByteArray(), + Assert.assertArrayEquals( + internalTransactionListFromProtocol.get(i).getHash().toByteArray(), internalTransactionsList.get(i).getHash()); Assert.assertEquals( new String(internalTransactionListFromProtocol.get(i).getNote().toByteArray()), internalTransactionsList.get(i).getNote()); - Assert.assertEquals( + Assert.assertArrayEquals( internalTransactionListFromProtocol.get(i).getTransferToAddress().toByteArray(), internalTransactionsList.get(i).getTransferToAddress()); List callValueInfoListFromProtocol = diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java new file mode 100644 index 00000000000..e694f1c194f --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeImplMockTest.java @@ -0,0 +1,53 @@ +package org.tron.common.runtime; + +import java.lang.reflect.Method; + +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Test; +import org.tron.core.vm.program.Program; + + + +@Slf4j +public class RuntimeImplMockTest { + @After + public void clearMocks() { + + } + + @Test + public void testSetResultCode1() throws Exception { + RuntimeImpl runtime = new RuntimeImpl(); + ProgramResult programResult = new ProgramResult(); + Method privateMethod = RuntimeImpl.class.getDeclaredMethod( + "setResultCode", ProgramResult.class); + privateMethod.setAccessible(true); + + Program.BadJumpDestinationException badJumpDestinationException + = new Program.BadJumpDestinationException("Operation with pc isn't 'JUMPDEST': PC[%d];", 0); + programResult.setException(badJumpDestinationException); + privateMethod.invoke(runtime, programResult); + + Program.OutOfTimeException outOfTimeException + = new Program.OutOfTimeException("CPU timeout for 0x0a executing"); + programResult.setException(outOfTimeException); + privateMethod.invoke(runtime, programResult); + + Program.PrecompiledContractException precompiledContractException + = new Program.PrecompiledContractException("precompiled contract exception"); + programResult.setException(precompiledContractException); + privateMethod.invoke(runtime, programResult); + + Program.StackTooSmallException stackTooSmallException + = new Program.StackTooSmallException("Expected stack size %d but actual %d;", 100, 10); + programResult.setException(stackTooSmallException); + privateMethod.invoke(runtime, programResult); + + Program.JVMStackOverFlowException jvmStackOverFlowException + = new Program.JVMStackOverFlowException(); + programResult.setException(jvmStackOverFlowException); + privateMethod.invoke(runtime, programResult); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java index cd23edbcb5e..0b7721a325d 100644 --- a/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeImplTest.java @@ -3,26 +3,19 @@ import static org.tron.common.runtime.TvmTestUtils.generateDeploySmartContractAndGetTransaction; import static org.tron.common.runtime.TvmTestUtils.generateTriggerSmartContractAndGetTransaction; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.actuator.VMActuator; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -38,31 +31,27 @@ @Slf4j -public class RuntimeImplTest { +public class RuntimeImplTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; private Repository repository; - private String dbPath = "output_RuntimeImplTest"; - private Application AppT; - private byte[] callerAddress; - private long callerTotalBalance = 4_000_000_000L; - private byte[] creatorAddress; - private long creatorTotalBalance = 3_000_000_000L; + private static final byte[] callerAddress; + private final long callerTotalBalance = 4_000_000_000L; + private static final byte[] creatorAddress; + private final long creatorTotalBalance = 3_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + callerAddress = Hex + .decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"); + creatorAddress = Hex + .decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abd"); + } /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - callerAddress = Hex - .decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"); - creatorAddress = Hex - .decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abd"); - dbManager = context.getBean(Manager.class); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(5_000_000_000L); // unit is trx repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); @@ -117,11 +106,10 @@ public void getCreatorEnergyLimit2Test() throws ContractValidateException, Contr + "060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc56" + "5b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce25765" + "4c8c17b0029"; - String libraryAddressPair = null; Transaction trx = generateDeploySmartContractAndGetTransaction(contractName, creatorAddress, ABI, - code, value, feeLimit, consumeUserResourcePercent, libraryAddressPair); + code, value, feeLimit, consumeUserResourcePercent, null); RuntimeImpl runtimeImpl = new RuntimeImpl(); runtimeImpl.execute( @@ -167,7 +155,6 @@ public void getCreatorEnergyLimit2Test() throws ContractValidateException, Contr expectEnergyLimit4); feeLimit = 3_000_000_000L; - value = 10L; long expectEnergyLimit5 = 20_009_999L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -175,7 +162,6 @@ public void getCreatorEnergyLimit2Test() throws ContractValidateException, Contr expectEnergyLimit5); feeLimit = 3_000L; - value = 10L; long expectEnergyLimit6 = 30L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -207,11 +193,10 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() + "060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc56" + "5b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce25765" + "4c8c17b0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractWithCreatorEnergyLimitAndReturnTvmTestResult(contractName, creatorAddress, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, dbManager, null, + feeLimit, consumeUserResourcePercent, null, dbManager, null, creatorEnergyLimit); byte[] contractAddress = result.getContractAddress(); @@ -229,8 +214,6 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() AccountCapsule callerAccount = repository.getAccount(callerAddress); TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit1 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -245,8 +228,6 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() repository.putAccountValue(creatorAddress, creatorAccount); repository.commit(); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit2 = 10_005_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -277,8 +258,6 @@ public void getCallerAndCreatorEnergyLimit2With0PercentTest() repository.putAccountValue(callerAddress, callerAccount); repository.commit(); - value = 10L; - feeLimit = 5_000_000_000L; long expectEnergyLimit5 = 30_014_999L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -311,11 +290,10 @@ public void getCallerAndCreatorEnergyLimit2With40PercentTest() + "5060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc5" + "65b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce2576" + "54c8c17b0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractWithCreatorEnergyLimitAndReturnTvmTestResult(contractName, creatorAddress, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, dbManager, null, + feeLimit, consumeUserResourcePercent, null, dbManager, null, creatorEnergyLimit); byte[] contractAddress = result.getContractAddress(); @@ -333,8 +311,6 @@ public void getCallerAndCreatorEnergyLimit2With40PercentTest() AccountCapsule callerAccount = repository.getAccount(callerAddress); TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit1 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -349,8 +325,6 @@ public void getCallerAndCreatorEnergyLimit2With40PercentTest() repository.putAccountValue(creatorAddress, creatorAccount); repository.commit(); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit2 = 10_005_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -391,11 +365,10 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() + "060018201915060aa565b505050565b600080600091505b8282101560e1576001905060018201915060cc56" + "5b5050505600a165627a7a72305820267cf0ebf31051a92ff62bed7490045b8063be9f1e1a22d07dce25765" + "4c8c17b0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractWithCreatorEnergyLimitAndReturnTvmTestResult(contractName, creatorAddress, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, dbManager, null, + feeLimit, consumeUserResourcePercent, null, dbManager, null, creatorEnergyLimit); byte[] contractAddress = result.getContractAddress(); @@ -413,8 +386,6 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() AccountCapsule callerAccount = repository.getAccount(callerAddress); TriggerSmartContract contract = ContractCapsule.getTriggerContractFromTransaction(trx); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit1 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -429,8 +400,6 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() repository.putAccountValue(creatorAddress, creatorAccount); repository.commit(); - feeLimit = 1_000_000_000L; - value = 0L; long expectEnergyLimit2 = 10_000_000L; Assert.assertEquals( ((VMActuator) runtimeImpl.getActuator2()) @@ -445,21 +414,6 @@ public void getCallerAndCreatorEnergyLimit2With100PercentTest() .getTotalEnergyLimitWithFixRatio(creatorAccount, callerAccount, contract, feeLimit, value), expectEnergyLimit3); - - } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } } diff --git a/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java b/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java index 2a14f52e487..c9d61db9270 100644 --- a/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java +++ b/framework/src/test/java/org/tron/common/runtime/RuntimeTransferComplexTest.java @@ -2,48 +2,37 @@ import static org.tron.core.db.TransactionTrace.convertToTronAddress; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.DataWord; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.DataWord; @Slf4j -public class RuntimeTransferComplexTest { +public class RuntimeTransferComplexTest extends BaseTest { - private static final String dbPath = "output_RuntimeTransferComplexTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; + private static RepositoryImpl repository; + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } @@ -51,29 +40,18 @@ public class RuntimeTransferComplexTest { /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), 1000000000); - deposit.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); - deposit.addBalance(Hex.decode(TRANSFER_TO), 10); - deposit.commit(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); + @Before + public void init() { + if (init) { + return; } + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), 1000000000); + repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); + repository.addBalance(Hex.decode(TRANSFER_TO), 10); + repository.commit(); + init = true; } /** @@ -99,7 +77,7 @@ public void TransferTrxToContractAccountWhenDeployAContract() .generateDeploySmartContractAndGetTransaction(contractName, address, ABI, code, value, fee, consumeUserResourcePercent, null); byte[] contractAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, repository, null); Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(dbManager.getAccountStore().get(contractAddress).getBalance(), 100); recoverDeposit(); @@ -130,8 +108,8 @@ public void TransferTrxToContractAccountFailIfNotPayable() .generateDeploySmartContractAndGetTransaction(contractName, address, ABI, code, value, fee, consumeUserResourcePercent, null); byte[] contractAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, deposit, null); - Assert.assertNotNull(runtime.getRuntimeError().contains("REVERT")); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, repository, null); + Assert.assertTrue(runtime.getRuntimeError().contains("REVERT")); Assert.assertNull(dbManager.getAccountStore().get(contractAddress)); recoverDeposit(); } @@ -168,7 +146,7 @@ public void TransferTrxToContractAccountWhenTriggerAContract() byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); + feeLimit, consumeUserResourcePercent, null, repository, null); String selectorStr = "transferTo(address)"; String params = @@ -180,7 +158,7 @@ public void TransferTrxToContractAccountWhenTriggerAContract() Transaction transaction = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(address, contractAddress, triggerData, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction, repository, null); Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(dbManager.getAccountStore().get(contractAddress).getBalance(), 100 - 5); Assert.assertEquals(dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getBalance(), @@ -193,34 +171,25 @@ public void TransferTrxToContractAccountWhenTriggerAContract() * payable { CALLED_INSTANCE = calledContract(_addr); } // expect calledContract -5, toAddress +5 * function testCallTransferToInCalledContract(address toAddress) { * CALLED_INSTANCE.transferTo(toAddress); } - * * // expect calledContract -0, toAddress +0 function testRevertForCall(address toAddress){ * CALLED_INSTANCE.transferTo(toAddress); revert(); } function testExceptionForCall(address * toAddress){ CALLED_INSTANCE.transferTo(toAddress); assert(1==2); } // expect c +100 -5, * toAddress +0 function testTransferToInCreatedContract(address toAddress) payable * returns(address){ createdContract c = (new createdContract).value(100)(); * c.transferTo(toAddress); return address(c); } - * * // expect c +100 -5, toAddress not exist function testRevertForCreate(address toAddress) * payable returns(address){ createdContract c = (new createdContract).value(100)(); * c.transferTo(toAddress); revert(); return address(c); } - * * // expect c +100 -5, toAddress not exist function testExceptionForCreate(address toAddress) * payable returns(address){ createdContract c = (new createdContract).value(100)(); * c.transferTo(toAddress); assert(1==2); return address(c); } - * * function getBalance() public view returns(uint256){ return this.balance; } } - * * contract calledContract { constructor() payable {} function transferTo(address toAddress) * payable{ toAddress.transfer(5); } - * * function getBalance() public view returns(uint256){ return this.balance; } - * * } - * * contract createdContract { constructor() payable {} function transferTo(address toAddress){ * toAddress.transfer(5); } - * * function getBalance() public view returns(uint256){ return this.balance; } } */ @@ -249,7 +218,7 @@ public void TransferCallValueTestWhenUsingCallAndCreate() Transaction transaction1 = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData1, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction1, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction1, repository, null); Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(dbManager.getAccountStore().get(callerAddress).getBalance(), 1000); //Not changed @@ -268,7 +237,7 @@ public void TransferCallValueTestWhenUsingCallAndCreate() Transaction transaction2 = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData2, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction2, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction2, repository, null); Assert.assertTrue(runtime.getRuntimeError().contains("REVERT")); Assert.assertEquals(dbManager.getAccountStore().get(callerAddress).getBalance(), 1000); //Not changed @@ -287,7 +256,7 @@ public void TransferCallValueTestWhenUsingCallAndCreate() Transaction transaction3 = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData3, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction3, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction3, repository, null); Assert.assertTrue(runtime.getRuntimeError().contains("Invalid operation code: opCode[fe];")); Assert.assertEquals(dbManager.getAccountStore().get(callerAddress).getBalance(), 1000); //Not changed @@ -306,7 +275,7 @@ public void TransferCallValueTestWhenUsingCallAndCreate() Transaction transaction4 = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData4, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction4, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction4, repository, null); byte[] createdAddress = convertToTronAddress( new DataWord(runtime.getResult().getHReturn()).getLast20Bytes()); Assert.assertNull(runtime.getRuntimeError()); @@ -327,7 +296,7 @@ public void TransferCallValueTestWhenUsingCallAndCreate() Transaction transaction5 = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData5, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction5, deposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction5, repository, null); byte[] createdAddress2 = convertToTronAddress( new DataWord(runtime.getResult().getHReturn()).getLast20Bytes()); Assert.assertTrue(Hex.toHexString(new DataWord(createdAddress2).getLast20Bytes()) @@ -350,9 +319,7 @@ public void TransferCallValueTestWhenUsingCallAndCreate() Transaction transaction6 = TvmTestUtils .generateTriggerSmartContractAndGetTransaction(msgSenderAddress, callerAddress, triggerData6, triggerCallValue, feeLimit); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction6, deposit, null); - byte[] createdAddress3 = convertToTronAddress( - new DataWord(runtime.getResult().getHReturn()).getLast20Bytes()); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction6, repository, null); Assert.assertTrue(Hex.toHexString(new DataWord(createdAddress2).getLast20Bytes()) .equalsIgnoreCase("0000000000000000000000000000000000000000")); Assert.assertTrue(runtime.getRuntimeError().contains("Invalid operation code: opCode[fe];")); @@ -393,10 +360,9 @@ private byte[] deployCalledContract() long feeLimit = 100000000; long consumeUserResourcePercent = 0; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, null, deposit, null); - return contractAddress; + feeLimit, consumeUserResourcePercent, null, repository, null); } private byte[] deployCallerContract(byte[] calledAddress) @@ -474,15 +440,13 @@ private byte[] deployCallerContract(byte[] calledAddress) long value = 1000; long feeLimit = 100000000; long consumeUserResourcePercent = 0; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, callerAddress, callerABI, - callerCode, value, feeLimit, consumeUserResourcePercent, null, deposit, null); - return contractAddress; + callerCode, value, feeLimit, consumeUserResourcePercent, null, repository, null); } private void recoverDeposit() { - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); } diff --git a/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java b/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java index b4eac4936e9..ec2cd5a5e02 100644 --- a/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java +++ b/framework/src/test/java/org/tron/common/runtime/TvmTestUtils.java @@ -10,9 +10,10 @@ import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.tron.common.crypto.Hash; -import org.tron.common.storage.Deposit; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.Parameter.CommonConstant; +import org.tron.common.utils.client.WalletClient; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Wallet; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; @@ -23,15 +24,14 @@ import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; + import org.tron.protos.Protocol.Transaction; 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; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.PublicMethed; /** @@ -45,36 +45,36 @@ public class TvmTestUtils { public static byte[] deployContractWholeProcessReturnContractAddress(String contractName, byte[] callerAddress, String abi, String code, long value, long feeLimit, long consumeUserResourcePercent, - String libraryAddressPair, DepositImpl deposit, BlockCapsule block) + String libraryAddressPair, RepositoryImpl repository, BlockCapsule block) throws ContractExeException, ReceiptCheckErrException, ContractValidateException, VMIllegalException { Transaction trx = generateDeploySmartContractAndGetTransaction(contractName, callerAddress, abi, code, value, feeLimit, consumeUserResourcePercent, libraryAddressPair); - processTransactionAndReturnRuntime(trx, deposit, block); + processTransactionAndReturnRuntime(trx, repository, block); return WalletUtil.generateContractAddress(trx); } public static byte[] deployContractWholeProcessReturnContractAddress(String contractName, byte[] callerAddress, String abi, String code, long value, long feeLimit, long consumeUserResourcePercent, - String libraryAddressPair, long tokenValue, long tokenId, DepositImpl deposit, + String libraryAddressPair, long tokenValue, long tokenId, RepositoryImpl repository, BlockCapsule block) throws ContractExeException, ReceiptCheckErrException, ContractValidateException, VMIllegalException { Transaction trx = generateDeploySmartContractAndGetTransaction(contractName, callerAddress, abi, code, value, feeLimit, consumeUserResourcePercent, tokenValue, tokenId, libraryAddressPair); - processTransactionAndReturnRuntime(trx, deposit, block); + processTransactionAndReturnRuntime(trx, repository, block); return WalletUtil.generateContractAddress(trx); } public static Runtime triggerContractWholeProcessReturnContractAddress(byte[] callerAddress, - byte[] contractAddress, byte[] data, long callValue, long feeLimit, DepositImpl deposit, + byte[] contractAddress, byte[] data, long callValue, long feeLimit, RepositoryImpl repository, BlockCapsule block) throws ContractExeException, ReceiptCheckErrException, ContractValidateException, VMIllegalException { Transaction trx = generateTriggerSmartContractAndGetTransaction(callerAddress, contractAddress, data, callValue, feeLimit); - return processTransactionAndReturnRuntime(trx, deposit, block); + return processTransactionAndReturnRuntime(trx, repository, block); } /** @@ -163,16 +163,16 @@ public static Transaction generateDeploySmartContractWithCreatorEnergyLimitAndGe } /** - * use given input Transaction,deposit,block and execute TVM (for both Deploy and Trigger + * use given input Transaction,repository,block and execute TVM (for both Deploy and Trigger * contracts). */ public static Runtime processTransactionAndReturnRuntime(Transaction trx, - Deposit deposit, BlockCapsule block) + Repository repository, BlockCapsule block) throws ContractExeException, ContractValidateException, ReceiptCheckErrException, VMIllegalException { TransactionCapsule trxCap = new TransactionCapsule(trx); - deposit.commit(); + repository.commit(); TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); // init trace.init(block); @@ -203,11 +203,11 @@ public static Runtime processTransactionAndReturnRuntime(Transaction trx, } public static TransactionTrace processTransactionAndReturnTrace(Transaction trx, - DepositImpl deposit, BlockCapsule block) + RepositoryImpl repository, BlockCapsule block) throws ContractExeException, ContractValidateException, ReceiptCheckErrException, VMIllegalException { TransactionCapsule trxCap = new TransactionCapsule(trx); - deposit.commit(); + repository.commit(); TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); // init trace.init(block); @@ -621,7 +621,7 @@ public static CreateSmartContract createSmartContract(byte[] owner, String contr String abiString, String code, long value, long consumeUserResourcePercent) { Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - SmartContract.ABI abi = PublicMethed.jsonStr2Abi(abiString); + SmartContract.ABI abi = jsonStr2Abi(abiString); if (abi == null) { return null; } 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 0b24d357a8a..ded7bb01af3 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 @@ -7,20 +7,21 @@ import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; + import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class AllowTvmCompatibleEvmTest extends VMTestBase { @@ -73,7 +74,7 @@ public void testEthRipemd160() throws ContractExeException, ReceiptCheckErrExcep contractName, address, abi, factoryCode, value, feeLimit, consumeUserResourcePercent, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: getRipemd160() @@ -86,7 +87,7 @@ public void testEthRipemd160() throws ContractExeException, ReceiptCheckErrExcep factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); byte[] returnValue = result.getRuntime().getResult().getHReturn(); Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(returnValue, + Assert.assertArrayEquals(returnValue, hexToBytes("a76d892cc3522eab763529dfc84b12c080ee1" + "fe8000000000000000000000000")); } @@ -198,7 +199,7 @@ public void testBlake2f() throws ContractExeException, ReceiptCheckErrException, contractName, address, abi, factoryCode, value, feeLimit, consumeUserResourcePercent, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: callF() @@ -211,7 +212,7 @@ public void testBlake2f() throws ContractExeException, ReceiptCheckErrException, factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); byte[] returnValue = result.getRuntime().getResult().getHReturn(); Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(returnValue, + Assert.assertArrayEquals(returnValue, hexToBytes("ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87" + "c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923")); } @@ -244,7 +245,7 @@ public void testGasPrice() throws ContractExeException, ReceiptCheckErrException contractName, address, abi, factoryCode, value, feeLimit, consumeUserResourcePercent, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: getprice() @@ -257,7 +258,7 @@ public void testGasPrice() throws ContractExeException, ReceiptCheckErrException factoryAddress, Hex.decode(hexInput), 0, feeLimit, manager, null); byte[] returnValue = result.getRuntime().getResult().getHReturn(); Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(returnValue, + Assert.assertArrayEquals(returnValue, longTo32Bytes(manager.getDynamicPropertiesStore().getEnergyFee())); } @@ -279,7 +280,7 @@ public void testChainId() throws ContractExeException, ReceiptCheckErrException, Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( contractName, address, "[]", contractCode, 0, feeLimit, 0, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: getChainId() 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 c6b3ec10a98..e93eca39092 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 @@ -5,11 +5,12 @@ import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -17,7 +18,6 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class AllowTvmLondonTest extends VMTestBase { @@ -61,7 +61,7 @@ public void testBaseFee() throws ContractExeException, ReceiptCheckErrException, contractName, address, abi, factoryCode, value, feeLimit, consumeUserResourcePercent, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: getbasefee() @@ -74,7 +74,7 @@ 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.assertEquals(returnValue, + Assert.assertArrayEquals(returnValue, longTo32Bytes(manager.getDynamicPropertiesStore().getEnergyFee())); } @@ -103,7 +103,7 @@ public void testStartWithEF() throws ContractExeException, ReceiptCheckErrExcept Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( contractName, address, abi, factoryCode, value, feeLimit, consumeUserResourcePercent, null); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNotNull(runtime.getRuntimeError()); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java index 843a102bfff..582f5157b27 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeTest.java @@ -17,29 +17,23 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.exception.TronException; import org.tron.core.exception.VMIllegalException; @@ -54,53 +48,45 @@ /** * pragma solidity ^0.4.2; - * * contract Fibonacci { - * * event Notify(uint input, uint result); - * * function fibonacci(uint number) constant returns(uint result) { if (number == 0) { return 0; } * else if (number == 1) { return 1; } else { uint256 first = 0; uint256 second = 1; uint256 ret = * 0; for(uint256 i = 2; i <= number; i++) { ret = first + second; first = second; second = ret; } * return ret; } } - * * function fibonacciNotify(uint number) returns(uint result) { result = fibonacci(number); * Notify(number, result); } } */ -public class BandWidthRuntimeOutOfTimeTest { +public class BandWidthRuntimeOutOfTimeTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeOutOfTimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; + private static final String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static boolean init; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w", "--debug" }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } - private String trx2ContractAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647828000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -124,16 +110,7 @@ public static void init() { .put(Commons.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule2); dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000); - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -155,7 +132,6 @@ public void testSuccess() { new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); trace.init(blockCapsule); trace.exec(); trace.finalization(); @@ -178,7 +154,8 @@ public void testSuccess() { private byte[] createContract() throws ContractValidateException, AccountResourceInsufficientException, - TooBigTransactionResultException, ContractExeException, VMIllegalException { + TooBigTransactionResultException, ContractExeException, VMIllegalException, + TooBigTransactionException { AccountCapsule owner = dbManager.getAccountStore() .get(Commons.decodeFromBase58Check(OwnerAddress)); long energy = owner.getEnergyUsage(); @@ -218,9 +195,7 @@ private byte[] createContract() TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); owner = dbManager.getAccountStore() diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java index 07906ef23f4..7e75f2b31d1 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeOutOfTimeWithCheckTest.java @@ -17,30 +17,24 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.exception.TronException; import org.tron.core.exception.VMIllegalException; @@ -56,52 +50,44 @@ /** * pragma solidity ^0.4.2; - * * contract Fibonacci { - * * event Notify(uint input, uint result); - * * function fibonacci(uint number) constant returns(uint result) { if (number == 0) { return 0; } * else if (number == 1) { return 1; } else { uint256 first = 0; uint256 second = 1; uint256 ret = * 0; for(uint256 i = 2; i <= number; i++) { ret = first + second; first = second; second = ret; } * return ret; } } - * * function fibonacciNotify(uint number) returns(uint result) { result = fibonacci(number); * Notify(number, result); } } */ -public class BandWidthRuntimeOutOfTimeWithCheckTest { +public class BandWidthRuntimeOutOfTimeWithCheckTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeOutOfTimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String dbDirectory = "db_BandWidthRuntimeOutOfTimeTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeOutOfTimeTest_test"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static boolean init; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w" + "--debug" }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } - private String trx2ContractAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647837000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -125,16 +111,7 @@ public static void init() { .put(Commons.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule2); dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000); - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -172,16 +149,15 @@ public void testSuccess() { Assert.assertEquals(990000000, balance); Assert.assertEquals(9950000 * Constant.SUN_PER_ENERGY, balance + energy * Constant.SUN_PER_ENERGY); - } catch (TronException e) { - Assert.assertNotNull(e); - } catch (ReceiptCheckErrException e) { + } catch (TronException | ReceiptCheckErrException e) { Assert.assertNotNull(e); } } private byte[] createContract() throws ContractValidateException, AccountResourceInsufficientException, - TooBigTransactionResultException, ContractExeException, VMIllegalException { + TooBigTransactionResultException, ContractExeException, VMIllegalException, + TooBigTransactionException { AccountCapsule owner = dbManager.getAccountStore() .get(Commons.decodeFromBase58Check(OwnerAddress)); long energy = owner.getEnergyUsage(); @@ -222,7 +198,6 @@ private byte[] createContract() new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); trace.init(blockCapsule); trace.exec(); trace.finalization(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java index 2c9bda15e88..40a4003f625 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeTest.java @@ -15,33 +15,29 @@ package org.tron.common.runtime.vm; +import static org.tron.common.math.Maths.max; + import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.exception.TronException; import org.tron.core.exception.VMIllegalException; @@ -50,44 +46,42 @@ 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.Protocol.Transaction.Result; +import org.tron.protos.Protocol.Transaction.Result.contractResult; import org.tron.protos.Protocol.Transaction.raw; import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -public class BandWidthRuntimeTest { +public class BandWidthRuntimeTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; - private static String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; + private static final String dbDirectory = "db_BandWidthRuntimeTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeTest_test"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; + private static boolean init; - static { + @BeforeClass + public static void init() { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w" }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); + @Before + public void before() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526547838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -123,25 +117,13 @@ public static void init() { dbManager.getDynamicPropertiesStore() .saveLatestBlockHeaderTimestamp(System.currentTimeMillis() / 1000); - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test public void testSuccess() { try { byte[] contractAddress = createContract(); - AccountCapsule triggerOwner = dbManager.getAccountStore() - .get(Commons.decodeFromBase58Check(TriggerOwnerAddress)); - long energy = triggerOwner.getEnergyUsage(); TriggerSmartContract triggerContract = TvmTestUtils.createTriggerContract(contractAddress, "setCoin(uint256)", "3", false, 0, Commons.decodeFromBase58Check(TriggerOwnerAddress)); @@ -152,16 +134,14 @@ public void testSuccess() { TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); - triggerOwner = dbManager.getAccountStore() + AccountCapsule triggerOwner = dbManager.getAccountStore() .get(Commons.decodeFromBase58Check(TriggerOwnerAddress)); - energy = triggerOwner.getEnergyUsage(); + long energy = triggerOwner.getEnergyUsage(); long balance = triggerOwner.getBalance(); Assert.assertEquals(45706, trace.getReceipt().getEnergyUsageTotal()); Assert.assertEquals(45706, energy); @@ -187,7 +167,7 @@ public void testSuccessNoBandd() { dbManager.consumeBandwidth(trxCap, trace); long bandWidth = trxCap.getSerializedSize() + Constant.MAX_RESULT_SIZE_IN_TX; BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); + trace.init(blockCapsule); trace.exec(); trace.finalization(); @@ -210,7 +190,8 @@ public void testSuccessNoBandd() { private byte[] createContract() throws ContractValidateException, AccountResourceInsufficientException, - TooBigTransactionResultException, ContractExeException, VMIllegalException { + TooBigTransactionResultException, ContractExeException, VMIllegalException, + TooBigTransactionException { AccountCapsule owner = dbManager.getAccountStore() .get(Commons.decodeFromBase58Check(OwnerAddress)); long energy = owner.getEnergyUsage(); @@ -242,7 +223,6 @@ private byte[] createContract() new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); trace.init(blockCapsule); trace.exec(); trace.finalization(); @@ -260,4 +240,18 @@ private byte[] createContract() Assert.assertNull(trace.getRuntimeError()); return trace.getRuntimeResult().getContractAddress(); } + + @Test + public void testMaxContractResultSize() { + int maxSize = 0; + for (contractResult cr : contractResult.values()) { + if (cr.name().equals("UNRECOGNIZED")) { + continue; + } + Result result = Result.newBuilder().setContractRet(cr).build(); + maxSize = max(maxSize, result.getSerializedSize(), + dbManager.getDynamicPropertiesStore().disableJavaLangMath()); + } + Assert.assertEquals(2, maxSize); + } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java index 2ac91063792..aae8cb5702d 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BandWidthRuntimeWithCheckTest.java @@ -17,32 +17,24 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.exception.TronException; import org.tron.core.exception.VMIllegalException; @@ -58,54 +50,45 @@ /** * pragma solidity ^0.4.2; - * * contract Fibonacci { - * * event Notify(uint input, uint result); - * * function fibonacci(uint number) constant returns(uint result) { if (number == 0) { return 0; } * else if (number == 1) { return 1; } else { uint256 first = 0; uint256 second = 1; uint256 ret = * 0; for(uint256 i = 2; i <= number; i++) { ret = first + second; first = second; second = ret; } * return ret; } } - * * function fibonacciNotify(uint number) returns(uint result) { result = fibonacci(number); * Notify(number, result); } } */ -public class BandWidthRuntimeWithCheckTest { +public class BandWidthRuntimeWithCheckTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_BandWidthRuntimeTest_test"; - private static String dbDirectory = "db_BandWidthRuntimeTest_test"; - private static String indexDirectory = "index_BandWidthRuntimeTest_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; + private static final String dbDirectory = "db_BandWidthRuntimeWithCheckTest_test"; + private static final String indexDirectory = "index_BandWidthRuntimeWithCheckTest_test"; + private static final String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; + private static final String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; + private static final String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; - private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; - private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; - private static String TriggerOwnerTwoAddress = "TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj"; + private static boolean init; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w" }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(10_000_000L); @@ -135,17 +118,7 @@ public static void init() { accountCapsule3.setFrozenForEnergy(10_000_000L, 0L); dbManager.getAccountStore() .put(Commons.decodeFromBase58Check(TriggerOwnerTwoAddress), accountCapsule3); - - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -166,9 +139,8 @@ public void testSuccess() { TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); - trace.init(blockCapsule); + + trace.init(null); trace.exec(); trace.finalization(); @@ -181,9 +153,7 @@ public void testSuccess() { Assert.assertEquals(57466800, balance); Assert.assertEquals(624668 * Constant.SUN_PER_ENERGY, balance + energy * Constant.SUN_PER_ENERGY); - } catch (TronException e) { - Assert.assertNotNull(e); - } catch (ReceiptCheckErrException e) { + } catch (TronException | ReceiptCheckErrException e) { Assert.assertNotNull(e); } @@ -205,9 +175,7 @@ public void testSuccessNoBandWidth() { new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); long bandWidth = trxCap.getSerializedSize() + Constant.MAX_RESULT_SIZE_IN_TX; - BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); - trace.init(blockCapsule); + trace.init(null); trace.exec(); trace.finalization(); trace.check(); @@ -222,9 +190,7 @@ public void testSuccessNoBandWidth() { Assert.assertEquals(0, receipt.getEnergyFee()); Assert.assertEquals(totalBalance, balance); - } catch (TronException e) { - Assert.assertNotNull(e); - } catch (ReceiptCheckErrException e) { + } catch (TronException | ReceiptCheckErrException e) { Assert.assertNotNull(e); } } @@ -232,7 +198,7 @@ public void testSuccessNoBandWidth() { private byte[] createContract() throws ContractValidateException, AccountResourceInsufficientException, TooBigTransactionResultException, ContractExeException, ReceiptCheckErrException, - VMIllegalException { + VMIllegalException, TooBigTransactionException { AccountCapsule owner = dbManager.getAccountStore() .get(Commons.decodeFromBase58Check(OwnerAddress)); long energy = owner.getEnergyUsage(); @@ -272,9 +238,8 @@ private byte[] createContract() TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), new RuntimeImpl()); dbManager.consumeBandwidth(trxCap, trace); - BlockCapsule blockCapsule = null; - DepositImpl deposit = DepositImpl.createRoot(dbManager); - trace.init(blockCapsule); + + trace.init(null); trace.exec(); trace.finalization(); trace.check(); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java index 3af76597eb4..cf67ae4b087 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BatchSendTest.java @@ -1,71 +1,48 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j -public class BatchSendTest { +public class BatchSendTest extends BaseTest { - private static final String dbPath = "output_BatchSendTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; - private static final long TOTAL_SUPPLY = 1000_000_000L; - private static final int TRX_NUM = 10; - private static final int NUM = 1; - private static final long START_TIME = 1; - private static final long END_TIME = 2; - private static final int VOTE_SCORE = 2; - private static final String DESCRIPTION = "TRX"; - private static final String URL = "https://tron.network/"; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; - private static AccountCapsule ownerCapsule; + private static RepositoryImpl repository; + private static final AccountCapsule ownerCapsule; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); - deposit.addBalance(Hex.decode(TRANSFER_TO), 10); - deposit.commit(); + ownerCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -73,40 +50,31 @@ public class BatchSendTest { AccountType.AssetIssue); ownerCapsule.setBalance(1000_1000_1000L); + + + } + + @Before + public void before() { + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); + repository.addBalance(Hex.decode(TRANSFER_TO), 10); + repository.commit(); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); dbManager.getDynamicPropertiesStore().saveAllowTvmTransferTrc10(1); dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); dbManager.getDynamicPropertiesStore().saveAllowTvmSolidity059(1); - - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** * pragma solidity ^0.5.4; - * * contract TestBatchSendTo { constructor() public payable{} - * * function depositIn() public payable{} - * - * * function batchSendTo (address payable to1 ,address payable to2 ,address payable to3, uint256 * m1,uint256 m2,uint256 m3) public { to1.send(m1 ); to2.send(m2 ); to3.send(m3 ); } - * * } */ @Test @@ -115,7 +83,7 @@ public void TransferTokenTest() ContractValidateException { // 1. Deploy*/ byte[] contractAddress = deployTransferContract(); - deposit.commit(); + repository.commit(); Assert.assertEquals(1000, dbManager.getAccountStore().get(contractAddress).getBalance()); @@ -125,6 +93,7 @@ public void TransferTokenTest() ECKey ecKey3 = new ECKey(Utils.getRandom()); List params = new ArrayList<>(); + logger.info("show db key: {}", StringUtil.createDbKey(ByteString.copyFrom("test".getBytes()))); params.add(StringUtil.encode58Check(ecKey1.getAddress())); params.add(StringUtil.encode58Check(ecKey2.getAddress())); params.add(StringUtil.encode58Check(ecKey3.getAddress())); @@ -180,10 +149,9 @@ private byte[] deployTransferContract() long tokenValue = 0; long tokenId = 0; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, tokenValue, tokenId, - deposit, null); - return contractAddress; + repository, null); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java index f7226bb3b3d..fc60d8c0648 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/BatchValidateSignContractTest.java @@ -6,16 +6,16 @@ import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; -import org.junit.Ignore; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.Hash; import org.tron.common.utils.StringUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.db.TransactionTrace; import org.tron.core.vm.PrecompiledContracts; import org.tron.core.vm.PrecompiledContracts.BatchValidateSign; -import stest.tron.wallet.common.client.utils.AbiUtil; + @Slf4j public class BatchValidateSignContractTest { @@ -73,13 +73,12 @@ public void staticCallTest() { .add(StringUtil.encode58Check(TransactionTrace.convertToTronAddress(new byte[20]))); ret = validateMultiSign(hash, signatures, addresses); Assert.assertEquals(ret.getValue().length, 32); - Assert.assertEquals(ret.getValue(), new byte[32]); + Assert.assertArrayEquals(ret.getValue(), new byte[32]); System.gc(); // force triggering full gc to avoid timeout for next test } - + @Test public void correctionTest() { - contract.setConstantCall(false); List signatures = new ArrayList<>(); List addresses = new ArrayList<>(); byte[] hash = Hash.sha3(longData); @@ -119,7 +118,7 @@ public void correctionTest() { List incorrectSigns = new ArrayList<>(signatures); incorrectSigns.remove(incorrectSigns.size() - 1); ret = validateMultiSign(hash, incorrectSigns, addresses); - Assert.assertEquals(ret.getValue(), DataWord.ZERO().getData()); + Assert.assertArrayEquals(ret.getValue(), DataWord.ZERO().getData()); System.gc(); // force triggering full gc to avoid timeout for next test } @@ -128,7 +127,8 @@ Pair validateMultiSign(byte[] hash, List signatures, List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); byte[] input = Hex.decode(AbiUtil.parseParameters(METHOD_SIGN, parameters)); contract.getEnergyForData(input); - contract.setVmShouldEndInUs(System.nanoTime() / 1000 + 500 * 1000); + long maxExecutionTime = 2000; // ms + contract.setVmShouldEndInUs(System.nanoTime() / 1000 + maxExecutionTime * 1000); Pair ret = contract.execute(input); logger.info("BytesArray:{},HexString:{}", Arrays.toString(ret.getValue()), Hex.toHexString(ret.getValue())); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java index 8538209f609..c158b2e400f 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ChargeTest.java @@ -1,58 +1,46 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j +public class ChargeTest extends BaseTest { -public class ChargeTest { - - private Manager dbManager; - private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_ChargeTest"; - private String OWNER_ADDRESS; - private Application AppT; + private RepositoryImpl repository; + private static String OWNER_ADDRESS; private long totalBalance = 100_000_000_000_000L; + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); - deposit.commit(); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); + repository.commit(); } // pragma solidity ^0.4.16; @@ -87,11 +75,10 @@ public void testOverflow() + "3901905600608060405260358060116000396000f3006080604052600080fd00a165627a7a723058201738d" + "6aa899dc00d4e99de944eb74d30a9ba1fcae37b99dc6299d95e992ca8b40029a165627a7a72305820683901" + "37ba70dfc460810603eba8500b050ed3cd01e66f55ec07d387ec1cd2750029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 51293; // 200 * code.length() + 93 Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -107,7 +94,7 @@ public void testOverflow() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof ArithmeticException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -153,11 +140,10 @@ public void testNegative() + "5600608060405260358060116000396000f3006080604052600080fd00a165627a7a72305820ef54aac72ef" + "ff56dbe894e7218d009a87368bb70338bb385db5d3dec9927bc2c0029a165627a7a723058201620679ac2ae" + "640d0a6c26e9cb4523e98eb0de8fff26975c5bb4c7fda1c98d720029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 68111; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -173,7 +159,7 @@ public void testNegative() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof ArithmeticException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -188,7 +174,7 @@ public void testNegative() long expectEnergyUsageTotal3 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal3); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof ArithmeticException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance @@ -196,27 +182,6 @@ public void testNegative() } - @Test - @Ignore - public void testFallback() - throws ContractExeException, ContractValidateException, ReceiptCheckErrException { - // done in EnergyWhenSendAndTransferTest.java - - } - - // contract TestCallDepth { - // - // function CallstackExploit(int256 counter) external { - // if (counter > 0) { - // this.CallstackExploit.gas(msg.gas - 2000)(counter - 1); - // } else {} - // } - // - // function Call(int256 counter) { - // this.CallstackExploit(counter); - // } - // } - @Test public void testCallDepth() throws ContractExeException, ContractValidateException, @@ -242,11 +207,10 @@ public void testCallDepth() + "152602001915050600060405180830381600087803b15801561012d57600080fd5b505af115801561014157" + "3d6000803e3d6000fd5b50505050505600a165627a7a72305820510367f4437b1af16931cacc744eb6f3102" + "d72f0c369aa795a4dc49a7f90a3e90029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 74517; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -264,8 +228,8 @@ public void testCallDepth() long expectEnergyUsageTotal2 = 27743; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -359,11 +323,10 @@ public void testCallDepthAndWidth() + "8e9050565b50505600a165627a7a72305820a9e7e1401001d6c131ebf4727fbcedede08d16416dc0447cef60" + "e0b9516c6a260029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 286450; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -381,8 +344,8 @@ public void testCallDepthAndWidth() long expectEnergyUsageTotal2 = 243698; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -427,11 +390,9 @@ public void testCreateDepthAndWidth() + "029a165627a7a7230582071d51c39c93b0aba5baeacea0b2bd5ca5342d028bb834046eca92975a3517a4c0" + "029"; - String libraryAddressPair = null; - TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 201839; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -449,24 +410,11 @@ public void testCreateDepthAndWidth() long expectEnergyUsageTotal2 = 4481164; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } 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 9b470f2df50..f400b3215ee 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 @@ -7,18 +7,26 @@ import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.ByteArray; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; +import org.tron.common.utils.client.utils.DataWord; +import org.tron.core.Wallet; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.JsonRpcInvalidParamsException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.services.NodeInfoService; +import org.tron.core.services.jsonrpc.TronJsonRpcImpl; +import org.tron.core.vm.config.ConfigLoader; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.DataWord; + @Slf4j public class Create2Test extends VMTestBase { @@ -97,6 +105,11 @@ triggercontract Txxxxxxxxxxx deploy(bytes,uint256) bytes,uint256 false 100000000 */ + @Before + public void before() { + ConfigLoader.disable = false; + } + @Test public void testCreate2() throws ContractExeException, ReceiptCheckErrException, @@ -144,7 +157,7 @@ public void testCreate2() null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); for (int i = 0; i < 3; i++) { - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); if (runtime.getRuntimeError() == null) { break; } @@ -154,9 +167,16 @@ public void testCreate2() // Trigger contract method: deploy(bytes,uint) long salt = 100L; String hexInput = AbiUtil.parseMethod(methodSign, Arrays.asList(testCode, salt)); + + long preTime = manager.getDynamicPropertiesStore().getMaxCpuTimeOfOneTx(); + // set max cpu time to 500 + manager.getDynamicPropertiesStore().saveMaxCpuTimeOfOneTx(500L); TVMTestResult result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); + // restore max cpu time + manager.getDynamicPropertiesStore().saveMaxCpuTimeOfOneTx(preTime); + Assert.assertNull(result.getRuntime().getRuntimeError()); byte[] returnValue = result.getRuntime().getResult().getHReturn(); @@ -167,17 +187,35 @@ public void testCreate2() byte[] expectedContract = generateContractAddress2(address, new DataWord(salt).getData(), Hex.decode(testCode)); // check deployed contract - Assert.assertEquals(actualContract, expectedContract); + Assert.assertArrayEquals(actualContract, expectedContract); // trigger deployed contract String methodToTrigger = "plusOne()"; - for (int i = 1; i < 3; i++) { + long loop = 2; + for (int i = 1; i <= loop; i++) { hexInput = AbiUtil.parseMethod(methodToTrigger, Collections.emptyList()); result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), actualContract, Hex.decode(hexInput), 0, fee, manager, null); Assert.assertNull(result.getRuntime().getRuntimeError()); - Assert.assertEquals(result.getRuntime().getResult().getHReturn(), new DataWord(i).getData()); + Assert.assertArrayEquals(result.getRuntime().getResult().getHReturn(), + new DataWord(i).getData()); + } + testJsonRpc(actualContract, loop); + } + + private void testJsonRpc(byte[] actualContract, long loop) { + TronJsonRpcImpl tronJsonRpc; + NodeInfoService nodeInfoService; + nodeInfoService = context.getBean(NodeInfoService.class); + Wallet wallet = context.getBean(Wallet.class); + tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, manager); + try { + String res = + tronJsonRpc.getStorageAt(ByteArray.toHexString(actualContract), "0", "latest"); + Assert.assertEquals(loop, ByteArray.jsonHexToLong(res)); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/CreateContractSuicideTest.java b/framework/src/test/java/org/tron/common/runtime/vm/CreateContractSuicideTest.java index bf0de449cbd..917c3dec030 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/CreateContractSuicideTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/CreateContractSuicideTest.java @@ -3,18 +3,19 @@ import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.core.config.Parameter.ForkBlockVersionEnum; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.program.Program.OutOfEnergyException; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.Transaction; @Slf4j @@ -143,26 +144,26 @@ public void testAAfterAllowMultiSignProposal() Transaction aTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testA", address, abi, aCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime aRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(aTrx, DepositImpl.createRoot(manager), null); + Runtime aRuntime = TvmTestUtils.processTransactionAndReturnRuntime(aTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertEquals(aRuntime.getRuntimeError(), "REVERT opcode executed"); Transaction bTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testB", address, abi, bCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime bRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(bTrx, DepositImpl.createRoot(manager), null); + Runtime bRuntime = TvmTestUtils.processTransactionAndReturnRuntime(bTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertEquals(bRuntime.getRuntimeError(), "REVERT opcode executed"); Transaction cTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testC", address, abi, cCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime cRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(cTrx, DepositImpl.createRoot(manager), null); + Runtime cRuntime = TvmTestUtils.processTransactionAndReturnRuntime(cTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertTrue(cRuntime.getResult().getException() instanceof OutOfEnergyException); Transaction dTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testC", address, abi, dCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime dRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(dTrx, DepositImpl.createRoot(manager), null); + Runtime dRuntime = TvmTestUtils.processTransactionAndReturnRuntime(dTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertEquals(dRuntime.getRuntimeError(), "REVERT opcode executed"); } @@ -179,26 +180,26 @@ public void testABeforeAllowMultiSignProposal() byte[] address = Hex.decode(OWNER_ADDRESS); Transaction aTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testA", address, abi, aCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime aRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(aTrx, DepositImpl.createRoot(manager), null); + Runtime aRuntime = TvmTestUtils.processTransactionAndReturnRuntime(aTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertEquals(aRuntime.getRuntimeError(), "Unknown Exception"); Transaction bTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testB", address, abi, bCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime bRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(bTrx, DepositImpl.createRoot(manager), null); + Runtime bRuntime = TvmTestUtils.processTransactionAndReturnRuntime(bTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertEquals(bRuntime.getRuntimeError(), "REVERT opcode executed"); Transaction cTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testC", address, abi, cCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime cRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(cTrx, DepositImpl.createRoot(manager), null); + Runtime cRuntime = TvmTestUtils.processTransactionAndReturnRuntime(cTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertTrue(cRuntime.getResult().getException() instanceof OutOfEnergyException); Transaction dTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( "testC", address, abi, dCode, value, fee, consumeUserResourcePercent, null, engeryLimit); - Runtime dRuntime = TvmTestUtils - .processTransactionAndReturnRuntime(dTrx, DepositImpl.createRoot(manager), null); + Runtime dRuntime = TvmTestUtils.processTransactionAndReturnRuntime(dTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); Assert.assertEquals(dRuntime.getRuntimeError(), "REVERT opcode executed"); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java b/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java index 8da6e4c96ea..172e3f17f1b 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/DataWordTest.java @@ -18,14 +18,22 @@ package org.tron.common.runtime.vm; +import static org.apache.commons.lang3.ArrayUtils.isNotEmpty; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; +import static org.tron.common.runtime.vm.DataWord.isZero; import java.math.BigInteger; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.ArrayUtils; import org.bouncycastle.util.encoders.Hex; +import org.eclipse.jetty.util.ArrayUtil; import org.junit.Test; +import org.tron.core.db.ByteArrayWrapper; @Slf4j public class DataWordTest { @@ -70,16 +78,16 @@ public void testAddPerformance() { DataWord x = new DataWord(one); x.add(x); } - System.out.println("Add1: " + (System.currentTimeMillis() - now1) + "ms"); + logger.info("Add1: " + (System.currentTimeMillis() - now1) + "ms"); long now2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { DataWord x = new DataWord(one); x.add2(x); } - System.out.println("Add2: " + (System.currentTimeMillis() - now2) + "ms"); + logger.info("Add2: " + (System.currentTimeMillis() - now2) + "ms"); } else { - System.out.println("ADD performance test is disabled."); + logger.info("ADD performance test is disabled."); } } @@ -90,11 +98,11 @@ public void testAdd2() { DataWord x = new DataWord(two); x.add(new DataWord(two)); - System.out.println(Hex.toHexString(x.getData())); + logger.info(Hex.toHexString(x.getData())); DataWord y = new DataWord(two); y.add2(new DataWord(two)); - System.out.println(Hex.toHexString(y.getData())); + logger.info(Hex.toHexString(y.getData())); } @Test @@ -107,12 +115,12 @@ public void testAdd3() { DataWord x = new DataWord(three); x.add(new DataWord(three)); assertEquals(32, x.getData().length); - System.out.println(Hex.toHexString(x.getData())); + logger.info(Hex.toHexString(x.getData())); // FAIL // DataWord y = new DataWord(three); // y.add2(new DataWord(three)); - // System.out.println(Hex.toHexString(y.getData())); + // logger.info(Hex.toHexString(y.getData())); } @Test @@ -128,8 +136,8 @@ public void testMod() { } two[31] = 0x56; // 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff56 - DataWord x = new DataWord(one);// System.out.println(x.value()); - DataWord y = new DataWord(two);// System.out.println(y.value()); + DataWord x = new DataWord(one);// logger.info(x.value()); + DataWord y = new DataWord(two);// logger.info(y.value()); y.mod(x); assertEquals(32, y.getData().length); assertEquals(expected, Hex.toHexString(y.getData())); @@ -143,8 +151,8 @@ public void testMul() { byte[] two = new byte[32]; two[11] = 0x1; // 0x0000000000000000000000010000000000000000000000000000000000000000 - DataWord x = new DataWord(one);// System.out.println(x.value()); - DataWord y = new DataWord(two);// System.out.println(y.value()); + DataWord x = new DataWord(one);// logger.info(x.value()); + DataWord y = new DataWord(two);// logger.info(y.value()); x.mul(y); assertEquals(32, y.getData().length); assertEquals("0000000000000000000000010000000000000000000000000000000000000000", @@ -160,8 +168,8 @@ public void testMulOverflow() { byte[] two = new byte[32]; two[0] = 0x1; // 0x1000000000000000000000000000000000000000000000000000000000000000 - DataWord x = new DataWord(one);// System.out.println(x.value()); - DataWord y = new DataWord(two);// System.out.println(y.value()); + DataWord x = new DataWord(one);// logger.info(x.value()); + DataWord y = new DataWord(two);// logger.info(y.value()); x.mul(y); assertEquals(32, y.getData().length); assertEquals("0100000000000000000000000000000000000000000000000000000000000000", @@ -226,8 +234,8 @@ public void testPow() { BigInteger result1 = x.modPow(x, y); BigInteger result2 = pow(x, y); - System.out.println(result1); - System.out.println(result2); + logger.info(result1.toString()); + logger.info(result2.toString()); } @Test @@ -238,7 +246,7 @@ public void testSignExtend1() { String expected = "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -249,7 +257,7 @@ public void testSignExtend2() { String expected = "00000000000000000000000000000000000000000000000000000000000000f2"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -261,7 +269,7 @@ public void testSignExtend3() { String expected = "00000000000000000000000000000000000000000000000000000000000000ab"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -273,7 +281,7 @@ public void testSignExtend4() { String expected = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -285,7 +293,7 @@ public void testSignExtend5() { String expected = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -297,7 +305,7 @@ public void testSignExtend6() { String expected = "0000000000000000000000000000000000000000000000000000000002345678"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -309,7 +317,7 @@ public void testSignExtend7() { String expected = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffff82345678"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -322,7 +330,7 @@ public void testSignExtend8() { String expected = "0034567882345678823456788234567882345678823456788234567882345678"; x.signExtend(k); - System.out.println(x.toString()); + logger.info(x.toString()); assertEquals(expected, x.toString()); } @@ -576,9 +584,39 @@ private void testShiftRightSigned(String[][] cases) { DataWord arg = new DataWord(c[1]); DataWord expected = new DataWord(c[2]); DataWord actual = value.shiftRightSigned(arg); - assertEquals(i + " " + Arrays.asList(c).toString(), expected, actual); + assertEquals(i + " " + Arrays.asList(c), expected, actual); } } + @Test + public void testIsZero() { + DataWord dataWord = new DataWord(new byte[0]); + DataWord d = new DataWord(new ByteArrayWrapper(new byte[0])); + assertTrue(d.isZero()); + d.negate(); + assertThrows(IllegalArgumentException.class, () -> new ByteArrayWrapper(null)); + assertTrue(dataWord.isZero()); + assertTrue(isZero(new byte[0])); + assertFalse(isZero(new byte[]{1})); + DataWord dataWord1 = new DataWord(new byte[]{0, 1}); + assertFalse(dataWord1.isZero()); + assertTrue(isNotEmpty(new DataWord((byte[]) null).getClonedData())); + assertTrue(isNotEmpty(dataWord1.getClonedData())); + logger.info(dataWord.toPrefixString()); + logger.info(dataWord1.toPrefixString()); + logger.info(new DataWord((new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8})).toPrefixString()); + logger.info(dataWord.shortHex()); + logger.info(DataWord.shortHex(new byte[0])); + logger.info(DataWord.bigIntValue(new byte[]{1})); + logger.info(dataWord.bigIntValue()); + logger.info("dataWord is Hex: {}", dataWord.isHex("test")); + logger.info(dataWord.asString()); + logger.info(Arrays.toString(dataWord.getNoEndZeroesData())); + DataWord tmp = dataWord; + assertEquals(dataWord, tmp); + assertNotEquals(dataWord, null); + assertEquals(-1, dataWord.compareTo(null)); + } + } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/DepositTest.java b/framework/src/test/java/org/tron/common/runtime/vm/DepositTest.java deleted file mode 100644 index e88e2788f9d..00000000000 --- a/framework/src/test/java/org/tron/common/runtime/vm/DepositTest.java +++ /dev/null @@ -1,426 +0,0 @@ -package org.tron.common.runtime.vm; - -import java.io.File; -import java.util.Arrays; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.runtime.Runtime; -import org.tron.common.runtime.TVMTestResult; -import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.Deposit; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; -import org.tron.common.utils.WalletUtil; -import org.tron.core.Constant; -import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.Parameter.ForkBlockVersionConsts; -import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.exception.ContractExeException; -import org.tron.core.exception.ContractValidateException; -import org.tron.core.exception.ReceiptCheckErrException; -import org.tron.core.exception.VMIllegalException; -import org.tron.protos.Protocol.AccountType; -import org.tron.protos.Protocol.Transaction; - -@Slf4j -public class DepositTest { - - private Manager manager; - private TronApplicationContext context; - private String dbPath = "output_DepostitTest"; - private String OWNER_ADDRESS; - private Deposit rootDeposit; - - @Before - public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - manager = context.getBean(Manager.class); - rootDeposit = DepositImpl.createRoot(manager); - rootDeposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - rootDeposit.addBalance(Hex.decode(OWNER_ADDRESS), 30000000000000L); - rootDeposit.commit(); - } - - /* pragma solidity ^0.4.0; - - contract A { - uint256 public n1; - uint256 public n2; - function callBcallA(address addr, uint256 _n1, uint256 _n2) public { - n1 = _n1; - string memory method = "callA(address,uint256)"; - bytes4 methodId = bytes4(keccak256(method)); - addr.call(methodId, address(this), _n2); - } - - function callBcallARevert(address addr, uint256 _n1, uint256 _n2) public { - n1 = _n1; - string memory method = "callARevert(address,uint256)"; - bytes4 methodId = bytes4(keccak256(method)); - addr.call(methodId, address(this), _n2); - } - - - function changeN(uint256 _n2) { - n2 = _n2; - } - - } - - contract B { - function callA(address addr, uint256 _n2) { - string memory method = "changeN(uint256)"; - bytes4 methodId = bytes4(keccak256(method)); - addr.call(methodId, _n2); - } - - function callARevert(address addr, uint256 _n2) { - string memory method = "changeN(uint256)"; - bytes4 methodId = bytes4(keccak256(method)); - addr.call(methodId, _n2); - revert(); - } - }*/ - - - @Test - @Ignore - public void loopCallTest() - throws ContractExeException, ReceiptCheckErrException, - VMIllegalException, ContractValidateException { - byte[] stats = new byte[27]; - Arrays.fill(stats, (byte) 1); - this.manager.getDynamicPropertiesStore() - .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); - this.manager.getDynamicPropertiesStore() - .saveLatestBlockHeaderNumber(CommonParameter.getInstance() - .getBlockNumForEnergyLimit() + 1); - - String contractA = "A"; - String contractB = "B"; - byte[] address = Hex.decode(OWNER_ADDRESS); - - String aABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"n1\",\"outputs\":[{\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":" - + "\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"n2\",\"outputs\":[{\"name\"" - + ":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":" - + "\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_n2\",\"type\":\"uint256\"}]," - + "\"name\":\"changeN\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"" - + ",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":" - + "\"address\"},{\"name\":\"_n1\",\"type\":\"uint256\"},{\"name\":\"_n2\",\"type\":" - + "\"uint256\"}],\"name\":\"callBcallARevert\",\"outputs\":[],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"},{\"name\":\"_n1\",\"type\":" - + "\"uint256\"},{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callBcallA\"," - + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":" - + "\"function\"}]"; - - String bABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}," - + "{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callA\",\"outputs\":[],\"payable\"" - + ":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"},{\"name\":\"_n2\",\"type\":" - + "\"uint256\"}],\"name\":\"callARevert\",\"outputs\":[],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; - - String aCode = "608060405234801561001057600080fd5b506102c8806100206000396000f300608060405260043" - + "61061006c5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350" - + "4166336fe1f2581146100715780634aaa831d146100985780636aac216d146100ad578063a71d1d68146100c" - + "7578063b9d3e3ce146100fb575b600080fd5b34801561007d57600080fd5b5061008661012f565b604080519" - + "18252519081900360200190f35b3480156100a457600080fd5b50610086610135565b3480156100b95760008" - + "0fd5b506100c560043561013b565b005b3480156100d357600080fd5b506100c573fffffffffffffffffffff" - + "fffffffffffffffffff60043516602435604435610140565b34801561010757600080fd5b506100c573fffff" - + "fffffffffffffffffffffffffffffffffff6004351660243560443561024e565b60005481565b60015481565" - + "b600155565b6000828155604080518082018252601c8082527f63616c6c41526576657274286164647265737" - + "32c75696e7432353629000000006020830190815292519193928492918291908083835b602083106101a9578" - + "0518252601f19909201916020918201910161018a565b5181516000196020949094036101000a93909301928" - + "3169219169190911790526040805193909101839003832063ffffffff7c01000000000000000000000000000" - + "00000000000000000000000000000808304918216028552306004860152602485018a9052915190965073fff" - + "fffffffffffffffffffffffffffffffffffff8b16955090935060448084019360009350829003018183875af" - + "1505050505050505050565b600082815560408051808201825260168082527f63616c6c41286164647265737" - + "32c75696e7432353629000000000000000000006020830190815292519193928492918291908083836101a95" - + "600a165627a7a72305820f6164f67f8344af6aa83a5f724f6c3cb7d09905c4bc94729d1d72e9f11d0df1900" - + "29"; - - String bCode = "608060405234801561001057600080fd5b5061029f806100206000396000f300608060405260043" - + "6106100325763ffffffff60e060020a600035041663417c7cc581146100375780637a9a0e721461006a575b6" - + "00080fd5b34801561004357600080fd5b5061006873ffffffffffffffffffffffffffffffffffffffff60043" - + "51660243561009b565b005b34801561007657600080fd5b5061006873fffffffffffffffffffffffffffffff" - + "fffffffff60043516602435610187565b60408051808201825260108082527f6368616e67654e2875696e743" - + "23536290000000000000000000000000000000060208301908152925191926000928492909182918083835b6" - + "02083106101015780518252601f1990920191602091820191016100e2565b6001836020036101000a0380198" - + "25116818451168082178552505050505050905001915050604051809103902090508373fffffffffffffffff" - + "fffffffffffffffffffffff168160e060020a9004846040518263ffffffff1660e060020a028152600401808" - + "281526020019150506000604051808303816000875af15050505050505050565b60408051808201825260108" - + "082527f6368616e67654e2875696e74323536290000000000000000000000000000000060208301908152925" - + "191926000928492909182918083835b602083106101ed5780518252601f1990920191602091820191016101c" - + "e565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809" - + "103902090508373ffffffffffffffffffffffffffffffffffffffff168160e060020a9004846040518263fff" - + "fffff1660e060020a028152600401808281526020019150506000604051808303816000875af192505050506" - + "00080fd00a165627a7a723058209cb73b547b599b5d2a96ade83e03d656f8025f4ac7642f8b9aab37cc2574f" - + "8310029"; - - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - long engeryLiimt = 100000000; - - Transaction aTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractA, address, aABI, aCode, value, fee, consumeUserResourcePercent, - null, engeryLiimt); - Runtime runtime = TvmTestUtils - .processTransactionAndReturnRuntime(aTrx, DepositImpl.createRoot(manager), - null); - Assert.assertNull(runtime.getRuntimeError()); - - Transaction bTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractB, address, bABI, bCode, value, fee, consumeUserResourcePercent, - null, engeryLiimt); - runtime = TvmTestUtils - .processTransactionAndReturnRuntime(bTrx, DepositImpl.createRoot(manager), null); - Assert.assertNull(runtime.getRuntimeError()); - - byte[] aAddress = WalletUtil.generateContractAddress(aTrx); - byte[] bAddress = WalletUtil.generateContractAddress(bTrx); - - // trigger contractA - // callBcallA(address,uint256,uint256) - // ,1,2 - // - String params1 = Hex.toHexString(new DataWord(bAddress).getData()) - + "000000000000000000000000000000000000000000000000000000000000000100000000000000000000000" - + "00000000000000000000000000000000000000002"; - System.err.println(params1); - - byte[] triggerData = TvmTestUtils - .parseAbi("callBcallARevert(address,uint256,uint256)", params1); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // check result - // expected: n1 = 1; n2 = 0 - byte[] checkN1Data = TvmTestUtils.parseAbi("n1()", null); - byte[] checkN2Data = TvmTestUtils.parseAbi("n2()", null); - - TVMTestResult checkN1 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); - TVMTestResult checkN2 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); - - System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); - System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); - - Assert.assertEquals(checkN1.getRuntime().getResult().getHReturn(), - new DataWord(1).getData()); - Assert.assertEquals(checkN2.getRuntime().getResult().getHReturn(), - new DataWord(0).getData()); - - // trigger contractA - // callBcallA(address,uint256,uint256) - // ,100,1000 - String params2 = Hex.toHexString(new DataWord(bAddress).getData()) - + "000000000000000000000000000000000000000000000000000000000000006400000000000000000000000" - + "000000000000000000000000000000000000003e8"; - triggerData = TvmTestUtils.parseAbi("callBcallA(address,uint256,uint256)", params2); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - checkN1 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); - checkN2 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); - System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); - System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); - Assert.assertEquals(checkN1.getRuntime().getResult().getHReturn(), - new DataWord(100).getData()); - Assert - .assertEquals(checkN2.getRuntime().getResult().getHReturn(), - new DataWord(1000).getData()); - CommonParameter.setENERGY_LIMIT_HARD_FORK(false); - } - - @Test - public void loopCallTestOldVersion() - throws ContractExeException, ReceiptCheckErrException, - VMIllegalException, ContractValidateException { - byte[] stats = new byte[27]; - Arrays.fill(stats, (byte) 0); - this.manager.getDynamicPropertiesStore() - .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); - - String contractA = "A"; - String contractB = "B"; - byte[] address = Hex.decode(OWNER_ADDRESS); - - String aABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"n1\",\"outputs\":[{\"name\":\"\"," - + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":" - + "\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"n2\",\"outputs\":[{\"name\"" - + ":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\"" - + ":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_n2\",\"type\":\"uint256\"}]" - + ",\"name\":\"changeN\",\"outputs\":[],\"payable\":false,\"stateMutability\":" - + "\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":" - + "\"addr\",\"type\":\"address\"},{\"name\":\"_n1\",\"type\":\"uint256\"},{\"name\":" - + "\"_n2\",\"type\":\"uint256\"}],\"name\":\"callBcallARevert\",\"outputs\":[],\"payable\":" - + "false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," - + "\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"},{\"name\":\"_n1\",\"type\"" - + ":\"uint256\"},{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callBcallA\"," - + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":" - + "\"function\"}]"; - String bABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}," - + "{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callA\",\"outputs\":[]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," - + "{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}," - + "{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callARevert\",\"outputs\":[]," - + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; - - String aCode = "608060405234801561001057600080fd5b506102c8806100206000396000f300608060405260043" - + "61061006c5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350" - + "4166336fe1f2581146100715780634aaa831d146100985780636aac216d146100ad578063a71d1d68146100c" - + "7578063b9d3e3ce146100fb575b600080fd5b34801561007d57600080fd5b5061008661012f565b604080519" - + "18252519081900360200190f35b3480156100a457600080fd5b50610086610135565b3480156100b95760008" - + "0fd5b506100c560043561013b565b005b3480156100d357600080fd5b506100c573fffffffffffffffffffff" - + "fffffffffffffffffff60043516602435604435610140565b34801561010757600080fd5b506100c573fffff" - + "fffffffffffffffffffffffffffffffffff6004351660243560443561024e565b60005481565b60015481565" - + "b600155565b6000828155604080518082018252601c8082527f63616c6c41526576657274286164647265737" - + "32c75696e7432353629000000006020830190815292519193928492918291908083835b602083106101a9578" - + "0518252601f19909201916020918201910161018a565b5181516000196020949094036101000a93909301928" - + "3169219169190911790526040805193909101839003832063ffffffff7c01000000000000000000000000000" - + "00000000000000000000000000000808304918216028552306004860152602485018a9052915190965073fff" - + "fffffffffffffffffffffffffffffffffffff8b16955090935060448084019360009350829003018183875af" - + "1505050505050505050565b600082815560408051808201825260168082527f63616c6c41286164647265737" - + "32c75696e7432353629000000000000000000006020830190815292519193928492918291908083836101a95" - + "600a165627a7a72305820f6164f67f8344af6aa83a5f724f6c3cb7d09905c4bc94729d1d72e9f11d0df1900" - + "29"; - - String bCode = "608060405234801561001057600080fd5b5061029f806100206000396000f300608060405260043" - + "6106100325763ffffffff60e060020a600035041663417c7cc581146100375780637a9a0e721461006a575b6" - + "00080fd5b34801561004357600080fd5b5061006873ffffffffffffffffffffffffffffffffffffffff60043" - + "51660243561009b565b005b34801561007657600080fd5b5061006873fffffffffffffffffffffffffffffff" - + "fffffffff60043516602435610187565b60408051808201825260108082527f6368616e67654e2875696e743" - + "23536290000000000000000000000000000000060208301908152925191926000928492909182918083835b6" - + "02083106101015780518252601f1990920191602091820191016100e2565b6001836020036101000a0380198" - + "25116818451168082178552505050505050905001915050604051809103902090508373fffffffffffffffff" - + "fffffffffffffffffffffff168160e060020a9004846040518263ffffffff1660e060020a028152600401808" - + "281526020019150506000604051808303816000875af15050505050505050565b60408051808201825260108" - + "082527f6368616e67654e2875696e74323536290000000000000000000000000000000060208301908152925" - + "191926000928492909182918083835b602083106101ed5780518252601f1990920191602091820191016101c" - + "e565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809" - + "103902090508373ffffffffffffffffffffffffffffffffffffffff168160e060020a9004846040518263fff" - + "fffff1660e060020a028152600401808281526020019150506000604051808303816000875af192505050506" - + "00080fd00a165627a7a723058209cb73b547b599b5d2a96ade83e03d656f8025f4ac7642f8b9aab37cc2574f" - + "8310029"; - - long value = 0; - long fee = 100000000; - long consumeUserResourcePercent = 0; - - Transaction aTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractA, address, aABI, aCode, value, fee, consumeUserResourcePercent, - null); - Deposit rootDeposit = DepositImpl.createRoot(manager); - Runtime runtime = TvmTestUtils.processTransactionAndReturnRuntime(aTrx, rootDeposit, - null); - Assert.assertNull(runtime.getRuntimeError()); - - Transaction bTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( - contractB, address, bABI, bCode, value, fee, consumeUserResourcePercent, - null); - rootDeposit = DepositImpl.createRoot(manager); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(bTrx, rootDeposit, null); - Assert.assertNull(runtime.getRuntimeError()); - - byte[] aAddress = WalletUtil.generateContractAddress(aTrx); - byte[] bAddress = WalletUtil.generateContractAddress(bTrx); - - // trigger contractA - // callBcallA(address,uint256,uint256) - // ,1,2 - // - String params1 = Hex.toHexString(new DataWord(bAddress).getData()) - + "000000000000000000000000000000000000000000000000000000000000000100000000000000000000000" - + "00000000000000000000000000000000000000002"; - - byte[] triggerData = TvmTestUtils - .parseAbi("callBcallARevert(address,uint256,uint256)", params1); - TVMTestResult result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - - // check result - // expected: n1 = 1; n2 = 0 - byte[] checkN1Data = TvmTestUtils.parseAbi("n1()", null); - byte[] checkN2Data = TvmTestUtils.parseAbi("n2()", null); - - TVMTestResult checkN1 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); - TVMTestResult checkN2 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); - - System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); - System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); - - Assert.assertEquals(checkN1.getRuntime().getResult().getHReturn(), - new DataWord(1).getData()); - Assert.assertEquals(checkN2.getRuntime().getResult().getHReturn(), - new DataWord(2).getData()); - - // trigger contractA - // callBcallA(address,uint256,uint256) - // ,100,1000 - String params2 = Hex.toHexString(new DataWord(bAddress).getData()) - + "000000000000000000000000000000000000000000000000000000000000006400000000000000000000000" - + "000000000000000000000000000000000000003e8"; - triggerData = TvmTestUtils.parseAbi("callBcallA(address,uint256,uint256)", params2); - result = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, triggerData, 0, fee, manager, null); - Assert.assertNull(result.getRuntime().getRuntimeError()); - checkN1 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN1Data, 0, fee, manager, null); - checkN2 = TvmTestUtils - .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), - aAddress, checkN2Data, 0, fee, manager, null); - System.out.println(Hex.toHexString(checkN1.getRuntime().getResult().getHReturn())); - System.out.println(Hex.toHexString(checkN2.getRuntime().getResult().getHReturn())); - Assert.assertEquals(checkN1.getRuntime().getResult().getHReturn(), - new DataWord(100).getData()); - Assert - .assertEquals(checkN2.getRuntime().getResult().getHReturn(), - new DataWord(1000).getData()); - CommonParameter.setENERGY_LIMIT_HARD_FORK(false); - } - - - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } - } - -} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java index a2fbb5f0816..8b985d4bb1d 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenAssertStyleTest.java @@ -1,46 +1,40 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.program.Program.IllegalOperationException; import org.tron.core.vm.program.Program.OutOfMemoryException; import org.tron.core.vm.program.Program.PrecompiledContractException; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j -public class EnergyWhenAssertStyleTest { +public class EnergyWhenAssertStyleTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_EnergyWhenAssertStyleTest"; - private String OWNER_ADDRESS; - private Application AppT; + private RepositoryImpl repository; + private static String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } /** @@ -48,15 +42,10 @@ public class EnergyWhenAssertStyleTest { */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); - deposit.commit(); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); + repository.commit(); } // An assert-style exception is generated in the following situations: @@ -103,11 +92,10 @@ public void outOfIndexTest() + "25261016082019092526060916020820161014080388339019050509050600a81600a815181101515608c57" + "fe5b60209081029091010152505600a165627a7a723058201aaf6626083e32afa834a13d3365784c509d10f" + "57ce1024f88c697cf0718795e0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 39487; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -122,7 +110,7 @@ public void outOfIndexTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -158,11 +146,10 @@ public void bytesNTest() + "1e76e10781146043575b600080fd5b348015604e57600080fd5b5060556057565b005b72012345000000000" + "00000000000000000000000601460008282fe00a165627a7a72305820a1c7c81d642cc0aa11c43d63614a5b" + "3c018e4af84700af4bfde5f2efb18b55130029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 31875; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -177,7 +164,7 @@ public void bytesNTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -211,11 +198,10 @@ public void divZeroTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "b87d948d81146043575b600080fd5b348015604e57600080fd5b5060556057565b005b60008080600afe00a" + "165627a7a7230582084ed35f2e244d6721bb5f5fcaf53d237ea050b3de84d5cc7fee74584fd2ff31f0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 27875; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -230,7 +216,7 @@ public void divZeroTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -266,11 +252,10 @@ public void shiftByNegativeTest() + "e88e362a81146043575b600080fd5b348015604e57600080fd5b5060556057565b005b60091960008161040" + "0fe00a165627a7a7230582086c99cfe65e26909bb0fb3a2bdaf2385ad8dfff72680adab954063a4fe1d549b" + "0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 28475; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -285,7 +270,7 @@ public void shiftByNegativeTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -321,11 +306,10 @@ public void enumTypeTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "5a43cddc81146043575b600080fd5b348015604e57600080fd5b5060556057565b005b6000600afe00a1656" + "27a7a72305820b24a4d459b753723d300f56c408c6120d5ef0c7ddb166d66ccf4277a76ad83ed0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 27475; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -340,7 +324,7 @@ public void enumTypeTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -375,11 +359,10 @@ public void functionPointerTest() + "e9ad8ee781146043575b600080fd5b348015604e57600080fd5b5060556057565b005b606a606660018263f" + "fffffff16565b5050565bfe00a165627a7a723058201c8982fa288ec7aad86b1d1992ecc5d08c4b22e4fe03" + "7981f91aff8bcbd900680029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 30475; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -394,7 +377,7 @@ public void functionPointerTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -428,11 +411,10 @@ public void assertTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "2b813bc081146043575b600080fd5b348015604e57600080fd5b5060556057565b005bfe00a165627a7a723" + "058208ce7511bd3a946a22baaba2b4521cbf29d2481ad52887c5567e422cd89726eda0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 26675; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -447,7 +429,7 @@ public void assertTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof IllegalOperationException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -496,11 +478,10 @@ public void systemPrecompileTest() + "fffffff868116825260208201869052825193169381830193909290918290030181855af491505015156101" + "2957600080fd5b50505600a165627a7a723058206090aa7a8ac0e45fac642652417495e81dad6f1592343bf" + "f8cfe97f61cf74e880029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 89214; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -519,7 +500,7 @@ public void systemPrecompileTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert.assertTrue( result.getRuntime().getResult().getException() instanceof PrecompiledContractException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -556,11 +537,10 @@ public void outOfMemTest() + "b82821015609957604080516230040080825263060080208201909252906020820163060080008038833901" + "9050506001909201919050605f565b5050505600a165627a7a723058209e5d294a7bf5133b304bc6851c749" + "cd5e1f4748230405755e6bd2e31549ae1d00029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 40487; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -575,32 +555,12 @@ public void outOfMemTest() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof OutOfMemoryException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - @Test - @Ignore - public void overflowTest() - throws ContractExeException, ReceiptCheckErrException, ContractValidateException { - // done in ChargeTest - } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java index ef9fc05f159..19231b225f1 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenRequireStyleTest.java @@ -1,43 +1,36 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.program.Program.OutOfEnergyException; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j +public class EnergyWhenRequireStyleTest extends BaseTest { -public class EnergyWhenRequireStyleTest { - - private Manager dbManager; - private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_EnergyWhenRequireStyleTest"; - private String OWNER_ADDRESS; - private Application AppT; + private RepositoryImpl repository; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } /** @@ -45,15 +38,10 @@ public class EnergyWhenRequireStyleTest { */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); - deposit.commit(); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); + repository.commit(); } // A require-style exception is generated in the following situations: @@ -99,11 +87,10 @@ public void throwTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "50bff6bf81146043575b600080fd5b348015604e57600080fd5b506055603e565b0000a165627a7a7230582" + "0f51282c5910e3ff1b5f2e9509f3cf23c7035027aae1947ab46e5a9252fb061eb0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 26275; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -119,8 +106,8 @@ public void throwTest() long expectEnergyUsageTotal2 = 124; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -152,11 +139,10 @@ public void requireTest() + "03e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663" + "357815c481146043575b600080fd5b348015604e57600080fd5b506055603e565b0000a165627a7a7230582" + "054141931bcc37d4f266815f02d2fb113f5af20825cbce45d3b0f2fe90ac0145d0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 26275; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -172,8 +158,8 @@ public void requireTest() long expectEnergyUsageTotal2 = 124; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -216,11 +202,10 @@ public void thisFunctionViaMessageCallTest() + "000000000000000028152600401600060405180830381600088803b15801560db57600080fd5b5087f11580" + "1560ee573d6000803e3d6000fd5b50505050505600a165627a7a7230582087d830c44fb566498789b212e3d" + "0374f7a7589a2efdda11b3a4c03051b57891a0029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 57905; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -236,8 +221,8 @@ public void thisFunctionViaMessageCallTest() long expectEnergyUsageTotal2 = 5339; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -293,11 +278,10 @@ public void thatFunctionViaMessageCallTest() + "0006000350416632b813bc081146043575b600080fd5b348015604e57600080fd5b5060556057565b005bfe" + "00a165627a7a72305820c02c76575c2a0ada80c3f6db47f885cece6c254d1e7c79eb6ddc1c1d4e70ebae002" + "9a165627a7a72305820cf879e62f738b44636adf61bd4b2fb38c10f027d2a4484d58baf44a06dc97bd90029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 97341; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -313,8 +297,8 @@ public void thatFunctionViaMessageCallTest() long expectEnergyUsageTotal2 = 64125; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); @@ -355,11 +339,10 @@ public void newContractTest1() + "10066610087565b604051809103906000f080158015610082573d6000803e3d6000fd5b505050565b604051" + "6013806100978339019056006080604052348015600f57600080fd5b50fe00a165627a7a72305820685ff8f" + "74890f671deb4d3881a4b72ab0daac2ab0d36112e1ebdf98a43ac4d940029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 42687; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -376,7 +359,7 @@ public void newContractTest1() long expectEnergyUsageTotal2 = feeLimit / 100; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); // todo: revert should be true!! see later - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); Assert .assertTrue(result.getRuntime().getResult().getException() instanceof OutOfEnergyException); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), @@ -432,22 +415,21 @@ public void receiveTrxWithoutPayableTest() + "4052348015600f57600080fd5b500000a165627a7a72305820a82006ee5ac783bcea7085501eaed33360b31" + "20278f1f39e611afedc9f4a693b0029a165627a7a72305820a50d9536f182fb6aefc737fdc3a675630e75a0" + "8de88deb6b1bee6d4b6dff04730029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 42; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - expectEnergyUsageTotal * 100); result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, 0, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); byte[] contractAddress = result.getContractAddress(); long expectEnergyUsageTotal2 = 100341; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); @@ -461,21 +443,13 @@ public void receiveTrxWithoutPayableTest() long expectEnergyUsageTotal3 = 51833; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal3); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2 + expectEnergyUsageTotal3) * 100); } - @Test - @Ignore - public void transferTest() - throws ContractExeException, ReceiptCheckErrException, ContractValidateException { - // done in EnergyWhenSendAndTransferTest - - } - // pragma solidity ^0.4.16; // // contract TestRevertContract { @@ -511,11 +485,10 @@ public void revertTest() + "6312065fe08114604d578063a26388bb146071575b600080fd5b348015605857600080fd5b50605f6085565" + "b60408051918252519081900360200190f35b348015607c57600080fd5b5060836048565b005b3031905600" + "a165627a7a7230582059cab3a7a5851a7852c728ec8729456a04dc022674976f3f26bfd51491dbf1080029"; - String libraryAddressPair = null; TVMTestResult result = TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); long expectEnergyUsageTotal = 36481; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); @@ -531,31 +504,11 @@ public void revertTest() long expectEnergyUsageTotal2 = 146; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - @Test - @Ignore - public void reach64CallDepth() { - // done in ChargeTest - } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java index a012617fb12..009b332324b 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenSendAndTransferTest.java @@ -1,55 +1,45 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j -public class EnergyWhenSendAndTransferTest { +public class EnergyWhenSendAndTransferTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_EnergyWhenSendAndTransferTest"; - private String OWNER_ADDRESS; - private Application AppT; + private RepositoryImpl repository; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); - deposit.commit(); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); + repository.commit(); } // solidity for callValueTest @@ -100,7 +90,7 @@ public void callValueTest() long expectEnergyUsageTotal = 174639; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); byte[] contractAddress = result.getContractAddress(); - Assert.assertEquals(deposit.getAccount(contractAddress).getBalance(), value); + Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - expectEnergyUsageTotal * 100); @@ -123,7 +113,7 @@ public void callValueTest() long expectEnergyUsageTotal3 = 9459; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal3); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - (expectEnergyUsageTotal + expectEnergyUsageTotal2 + expectEnergyUsageTotal3) * 100); } @@ -167,7 +157,7 @@ public void sendTest() VMIllegalException { long value = 1000L; - long feeLimit = 1000_000_000L; // sun + long feeLimit = 100_000_000L; // sun long consumeUserResourcePercent = 100; byte[] address = Hex.decode(OWNER_ADDRESS); TVMTestResult result = deploySendAndTransferTestContract(value, feeLimit, @@ -176,7 +166,7 @@ public void sendTest() long expectEnergyUsageTotal = 140194; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); byte[] contractAddress = result.getContractAddress(); - Assert.assertEquals(deposit.getAccount(contractAddress).getBalance(), value); + Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - expectEnergyUsageTotal * 100); @@ -188,9 +178,9 @@ public void sendTest() long expectEnergyUsageTotal2 = 7025; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), false); - Assert.assertEquals(deposit.getAccount(contractAddress).getBalance(), value); + Assert.assertNull(result.getRuntime().getResult().getException()); + Assert.assertFalse(result.getRuntime().getResult().isRevert()); + Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } @@ -211,7 +201,7 @@ public void transferTest() long expectEnergyUsageTotal = 140194; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal); byte[] contractAddress = result.getContractAddress(); - Assert.assertEquals(deposit.getAccount(contractAddress).getBalance(), value); + Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - expectEnergyUsageTotal * 100); @@ -223,9 +213,9 @@ public void transferTest() long expectEnergyUsageTotal2 = 7030; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().getException(), null); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertEquals(deposit.getAccount(contractAddress).getBalance(), value); + Assert.assertNull(result.getRuntime().getResult().getException()); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertEquals(repository.getAccount(contractAddress).getBalance(), value); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - value - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } @@ -259,11 +249,10 @@ public TVMTestResult deployCallValueTestContract(long value, long feeLimit, + "b602a90565b6000805b600a81101560945760008181526020819052604090208190556001016074565b5090" + "5600a165627a7a723058205ded543feb546472be4e116e713a2d46b8dafc823ca31256e67a1be92a6752730" + "029"; - String libraryAddressPair = null; return TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); } public TVMTestResult deploySendAndTransferTestContract(long value, long feeLimit, @@ -293,25 +282,9 @@ public TVMTestResult deploySendAndTransferTestContract(long value, long feeLimit + "2600160008181526020527fada5013122d395ba3c54772283fb069b10426056ef8ca54750cb9bb552a59e7d" + "550000a165627a7a7230582029b27c10c1568d590fa66bc0b7d42537a314c78d028f59a188fa411f7fc15c4" + "f0029"; - String libraryAddressPair = null; return TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, feeLimit, - consumeUserResourcePercent, libraryAddressPair, dbManager, null); + consumeUserResourcePercent, null, dbManager, null); } - - /** - * Release resources. - */ - @After - public void destroy() { - context.destroy(); - Args.clearParam(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.warn("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java index f4305769751..2559b43a020 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/EnergyWhenTimeoutStyleTest.java @@ -1,59 +1,48 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.program.Program.OutOfEnergyException; import org.tron.core.vm.program.Program.OutOfTimeException; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j -public class EnergyWhenTimeoutStyleTest { - - private Manager dbManager; - private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_CPUTimeTest"; - private String OWNER_ADDRESS; - private Application AppT; +public class EnergyWhenTimeoutStyleTest extends BaseTest { + + private RepositoryImpl repository; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, + Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, - Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); - deposit.commit(); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); + repository.commit(); } // solidity for endlessLoopTest @@ -108,7 +97,6 @@ public void endlessLoopTest() /* =================================== CALL setVote(uint256) =============================== */ String params = "0000000000000000000000000000000000000000000000000000000000000003"; byte[] triggerData = TvmTestUtils.parseAbi("setVote(uint256)", params); - boolean haveException = false; result = TvmTestUtils .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), contractAddress, triggerData, value, feeLimit, dbManager, null); @@ -143,27 +131,11 @@ public TVMTestResult deployEndlessLoopContract(long value, long feeLimit, + "60011560cb576001600080828254019250508190555060b1565b505600a165627a7a72305820290a38c9bbaf" + "ccaf6c7f752ab56d229e354da767efb72715ee9fdb653b9f4b6c0029"; - String libraryAddressPair = null; return TvmTestUtils .deployContractAndReturnTvmTestResult(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, + feeLimit, consumeUserResourcePercent, null, dbManager, null); } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java index f3a3c13f8bd..d2ad875e4b0 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ExtCodeHashTest.java @@ -4,17 +4,17 @@ import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class ExtCodeHashTest extends VMTestBase { @@ -50,7 +50,7 @@ public void testExtCodeHash() contractName, address, ABI, factoryCode, value, fee, consumeUserResourcePercent, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: getCodeHashByAddr(address) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java b/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java index 3b3168132f2..e1459637e19 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/FreezeTest.java @@ -4,9 +4,9 @@ import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT; import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.function.Consumer; import lombok.extern.slf4j.Slf4j; @@ -14,19 +14,19 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.TronApplicationContext; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.Deposit; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.Commons; import org.tron.common.utils.FastByteComparisons; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; @@ -43,9 +43,10 @@ import org.tron.core.vm.EnergyCost; import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction.Result.contractResult; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class FreezeTest { @@ -120,24 +121,25 @@ public class FreezeTest { private static final String userCStr = "27juXSbMvL6pb8VgmKRgW6ByCfw5RqZjUuo"; private static final byte[] userC = Commons.decode58Check(userCStr); - private static String dbPath; + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static TronApplicationContext context; private static Manager manager; private static byte[] owner; - private static Deposit rootDeposit; + private static Repository rootRepository; @Before public void init() throws Exception { - dbPath = "output_" + FreezeTest.class.getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); manager = context.getBean(Manager.class); owner = Hex.decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"); - rootDeposit = DepositImpl.createRoot(manager); - rootDeposit.createAccount(owner, Protocol.AccountType.Normal); - rootDeposit.addBalance(owner, 900_000_000_000_000_000L); - rootDeposit.commit(); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(owner, Protocol.AccountType.Normal); + rootRepository.addBalance(owner, 900_000_000_000_000_000L); + rootRepository.commit(); ConfigLoader.disable = true; manager.getDynamicPropertiesStore().saveAllowTvmFreeze(1); @@ -147,6 +149,7 @@ public void init() throws Exception { VMConfig.initAllowTvmSolidity059(1); VMConfig.initAllowTvmIstanbul(1); VMConfig.initAllowTvmFreeze(1); + VMConfig.initAllowTvmFreezeV2(0); } private byte[] deployContract(String contractName, String code) throws Exception { @@ -526,7 +529,7 @@ public void testCreate2SuicideToAccount() throws Exception { long frozenBalance = 1_000_000; freezeForSelf(contract, frozenBalance, 0); freezeForSelf(contract, frozenBalance, 1); - long salt = 1; + long salt = 2; byte[] predictedAddr = getCreate2Addr(factory, salt); freezeForOther(contract, predictedAddr, frozenBalance, 0); freezeForOther(contract, predictedAddr, frozenBalance, 1); @@ -798,7 +801,9 @@ private TVMTestResult freezeForOther(byte[] callerAddr, if (oldReceiver != null) { newReceiver.setBalance(oldReceiver.getBalance()); oldReceiver.setEnergyUsage(0); + oldReceiver.setNewWindowSize(ENERGY, 28800); newReceiver.setEnergyUsage(0); + newReceiver.setNewWindowSize(ENERGY,28800); if (res == 0) { oldReceiver.setAcquiredDelegatedFrozenBalanceForBandwidth(0); newReceiver.setAcquiredDelegatedFrozenBalanceForBandwidth(0); @@ -912,7 +917,9 @@ private TVMTestResult unfreezeForOther(byte[] callerAddr, || acquiredBalance - newAcquiredBalance == delegatedFrozenBalance); newReceiver.setBalance(oldReceiver.getBalance()); newReceiver.setEnergyUsage(0); + newReceiver.setNewWindowSize(ENERGY,28800); oldReceiver.setEnergyUsage(0); + oldReceiver.setNewWindowSize(ENERGY,28800); if (res == 0) { oldReceiver.setAcquiredDelegatedFrozenBalanceForBandwidth(0); newReceiver.setAcquiredDelegatedFrozenBalanceForBandwidth(0); @@ -1036,10 +1043,5 @@ public void destroy() { VMConfig.initVmHardFork(false); Args.clearParam(); context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java b/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java new file mode 100644 index 00000000000..907398f163b --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/FreezeV2Test.java @@ -0,0 +1,1053 @@ +package org.tron.common.runtime.vm; + +import static org.tron.common.math.Maths.min; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.core.config.Parameter.ChainConstant.WINDOW_SIZE_MS; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Consumer; +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.Runtime; +import org.tron.common.runtime.RuntimeImpl; +import org.tron.common.runtime.TVMTestResult; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.Commons; +import org.tron.common.utils.FastByteComparisons; +import org.tron.common.utils.StringUtil; +import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.actuator.UnfreezeBalanceV2Actuator; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.capsule.VotesCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.BandwidthProcessor; +import org.tron.core.db.EnergyProcessor; +import org.tron.core.db.Manager; +import org.tron.core.db.TransactionTrace; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DelegatedResourceStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Transaction.Result.contractResult; +import org.tron.protos.contract.Common; + +@Slf4j +public class FreezeV2Test { + + private static final String FREEZE_V2_CODE = "60" + + "80604052610e85806100136000396000f3fe60806040526004361061010d5760003560e01c80635897454711" + + "610095578063b335634e11610064578063b335634e14610457578063c1a98a3714610491578063df860ab314" + + "6104cb578063f0130dc914610525578063f70eb4c51461055f57600080fd5b8063589745471461035d578063" + + "85510c71146103975780639eb506e2146103ee578063a465bb191461042857600080fd5b8063236051ed1161" + + "00dc578063236051ed146102235780632fe36be51461026b57806333e7645d146102a5578063350a02341461" + + "02f45780633dcba6fc1461032e57600080fd5b8063089480871461011957806308bee6c4146101555780630a" + + "2dd8521461018f578063212743c9146101e957600080fd5b3661011457005b600080fd5b3480156101255760" + + "0080fd5b50d3801561013257600080fd5b50d2801561013f57600080fd5b5061015361014e366004610c9156" + + "5b610599565b005b34801561016157600080fd5b50d3801561016e57600080fd5b50d2801561017b57600080" + + "fd5b5061015361018a366004610cd4565b61060a565b34801561019b57600080fd5b50d380156101a8576000" + + "80fd5b50d280156101b557600080fd5b506101c96101c4366004610cf6565b61065d565b6040805193845260" + + "20840192909252908201526060015b60405180910390f35b3480156101f557600080fd5b50d3801561020257" + + "600080fd5b50d2801561020f57600080fd5b5061015361021e366004610d2b565b6106d5565b34801561022f" + + "57600080fd5b50d3801561023c57600080fd5b50d2801561024957600080fd5b5061025d610258366004610c" + + "f6565b6106e1565b6040519081526020016101e0565b34801561027757600080fd5b50d38015610284576000" + + "80fd5b50d2801561029157600080fd5b506101536102a0366004610cd4565b61074a565b3480156102b15760" + + "0080fd5b50d380156102be57600080fd5b50d280156102cb57600080fd5b506102df6102da366004610cf656" + + "5b610795565b604080519283526020830191909152016101e0565b34801561030057600080fd5b50d3801561" + + "030d57600080fd5b50d2801561031a57600080fd5b50610153610329366004610c91565b610802565b348015" + + "61033a57600080fd5b50d3801561034757600080fd5b50d2801561035457600080fd5b5061015361086a565b" + + "34801561036957600080fd5b50d3801561037657600080fd5b50d2801561038357600080fd5b5061025d6103" + + "92366004610cf6565b610897565b3480156103a357600080fd5b50d380156103b057600080fd5b50d2801561" + + "03bd57600080fd5b506103c66108bd565b604080519586526020860194909452928401919091526060830152" + + "608082015260a0016101e0565b3480156103fa57600080fd5b50d3801561040757600080fd5b50d280156104" + + "1457600080fd5b5061025d610423366004610cf6565b610a69565b34801561043457600080fd5b50d3801561" + + "044157600080fd5b50d2801561044e57600080fd5b5061025d610a8f565b34801561046357600080fd5b50d3" + + "801561047057600080fd5b50d2801561047d57600080fd5b5061025d61048c366004610d58565b610ad0565b" + + "34801561049d57600080fd5b50d380156104aa57600080fd5b50d280156104b757600080fd5b5061025d6104" + + "c6366004610cf6565b610b42565b3480156104d757600080fd5b50d380156104e457600080fd5b50d2801561" + + "04f157600080fd5b50610505610500366004610da6565b610b68565b60408051948552602085019390935291" + + "83015260608201526080016101e0565b34801561053157600080fd5b50d3801561053e57600080fd5b50d280" + + "1561054b57600080fd5b5061025d61055a366004610cf6565b610bf2565b34801561056b57600080fd5b50d3" + + "801561057857600080fd5b50d2801561058557600080fd5b5061025d610594366004610d2b565b610c18565b" + + "806001600160a01b03168383de1580156105b7573d6000803e3d6000fd5b5060408051848152602081018490" + + "526001600160a01b038316918101919091527fe0dda9e5664a3dcfa0628dc0392b74a4b2c63ba4887270f855" + + "7c1ed7deef3c82906060015b60405180910390a1505050565b8181da15801561061e573d6000803e3d6000fd" + + "5b5060408051838152602081018390527fc20c50cd22b066cd9d0cbbe9adbdee2f66da283d9971f5ff840fb0" + + "1af79d980891015b60405180910390a15050565b604080516001600160a01b03841681526020810183905260" + + "00918291829182918291630100001291016040805180830381855afa1580156106a2573d6000803e3d6000fd" + + "5b5050506040513d601f19601f820116820180604052508101906106c59190610de4565b9098909750439650" + + "945050505050565b806001600160a01b0316ff5b604080516001600160a01b03841681526020810183905260" + + "0091630100001491015b602060405180830381855afa158015610720573d6000803e3d6000fd5b5050506040" + + "513d601f19601f820116820180604052508101906107439190610e08565b9392505050565b8181db15801561" + + "075e573d6000803e3d6000fd5b5060408051838152602081018390527fa2339ebec95cc02eea0ca9e15e5b1b" + + "4dd568105de8c4e47d2c6b96b1969348e89101610651565b604080516001600160a01b038416815260208101" + + "8390526000918291630100000f9101602060405180830381855afa1580156107d5573d6000803e3d6000fd5b" + + "5050506040513d601f19601f820116820180604052508101906107f89190610e08565b944394509250505056" + + "5b806001600160a01b03168383df158015610820573d6000803e3d6000fd5b50604080518481526020810184" + + "90526001600160a01b038316918101919091527fd087798e9716d31cc0ef7780cb451270a6e4b447359da1b9" + + "f169996c3a942801906060016105fd565bdc506040517f2ba20738f2500f7585581bf668aa65ab6de7d1c182" + + "2de5737455214184f37ed590600090a1565b604080516001600160a01b038416815260208101839052600091" + + "630100000e9101610703565b600080600080600080600160405181601f820153602081602083630100000b5a" + + "fa6108ee576040513d6000823e3d81fd5b602081016040528051925067ffffffffffffffff8316831461090f" + + "57600080fd5b50506000600260405181601f820153602081602083630100000b5afa61093b576040513d6000" + + "823e3d81fd5b602081016040528051925067ffffffffffffffff8316831461095c57600080fd5b5050600060" + + "0360405181601f820153602081602083630100000b5afa610988576040513d6000823e3d81fd5b6020810160" + + "40528051925067ffffffffffffffff831683146109a957600080fd5b50506000600460405181601f82015360" + + "2081602083630100000b5afa6109d5576040513d6000823e3d81fd5b602081016040528051925067ffffffff" + + "ffffffff831683146109f657600080fd5b50506000600560405181601f820153602081602083630100000b5a" + + "fa610a22576040513d6000823e3d81fd5b602081016040528051925067ffffffffffffffff83168314610a43" + + "57600080fd5b505067ffffffffffffffff9485169a938516995091841697508316955090911692509050565b" + + "604080516001600160a01b03841681526020810183905260009163010000139101610703565b6000dd90507f" + + "6a5f656ed489ef1dec34a7317ceb95e7363440f72efdb653107e66982370f06181604051610ac59181526020" + + "0190565b60405180910390a190565b604080516001600160a01b038086168252841660208201529081018290" + + "52600090630100001090606001602060405180830381855afa158015610b17573d6000803e3d6000fd5b5050" + + "506040513d601f19601f82011682018060405250810190610b3a9190610e08565b949350505050565b604080" + + "516001600160a01b03841681526020810183905260009163010000159101610703565b604080516001600160" + + "a01b038516815260208101849052908101829052600090819081908190819081908190630100001190606001" + + "606060405180830381855afa158015610bba573d6000803e3d6000fd5b5050506040513d601f19601f820116" + + "82018060405250810190610bdd9190610e21565b919c909b509099504398509650505050505050565b604080" + + "516001600160a01b038416815260208101839052600091630100000d9101610703565b6040516001600160a0" + + "1b0382168152600090630100000c90602001602060405180830381855afa158015610c50573d6000803e3d60" + + "00fd5b5050506040513d601f19601f82011682018060405250810190610c739190610e08565b92915050565b" + + "6001600160a81b0381168114610c8e57600080fd5b50565b600080600060608486031215610ca657600080fd" + + "5b83359250602084013591506040840135610cbf81610c79565b9295919450506001600160a01b0390911691" + + "50565b60008060408385031215610ce757600080fd5b50508035926020909101359150565b60008060408385" + + "031215610d0957600080fd5b8235610d1481610c79565b6001600160a01b0316946020939093013593505050" + + "565b600060208284031215610d3d57600080fd5b8135610d4881610c79565b6001600160a01b031693925050" + + "50565b600080600060608486031215610d6d57600080fd5b8335610d7881610c79565b6001600160a01b0390" + + "81169350602085013590610d9482610c79565b93969316945050506040919091013590565b60008060006060" + + "8486031215610dbb57600080fd5b8335610dc681610c79565b6001600160a01b031695602085013595506040" + + "909401359392505050565b60008060408385031215610df757600080fd5b5050805160209091015190929091" + + "50565b600060208284031215610e1a57600080fd5b5051919050565b600080600060608486031215610e3657" + + "600080fd5b835192506020840151915060408401519050925092509256fea26474726f6e582212206da319ce" + + "ceb62dd2226a1f18adea5269deb830ff85c48e54bc8a6ed8822d8a3a64736f6c63430008110033"; + + private static final long value = 100_000_000_000_000_000L; + private static final long fee = 1_000_000_000; + private static final String userAStr = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; + private static final byte[] userA = Commons.decode58Check(userAStr); + private static final String userBStr = "27jzp7nVEkH4Hf3H1PHPp4VDY7DxTy5eydL"; + private static final byte[] userB = Commons.decode58Check(userBStr); + private static final String userCStr = "27juXSbMvL6pb8VgmKRgW6ByCfw5RqZjUuo"; + private static final byte[] userC = Commons.decode58Check(userCStr); + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + private static TronApplicationContext context; + private static Manager manager; + private static byte[] owner; + private static Repository rootRepository; + + @Before + public void init() throws Exception { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + manager = context.getBean(Manager.class); + owner = Hex.decode(Wallet.getAddressPreFixString() + + "abd4b9367799eaa3197fecb144eb71de1e049abc"); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(owner, Protocol.AccountType.Normal); + rootRepository.addBalance(owner, 900_000_000_000_000_000L); + rootRepository.commit(); + + ConfigLoader.disable = true; + manager.getDynamicPropertiesStore().saveAllowTvmFreeze(1); + manager.getDynamicPropertiesStore().saveUnfreezeDelayDays(30); + manager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + manager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + VMConfig.initVmHardFork(true); + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmSolidity059(1); + VMConfig.initAllowTvmIstanbul(1); + VMConfig.initAllowTvmFreezeV2(1); + VMConfig.initAllowTvmVote(1); + } + + private byte[] deployContract(String contractName, String code) throws Exception { + return deployContract(owner, contractName, code, 0, 100_000); + } + + private byte[] deployContract(byte[] deployer, + String contractName, + String code, + long consumeUserResourcePercent, + long originEnergyLimit) throws Exception { + Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractName, deployer, "[]", code, value, fee, consumeUserResourcePercent, + null, originEnergyLimit); + byte[] contractAddr = WalletUtil.generateContractAddress(trx); + //String contractAddrStr = StringUtil.encode58Check(contractAddr); + TransactionCapsule trxCap = new TransactionCapsule(trx); + TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), + new RuntimeImpl()); + trxCap.setTrxTrace(trace); + trace.init(null); + trace.exec(); + trace.finalization(); + Runtime runtime = trace.getRuntime(); + Assert.assertEquals(SUCCESS, runtime.getResult().getResultCode()); + Assert.assertEquals(value, manager.getAccountStore().get(contractAddr).getBalance()); + + return contractAddr; + } + + private TVMTestResult triggerContract(byte[] callerAddr, + byte[] contractAddr, + long feeLimit, + contractResult expectedResult, + Consumer check, + String method, + Object... args) throws Exception { + String hexInput = AbiUtil.parseMethod(method, Arrays.asList(args)); + TransactionCapsule trxCap = new TransactionCapsule( + TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + callerAddr, contractAddr, Hex.decode(hexInput), 0, feeLimit)); + TransactionTrace trace = new TransactionTrace(trxCap, StoreFactory.getInstance(), + new RuntimeImpl()); + trxCap.setTrxTrace(trace); + trace.init(null); + trace.exec(); + trace.finalization(); + trace.setResult(); + TVMTestResult result = new TVMTestResult(trace.getRuntime(), trace.getReceipt(), null); + Assert.assertEquals(expectedResult, result.getReceipt().getResult()); + if (check != null) { + check.accept(result.getRuntime().getResult().getHReturn()); + } + return result; + } + + private TVMTestResult triggerFreeze(byte[] callerAddr, + byte[] contractAddr, + long frozenBalance, + long res, + contractResult expectedResult, + Consumer check) throws Exception { + return triggerContract(callerAddr, contractAddr, fee, expectedResult, check, + "freezeBalanceV2(uint256,uint256)", frozenBalance, res); + } + + private TVMTestResult triggerUnfreeze(byte[] callerAddr, + byte[] contractAddr, + long unfreezeBalance, + long res, + contractResult expectedResult, + Consumer check) throws Exception { + return triggerContract(callerAddr, contractAddr, fee, expectedResult, check, + "unfreezeBalanceV2(uint256,uint256)", unfreezeBalance, res); + } + + private TVMTestResult triggerWithdrawExpireUnfreeze( + byte[] callerAddr, byte[] contractAddr, contractResult expectedResult, Consumer check) + throws Exception { + return triggerContract( + callerAddr, contractAddr, fee, expectedResult, check, "withdrawExpireUnfreeze()"); + } + + private TVMTestResult triggerCancelAllUnfreezeV2( + byte[] callerAddr, byte[] contractAddr, contractResult expectedResult, Consumer check) + throws Exception { + CommonParameter.getInstance().saveCancelAllUnfreezeV2Details = true; + return triggerContract( + callerAddr, contractAddr, fee, expectedResult, check, "cancelAllUnfreezeBalanceV2()"); + } + + private TVMTestResult triggerDelegateResource( + byte[] callerAddr, byte[] contractAddr, contractResult expectedResult, + Consumer check, byte[] receiverAddr, long amount, long res) + throws Exception { + return triggerContract(callerAddr, contractAddr, fee, expectedResult, check, + "delegateResource(uint256,uint256,address)", + amount, res, StringUtil.encode58Check(receiverAddr)); + } + + private TVMTestResult triggerUnDelegateResource( + byte[] callerAddr, byte[] contractAddr, contractResult expectedResult, + Consumer check, byte[] receiverAddr, long amount, long res) + throws Exception { + return triggerContract( + callerAddr, contractAddr, fee, expectedResult, check, + "unDelegateResource(uint256,uint256,address)", + amount, res, StringUtil.encode58Check(receiverAddr)); + } + + private TVMTestResult triggerSuicide( + byte[] callerAddr, byte[] contractAddr, contractResult expectedResult, + Consumer check, byte[] inheritorAddress) + throws Exception { + return triggerContract( + callerAddr, contractAddr, fee, expectedResult, check, + "killme(address)", StringUtil.encode58Check(inheritorAddress)); + } + + @Test + public void testFreezeV2Operations() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000; + + // trigger freezeBalanceV2(uint256,uint256) to get bandwidth + freezeV2(owner, contract, frozenBalance, 0); + + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, frozenBalance, 1); + + // trigger freezeBalanceV2(uint256,uint256) to get tp + freezeV2(owner, contract, frozenBalance, 2); + + // tests of freezeBalanceV2(uint256,uint256) with invalid args + freezeV2WithException(owner, contract, frozenBalance, 3); + freezeV2WithException(owner, contract, 0, 0); + freezeV2WithException(owner, contract, -frozenBalance, 0); + freezeV2WithException(owner, contract, frozenBalance - 1, 1); + freezeV2WithException(owner, contract, value, 0); + + // invalid args + unfreezeV2WithException(owner, contract, frozenBalance, 3); + unfreezeV2WithException(owner, contract, -frozenBalance, 2); + unfreezeV2WithException(owner, contract, 0, 2); + unfreezeV2WithException(owner, contract, frozenBalance + 100, 2); + // full unfreeze list exception + AccountCapsule ownerCapsule = manager.getAccountStore().get(contract); + long now = manager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + int unfreezingCount = ownerCapsule.getUnfreezingV2Count(now); + List unFreezeV2List = + new ArrayList<>(ownerCapsule.getUnfrozenV2List()); + for (; unfreezingCount < UnfreezeBalanceV2Actuator.getUNFREEZE_MAX_TIMES(); unfreezingCount++) { + ownerCapsule.addUnfrozenV2List(BANDWIDTH, 1, now + 30000); + } + manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + unfreezeV2WithException(owner, contract, frozenBalance, 2); + ownerCapsule = manager.getAccountStore().get(contract); + ownerCapsule.clearUnfrozenV2(); + unFreezeV2List.forEach(ownerCapsule::addUnfrozenV2); + manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + // unfreeze + unfreezeV2(owner, contract, frozenBalance, 0); + unfreezeV2(owner, contract, frozenBalance, 1); + unfreezeV2(owner, contract, frozenBalance, 2); + // no enough balance + unfreezeV2WithException(owner, contract, frozenBalance, 0); + unfreezeV2WithException(owner, contract, frozenBalance, 1); + unfreezeV2WithException(owner, contract, frozenBalance, 2); + + // withdrawExpireUnfreeze + withdrawExpireUnfreeze(owner, contract, 0); + clearUnfreezeV2ExpireTime(contract, 0); + withdrawExpireUnfreeze(owner, contract, frozenBalance); + + withdrawExpireUnfreeze(owner, contract, 0); + clearUnfreezeV2ExpireTime(contract, 1); + withdrawExpireUnfreeze(owner, contract, frozenBalance); + + withdrawExpireUnfreeze(owner, contract, 0); + clearUnfreezeV2ExpireTime(contract, 2); + withdrawExpireUnfreeze(owner, contract, frozenBalance); + + // cancelAllUnfreezeV2 + freezeV2(owner, contract, frozenBalance, 0); + cancelAllUnfreezeV2(owner, contract, 0); + unfreezeV2(owner, contract, frozenBalance, 0); + cancelAllUnfreezeV2(owner, contract, 0); + freezeV2(owner, contract, frozenBalance, 1); + unfreezeV2(owner, contract, frozenBalance, 1); + clearUnfreezeV2ExpireTime(contract, 1); + cancelAllUnfreezeV2(owner, contract, frozenBalance); + } + + @Test + public void testDelegateResourceOperations() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long resourceAmount = 1_000_000; + // trigger freezeBalanceV2(uint256,uint256) to get bandwidth + freezeV2(owner, contract, resourceAmount, 0); + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, resourceAmount, 1); + // trigger freezeBalanceV2(uint256,uint256) to get tp + freezeV2(owner, contract, resourceAmount, 2); + + delegateResourceWithException(owner, contract, userA, resourceAmount, 0); + rootRepository.createAccount(userA, Protocol.AccountType.Normal); + rootRepository.commit(); + delegateResourceWithException(owner, contract, userA, 0, 0); + delegateResourceWithException(owner, contract, userA, resourceAmount * 2, 0); + delegateResourceWithException(owner, contract, userA, resourceAmount - 100, 0); + delegateResourceWithException(owner, contract, userA, resourceAmount, 2); + delegateResourceWithException(owner, contract, userA, resourceAmount, 3); + delegateResourceWithException(owner, contract, contract, resourceAmount, 0); + rootRepository.createAccount(userC, Protocol.AccountType.Contract); + rootRepository.commit(); + delegateResourceWithException(owner, contract, userC, resourceAmount, 0); + + delegateResource(owner, contract, userA, resourceAmount, 0); + delegateResourceWithException(owner, contract, userA, resourceAmount, 0); + delegateResource(owner, contract, userA, resourceAmount, 1); + + // unDelegate + // invalid args + unDelegateResourceWithException(owner, contract, userA, resourceAmount, 2); + unDelegateResourceWithException(owner, contract, userA, resourceAmount, 3); + unDelegateResourceWithException(owner, contract, userB, resourceAmount, 0); + rootRepository.createAccount(userB, Protocol.AccountType.Normal); + rootRepository.commit(); + unDelegateResourceWithException(owner, contract, userB, resourceAmount, 0); + unDelegateResourceWithException(owner, contract, contract, resourceAmount, 0); + unDelegateResourceWithException(owner, contract, userA, resourceAmount * 2, 0); + unDelegateResourceWithException(owner, contract, userA, 0, 0); + unDelegateResourceWithException(owner, contract, userA, -resourceAmount, 0); + + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(System.currentTimeMillis()); + unDelegateResource(owner, contract, userA, resourceAmount, 0); + unDelegateResourceWithException(owner, contract, userA, resourceAmount, 0); + unDelegateResource(owner, contract, userA, resourceAmount, 1); + + // no enough delegated resource + unDelegateResourceWithException(owner, contract, userA, resourceAmount, 0); + unDelegateResourceWithException(owner, contract, userA, resourceAmount, 1); + } + + @Test + public void testUnfreezeVotes() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000_000L; + + // trigger freezeBalanceV2(uint256,uint256) to get tp + freezeV2(owner, contract, frozenBalance, 2); + + // vote + AccountCapsule accountCapsule = manager.getAccountStore().get(contract); + VotesCapsule votesCapsule = + new VotesCapsule(ByteString.copyFrom(contract), accountCapsule.getVotesList()); + accountCapsule.addVotes(ByteString.copyFrom(userA), 500); + votesCapsule.addNewVotes(ByteString.copyFrom(userA), 500); + accountCapsule.addVotes(ByteString.copyFrom(userB), 500); + votesCapsule.addNewVotes(ByteString.copyFrom(userB), 500); + manager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + manager.getVotesStore().put(votesCapsule.createDbKey(), votesCapsule); + + // unfreeze half tp + unfreezeV2(owner, contract, frozenBalance / 2, 2); + accountCapsule = manager.getAccountStore().get(contract); + for (Protocol.Vote vote : accountCapsule.getVotesList()) { + Assert.assertEquals(250, vote.getVoteCount()); + } + + votesCapsule = manager.getVotesStore().get(contract); + Assert.assertNotNull(votesCapsule); + for (Protocol.Vote vote : votesCapsule.getOldVotes()) { + Assert.assertEquals(500, vote.getVoteCount()); + } + for (Protocol.Vote vote : votesCapsule.getNewVotes()) { + Assert.assertEquals(250, vote.getVoteCount()); + } + // unfreeze all tp + unfreezeV2(owner, contract, frozenBalance / 2, 2); + accountCapsule = manager.getAccountStore().get(contract); + Assert.assertEquals(0, accountCapsule.getVotesList().size()); + Assert.assertEquals(-1, accountCapsule.getInstance().getOldTronPower()); + } + + @Test + public void testUnfreezeWithOldTronPower() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000_000L; + long now = System.currentTimeMillis(); + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, frozenBalance, 1); + AccountCapsule ownerCapsule = manager.getAccountStore().get(contract); + ownerCapsule.setOldTronPower(frozenBalance); + ownerCapsule.addVotes(ByteString.copyFrom(userA), 100L); + Assert.assertEquals(frozenBalance, ownerCapsule.getAllFrozenBalanceForEnergy()); + manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + // unfreeze all balance + unfreezeV2(owner, contract, frozenBalance, 1); + ownerCapsule = manager.getAccountStore().get(contract); + Assert.assertEquals(0, ownerCapsule.getVotesList().size()); + Assert.assertEquals(-1, ownerCapsule.getInstance().getOldTronPower()); + } + + @Test + public void testUnfreezeWithoutOldTronPower() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000_000L; + long now = System.currentTimeMillis(); + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, frozenBalance, 1); + AccountCapsule ownerCapsule = manager.getAccountStore().get(contract); + ownerCapsule.setOldTronPower(-1L); + ownerCapsule.addVotes(ByteString.copyFrom(userA), 100L); + Assert.assertEquals(frozenBalance, ownerCapsule.getAllFrozenBalanceForEnergy()); + manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + // unfreeze all balance + unfreezeV2(owner, contract, frozenBalance, 1); + ownerCapsule = manager.getAccountStore().get(contract); + Assert.assertEquals(1, ownerCapsule.getVotesList().size()); + Assert.assertEquals(-1, ownerCapsule.getInstance().getOldTronPower()); + } + + @Test + public void testUnfreezeTronPowerWithOldTronPower() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000_000L; + long now = System.currentTimeMillis(); + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, frozenBalance, 1); + // trigger freezeBalanceV2(uint256,uint256) to get tp + freezeV2(owner, contract, frozenBalance, 2); + AccountCapsule ownerCapsule = manager.getAccountStore().get(contract); + ownerCapsule.setOldTronPower(-1L); + ownerCapsule.addVotes(ByteString.copyFrom(userA), 100L); + Assert.assertEquals(frozenBalance, ownerCapsule.getAllFrozenBalanceForEnergy()); + manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + // unfreeze + unfreezeV2(owner, contract, frozenBalance, 2); + ownerCapsule = manager.getAccountStore().get(contract); + Assert.assertEquals(0, ownerCapsule.getVotesList().size()); + Assert.assertEquals(-1, ownerCapsule.getInstance().getOldTronPower()); + } + + @Test + public void testSuicideToOtherAccount() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000_000L; + long now = System.currentTimeMillis(); + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, frozenBalance, 1); + freezeV2(owner, contract, frozenBalance, 2); + rootRepository.createAccount(userA, Protocol.AccountType.Normal); + rootRepository.createAccount(userB, Protocol.AccountType.Normal); + rootRepository.commit(); + + // not empty delegate resource exception + delegateResource(owner, contract, userA, frozenBalance / 2, 1); + suicideWithException(owner, contract, userB); + unDelegateResource(owner, contract, userA, frozenBalance / 2, 1); + // not empty unfreezing list exception + unfreezeV2(owner, contract, frozenBalance / 2, 1); + suicideWithException(owner, contract, userB); + cancelAllUnfreezeV2(owner, contract, 0); + + AccountCapsule contractCapsule = manager.getAccountStore().get(contract); + contractCapsule.setLatestConsumeTimeForEnergy(ChainBaseManager.getInstance().getHeadSlot()); + contractCapsule.setNewWindowSize(ENERGY, WINDOW_SIZE_MS / BLOCK_PRODUCED_INTERVAL); + contractCapsule.setEnergyUsage(frozenBalance); + manager.getAccountStore().put(contract, contractCapsule); + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now + 30000); + suicide(owner, contract, userB); + } + + @Test + public void testSuicideToBlackHole() throws Exception { + byte[] contract = deployContract("TestFreezeV2", FREEZE_V2_CODE); + long frozenBalance = 1_000_000_000L; + long now = System.currentTimeMillis(); + manager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + // trigger freezeBalanceV2(uint256,uint256) to get energy + freezeV2(owner, contract, frozenBalance, 1); + + suicide(owner, contract, contract); + } + + private TVMTestResult freezeV2( + byte[] callerAddr, byte[] contractAddr, long frozenBalance, long res) throws Exception { + DynamicPropertiesStore dynamicStore = manager.getDynamicPropertiesStore(); + long oldTotalNetWeight = dynamicStore.getTotalNetWeight(); + long oldTotalEnergyWeight = dynamicStore.getTotalEnergyWeight(); + long oldTronPowerWeight = dynamicStore.getTotalTronPowerWeight(); + + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldOwner = accountStore.get(contractAddr); + + TVMTestResult result = + triggerFreeze(callerAddr, contractAddr, frozenBalance, res, SUCCESS, null); + + AccountCapsule newOwner = accountStore.get(contractAddr); + Assert.assertEquals(oldOwner.getBalance() - frozenBalance, newOwner.getBalance()); + newOwner.setBalance(oldOwner.getBalance()); + if (res == 0) { + Assert.assertEquals( + oldOwner.getFrozenV2BalanceForBandwidth() + frozenBalance, + newOwner.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals( + oldTotalNetWeight + frozenBalance / TRX_PRECISION, dynamicStore.getTotalNetWeight()); + Assert.assertEquals(oldTotalEnergyWeight, dynamicStore.getTotalEnergyWeight()); + Assert.assertEquals(oldTronPowerWeight, dynamicStore.getTotalTronPowerWeight()); + } else if (res == 1) { + Assert.assertEquals( + oldOwner.getFrozenV2BalanceForEnergy() + frozenBalance, + newOwner.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(oldTotalNetWeight, dynamicStore.getTotalNetWeight()); + Assert.assertEquals(oldTronPowerWeight, dynamicStore.getTotalTronPowerWeight()); + Assert.assertEquals( + oldTotalEnergyWeight + frozenBalance / TRX_PRECISION, + dynamicStore.getTotalEnergyWeight()); + } else { + Assert.assertEquals( + oldOwner.getTronPowerFrozenV2Balance() + frozenBalance, + newOwner.getTronPowerFrozenV2Balance()); + Assert.assertEquals(oldTotalNetWeight, dynamicStore.getTotalNetWeight()); + Assert.assertEquals(oldTotalEnergyWeight, dynamicStore.getTotalEnergyWeight()); + Assert.assertEquals( + oldTronPowerWeight + frozenBalance / TRX_PRECISION, + dynamicStore.getTotalTronPowerWeight()); + } + + return result; + } + + private TVMTestResult freezeV2WithException( + byte[] callerAddr, byte[] contractAddr, long frozenBalance, long res) throws Exception { + return triggerFreeze(callerAddr, contractAddr, frozenBalance, res, REVERT, null); + } + + private TVMTestResult unfreezeV2WithException( + byte[] callerAddr, byte[] contractAddr, long unfreezeBalance, long res) throws Exception { + return triggerUnfreeze(callerAddr, contractAddr, unfreezeBalance, res, REVERT, null); + } + + private TVMTestResult unfreezeV2( + byte[] callerAddr, byte[] contractAddr, long unfreezeBalance, long res) throws Exception { + DynamicPropertiesStore dynamicStore = manager.getDynamicPropertiesStore(); + long oldTotalNetWeight = dynamicStore.getTotalNetWeight(); + long oldTotalEnergyWeight = dynamicStore.getTotalEnergyWeight(); + long oldTotalTronPowerWeight = dynamicStore.getTotalTronPowerWeight(); + + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldOwner = accountStore.get(contractAddr); + long frozenBalance; + if (res == 0) { + frozenBalance = oldOwner.getFrozenV2BalanceForBandwidth(); + } else if (res == 1) { + frozenBalance = oldOwner.getFrozenV2BalanceForEnergy(); + } else { + frozenBalance = oldOwner.getTronPowerFrozenV2Balance(); + } + Assert.assertTrue(frozenBalance > 0); + + TVMTestResult result = + triggerUnfreeze(callerAddr, contractAddr, unfreezeBalance, res, SUCCESS, null); + + AccountCapsule newOwner = accountStore.get(contractAddr); + if (res == 0) { + Assert.assertEquals( + oldOwner.getFrozenV2BalanceForBandwidth() - unfreezeBalance, + newOwner.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals( + oldTotalNetWeight - unfreezeBalance / TRX_PRECISION, dynamicStore.getTotalNetWeight()); + Assert.assertEquals(oldTotalEnergyWeight, dynamicStore.getTotalEnergyWeight()); + Assert.assertEquals(oldTotalTronPowerWeight, dynamicStore.getTotalTronPowerWeight()); + } else if (res == 1) { + Assert.assertEquals( + oldOwner.getFrozenV2BalanceForEnergy() - unfreezeBalance, + newOwner.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(oldTotalNetWeight, dynamicStore.getTotalNetWeight()); + Assert.assertEquals(oldTotalTronPowerWeight, dynamicStore.getTotalTronPowerWeight()); + Assert.assertEquals( + oldTotalEnergyWeight - unfreezeBalance / TRX_PRECISION, + dynamicStore.getTotalEnergyWeight()); + } else { + Assert.assertEquals( + oldOwner.getTronPowerFrozenV2Balance() - unfreezeBalance, + newOwner.getTronPowerFrozenV2Balance()); + Assert.assertEquals(oldTotalEnergyWeight, dynamicStore.getTotalEnergyWeight()); + Assert.assertEquals(oldTotalNetWeight, dynamicStore.getTotalNetWeight()); + Assert.assertEquals( + oldTotalTronPowerWeight - unfreezeBalance / TRX_PRECISION, + dynamicStore.getTotalTronPowerWeight()); + } + + return result; + } + + private void clearUnfreezeV2ExpireTime(byte[] owner, long res) { + AccountCapsule accountCapsule = manager.getAccountStore().get(owner); + long now = manager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + List newUnfreezeV2List = new ArrayList<>(); + accountCapsule.getUnfrozenV2List().forEach(unFreezeV2 -> { + if (unFreezeV2.getType().getNumber() == res) { + newUnfreezeV2List.add(unFreezeV2.toBuilder().setUnfreezeExpireTime(now).build()); + } else { + newUnfreezeV2List.add(unFreezeV2); + } + }); + accountCapsule.clearUnfrozenV2(); + newUnfreezeV2List.forEach(accountCapsule::addUnfrozenV2); + manager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + } + + private TVMTestResult withdrawExpireUnfreeze( + byte[] callerAddr, byte[] contractAddr, long expectedWithdrawBalance) throws Exception { + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldOwner = accountStore.get(contractAddr); + long oldBalance = oldOwner.getBalance(); + + TVMTestResult result = triggerWithdrawExpireUnfreeze(callerAddr, contractAddr, SUCCESS, null); + + AccountCapsule newOwner = accountStore.get(contractAddr); + Assert.assertEquals(oldBalance + expectedWithdrawBalance, newOwner.getBalance()); + oldOwner.setBalance(newOwner.getBalance()); + oldOwner.clearUnfrozenV2(); + newOwner.getUnfrozenV2List().forEach(oldOwner::addUnfrozenV2); + Assert.assertArrayEquals(oldOwner.getData(), newOwner.getData()); + + return result; + } + + private TVMTestResult cancelAllUnfreezeV2( + byte[] callerAddr, byte[] contractAddr, long expectedWithdrawBalance) throws Exception { + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldOwner = accountStore.get(contractAddr); + long oldBalance = oldOwner.getBalance(); + long now = manager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + long oldFrozenBalance = + oldOwner.getFrozenV2List().stream().mapToLong(Protocol.Account.FreezeV2::getAmount).sum(); + long oldUnfreezingBalance = + oldOwner.getUnfrozenV2List().stream() + .filter(unFreezeV2 -> unFreezeV2.getUnfreezeExpireTime() > now) + .mapToLong(Protocol.Account.UnFreezeV2::getUnfreezeAmount) + .sum(); + + TVMTestResult result = triggerCancelAllUnfreezeV2(callerAddr, contractAddr, SUCCESS, null); + + AccountCapsule newOwner = accountStore.get(contractAddr); + long newUnfreezeV2Amount = newOwner.getUnfreezingV2Count(now); + long newFrozenBalance = + newOwner.getFrozenV2List().stream().mapToLong(Protocol.Account.FreezeV2::getAmount).sum(); + Assert.assertEquals(0, newUnfreezeV2Amount); + Assert.assertEquals(expectedWithdrawBalance, newOwner.getBalance() - oldBalance); + Assert.assertEquals(oldFrozenBalance + oldUnfreezingBalance, newFrozenBalance); + + return result; + } + + private TVMTestResult delegateResource( + byte[] callerAddr, byte[] contractAddr, byte[] receiverAddr, long amount, long res) + throws Exception { + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldOwner = accountStore.get(contractAddr); + AccountCapsule oldReceiver = accountStore.get(receiverAddr); + + DelegatedResourceStore delegatedResourceStore = manager.getDelegatedResourceStore(); + DelegatedResourceCapsule oldDelegatedResource = delegatedResourceStore.get( + DelegatedResourceCapsule.createDbKeyV2(contractAddr, receiverAddr, false)); + if (oldDelegatedResource == null) { + oldDelegatedResource = new DelegatedResourceCapsule( + ByteString.copyFrom(contractAddr), + ByteString.copyFrom(receiverAddr)); + } + + TVMTestResult result = triggerDelegateResource( + callerAddr, contractAddr, SUCCESS, null, receiverAddr, amount, res); + + AccountCapsule newOwner = accountStore.get(contractAddr); + AccountCapsule newReceiver = accountStore.get(receiverAddr); + Assert.assertNotNull(newReceiver); + if (res == 0) { + Assert.assertEquals(oldOwner.getDelegatedFrozenV2BalanceForBandwidth() + amount, + newOwner.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(oldReceiver.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + amount, + newReceiver.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + } else { + Assert.assertEquals(oldOwner.getDelegatedFrozenV2BalanceForEnergy() + amount, + newOwner.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(oldReceiver.getAcquiredDelegatedFrozenV2BalanceForEnergy() + amount, + newReceiver.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + } + newReceiver.setBalance(oldReceiver.getBalance()); + oldReceiver.setEnergyUsage(0); + oldReceiver.setNewWindowSize(ENERGY, 28800); + newReceiver.setEnergyUsage(0); + newReceiver.setNewWindowSize(ENERGY,28800); + if (res == 0) { + oldReceiver.setAcquiredDelegatedFrozenV2BalanceForBandwidth(0); + newReceiver.setAcquiredDelegatedFrozenV2BalanceForBandwidth(0); + } else { + oldReceiver.setAcquiredDelegatedFrozenV2BalanceForEnergy(0); + newReceiver.setAcquiredDelegatedFrozenV2BalanceForEnergy(0); + } + Assert.assertArrayEquals(oldReceiver.getData(), newReceiver.getData()); + + DelegatedResourceCapsule newDelegatedResource = manager.getDelegatedResourceStore().get( + DelegatedResourceCapsule.createDbKeyV2(contractAddr, receiverAddr, false)); + Assert.assertNotNull(newDelegatedResource); + if (res == 0) { + Assert.assertEquals(amount + oldDelegatedResource.getFrozenBalanceForBandwidth(), + newDelegatedResource.getFrozenBalanceForBandwidth()); + Assert.assertEquals(oldDelegatedResource.getFrozenBalanceForEnergy(), + newDelegatedResource.getFrozenBalanceForEnergy()); + } else { + Assert.assertEquals(oldDelegatedResource.getFrozenBalanceForBandwidth(), + newDelegatedResource.getFrozenBalanceForBandwidth()); + Assert.assertEquals(amount + oldDelegatedResource.getFrozenBalanceForEnergy(), + newDelegatedResource.getFrozenBalanceForEnergy()); + } + + return result; + } + + private TVMTestResult delegateResourceWithException( + byte[] callerAddr, byte[] contractAddr, byte[] receiverAddr, long amount, long res) + throws Exception { + return triggerDelegateResource( + callerAddr, contractAddr, REVERT, null, receiverAddr, amount, res); + } + + private TVMTestResult unDelegateResource( + byte[] callerAddr, byte[] contractAddr, byte[] receiverAddr, long amount, long res) + throws Exception { + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldOwner = accountStore.get(contractAddr); + AccountCapsule oldReceiver = accountStore.get(receiverAddr); + DynamicPropertiesStore dynamicStore = manager.getDynamicPropertiesStore(); + long acquiredBalance = 0; + long transferUsage = 0; + if (oldReceiver != null) { + acquiredBalance = res == 0 ? oldReceiver.getAcquiredDelegatedFrozenV2BalanceForBandwidth() : + oldReceiver.getAcquiredDelegatedFrozenV2BalanceForEnergy(); + + long unDelegateMaxUsage; + if (res == 0) { + unDelegateMaxUsage = (long) (amount / TRX_PRECISION + * ((double) (dynamicStore.getTotalNetLimit()) / dynamicStore.getTotalNetWeight())); + transferUsage = (long) (oldReceiver.getNetUsage() + * ((double) (amount) / oldReceiver.getAllFrozenBalanceForBandwidth())); + } else { + unDelegateMaxUsage = (long) (amount / TRX_PRECISION + * ((double) (dynamicStore.getTotalEnergyCurrentLimit()) + / dynamicStore.getTotalEnergyWeight())); + transferUsage = (long) (oldReceiver.getEnergyUsage() + * ((double) (amount) / oldReceiver.getAllFrozenBalanceForEnergy())); + } + transferUsage = min(unDelegateMaxUsage, transferUsage, + manager.getDynamicPropertiesStore().disableJavaLangMath()); + } + + DelegatedResourceStore delegatedResourceStore = manager.getDelegatedResourceStore(); + DelegatedResourceCapsule oldDelegatedResource = delegatedResourceStore.get( + DelegatedResourceCapsule.createDbKeyV2(contractAddr, receiverAddr, false)); + Assert.assertNotNull(oldDelegatedResource); + long delegatedFrozenBalance = res == 0 ? oldDelegatedResource.getFrozenBalanceForBandwidth() : + oldDelegatedResource.getFrozenBalanceForEnergy(); + Assert.assertTrue(delegatedFrozenBalance > 0); + Assert.assertTrue(amount <= delegatedFrozenBalance); + + TVMTestResult result = + triggerUnDelegateResource( + callerAddr, contractAddr, SUCCESS, null, receiverAddr, amount, res); + // check owner account + AccountCapsule newOwner = accountStore.get(contractAddr); + newOwner.setBalance(oldOwner.getBalance()); + if (res == 0) { + Assert.assertEquals( + oldOwner.getDelegatedFrozenV2BalanceForBandwidth() - amount, + newOwner.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals( + oldOwner.getFrozenV2BalanceForBandwidth() + amount, + newOwner.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(oldOwner.getNetUsage() + transferUsage, newOwner.getNetUsage()); + } else { + Assert.assertEquals( + oldOwner.getDelegatedFrozenV2BalanceForEnergy() - amount, + newOwner.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals( + oldOwner.getFrozenV2BalanceForEnergy() + amount, newOwner.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(oldOwner.getEnergyUsage() + transferUsage, newOwner.getEnergyUsage()); + } + + // check receiver account + AccountCapsule newReceiver = accountStore.get(receiverAddr); + if (oldReceiver != null) { + Assert.assertNotNull(newReceiver); + long newAcquiredBalance = + res == 0 + ? newReceiver.getAcquiredDelegatedFrozenV2BalanceForBandwidth() + : newReceiver.getAcquiredDelegatedFrozenV2BalanceForEnergy(); + Assert.assertTrue(newAcquiredBalance == 0 || acquiredBalance - newAcquiredBalance == amount); + if (res == 0) { + Assert.assertEquals( + oldReceiver.getNetUsage() - transferUsage, + newReceiver.getNetUsage()); + Assert.assertEquals( + ChainBaseManager.getInstance().getHeadSlot(), + newReceiver.getLastConsumeTime(BANDWIDTH)); + } else { + Assert.assertEquals( + oldReceiver.getEnergyUsage() + transferUsage, + newReceiver.getEnergyUsage()); + Assert.assertEquals( + ChainBaseManager.getInstance().getHeadSlot(), + newReceiver.getLastConsumeTime(ENERGY)); + } + } else { + Assert.assertNull(newReceiver); + } + + // check delegated resource store + DelegatedResourceCapsule newDelegatedResource = delegatedResourceStore.get( + DelegatedResourceCapsule.createDbKeyV2(contractAddr, receiverAddr, false)); + Assert.assertNotNull(newDelegatedResource); + if (res == 0) { + Assert.assertEquals(0, newDelegatedResource.getFrozenBalanceForBandwidth()); + Assert.assertEquals(oldDelegatedResource.getFrozenBalanceForEnergy(), + newDelegatedResource.getFrozenBalanceForEnergy()); + } else { + Assert.assertEquals(oldDelegatedResource.getFrozenBalanceForBandwidth(), + newDelegatedResource.getFrozenBalanceForBandwidth()); + Assert.assertEquals(0, newDelegatedResource.getFrozenBalanceForEnergy()); + } + + return result; + } + + private TVMTestResult unDelegateResourceWithException( + byte[] callerAddr, byte[] contractAddr, byte[] receiverAddr, long amount, long res) + throws Exception { + return triggerUnDelegateResource( + callerAddr, contractAddr, REVERT, null, receiverAddr, amount, res); + } + + private TVMTestResult suicide(byte[] callerAddr, byte[] contractAddr, byte[] inheritorAddr) + throws Exception { + if (FastByteComparisons.isEqual(contractAddr, inheritorAddr)) { + inheritorAddr = manager.getAccountStore().getBlackholeAddress(); + } + DynamicPropertiesStore dynamicStore = manager.getDynamicPropertiesStore(); + long oldTotalNetWeight = dynamicStore.getTotalNetWeight(); + long oldTotalEnergyWeight = dynamicStore.getTotalEnergyWeight(); + long now = dynamicStore.getLatestBlockHeaderTimestamp(); + + AccountStore accountStore = manager.getAccountStore(); + AccountCapsule oldContract = accountStore.get(contractAddr); + AccountCapsule oldInheritor = accountStore.get(inheritorAddr); + long oldBalanceOfInheritor = 0; + long oldInheritorFrozenBalance = 0; + long oldInheritorBandwidthUsage = 0; + long oldInheritorEnergyUsage = 0; + if (oldInheritor != null) { + oldBalanceOfInheritor = oldInheritor.getBalance(); + oldInheritorFrozenBalance = oldInheritor.getFrozenBalance(); + oldInheritorBandwidthUsage = oldInheritor.getUsage(BANDWIDTH); + oldInheritorEnergyUsage = oldInheritor.getUsage(ENERGY); + } + BandwidthProcessor bandwidthProcessor = new BandwidthProcessor(ChainBaseManager.getInstance()); + bandwidthProcessor.updateUsage(oldContract); + oldContract.setLatestConsumeTime(now); + EnergyProcessor energyProcessor = + new EnergyProcessor( + manager.getDynamicPropertiesStore(), ChainBaseManager.getInstance().getAccountStore()); + energyProcessor.updateUsage(oldContract); + oldContract.setLatestConsumeTimeForEnergy(now); + + TVMTestResult result = triggerSuicide(callerAddr, contractAddr, SUCCESS, null, inheritorAddr); + + Assert.assertNull(accountStore.get(contractAddr)); + AccountCapsule newInheritor = accountStore.get(inheritorAddr); + Assert.assertNotNull(newInheritor); + long expectedIncreasingBalance = + oldContract.getBalance() + + oldContract.getUnfrozenV2List().stream() + .filter(unFreezeV2 -> unFreezeV2.getUnfreezeExpireTime() <= now) + .mapToLong(Protocol.Account.UnFreezeV2::getUnfreezeAmount) + .sum(); + if (FastByteComparisons.isEqual( + inheritorAddr, manager.getAccountStore().getBlackholeAddress())) { + Assert.assertEquals( + expectedIncreasingBalance, + newInheritor.getBalance() - oldBalanceOfInheritor - result.getReceipt().getEnergyFee()); + } else { + Assert.assertEquals( + expectedIncreasingBalance, newInheritor.getBalance() - oldBalanceOfInheritor); + } + + Assert.assertEquals(0, oldContract.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, oldContract.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals( + oldContract.getFrozenBalance(), + newInheritor.getFrozenBalance() - oldInheritorFrozenBalance); + if (oldInheritor != null) { + if (oldContract.getNetUsage() > 0) { + bandwidthProcessor.unDelegateIncrease(oldInheritor, oldContract, oldContract.getNetUsage(), + Common.ResourceCode.BANDWIDTH, now); + Assert.assertEquals( + oldInheritor.getNetUsage(), newInheritor.getNetUsage() - oldInheritorBandwidthUsage); + Assert.assertEquals( + ChainBaseManager.getInstance().getHeadSlot(), newInheritor.getLatestConsumeTime()); + } + if (oldContract.getEnergyUsage() > 0) { + energyProcessor.unDelegateIncrease(oldInheritor, oldContract, + oldContract.getEnergyUsage(), Common.ResourceCode.ENERGY, now); + Assert.assertEquals( + oldInheritor.getEnergyUsage(), newInheritor.getEnergyUsage() - oldInheritorEnergyUsage); + Assert.assertEquals( + ChainBaseManager.getInstance().getHeadSlot(), + newInheritor.getLatestConsumeTimeForEnergy()); + } + } + + long newTotalNetWeight = dynamicStore.getTotalNetWeight(); + long newTotalEnergyWeight = dynamicStore.getTotalEnergyWeight(); + Assert.assertEquals( + oldContract.getFrozenBalance(), (oldTotalNetWeight - newTotalNetWeight) * TRX_PRECISION); + Assert.assertEquals( + oldContract.getEnergyFrozenBalance(), + (oldTotalEnergyWeight - newTotalEnergyWeight) * TRX_PRECISION); + + return result; + } + + private TVMTestResult suicideWithException( + byte[] callerAddr, byte[] contractAddr, byte[] inheritorAddr) + throws Exception { + return triggerSuicide( + callerAddr, contractAddr, REVERT, null, inheritorAddr); + } + + @After + public void destroy() { + ConfigLoader.disable = false; + VMConfig.initVmHardFork(false); + Args.clearParam(); + context.destroy(); + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/InternalTransactionCallTest.java b/framework/src/test/java/org/tron/common/runtime/vm/InternalTransactionCallTest.java index 13269a783d0..75a8f32186c 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/InternalTransactionCallTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/InternalTransactionCallTest.java @@ -1,19 +1,19 @@ package org.tron.common.runtime.vm; -import java.io.File; +import java.io.IOException; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.After; +import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; -import org.testng.Assert; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.config.DefaultConfig; @@ -23,6 +23,8 @@ import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j @@ -31,8 +33,9 @@ public class InternalTransactionCallTest { private Runtime runtime; private Manager dbManager; private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_InternalTransactionCallTest"; + private RepositoryImpl repository; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); private String OWNER_ADDRESS; private Application AppT; @@ -40,18 +43,19 @@ public class InternalTransactionCallTest { * Init data. */ @Before - public void init() { + public void init() throws IOException { Args.clearParam(); - Args.setParam(new String[]{"--output-directory", dbPath, "--support-constant", "--debug"}, + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--support-constant", "--debug"}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); AppT = ApplicationFactory.create(context); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), 100000000); } @@ -94,13 +98,13 @@ public void callTest() + "0000000000000000000000000000000000000000000000000000000000000003"; byte[] triggerData = TvmTestUtils.parseAbi("callTest(address,uint256)", params); TvmTestUtils.triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData, 0, 1000000000, deposit, null); + contractAAddress, triggerData, 0, 1000000000, repository, null); /* =========== CALL numberForB() to check A's numberForB =================================== */ byte[] triggerData2 = TvmTestUtils.parseAbi("numberForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData2, 0, 1000000000, deposit, null); + contractAAddress, triggerData2, 0, 1000000000, repository, null); // A should not be changed Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -109,7 +113,7 @@ public void callTest() byte[] triggerData3 = TvmTestUtils.parseAbi("senderForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData3, 0, 1000000000, deposit, null); + contractAAddress, triggerData3, 0, 1000000000, repository, null); // A should be changed Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -118,7 +122,7 @@ public void callTest() byte[] triggerData4 = TvmTestUtils.parseAbi("numberForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractBAddress, triggerData4, 0, 1000000000, deposit, null); + contractBAddress, triggerData4, 0, 1000000000, repository, null); // B's numberForB should be changed to 3 Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000003"); @@ -127,7 +131,7 @@ public void callTest() byte[] triggerData5 = TvmTestUtils.parseAbi("senderForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractBAddress, triggerData5, 0, 1000000000, deposit, null); + contractBAddress, triggerData5, 0, 1000000000, repository, null); // B 's senderForB should be A Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), Hex.toHexString(new DataWord(new DataWord(contractAAddress).getLast20Bytes()).getData())); @@ -152,13 +156,13 @@ public void delegateCallTest() byte[] triggerData = TvmTestUtils.parseAbi("delegatecallTest(address,uint256)", params); TvmTestUtils.triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData, 0, 1000000000, deposit, null); + contractAAddress, triggerData, 0, 1000000000, repository, null); /* ============ CALL numberForB() to check A's numberForB =================================== */ byte[] triggerData2 = TvmTestUtils.parseAbi("numberForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData2, 0, 1000000000, deposit, null); + contractAAddress, triggerData2, 0, 1000000000, repository, null); // A should be changed to 3 Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000003"); @@ -167,7 +171,7 @@ public void delegateCallTest() byte[] triggerData3 = TvmTestUtils.parseAbi("senderForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData3, 0, 1000000000, deposit, null); + contractAAddress, triggerData3, 0, 1000000000, repository, null); // A's senderForB should be changed to caller's contract Address (OWNER_ADDRESS) Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), Hex.toHexString(new DataWord(new DataWord(OWNER_ADDRESS).getLast20Bytes()).getData())); @@ -176,7 +180,7 @@ public void delegateCallTest() byte[] triggerData4 = TvmTestUtils.parseAbi("numberForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractBAddress, triggerData4, 0, 1000000000, deposit, null); + contractBAddress, triggerData4, 0, 1000000000, repository, null); // B's numberForB should not be changed Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -185,7 +189,7 @@ public void delegateCallTest() byte[] triggerData5 = TvmTestUtils.parseAbi("senderForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractBAddress, triggerData5, 0, 1000000000, deposit, null); + contractBAddress, triggerData5, 0, 1000000000, repository, null); // B 's senderForB should not be changed Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -210,13 +214,13 @@ public void callCodeTest() + "0000000000000000000000000000000000000000000000000000000000000003"; byte[] triggerData = TvmTestUtils.parseAbi("callcodeTest(address,uint256)", params); TvmTestUtils.triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData, 0, 1000000000, deposit, null); + contractAAddress, triggerData, 0, 1000000000, repository, null); /* ========== CALL numberForB() to check A's numberForB =================================== */ byte[] triggerData2 = TvmTestUtils.parseAbi("numberForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData2, 0, 1000000000, deposit, null); + contractAAddress, triggerData2, 0, 1000000000, repository, null); // A should be changed to 3 Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000003"); @@ -225,7 +229,7 @@ public void callCodeTest() byte[] triggerData3 = TvmTestUtils.parseAbi("senderForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractAAddress, triggerData3, 0, 1000000000, deposit, null); + contractAAddress, triggerData3, 0, 1000000000, repository, null); // A's senderForB should be changed to A's contract Address Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), Hex.toHexString(new DataWord(new DataWord(contractAAddress).getLast20Bytes()).getData())); @@ -234,7 +238,7 @@ public void callCodeTest() byte[] triggerData4 = TvmTestUtils.parseAbi("numberForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractBAddress, triggerData4, 0, 1000000000, deposit, null); + contractBAddress, triggerData4, 0, 1000000000, repository, null); // B's numberForB should not be changed Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -243,7 +247,7 @@ public void callCodeTest() byte[] triggerData5 = TvmTestUtils.parseAbi("senderForB()", ""); runtime = TvmTestUtils .triggerContractWholeProcessReturnContractAddress(Hex.decode(OWNER_ADDRESS), - contractBAddress, triggerData5, 0, 1000000000, deposit, null); + contractBAddress, triggerData5, 0, 1000000000, repository, null); // B 's senderForB should not be changed Assert.assertEquals(Hex.toHexString(runtime.getResult().getHReturn()), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -306,7 +310,7 @@ public byte[] deployAContractandGetItsAddress() byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, deposit, null); + feeLimit, consumeUserResourcePercent, libraryAddressPair, repository, null); return contractAddress; } @@ -343,7 +347,7 @@ public byte[] deployBContractAndGetItsAddress() byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, - feeLimit, consumeUserResourcePercent, libraryAddressPair, deposit, null); + feeLimit, consumeUserResourcePercent, libraryAddressPair, repository, null); return contractAddress; } @@ -355,11 +359,5 @@ public byte[] deployBContractAndGetItsAddress() public void destroy() { context.destroy(); Args.clearParam(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.warn("Release resources failure."); - } - } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/InterpreterTest.java b/framework/src/test/java/org/tron/common/runtime/vm/InterpreterTest.java index c2c5305df42..d54330b95fe 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/InterpreterTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/InterpreterTest.java @@ -54,14 +54,14 @@ public static void destroy() { @Test public void testVMException() throws ContractValidateException { - invoke = new ProgramInvokeMockImpl(); byte[] op = {0x5b, 0x60, 0x00, 0x56}; // 0x5b - JUMPTEST // 0x60 0x00 - PUSH 0x00 // 0x56 - JUMP to 0 Transaction trx = Transaction.getDefaultInstance(); InternalTransaction interTrx = new InternalTransaction(trx, TrxType.TRX_UNKNOWN_TYPE); - program = new Program(op, invoke, interTrx); + invoke = new ProgramInvokeMockImpl(op, op); + program = new Program(op, op, invoke, interTrx); boolean result = false; @@ -96,7 +96,8 @@ public void JumpSingleOperation() throws ContractValidateException { // 0x56 - JUMP Transaction trx = Transaction.getDefaultInstance(); InternalTransaction interTrx = new InternalTransaction(trx, TrxType.TRX_UNKNOWN_TYPE); - program = new Program(op, invoke, interTrx); + invoke = new ProgramInvokeMockImpl(op, op); + program = new Program(op, op, invoke, interTrx); boolean result = false; @@ -134,7 +135,8 @@ public void JumpToInvalidDestination() throws ContractValidateException { // 0x56 - JUMP Transaction trx = Transaction.getDefaultInstance(); InternalTransaction interTrx = new InternalTransaction(trx, TrxType.TRX_UNKNOWN_TYPE); - program = new Program(op, invoke, interTrx); + invoke = new ProgramInvokeMockImpl(op, op); + program = new Program(op, op, invoke, interTrx); boolean result = false; @@ -173,7 +175,8 @@ public void JumpToLargeNumberDestination() throws ContractValidateException { // 0x56 - JUMP Transaction trx = Transaction.getDefaultInstance(); InternalTransaction interTrx = new InternalTransaction(trx, TrxType.TRX_UNKNOWN_TYPE); - program = new Program(op, invoke, interTrx); + invoke = new ProgramInvokeMockImpl(op, op); + program = new Program(op, op, invoke, interTrx); boolean result = false; diff --git a/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java index cd5b6566646..94561e856f1 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/IsContractTest.java @@ -3,12 +3,13 @@ import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -16,7 +17,6 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class IsContractTest extends VMTestBase { @@ -170,7 +170,7 @@ public void testIsContract() null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( @@ -178,7 +178,7 @@ public void testIsContract() null); byte[] factoryAddressOther = WalletUtil.generateContractAddress(trx); String factoryAddressStrOther = StringUtil.encode58Check(factoryAddressOther); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: isTest(address) diff --git a/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java index 46445e92826..f6116dbe97d 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/IsSRCandidateTest.java @@ -3,12 +3,13 @@ import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.InternalTransaction; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; @@ -22,7 +23,6 @@ import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class IsSRCandidateTest extends VMTestBase { @@ -146,7 +146,7 @@ public void testIsSRCandidate() contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: isSRCandidateTest(address) @@ -174,7 +174,7 @@ public void testIsSRCandidate() System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - Program program = new Program(null, programInvoke, rootInternalTransaction); + Program program = new Program(null, null, programInvoke, rootInternalTransaction); byte[] programResult = program.isSRCandidate(new DataWord(nonexistentAddr)).getData(); Assert.assertEquals( Hex.toHexString(programResult), @@ -201,7 +201,7 @@ public void testIsSRCandidate() System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); programResult = program.isSRCandidate(new DataWord(factoryAddress)).getData(); Assert.assertEquals( Hex.toHexString(programResult), @@ -230,7 +230,7 @@ public void testIsSRCandidate() System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); programResult = program.isSRCandidate(new DataWord(witnessAddr)).getData(); Assert.assertEquals( Hex.toHexString(programResult), @@ -258,7 +258,7 @@ public void testIsSRCandidate() System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); programResult = program.isSRCandidate(new DataWord()).getData(); Assert.assertEquals( Hex.toHexString(programResult), diff --git a/framework/src/test/java/org/tron/common/runtime/vm/IstanbulTest.java b/framework/src/test/java/org/tron/common/runtime/vm/IstanbulTest.java index 015f0f0e5e2..1613eab53cd 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/IstanbulTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/IstanbulTest.java @@ -1,8 +1,8 @@ package org.tron.common.runtime.vm; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; @@ -71,7 +71,7 @@ public void istanbulSelfBalanceChainIdTest() contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, null); byte[] istanbulAddress = WalletUtil.generateContractAddress(tx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(tx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(tx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // SELFBALANCE Test @@ -217,7 +217,7 @@ public void altBn128AddMulEnergyChangeTest() contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, null); byte[] istanbulAddress = WalletUtil.generateContractAddress(tx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(tx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(tx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // bn128 add @@ -447,7 +447,7 @@ public void altBn128PairingEnergyChangeTest() contractName, address, abi, factoryCode, value, fee, consumeUserResourcePercent, null); byte[] istanbulAddress = WalletUtil.generateContractAddress(tx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(tx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(tx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // bn128 add diff --git a/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java b/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java index 0966d86710a..dbbf6921567 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/MemoryTest.java @@ -18,15 +18,15 @@ package org.tron.common.runtime.vm; -import static java.lang.Math.ceil; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertTrue; +import static org.tron.common.math.Maths.ceil; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.core.vm.program.Memory; @Slf4j @@ -43,7 +43,7 @@ private static void checkMemoryExtend(int dataSize) { } private static int calcSize(int dataSize, int chunkSize) { - return (int) ceil((double) dataSize / chunkSize) * chunkSize; + return (int) ceil((double) dataSize / chunkSize, true) * chunkSize; } @Test 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 abdf8d3db78..3315005b7d2 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,8 @@ import static org.junit.Assert.assertEquals; import java.util.List; +import java.util.Random; + import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; @@ -12,29 +14,36 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.util.StringUtils; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.InternalTransaction; +import org.tron.common.utils.DecodeUtil; +import org.tron.core.Constant; import org.tron.core.config.args.Args; import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.EnergyCost; import org.tron.core.vm.JumpTable; import org.tron.core.vm.Op; import org.tron.core.vm.Operation; import org.tron.core.vm.OperationRegistry; import org.tron.core.vm.VM; +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.invoke.ProgramInvokeMockImpl; import org.tron.protos.Protocol; @Slf4j -public class OperationsTest { +public class OperationsTest extends BaseTest { private ProgramInvokeMockImpl invoke; private Program program; - private final JumpTable jumpTable = OperationRegistry.newTronV1OperationSet(); + private final JumpTable jumpTable = OperationRegistry.getTable(); @BeforeClass public static void init() { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); CommonParameter.getInstance().setDebug(true); VMConfig.initAllowTvmTransferTrc10(1); VMConfig.initAllowTvmConstantinople(1); @@ -46,6 +55,8 @@ public static void init() { @AfterClass public static void destroy() { + ConfigLoader.disable = false; + VMConfig.initVmHardFork(false); Args.clearParam(); VMConfig.initAllowTvmTransferTrc10(0); VMConfig.initAllowTvmConstantinople(0); @@ -92,9 +103,12 @@ public void testStackOverFlow() { @SneakyThrows private Program buildEmptyContext(byte[] ops) { + StoreFactory.init(); + StoreFactory storeFactory = StoreFactory.getInstance(); + storeFactory.setChainBaseManager(chainBaseManager); Program context = new Program( - ops, - new ProgramInvokeMockImpl(), + ops, ops, + new ProgramInvokeMockImpl(storeFactory, ops, ops), new InternalTransaction( Protocol.Transaction.getDefaultInstance(), InternalTransaction.TrxType.TRX_UNKNOWN_TYPE)); @@ -112,77 +126,77 @@ public void testArithmeticOperations() throws ContractValidateException { // test ADD byte[] op = {0x60, 0x01, 0x60, 0x01, 0x01}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x02), program.getStack().pop()); // test MUL op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x02}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(11, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // test SUB op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x03}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test DIV op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x04}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(11, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x02), program.getStack().pop()); // test SDIV op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x05}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(11, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01),program.getStack().pop()); // test MOD op = new byte[]{0x60, 0x02, 0x60, 0x01, 0x06}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(11, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // test SMOD op = new byte[]{0x60, 0x02, 0x60, 0x01, 0x07}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(11, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // test ADDMOD op = new byte[]{0x60, 0x02, 0x60, 0x01, 0x60, 0x01, 0x08}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(17, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test MULMOD op = new byte[]{0x60, 0x02, 0x60, 0x01, 0x60, 0x01, 0x09}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(17, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // test EXP op = new byte[]{0x60, 0x02, 0x60, 0x02, 0x0a}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(26, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x04), program.getStack().pop()); // test SIGNEXTEND op = new byte[]{0x60, 0x02, 0x60, 0x02, 0x0b}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(11, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x02), program.getStack().pop()); @@ -198,98 +212,98 @@ public void testLogicAndComparisonOperations() throws ContractValidateException // test LT = 0x10 byte[] op = {0x60, 0x01, 0x60, 0x02, 0x10}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test GT = 0X11 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0X11}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // test SLT = 0X12 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0X12}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test SGT = 0X13 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0X13}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // test EQ = 0X14 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0X14}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test ISZERO = 0x15 op = new byte[]{0x60, 0x01, 0x15}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(6, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test AND = 0x16 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x16}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test OR = 0x17 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x17}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x03), program.getStack().pop()); // test XOR = 0x18 op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x18}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x03), program.getStack().pop()); // test NOT = 0x19 op = new byte[]{0x60, 0x00, 0x19}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(6, program.getResult().getEnergyUsed()); Assert.assertEquals((byte) (-0x01), program.getStack().pop().getData()[31]); // test BYTE = 0x1a op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x1a}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test SHL = 0x1b op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x1b}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x02), program.getStack().pop()); // test SHR = 0x1c op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x1c}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // test SAR = 0x1d op = new byte[]{0x60, 0x01, 0x60, 0x02, 0x1d}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); @@ -306,7 +320,7 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // test SHA3 = 0x20 byte[] op = {0x60, 0x01, 0x60, 0x01, 0x20}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(45, program.getResult().getEnergyUsed()); Assert.assertEquals("bc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a", @@ -314,21 +328,22 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // test ADDRESS = 0x30 op = new byte[]{0x30}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); - Assert.assertEquals(invoke.getContractAddress(), program.getStack().pop()); + Assert.assertArrayEquals(invoke.getContractAddress().getLast20Bytes(), + program.getStack().pop().getLast20Bytes()); // test ORIGIN = 0x32 op = new byte[]{0x32}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(invoke.getOriginAddress(), program.getStack().pop()); // test CALLER = 0x33 op = new byte[]{0x33}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(invoke.getCallerAddress().getLast20Bytes()), @@ -336,28 +351,28 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // CALLVALUE = 0x34 op = new byte[]{0x34}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(invoke.getCallValue(), program.getStack().pop()); // CALLDATALOAD = 0x35 op = new byte[]{0x60, 0x01, 0x35}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(6, program.getResult().getEnergyUsed()); Assert.assertEquals(invoke.getDataValue(new DataWord(0x01)), program.getStack().pop()); // CALLDATASIZE = 0x36 op = new byte[]{0x60, 0x01, 0x36}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(5, program.getResult().getEnergyUsed()); Assert.assertEquals(invoke.getDataSize(), program.getStack().pop()); // CALLDATACOPY = 0x37 op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x60, 0x01, 0x37}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(15, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(invoke.getDataCopy(new DataWord(0x01), @@ -366,14 +381,14 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // CODESIZE = 0x38 op = new byte[]{0x38}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); // CODECOPY = 0x39 op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x60, 0x01, 0x39}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(15, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), new DataWord( @@ -381,14 +396,14 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // RETURNDATASIZE = 0x3d op = new byte[]{0x3d}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // RETURNDATACOPY = 0x3e op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x60, 0x01, 0x3e}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(50, program.getResult().getEnergyUsed()); Assert.assertNull( @@ -396,7 +411,7 @@ public void testCryptographicAndEnvironmentalOperations() throws ContractValidat // GASPRICE = 0x3a op = new byte[]{0x3a}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0), program.getStack().pop()); @@ -412,7 +427,7 @@ public void testBlockInformationOperations() throws ContractValidateException { // BLOCKHASH = 0x40 byte[] op = {0x40}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); program.stackPush(new DataWord(33)); testOperations(program); Assert.assertEquals(20, program.getResult().getEnergyUsed()); @@ -420,7 +435,7 @@ public void testBlockInformationOperations() throws ContractValidateException { // COINBASE = 0x41 op = new byte[]{0x41}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(invoke.getCoinbase().getLast20Bytes()), @@ -428,28 +443,28 @@ public void testBlockInformationOperations() throws ContractValidateException { // TIMESTAMP = 0x42 op = new byte[]{0x42}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(invoke.getTimestamp(), program.getStack().pop()); // NUMBER = 0x43 op = new byte[]{0x43}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(invoke.getNumber(), program.getStack().pop()); // DIFFICULTY = 0x44 op = new byte[]{0x44}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0), program.getStack().pop()); // GASLIMIT = 0x45 op = new byte[]{0x45}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(2, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0), program.getStack().pop()); @@ -470,28 +485,28 @@ public void testMemoryStorageAndFlowOperations() throws ContractValidateExceptio // POP = 0x50 byte[] op = {0x60, 0x01, 0x50}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(5, program.getResult().getEnergyUsed()); Assert.assertEquals(0, program.getStack().size()); // MLOAD = 0x51 op = new byte[]{0x60, 0x01, 0x51}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); // MSTORE = 0x52 op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x52}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(12, program.getResult().getEnergyUsed()); Assert.assertEquals(64, program.getMemSize()); // MSTORE8 = 0x53 op = new byte[]{0x60, 0x01, 0x60, 0x01, 0x53}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed(), 41); Assert.assertEquals(32, program.getMemSize()); @@ -499,8 +514,10 @@ public void testMemoryStorageAndFlowOperations() throws ContractValidateExceptio // JUMP = 0x56 // JUMPI = 0x57 // JUMPDEST = 0x5b - program = new Program(compile( - "PUSH1 0x01 PUSH1 0x05 JUMPI JUMPDEST PUSH1 0xCC"), invoke, interTrx); + op = compile( + "PUSH1 0x01 PUSH1 0x05 JUMPI JUMPDEST PUSH1 0xCC"); + invoke = new ProgramInvokeMockImpl(op, op); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -512,21 +529,21 @@ public void testMemoryStorageAndFlowOperations() throws ContractValidateExceptio // PC = 0x58 op = new byte[]{0x60, 0x01, 0x60, 0x00, 0x58}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(8, program.getResult().getEnergyUsed()); Assert.assertEquals(5, program.getPC()); // MSIZE = 0x59 op = new byte[]{0x60, 0x01, 0x60, 0x00, 0x59}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(8, program.getResult().getEnergyUsed()); Assert.assertEquals(0, program.getMemSize()); // GAS = 0x5a op = new byte[]{0x60, 0x01, 0x60, 0x00, 0x5a}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(8, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x2a), program.getStack().pop()); @@ -559,7 +576,7 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { for (int j = 0; j <= i; j++) { op[j + 1] = 0x01; } - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(3, program.getResult().getEnergyUsed()); byte[] result = new byte[i + 1]; @@ -591,7 +608,7 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { op[2 * j] = 0x60; op[2 * j + 1] = (byte) i; } - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(3L * (i + 2), program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(i), program.getStack().pop()); @@ -619,7 +636,7 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { op[2 * (j + 1)] = 0x60; op[2 * (j + 1) + 1] = (byte) i; } - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals((3L * (i + 3)), program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); @@ -627,8 +644,9 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { // test log(0-4) invoke.setEnergyLimit(5000); - program = new Program(compile( - "PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH1 0x20 PUSH1 0x00 LOG0"), invoke, interTrx); + byte[] op = compile( + "PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH1 0x20 PUSH1 0x00 LOG0"); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -645,9 +663,9 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { .getData())); Assert.assertEquals(646, program.getResult().getEnergyUsed()); - program = new Program(compile( - "PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999 PUSH1 0x20 PUSH1 0x00 LOG1"), - invoke, interTrx); + op = compile( + "PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999 PUSH1 0x20 PUSH1 0x00 LOG1"); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -665,9 +683,9 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { .getData())); Assert.assertEquals(1024, program.getResult().getEnergyUsed()); - program = new Program(compile( - "PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999 PUSH2 0x6666 PUSH1 0x20 PUSH1 0x00 LOG2"), - invoke, interTrx); + op = compile( + "PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999 PUSH2 0x6666 PUSH1 0x20 PUSH1 0x00 LOG2"); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -686,8 +704,9 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { .getData())); Assert.assertEquals(1402, program.getResult().getEnergyUsed()); - program = new Program(compile("PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999" - + " PUSH2 0x6666 PUSH2 0x3333 PUSH1 0x20 PUSH1 0x00 LOG3"), invoke, interTrx); + op = compile("PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999" + + " PUSH2 0x6666 PUSH2 0x3333 PUSH1 0x20 PUSH1 0x00 LOG3"); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -707,8 +726,9 @@ public void testPushDupSwapAndLogOperations() throws ContractValidateException { .getData())); Assert.assertEquals(1780, program.getResult().getEnergyUsed()); - program = new Program(compile("PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999 PUSH2" - + " 0x6666 PUSH2 0x3333 PUSH2 0x5555 PUSH1 0x20 PUSH1 0x00 LOG4"), invoke, interTrx); + op = compile("PUSH2 0x1234 PUSH1 0x00 MSTORE PUSH2 0x9999 PUSH2" + + " 0x6666 PUSH2 0x3333 PUSH2 0x5555 PUSH1 0x20 PUSH1 0x00 LOG4"); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -738,14 +758,14 @@ public void testOtherOperations() throws ContractValidateException { // STOP = 0x00 byte[] op = {0x00}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(0, program.getResult().getEnergyUsed()); Assert.assertTrue(program.isStopped()); // return = 0xf3 op = new byte[]{0x60, 0x01, 0x60, 0x01, (byte) 0xf3}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(1, program.getResult().getHReturn().length); @@ -753,7 +773,7 @@ public void testOtherOperations() throws ContractValidateException { // revert = 0xfd op = new byte[]{0x60, 0x01, 0x60, 0x01, (byte) 0xfd}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(9, program.getResult().getEnergyUsed()); Assert.assertEquals(1, program.getResult().getHReturn().length); @@ -771,7 +791,7 @@ public void testComplexOperations() throws ContractValidateException { // test BALANCE = 0x31 byte[] op = new byte[]{0x31}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); program.stackPush(new DataWord("41471fd3ad3e9eeadeec4608b92d16ce6b500704cc")); testOperations(program); Assert.assertEquals(20, program.getResult().getEnergyUsed()); @@ -779,7 +799,7 @@ public void testComplexOperations() throws ContractValidateException { // SELFBALANCE = 0x47 op = new byte[]{0x47}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testOperations(program); Assert.assertEquals(5, program.getResult().getEnergyUsed()); Assert.assertEquals(new DataWord(0),program.getStack().pop()); @@ -792,9 +812,8 @@ public void testComplexOperations() throws ContractValidateException { invoke.getDeposit().putStorageValue(Hex.decode( "41471fd3ad3e9eeadeec4608b92d16ce6b500704cc"), new DataWord(0xCC), new DataWord(0x01)); - program = new Program( - compile("PUSH1 0x22 PUSH1 0xAA SSTORE PUSH1 0x33 PUSH1 0xCC SSTORE PUSH1 0xCC SLOAD"), - invoke, interTrx); + op = compile("PUSH1 0x22 PUSH1 0xAA SSTORE PUSH1 0x33 PUSH1 0xCC SSTORE PUSH1 0xCC SLOAD"); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -809,7 +828,7 @@ public void testComplexOperations() throws ContractValidateException { // EXTCODESIZE = 0x3b op = new byte[]{0x3b}; - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); program.stackPush(new DataWord("471fd3ad3e9eeadeec4608b92d16ce6b500704cc")); testOperations(program); Assert.assertEquals(20, program.getResult().getEnergyUsed()); @@ -817,7 +836,7 @@ public void testComplexOperations() throws ContractValidateException { // EXTCODECOPY = 0x3c op = Hex.decode("60036007600073471FD3AD3E9EEADEEC4608B92D16CE6B500704CC3C123456"); - program = new Program(op, invoke, interTrx); + program = new Program(op, op, invoke, interTrx); testSingleOperation(program); testSingleOperation(program); testSingleOperation(program); @@ -829,6 +848,205 @@ public void testComplexOperations() throws ContractValidateException { } + @Test + public void testPush0() throws ContractValidateException { + VMConfig.initAllowTvmShangHai(1); + + invoke = new ProgramInvokeMockImpl(); + Protocol.Transaction trx = Protocol.Transaction.getDefaultInstance(); + InternalTransaction interTrx = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + + byte[] op = new byte[1]; + op[0] = Op.PUSH0; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(EnergyCost.getBaseTierCost(null), program.getResult().getEnergyUsed()); + Assert.assertEquals(DataWord.ZERO(), program.getStack().pop()); + + VMConfig.initAllowTvmShangHai(0); + } + + @Test + public void testSuicideCost() throws ContractValidateException { + invoke = new ProgramInvokeMockImpl(StoreFactory.getInstance(), new byte[0], new byte[21]); + program = new Program(null, null, invoke, + new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE)); + + byte[] receiver1 = generateRandomAddress(); + program.stackPush(new DataWord(receiver1)); + Assert.assertEquals(0, EnergyCost.getSuicideCost(program)); + invoke.getDeposit().createAccount(receiver1, Protocol.AccountType.Normal); + Assert.assertEquals(0, EnergyCost.getSuicideCost(program)); + + byte[] receiver2 = generateRandomAddress(); + program.stackPush(new DataWord(receiver2)); + Assert.assertEquals(25000, EnergyCost.getSuicideCost2(program)); + invoke.getDeposit().createAccount(receiver2, Protocol.AccountType.Normal); + Assert.assertEquals(0, EnergyCost.getSuicideCost2(program)); + } + + @Test + public void testSuicideAction() throws ContractValidateException { + invoke = new ProgramInvokeMockImpl( + StoreFactory.getInstance(), + new byte[0], + Hex.decode("41471fd3ad3e9eeadeec4608b92d16ce6b500704cc")); + + program = new Program(null, null, invoke, + new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE)); + + VMConfig.initAllowEnergyAdjustment(1); + byte prePrefixByte = DecodeUtil.addressPreFixByte; + DecodeUtil.addressPreFixByte = Constant.ADD_PRE_FIX_BYTE_MAINNET; + + program.suicide(new DataWord( + dbManager.getAccountStore().getBlackhole().getAddress().toByteArray())); + + DecodeUtil.addressPreFixByte = prePrefixByte; + VMConfig.initAllowEnergyAdjustment(0); + } + + @Test + public void testVoteWitnessCost() throws ContractValidateException { + // Build stack environment, the stack from top to bottom is 0x00, 0x80, 0x00, 0x80 + program = new Program(null, null, new ProgramInvokeMockImpl(), + new InternalTransaction( + Protocol.Transaction.getDefaultInstance(), + InternalTransaction.TrxType.TRX_UNKNOWN_TYPE)); + program.stackPush(DataWord.of((byte) 0x80)); + program.stackPush(DataWord.of((byte) 0x00)); + program.stackPush(DataWord.of((byte) 0x80)); + program.stackPush(DataWord.of((byte) 0x00)); + + // Test VoteWitness before EnergyAdjustment, should not have memory expand energy + Assert.assertEquals(30000, EnergyCost.getVoteWitnessCost(program)); + + // Test VoteWitness after EnergyAdjustment, should have memory expand energy + VMConfig.initAllowEnergyAdjustment(1); + + long memWords = (0x80 + 32) / 32; + long memoryExpandEnergy = 3 * memWords + memWords * memWords / 512; + Assert.assertEquals(30000 + memoryExpandEnergy, EnergyCost.getVoteWitnessCost2(program)); + } + + @Test + public void testTransientStorageOperations() throws ContractValidateException { + VMConfig.initAllowTvmCancun(1); + + invoke = new ProgramInvokeMockImpl(); + invoke.setEnergyLimit(20000); + Protocol.Transaction trx = Protocol.Transaction.getDefaultInstance(); + InternalTransaction interTrx = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + + // TLOAD = 0x5c; + byte[] op = new byte[] {0x60, 0x01, 0x5c}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(103, program.getResult().getEnergyUsed()); + Assert.assertEquals(new DataWord(0x00), program.getStack().pop()); + + // TSTORE = 0x5d; + op = new byte[] {0x60, 0x01, 0x60, 0x01, 0x5d}; + + invoke.setStaticCall(true); + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(20000, program.getResult().getEnergyUsed()); + Assert.assertTrue(program.getResult().getException() + instanceof Program.StaticCallModificationException); + + invoke.setStaticCall(false); + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(106, program.getResult().getEnergyUsed()); + Assert.assertArrayEquals(new DataWord(0x01).getData(), + program.getContractState().getTransientStorageValue( + program.getContractAddress().getData(), new DataWord(0x01).getData())); + + op = new byte[] {0x60, 0x02, 0x60, 0x01, 0x5c, 0x16}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + + // TLOAD = 0x5c; + op = new byte[] {0x60, 0x01, 0x5c}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(103, program.getResult().getEnergyUsed()); + Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); + + VMConfig.initAllowTvmCancun(0); + } + + @Test + public void testMCOPY() throws ContractValidateException { + VMConfig.initAllowTvmCancun(1); + + invoke = new ProgramInvokeMockImpl(); + Protocol.Transaction trx = Protocol.Transaction.getDefaultInstance(); + InternalTransaction interTrx = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + + // MCOPY = 0x5e + byte[] op = new byte[] {0x60, 0x20, 0x60, 0x01, 0x60, 0x20, 0x5e}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(21, program.getResult().getEnergyUsed()); + Assert.assertEquals(64, program.getMemSize()); + + op = + new byte[] { + 0x60, 0x01, 0x60, 0x01, 0x52, 0x60, 0x20, 0x60, 0x01, 0x60, 0x20, 0x5e, 0x60, 0x20, 0x51}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(new DataWord(0x01), program.getStack().pop()); + + VMConfig.initAllowTvmCancun(0); + } + + @Test + public void testBlobHash() throws ContractValidateException { + VMConfig.initAllowTvmBlob(1); + + invoke = new ProgramInvokeMockImpl(); + Protocol.Transaction trx = Protocol.Transaction.getDefaultInstance(); + InternalTransaction interTrx = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + + // BLOBAHASH = 0x49 + byte[] op = new byte[] {0x60, 0x20, 0x49}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(6, program.getResult().getEnergyUsed()); + Assert.assertEquals(DataWord.ZERO(), program.getStack().pop()); + + VMConfig.initAllowTvmBlob(0); + } + + @Test + public void testBlobBaseFee() throws ContractValidateException { + VMConfig.initAllowTvmBlob(1); + + invoke = new ProgramInvokeMockImpl(); + Protocol.Transaction trx = Protocol.Transaction.getDefaultInstance(); + InternalTransaction interTrx = + new InternalTransaction(trx, InternalTransaction.TrxType.TRX_UNKNOWN_TYPE); + + // BLOBBASEFEE = 0x4a + byte[] op = new byte[] {0x60, 0x20, 0x4a}; + program = new Program(op, op, invoke, interTrx); + testOperations(program); + Assert.assertEquals(5, program.getResult().getEnergyUsed()); + Assert.assertEquals(DataWord.ZERO(), program.getStack().pop()); + + VMConfig.initAllowTvmBlob(0); + } + private void testOperations(Program program) { try { while (!program.isStopped()) { @@ -864,10 +1082,10 @@ private void testOperations(Program program) { } catch (Program.JVMStackOverFlowException | Program.OutOfTimeException e) { throw e; } catch (RuntimeException e) { - if (StringUtils.isEmpty(e.getMessage())) { - program.setRuntimeFailure(new RuntimeException("Unknown Exception")); - } else { + if (StringUtils.hasLength(e.getMessage())) { program.setRuntimeFailure(e); + } else { + program.setRuntimeFailure(new RuntimeException("Unknown Exception")); } } catch (StackOverflowError soe) { logger.info("\n !!! StackOverflowError: update your java run command with -Xss !!!\n", soe); @@ -904,10 +1122,10 @@ private void testSingleOperation(Program program) { } catch (Program.JVMStackOverFlowException | Program.OutOfTimeException e) { throw e; } catch (RuntimeException e) { - if (StringUtils.isEmpty(e.getMessage())) { - program.setRuntimeFailure(new RuntimeException("Unknown Exception")); - } else { + if (StringUtils.hasLength(e.getMessage())) { program.setRuntimeFailure(e); + } else { + program.setRuntimeFailure(new RuntimeException("Unknown Exception")); } } catch (StackOverflowError soe) { logger.info("\n !!! StackOverflowError: update your java run command with -Xss !!!\n", soe); @@ -919,4 +1137,10 @@ private byte[] compile(String code) { return new BytecodeCompiler().compile(code); } + private byte[] generateRandomAddress() { + byte[] address = new byte[21]; + new Random().nextBytes(address); + address[0] = DecodeUtil.addressPreFixByte; + return address; + } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java index fe658d7ab68..dce2cc7d105 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsTest.java @@ -1,69 +1,100 @@ package org.tron.common.runtime.vm; +import static org.tron.common.utils.ByteUtil.stripLeadingZeroes; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import static org.tron.core.db.TransactionTrace.convertToTronAddress; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.ProgramResult; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.Commons; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.actuator.FreezeBalanceActuator; import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; import org.tron.core.store.StoreFactory; import org.tron.core.vm.PrecompiledContracts; import org.tron.core.vm.PrecompiledContracts.PrecompiledContract; +import org.tron.core.vm.config.VMConfig; import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Proposal.State; import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; +import org.tron.protos.contract.Common; @Slf4j -public class PrecompiledContractsTest { +public class PrecompiledContractsTest extends BaseTest { // common private static final DataWord voteContractAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010001"); - private static final DataWord withdrawBalanceAddr = new DataWord( - "0000000000000000000000000000000000000000000000000000000000010004"); private static final DataWord proposalApproveAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010005"); private static final DataWord proposalCreateAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010006"); private static final DataWord proposalDeleteAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010007"); - private static final DataWord convertFromTronBytesAddressAddr = new DataWord( - "0000000000000000000000000000000000000000000000000000000000010008"); private static final DataWord convertFromTronBase58AddressAddr = new DataWord( "0000000000000000000000000000000000000000000000000000000000010009"); - private static final String dbPath = "output_PrecompiledContracts_test"; + + // FreezeV2 PrecompileContracts + private static final DataWord getChainParameterAddr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000b"); + + private static final DataWord availableUnfreezeV2SizeAddr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000c"); + + private static final DataWord unfreezableBalanceV2Addr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000d"); + + private static final DataWord expireUnfreezeBalanceV2Addr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000e"); + + private static final DataWord delegatableResourceAddr = new DataWord( + "000000000000000000000000000000000000000000000000000000000100000f"); + + private static final DataWord resourceV2Addr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000010"); + + private static final DataWord checkUnDelegateResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000011"); + + private static final DataWord resourceUsageAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000012"); + + private static final DataWord totalResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000013"); + + private static final DataWord totalDelegatedResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000014"); + + private static final DataWord totalAcquiredResourceAddr = new DataWord( + "0000000000000000000000000000000000000000000000000000000001000015"); + private static final String ACCOUNT_NAME = "account"; private static final String OWNER_ADDRESS; private static final String WITNESS_NAME = "witness"; @@ -72,43 +103,15 @@ public class PrecompiledContractsTest { private static final String URL = "https://tron.network/"; // withdraw private static final long initBalance = 10_000_000_000L; - private static final long allowance = 32_000_000L; - private static TronApplicationContext context; - private static Application appT; - private static Manager dbManager; + private static final long latestTimestamp = 1_000_000L; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; WITNESS_ADDRESS = Wallet.getAddressPreFixString() + WITNESS_ADDRESS_BASE; } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -141,7 +144,7 @@ public void createCapsule() { .put(ownerAccountFirstCapsule.getAddress().toByteArray(), ownerAccountFirstCapsule); dbManager.getWitnessStore().put(witnessCapsule.getAddress().toByteArray(), witnessCapsule); - dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1000000); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(latestTimestamp); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(10); dbManager.getDynamicPropertiesStore().saveNextMaintenanceTime(2000000); } @@ -285,7 +288,842 @@ public void proposalTest() { } @Test - public void convertFromTronBytesAddressNativeTest() { + public void tvmFreezeV2SwitchTest() { + VMConfig.initAllowTvmFreezeV2(0L); + + PrecompiledContract getChainParameterPcc = + PrecompiledContracts.getContractForAddress(getChainParameterAddr); + PrecompiledContract availableUnfreezeV2SizePcc = + PrecompiledContracts.getContractForAddress(availableUnfreezeV2SizeAddr); + PrecompiledContract unfreezableBalanceV2Pcc = + PrecompiledContracts.getContractForAddress(unfreezableBalanceV2Addr); + PrecompiledContract expireUnfreezeBalanceV2Pcc = + PrecompiledContracts.getContractForAddress(expireUnfreezeBalanceV2Addr); + + PrecompiledContract delegatableResourcePcc = + PrecompiledContracts.getContractForAddress(delegatableResourceAddr); + PrecompiledContract resourceV2Pcc = + PrecompiledContracts.getContractForAddress(resourceV2Addr); + PrecompiledContract checkUnDelegateResourcePcc = + PrecompiledContracts.getContractForAddress(checkUnDelegateResourceAddr); + + PrecompiledContract resourceUsagePcc = + PrecompiledContracts.getContractForAddress(resourceUsageAddr); + PrecompiledContract totalResourcePcc = + PrecompiledContracts.getContractForAddress(totalResourceAddr); + PrecompiledContract totalDelegatedResourcePcc = + PrecompiledContracts.getContractForAddress(totalDelegatedResourceAddr); + PrecompiledContract totalAcquiredResourcePcc = + PrecompiledContracts.getContractForAddress(totalAcquiredResourceAddr); + + Assert.assertNull(getChainParameterPcc); + Assert.assertNull(availableUnfreezeV2SizePcc); + Assert.assertNull(expireUnfreezeBalanceV2Pcc); + Assert.assertNull(unfreezableBalanceV2Pcc); + + Assert.assertNull(delegatableResourcePcc); + Assert.assertNull(resourceV2Pcc); + Assert.assertNull(checkUnDelegateResourcePcc); + + Assert.assertNull(resourceUsagePcc); + Assert.assertNull(totalResourcePcc); + Assert.assertNull(totalDelegatedResourcePcc); + Assert.assertNull(totalAcquiredResourcePcc); + + // enable TvmFreezeV2. + VMConfig.initAllowTvmFreezeV2(1L); + + getChainParameterPcc = + PrecompiledContracts.getContractForAddress(getChainParameterAddr); + availableUnfreezeV2SizePcc = + PrecompiledContracts.getContractForAddress(availableUnfreezeV2SizeAddr); + unfreezableBalanceV2Pcc = + PrecompiledContracts.getContractForAddress(unfreezableBalanceV2Addr); + expireUnfreezeBalanceV2Pcc = + PrecompiledContracts.getContractForAddress(expireUnfreezeBalanceV2Addr); + + delegatableResourcePcc = + PrecompiledContracts.getContractForAddress(delegatableResourceAddr); + resourceV2Pcc = + PrecompiledContracts.getContractForAddress(resourceV2Addr); + checkUnDelegateResourcePcc = + PrecompiledContracts.getContractForAddress(checkUnDelegateResourceAddr); + + resourceUsagePcc = + PrecompiledContracts.getContractForAddress(resourceUsageAddr); + totalResourcePcc = + PrecompiledContracts.getContractForAddress(totalResourceAddr); + totalDelegatedResourcePcc = + PrecompiledContracts.getContractForAddress(totalDelegatedResourceAddr); + totalAcquiredResourcePcc = + PrecompiledContracts.getContractForAddress(totalAcquiredResourceAddr); + + Assert.assertNotNull(getChainParameterPcc); + Assert.assertNotNull(availableUnfreezeV2SizePcc); + Assert.assertNotNull(expireUnfreezeBalanceV2Pcc); + Assert.assertNotNull(unfreezableBalanceV2Pcc); + + Assert.assertNotNull(delegatableResourcePcc); + Assert.assertNotNull(resourceV2Pcc); + Assert.assertNotNull(checkUnDelegateResourcePcc); + + Assert.assertNotNull(resourceUsagePcc); + Assert.assertNotNull(totalResourcePcc); + Assert.assertNotNull(totalDelegatedResourcePcc); + Assert.assertNotNull(totalAcquiredResourcePcc); + } + + @Test + public void delegatableResourceTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract delegatableResourcePcc = + createPrecompiledContract(delegatableResourceAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + delegatableResourcePcc.setRepository(tempRepository); + + byte[] owner = new DataWord(ByteArray.fromHexString(OWNER_ADDRESS)).getData(); + byte[] zero = DataWord.ZERO().getData(); + byte[] one = new DataWord(1).getData(); + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + + Pair res = delegatableResourcePcc.execute(null); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(res.getRight())); + + res = delegatableResourcePcc.execute(encodeMultiWord(one, zero)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(res.getRight())); + + res = delegatableResourcePcc.execute(encodeMultiWord(owner, owner)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + accountCapsule.setAcquiredDelegatedFrozenBalanceForEnergy(10_000_000L); + accountCapsule.addFrozenBalanceForBandwidthV2(5_000_000L); + accountCapsule.addFrozenBalanceForEnergyV2(10_000_000L); + + tempRepository.putAccountValue(address, accountCapsule); + + res = delegatableResourcePcc.execute(encodeMultiWord(owner, zero)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(5_000_000L, ByteArray.toLong(res.getRight())); + + res = delegatableResourcePcc.execute(encodeMultiWord(owner, one)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(10_000_000L, ByteArray.toLong(res.getRight())); + + // with usage. + byte[] TOTAL_ENERGY_CURRENT_LIMIT = "TOTAL_ENERGY_CURRENT_LIMIT".getBytes(); + + long energyLimit = 1_000_000_000_000L; + tempRepository.getDynamicPropertiesStore().put(TOTAL_ENERGY_CURRENT_LIMIT, + new BytesCapsule(ByteArray.fromLong(energyLimit))); + + long energyWeight = 1_000_000L; // unit: trx + tempRepository.saveTotalEnergyWeight(energyWeight); + + // used all energy, recovered 1/2, delegatable: 1/2 + accountCapsule.setEnergyUsage(20_000_000L); + + long currentSlot = latestTimestamp / 3_000; + accountCapsule.setLatestConsumeTimeForEnergy(0L); + + // recovered 1/4, usage_left: 15_000_000 + // use delegated first, 10_000_000 + // then, 5_000_000 is delegatable. + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot * 4); + tempRepository.putAccountValue(address, accountCapsule); + + res = delegatableResourcePcc.execute(encodeMultiWord(owner, one)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(5_000_000L, ByteArray.toLong(res.getRight())); + + // recovered 1/2, usage_left 10_000_000 + // use delegated first, 10_000_000 + // then all the FrozenBalanceForEnergyV2 is delegatable + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot * 2); + tempRepository.putAccountValue(address, accountCapsule); + + res = delegatableResourcePcc.execute(encodeMultiWord(owner, one)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(10_000_000L, ByteArray.toLong(res.getRight())); + + // all recovered. + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot); + tempRepository.putAccountValue(address, accountCapsule); + res = delegatableResourcePcc.execute(encodeMultiWord(owner, one)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(10_000_000L, ByteArray.toLong(res.getRight())); + + // all used. + accountCapsule.setLatestConsumeTimeForEnergy(currentSlot); + tempRepository.putAccountValue(address, accountCapsule); + res = delegatableResourcePcc.execute(encodeMultiWord(owner, one)); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(res.getRight())); + } + + @Test + public void checkUnDelegateResourceTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract checkUnDelegateResourcePcc = + createPrecompiledContract(checkUnDelegateResourceAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + checkUnDelegateResourcePcc.setRepository(tempRepository); + + byte[] TOTAL_ENERGY_CURRENT_LIMIT = "TOTAL_ENERGY_CURRENT_LIMIT".getBytes(); + + long energyLimit = 1_000_000_000_000L; + tempRepository.getDynamicPropertiesStore().put(TOTAL_ENERGY_CURRENT_LIMIT, + new BytesCapsule(ByteArray.fromLong(energyLimit))); + + long energyWeight = 1_000_000L; // unit: trx + tempRepository.saveTotalEnergyWeight(energyWeight); + + byte[] owner = new DataWord(ByteArray.fromHexString(OWNER_ADDRESS)).getData(); + byte[] zero = DataWord.ZERO().getData(); + byte[] one = new DataWord(1).getData(); + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + + Pair res = checkUnDelegateResourcePcc.execute(null); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals(encodeMultiWord(zero, zero, zero), res.getRight()); + + res = checkUnDelegateResourcePcc.execute(encodeMultiWord(one, one, one)); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals(encodeMultiWord(zero, zero, zero), res.getRight()); + + res = checkUnDelegateResourcePcc.execute( + encodeMultiWord(owner, ByteArray.fromLong(1_000_000L), ByteArray.fromLong(10L))); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals(encodeMultiWord(zero, zero, zero), res.getRight()); + + long defaultWindowSizeMs = 86_400_000L; + long currentSlot = latestTimestamp / 3_000; + long defaultLeftTime = (defaultWindowSizeMs - currentSlot * 3_000) / 1_000; + + res = checkUnDelegateResourcePcc.execute( + encodeMultiWord(owner, ByteArray.fromLong(1_000_000L), one)); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals( + encodeMultiWord(zero, zero, ByteArray.fromLong(defaultLeftTime)), + res.getRight()); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + accountCapsule.setLatestConsumeTimeForEnergy(0L); + accountCapsule.setAcquiredDelegatedFrozenBalanceForEnergy(10_000_000L); + accountCapsule.addFrozenBalanceForEnergyV2(10_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + + res = checkUnDelegateResourcePcc.execute( + encodeMultiWord(owner, ByteArray.fromLong(10_000_000L), one)); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals( + encodeMultiWord(ByteArray.fromLong(10_000_000L), zero, + ByteArray.fromLong(defaultLeftTime)), + res.getRight()); + + // with usage. + + // used all energy, recovered 1/2, + accountCapsule.setEnergyUsage(20_000_000L); + + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot * 2); + tempRepository.putAccountValue(address, accountCapsule); + + res = checkUnDelegateResourcePcc.execute( + encodeMultiWord(owner, ByteArray.fromLong(10_000_000L), one)); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals( + encodeMultiWord( + ByteArray.fromLong(5_000_000L), + ByteArray.fromLong(5_000_000L), + ByteArray.fromLong(currentSlot * 3)), res.getRight()); + + // all recovered. + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot); + tempRepository.putAccountValue(address, accountCapsule); + res = checkUnDelegateResourcePcc.execute( + encodeMultiWord(owner, ByteArray.fromLong(10_000_000L), one)); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals( + encodeMultiWord( + ByteArray.fromLong(10_000_000L), + ByteArray.fromLong(0L), + ByteArray.fromLong(0L)), res.getRight()); + + // all used. + accountCapsule.setLatestConsumeTimeForEnergy(currentSlot); + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot * 2); + tempRepository.putAccountValue(address, accountCapsule); + res = checkUnDelegateResourcePcc.execute( + encodeMultiWord(owner, ByteArray.fromLong(10_000_000L), one)); + Assert.assertTrue(res.getLeft()); + Assert.assertArrayEquals( + encodeMultiWord( + ByteArray.fromLong(0L), + ByteArray.fromLong(10_000_000L), + ByteArray.fromLong(2 * currentSlot * 3)), res.getRight()); + } + + + @Test + public void getChainParameterTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract getChainParameterPcc = + createPrecompiledContract(getChainParameterAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + getChainParameterPcc.setRepository(tempRepository); + + byte[] TOTAL_NET_LIMIT = "TOTAL_NET_LIMIT".getBytes(); + byte[] TOTAL_ENERGY_CURRENT_LIMIT = "TOTAL_ENERGY_CURRENT_LIMIT".getBytes(); + byte[] UNFREEZE_DELAY_DAYS = "UNFREEZE_DELAY_DAYS".getBytes(); + + DataWord totalNetLimitId = new DataWord( + "0000000000000000000000000000000000000000000000000000000000000001"); + + DataWord totalNetWeightId = new DataWord( + "0000000000000000000000000000000000000000000000000000000000000002"); + + DataWord totalEnergyCurrentLimitId = new DataWord( + "0000000000000000000000000000000000000000000000000000000000000003"); + + DataWord totalEnergyWeightId = new DataWord( + "0000000000000000000000000000000000000000000000000000000000000004"); + + DataWord unfreezeDelayDaysId = new DataWord( + "0000000000000000000000000000000000000000000000000000000000000005"); + + DataWord invalidId = new DataWord( + "0000000000000000000000000000000000000000000000000000000000FFFFFF"); + + long netLimit = 90_000_000_000_000_000L; + tempRepository.getDynamicPropertiesStore().put(TOTAL_NET_LIMIT, + new BytesCapsule(ByteArray.fromLong(netLimit))); + Pair totalNetLimitRes = + getChainParameterPcc.execute(totalNetLimitId.getData()); + Assert.assertTrue(totalNetLimitRes.getLeft()); + Assert.assertEquals(ByteArray.toLong(totalNetLimitRes.getRight()), netLimit); + + long netWeight = 10_000_000_000L; + tempRepository.saveTotalNetWeight(netWeight); + Pair totalNetWeightRes = + getChainParameterPcc.execute(totalNetWeightId.getData()); + Assert.assertTrue(totalNetWeightRes.getLeft()); + Assert.assertEquals(ByteArray.toLong(totalNetWeightRes.getRight()), netWeight); + + long energyLimit = 9_000_000_000_000_000L; + tempRepository.getDynamicPropertiesStore().put(TOTAL_ENERGY_CURRENT_LIMIT, + new BytesCapsule(ByteArray.fromLong(energyLimit))); + Pair totalEnergyCurrentLimitRes = + getChainParameterPcc.execute(totalEnergyCurrentLimitId.getData()); + Assert.assertTrue(totalEnergyCurrentLimitRes.getLeft()); + Assert.assertEquals(ByteArray.toLong(totalEnergyCurrentLimitRes.getRight()), energyLimit); + + long energyWeight = 1_000_000_000L; + tempRepository.saveTotalEnergyWeight(energyWeight); + Pair totalEnergyWeightRes = + getChainParameterPcc.execute(totalEnergyWeightId.getData()); + Assert.assertTrue(totalEnergyWeightRes.getLeft()); + Assert.assertEquals(ByteArray.toLong(totalEnergyWeightRes.getRight()), energyWeight); + + long delayDays = 3L; + tempRepository.getDynamicPropertiesStore().put(UNFREEZE_DELAY_DAYS, + new BytesCapsule(ByteArray.fromLong(delayDays))); + Pair delayDaysRes = + getChainParameterPcc.execute(unfreezeDelayDaysId.getData()); + Assert.assertTrue(delayDaysRes.getLeft()); + Assert.assertEquals(ByteArray.toLong(delayDaysRes.getRight()), delayDays); + + long zero = 0L; + Pair invalidParamRes = getChainParameterPcc.execute(invalidId.getData()); + Assert.assertTrue(invalidParamRes.getLeft()); + Assert.assertEquals(ByteArray.toLong(invalidParamRes.getRight()), zero); + + } + + @Test + public void availableUnfreezeV2SizeTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract availableUnfreezeV2SizePcc = + createPrecompiledContract(availableUnfreezeV2SizeAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + availableUnfreezeV2SizePcc.setRepository(tempRepository); + + byte[] data = new DataWord(ByteArray.fromHexString(OWNER_ADDRESS)).getData(); + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + + Pair res = availableUnfreezeV2SizePcc.execute(data); + + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(32L, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + accountCapsule.addUnfrozenV2List( + Common.ResourceCode.BANDWIDTH, 1_000_000L, latestTimestamp + 86_400_000L); + accountCapsule.addUnfrozenV2List( + Common.ResourceCode.ENERGY, 1_000_000L, latestTimestamp + 86_400_000L); + + tempRepository.putAccountValue(address, accountCapsule); + res = availableUnfreezeV2SizePcc.execute(data); + + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(30L, ByteArray.toLong(res.getRight())); + + // expired unfreeze action, available size keep the same. + accountCapsule.addUnfrozenV2List( + Common.ResourceCode.ENERGY, 1_000_000L, latestTimestamp - 100_000L); + + tempRepository.putAccountValue(address, accountCapsule); + res = availableUnfreezeV2SizePcc.execute(data); + + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(30L, ByteArray.toLong(res.getRight())); + } + + @Test + public void unfreezableBalanceV2Test() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract unfreezableBalanceV2Pcc = + createPrecompiledContract(unfreezableBalanceV2Addr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + unfreezableBalanceV2Pcc.setRepository(tempRepository); + + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] address32 = new DataWord(address).getData(); + byte[] type = ByteUtil.longTo32Bytes(0); + byte[] data = ByteUtil.merge(address32, type); + + Pair res = unfreezableBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + accountCapsule.addFrozenBalanceForBandwidthV2(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = unfreezableBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + accountCapsule.addFrozenBalanceForBandwidthV2(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = unfreezableBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(2_000_000L, ByteArray.toLong(res.getRight())); + + type = ByteUtil.longTo32Bytes(1); + data = ByteUtil.merge(address32, type); + accountCapsule.addFrozenBalanceForEnergyV2(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = unfreezableBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + type = ByteUtil.longTo32Bytes(2); + data = ByteUtil.merge(address32, type); + accountCapsule.addFrozenForTronPowerV2(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = unfreezableBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + // new test round + tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + unfreezableBalanceV2Pcc.setRepository(tempRepository); + + byte[] owner = new DataWord(ByteArray.fromHexString(OWNER_ADDRESS)).getData(); + byte[] zero = DataWord.ZERO().getData(); + byte[] one = new DataWord(1).getData(); + + Pair result = unfreezableBalanceV2Pcc.execute(null); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(result.getRight())); + + result = unfreezableBalanceV2Pcc.execute(encodeMultiWord(one, zero)); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(result.getRight())); + + result = unfreezableBalanceV2Pcc.execute(encodeMultiWord(owner, owner)); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(result.getRight())); + + AccountCapsule capsule = tempRepository.getAccount(address); + capsule.addFrozenBalanceForBandwidthV2(5_000_000L); + capsule.addFrozenBalanceForEnergyV2(10_000_000L); + + tempRepository.putAccountValue(address, capsule); + + result = unfreezableBalanceV2Pcc.execute(encodeMultiWord(owner, zero)); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(5_000_000L, ByteArray.toLong(result.getRight())); + + result = unfreezableBalanceV2Pcc.execute(encodeMultiWord(owner, one)); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(10_000_000L, ByteArray.toLong(result.getRight())); + } + + @Test + public void expireUnfreezeBalanceV2Test() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract expireUnfreezeBalanceV2Pcc = + createPrecompiledContract(expireUnfreezeBalanceV2Addr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + expireUnfreezeBalanceV2Pcc.setRepository(tempRepository); + long now = dbManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] address32 = new DataWord(address).getData(); + byte[] time = ByteUtil.longTo32Bytes(now / 1000); + byte[] data = ByteUtil.merge(address32, time); + + Pair res = expireUnfreezeBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + Protocol.Account.UnFreezeV2 unFreezeV2 = + Protocol.Account.UnFreezeV2.newBuilder() + .setType(Common.ResourceCode.BANDWIDTH) + .setUnfreezeExpireTime(now) + .setUnfreezeAmount(1_000_000L) + .build(); + accountCapsule.addUnfrozenV2(unFreezeV2); + tempRepository.putAccountValue(address, accountCapsule); + res = expireUnfreezeBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + unFreezeV2 = + Protocol.Account.UnFreezeV2.newBuilder() + .setType(Common.ResourceCode.ENERGY) + .setUnfreezeExpireTime(now) + .setUnfreezeAmount(1_000_000L) + .build(); + accountCapsule.addUnfrozenV2(unFreezeV2); + tempRepository.putAccountValue(address, accountCapsule); + res = expireUnfreezeBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(2_000_000L, ByteArray.toLong(res.getRight())); + + unFreezeV2 = + Protocol.Account.UnFreezeV2.newBuilder() + .setType(Common.ResourceCode.TRON_POWER) + .setUnfreezeExpireTime(now + 1_000_000L) + .setUnfreezeAmount(1_000_000L) + .build(); + accountCapsule.addUnfrozenV2(unFreezeV2); + tempRepository.putAccountValue(address, accountCapsule); + res = expireUnfreezeBalanceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(2_000_000L, ByteArray.toLong(res.getRight())); + + // new test round + tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + expireUnfreezeBalanceV2Pcc.setRepository(tempRepository); + + byte[] owner = new DataWord(ByteArray.fromHexString(OWNER_ADDRESS)).getData(); + address = ByteArray.fromHexString(OWNER_ADDRESS); + + Pair result = expireUnfreezeBalanceV2Pcc.execute(null); + + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(result.getRight())); + + result = expireUnfreezeBalanceV2Pcc.execute( + encodeMultiWord(DataWord.ZERO().getData(), DataWord.ZERO().getData())); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(result.getRight())); + + result = expireUnfreezeBalanceV2Pcc.execute( + encodeMultiWord(owner, new DataWord(latestTimestamp / 1_000L).getData())); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(0L, ByteArray.toLong(result.getRight())); + + accountCapsule = tempRepository.getAccount(address); + accountCapsule.addUnfrozenV2List( + Common.ResourceCode.BANDWIDTH, 1_000_000L, latestTimestamp); + accountCapsule.addUnfrozenV2List( + Common.ResourceCode.ENERGY, 1_000_000L, latestTimestamp + 86_400_000L); + + tempRepository.putAccountValue(address, accountCapsule); + + result = expireUnfreezeBalanceV2Pcc.execute( + encodeMultiWord(owner, new DataWord(latestTimestamp / 1_000L).getData())); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(result.getRight())); + + result = expireUnfreezeBalanceV2Pcc.execute( + encodeMultiWord(owner, new DataWord((latestTimestamp + 86_400_000L) / 1_000L).getData())); + Assert.assertTrue(result.getLeft()); + Assert.assertEquals(2_000_000L, ByteArray.toLong(result.getRight())); + } + + @Test + public void resourceV2Test() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract resourceV2Pcc = + createPrecompiledContract(resourceV2Addr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + resourceV2Pcc.setRepository(tempRepository); + + String targetStr = "27k66nycZATHzBasFT9782nTsYWqVtxdtAc"; + byte[] targetAddr = Commons.decode58Check(targetStr); + byte[] target = new DataWord(targetAddr).getData(); + String fromStr = "27jzp7nVEkH4Hf3H1PHPp4VDY7DxTy5eydL"; + byte[] fromAddr = Commons.decode58Check(fromStr); + byte[] from = new DataWord(fromAddr).getData(); + byte[] type = ByteUtil.longTo32Bytes(0); + byte[] data = ByteUtil.merge(target, from, type); + + Pair res = resourceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule fromAccount = + tempRepository.createAccount(fromAddr, Protocol.AccountType.Normal); + fromAccount.addFrozenBalanceForBandwidthV2(1_000_000L); + tempRepository.putAccountValue(fromAddr, fromAccount); + data = ByteUtil.merge(from, from, type); + res = resourceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + data = ByteUtil.merge(from, from, ByteUtil.longTo32Bytes(1)); + res = resourceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule targetAccount = + tempRepository.createAccount(target, Protocol.AccountType.Normal); + byte[] key = DelegatedResourceCapsule.createDbKeyV2(fromAddr, targetAddr, false); + DelegatedResourceCapsule delegatedResource = + new DelegatedResourceCapsule( + ByteString.copyFrom(fromAddr), ByteString.copyFrom(targetAddr)); + delegatedResource.setFrozenBalanceForBandwidth(1_000_000L, 0); + tempRepository.updateDelegatedResource(key, delegatedResource); + targetAccount.addAcquiredDelegatedFrozenBalanceForBandwidth(1_000_000L); + fromAccount.addDelegatedFrozenBalanceForBandwidth(1_000_000L); + tempRepository.putAccountValue(fromAddr, fromAccount); + tempRepository.putAccountValue(targetAddr, targetAccount); + data = ByteUtil.merge(target, from, type); + res = resourceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + data = ByteUtil.merge(from, from, ByteUtil.longTo32Bytes(1)); + res = resourceV2Pcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + } + + @Test + public void resourceUsageTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract resourceUsagePcc = + createPrecompiledContract(resourceUsageAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + resourceUsagePcc.setRepository(tempRepository); + + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] address32 = new DataWord(address).getData(); + byte[] type = ByteUtil.longTo32Bytes(0); + byte[] data = ByteUtil.merge(address32, type); + + Pair res = resourceUsagePcc.execute(data); + Assert.assertTrue(res.getLeft()); + byte[] usage = Arrays.copyOfRange(res.getRight(), 0, 32); + Assert.assertEquals(0, ByteArray.toLong(usage)); + + // with usage. + byte[] TOTAL_ENERGY_CURRENT_LIMIT = "TOTAL_ENERGY_CURRENT_LIMIT".getBytes(); + + long energyLimit = 1_000_000_000_000L; + tempRepository.getDynamicPropertiesStore().put(TOTAL_ENERGY_CURRENT_LIMIT, + new BytesCapsule(ByteArray.fromLong(energyLimit))); + + long energyWeight = 1_000_000L; // unit: trx + tempRepository.saveTotalEnergyWeight(energyWeight); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + // used all energy, recovered 1/2, delegatable: 1/2 + accountCapsule.setEnergyUsage(20_000_000L); + + long currentSlot = latestTimestamp / 3_000; + accountCapsule.setLatestConsumeTimeForEnergy(0L); + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot * 2); + tempRepository.putAccountValue(address, accountCapsule); + + type = ByteUtil.longTo32Bytes(1); + res = resourceUsagePcc.execute(encodeMultiWord(address32, type)); + Assert.assertTrue(res.getLeft()); + usage = Arrays.copyOfRange(res.getRight(), 0, 32); + byte[] recoverDuration = Arrays.copyOfRange(res.getRight(), 32, 64); + Assert.assertEquals(10_000_000L, ByteArray.toLong(usage)); + Assert.assertEquals( + currentSlot * BLOCK_PRODUCED_INTERVAL / 1000, ByteArray.toLong(recoverDuration)); + + accountCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, currentSlot); + tempRepository.putAccountValue(address, accountCapsule); + res = resourceUsagePcc.execute(encodeMultiWord(address32, type)); + Assert.assertTrue(res.getLeft()); + usage = Arrays.copyOfRange(res.getRight(), 0, 32); + recoverDuration = Arrays.copyOfRange(res.getRight(), 32, 64); + Assert.assertEquals(0, ByteArray.toLong(usage)); + Assert.assertEquals(0, ByteArray.toLong(recoverDuration)); + + accountCapsule.setLatestConsumeTimeForEnergy(currentSlot); + tempRepository.putAccountValue(address, accountCapsule); + res = resourceUsagePcc.execute(encodeMultiWord(address32, type)); + Assert.assertTrue(res.getLeft()); + usage = Arrays.copyOfRange(res.getRight(), 0, 32); + recoverDuration = Arrays.copyOfRange(res.getRight(), 32, 64); + Assert.assertEquals(20_000_000L, ByteArray.toLong(usage)); + Assert.assertEquals( + currentSlot * BLOCK_PRODUCED_INTERVAL / 1000, ByteArray.toLong(recoverDuration)); + } + + @Test + public void totalResourceTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract totalResourcePcc = + createPrecompiledContract(totalResourceAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + totalResourcePcc.setRepository(tempRepository); + + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] address32 = new DataWord(address).getData(); + byte[] type = ByteUtil.longTo32Bytes(0); + byte[] data = ByteUtil.merge(address32, type); + + Pair res = totalResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + tempRepository.putAccountValue(address, accountCapsule); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + accountCapsule = tempRepository.getAccount(address); + accountCapsule.addFrozenBalanceForBandwidthV2(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = totalResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + accountCapsule.addAcquiredDelegatedFrozenBalanceForBandwidth(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = totalResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(2_000_000L, ByteArray.toLong(res.getRight())); + + accountCapsule.addFrozenBalanceForEnergyV2(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + type = ByteUtil.longTo32Bytes(1); + data = ByteUtil.merge(address32, type); + res = totalResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + res = totalResourcePcc.execute(ByteUtil.merge(address32, ByteUtil.longTo32Bytes(2))); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + } + + @Test + public void totalDelegatedResourceTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract totalDelegatedResourcePcc = + createPrecompiledContract(totalDelegatedResourceAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + totalDelegatedResourcePcc.setRepository(tempRepository); + + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] address32 = new DataWord(address).getData(); + byte[] type = ByteUtil.longTo32Bytes(0); + byte[] data = ByteUtil.merge(address32, type); + + Pair res = totalDelegatedResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + tempRepository.putAccountValue(address, accountCapsule); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + accountCapsule = tempRepository.getAccount(address); + accountCapsule.addDelegatedFrozenBalanceForBandwidth(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = totalDelegatedResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + accountCapsule.addDelegatedFrozenBalanceForEnergy(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + type = ByteUtil.longTo32Bytes(1); + data = ByteUtil.merge(address32, type); + res = totalDelegatedResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + res = totalDelegatedResourcePcc.execute(ByteUtil.merge(address32, ByteUtil.longTo32Bytes(2))); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + } + + @Test + public void totalAcquiredResourceTest() { + VMConfig.initAllowTvmFreezeV2(1L); + + PrecompiledContract totalAcquiredResourcePcc = + createPrecompiledContract(totalAcquiredResourceAddr, OWNER_ADDRESS); + Repository tempRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + totalAcquiredResourcePcc.setRepository(tempRepository); + + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] address32 = new DataWord(address).getData(); + byte[] type = ByteUtil.longTo32Bytes(0); + byte[] data = ByteUtil.merge(address32, type); + + Pair res = totalAcquiredResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + AccountCapsule accountCapsule = tempRepository.getAccount(address); + tempRepository.putAccountValue(address, accountCapsule); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); + + accountCapsule = tempRepository.getAccount(address); + accountCapsule.addAcquiredDelegatedFrozenBalanceForBandwidth(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + res = totalAcquiredResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + accountCapsule.addAcquiredDelegatedFrozenBalanceForEnergy(1_000_000L); + tempRepository.putAccountValue(address, accountCapsule); + type = ByteUtil.longTo32Bytes(1); + data = ByteUtil.merge(address32, type); + res = totalAcquiredResourcePcc.execute(data); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(1_000_000L, ByteArray.toLong(res.getRight())); + + res = totalAcquiredResourcePcc.execute(ByteUtil.merge(address32, ByteUtil.longTo32Bytes(2))); + Assert.assertTrue(res.getLeft()); + Assert.assertEquals(0, ByteArray.toLong(res.getRight())); } //@Test @@ -308,4 +1146,23 @@ public void convertFromTronBase58AddressNative() { new DataWord(Hex.decode(WITNESS_ADDRESS_BASE)).getData()); } + private static byte[] encodeMultiWord(byte[]... words) { + if (words == null) { + return null; + } + if (words.length == 1) { + return words[0]; + } + + byte[] res = new byte[words.length * 32]; + + for (int i = 0; i < words.length; i++) { + byte[] word = stripLeadingZeroes(words[i]); + + System.arraycopy(word, 0, res, 32 * (i + 1) - word.length, word.length); + } + + return res; + } + } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java index 8be1ebf88df..27e7891e6d8 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/PrecompiledContractsVerifyProofTest.java @@ -1,38 +1,39 @@ package org.tron.common.runtime.vm; +import static org.junit.Assert.assertNotNull; +import static org.tron.common.math.Maths.random; +import static org.tron.common.math.Maths.round; + import com.google.protobuf.ByteString; -import java.io.File; import java.math.BigInteger; import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.client.WalletClient; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; import org.tron.common.zksnark.LibrustzcashParam; import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.PedersenHashCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.vm.PrecompiledContracts.MerkleHash; import org.tron.core.vm.PrecompiledContracts.VerifyBurnProof; import org.tron.core.vm.PrecompiledContracts.VerifyMintProof; import org.tron.core.vm.PrecompiledContracts.VerifyTransferProof; import org.tron.core.zen.ShieldedTRC20ParametersBuilder; import org.tron.core.zen.ShieldedTRC20ParametersBuilder.ShieldedTRC20ParametersType; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; import org.tron.core.zen.address.FullViewingKey; @@ -42,55 +43,29 @@ import org.tron.core.zen.note.Note; import org.tron.keystore.Wallet; import org.tron.protos.contract.ShieldContract; -import stest.tron.wallet.common.client.WalletClient; @Slf4j -public class PrecompiledContractsVerifyProofTest { +public class PrecompiledContractsVerifyProofTest extends BaseTest { - private static final String dbPath = "output_PrecompiledContracts_VerifyProof_test"; private static final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; - private static final byte[] SHIELDED_CONTRACT_ADDRESS; + private static byte[] SHIELDED_CONTRACT_ADDRESS; private static final String PUBLIC_TO_ADDRESS_STR = "TBaBXpRAeBhs75TZT751LwyhrcR25XeUot"; - private static final byte[] PUBLIC_TO_ADDRESS; - private static final byte[] DEFAULT_OVK; - private static TronApplicationContext context; - private static Manager dbManager; - - static { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-test.conf"); - context = new TronApplicationContext(DefaultConfig.class); - DEFAULT_OVK = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); - PUBLIC_TO_ADDRESS = WalletClient.decodeFromBase58Check(PUBLIC_TO_ADDRESS_STR); - FullNodeHttpApiService.librustzcashInitZksnarkParams(); - } + private static byte[] PUBLIC_TO_ADDRESS; + private static byte[] DEFAULT_OVK; VerifyMintProof mintContract = new VerifyMintProof(); VerifyTransferProof transferContract = new VerifyTransferProof(); VerifyBurnProof burnContract = new VerifyBurnProof(); MerkleHash merkleHash = new MerkleHash(); - /** - * Init data. - */ @BeforeClass public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[]{"--output-directory", dbPath()}, "config-test.conf"); + DEFAULT_OVK = ByteArray + .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); + SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); + PUBLIC_TO_ADDRESS = WalletClient.decodeFromBase58Check(PUBLIC_TO_ADDRESS_STR); + ZksnarkInitService.librustzcashInitZksnarkParams(); } @Test @@ -110,7 +85,8 @@ public void verifyMintProofCorrect() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -152,9 +128,10 @@ public void verifyTransferProofCorrect() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -242,14 +219,16 @@ public void verifyTransferProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -308,8 +287,8 @@ public void verifyTransfer1v1ProofCorrect() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -358,7 +337,8 @@ public void verifyTransfer1v1ProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 100, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -413,8 +393,8 @@ public void verifyBurnWithCmCorrect() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -464,7 +444,8 @@ public void verifyBurnWithCmCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 50, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -519,8 +500,8 @@ public void verifyTransfer1v2ProofCorrect() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -569,14 +550,16 @@ public void verifyTransfer1v2ProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -637,9 +620,10 @@ public void verifyTransfer2v1ProofCorrect() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -727,7 +711,8 @@ public void verifyTransfer2v1ProofCorrect() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 100, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -780,12 +765,11 @@ public void verifyBurnProofCorrect() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -861,7 +845,8 @@ public void merkleHashCorrectTest() throws ZksnarkException { IncomingViewingKey ivk = fvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress paymentAddress = ivk.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = ivk.address(DiversifierT.random()).orElse(null); + assertNotNull(paymentAddress); Note note = new Note(paymentAddress.getD(), paymentAddress.getPkD(), randomLong(), rcm, new byte[512]); byte[] node = note.cm(); @@ -898,8 +883,8 @@ public void verifyBurnWithCmWrong() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm1); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(100)); @@ -949,7 +934,7 @@ public void verifyBurnWithCmWrong() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 50, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1019,7 +1004,7 @@ public void verifyMintWrongDataLength() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1045,9 +1030,10 @@ public void verifyTransferWrongDataLength() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1082,14 +1068,14 @@ public void verifyTransferWrongDataLength() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1110,8 +1096,8 @@ public void verifyBurnWrongDataLength() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.BURN); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1155,7 +1141,8 @@ public void verifyMintWrongLeafcount() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1181,9 +1168,10 @@ public void verifyTransferWrongLeafcount() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); for (long leafCount : leafCountList) { ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); @@ -1218,14 +1206,14 @@ public void verifyTransferWrongLeafcount() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1249,8 +1237,8 @@ public void verifyTransferDuplicateNf() throws ZksnarkException { IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1275,14 +1263,14 @@ public void verifyTransferDuplicateNf() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1307,9 +1295,10 @@ public void verifyTransferDuplicateReceiveNotes() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.TRANSFER); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1344,7 +1333,8 @@ public void verifyTransferDuplicateReceiveNotes() throws ZksnarkException { SpendingKey receiveSk = SpendingKey.random(); FullViewingKey receiveFvk = receiveSk.fullViewingKey(); IncomingViewingKey receiveIvk = receiveFvk.inViewingKey(); - PaymentAddress receivePaymentAddress = receiveIvk.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress = receiveIvk.address(new DiversifierT()).orElse(null); + assertNotNull(receivePaymentAddress); byte[] r = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(r); builder.addOutput(senderOvk, receivePaymentAddress.getD(), receivePaymentAddress.getPkD(), @@ -1376,7 +1366,8 @@ public void verifyMintWrongValue() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, 50, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1394,12 +1385,11 @@ public void verifyBurnWrongValue() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder(); builder.setShieldedTRC20ParametersType(ShieldedTRC20ParametersType.BURN); builder.setShieldedTRC20Address(SHIELDED_CONTRACT_ADDRESS); @@ -1443,7 +1433,8 @@ public void verifyMintProofWrongCM() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1473,7 +1464,8 @@ public void verifyMintProofWrongCV() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1502,7 +1494,8 @@ public void verifyMintProofWrongEpk() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1531,7 +1524,8 @@ public void verifyMintProofWrongProof() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1560,7 +1554,8 @@ public void verifyMintProofWrongBindingSignature() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1589,7 +1584,8 @@ public void verifyMintProofWrongHash() throws ZksnarkException { SpendingKey recvSk = SpendingKey.random(); FullViewingKey fullViewingKey = recvSk.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); + PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()) + .orElse(null); builder.addOutput(DEFAULT_OVK, paymentAddress, value, new byte[512]); ShieldedTRC20Parameters params = builder.build(false); @@ -1619,9 +1615,10 @@ public void verifyTransferProofWrongNf() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -1707,14 +1704,16 @@ public void verifyTransferProofWrongNf() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1745,9 +1744,10 @@ public void verifyTransferProofWrongRoot() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -1833,14 +1833,16 @@ public void verifyTransferProofWrongRoot() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1872,9 +1874,10 @@ public void verifyTransferProofWrongSpendCV() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -1960,14 +1963,16 @@ public void verifyTransferProofWrongSpendCV() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -1998,9 +2003,10 @@ public void verifyTransferProofWrongRk() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2086,14 +2092,16 @@ public void verifyTransferProofWrongRk() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2124,9 +2132,10 @@ public void verifyTransferProofWrongSpendProof() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2212,14 +2221,16 @@ public void verifyTransferProofWrongSpendProof() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2250,9 +2261,10 @@ public void verifyTransferProofWrongCm() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2338,14 +2350,16 @@ public void verifyTransferProofWrongCm() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2376,9 +2390,10 @@ public void verifyTransferProofWrongReceiveCV() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2464,14 +2479,16 @@ public void verifyTransferProofWrongReceiveCV() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2502,9 +2519,10 @@ public void verifyTransferProofWrongEpk() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2590,14 +2608,16 @@ public void verifyTransferProofWrongEpk() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2628,9 +2648,10 @@ public void verifyTransferProofWrongReceiveProof() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2716,14 +2737,16 @@ public void verifyTransferProofWrongReceiveProof() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2754,9 +2777,10 @@ public void verifyTransferProofWrongBindingSignature() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2842,14 +2866,16 @@ public void verifyTransferProofWrongBindingSignature() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -2880,9 +2906,10 @@ public void verifyTransferProofWrongHash() throws ZksnarkException { JLibrustzcash.librustzcashSaplingGenerateR(rcm1); byte[] rcm2 = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm2); - PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).get(); - PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress1 = senderIvk.address(DiversifierT.random()).orElse(null); + PaymentAddress senderPaymentAddress2 = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress1); + assertNotNull(senderPaymentAddress2); { //for mint1 ShieldedTRC20ParametersBuilder mintBuilder1 = new ShieldedTRC20ParametersBuilder(); mintBuilder1.setTransparentFromAmount(BigInteger.valueOf(30)); @@ -2968,14 +2995,16 @@ public void verifyTransferProofWrongHash() throws ZksnarkException { SpendingKey receiveSk1 = SpendingKey.random(); FullViewingKey receiveFvk1 = receiveSk1.fullViewingKey(); IncomingViewingKey receiveIvk1 = receiveFvk1.inViewingKey(); - PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress1 = receiveIvk1.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress1, 40, new byte[512]); //receiveNote2 SpendingKey receiveSk2 = SpendingKey.random(); FullViewingKey receiveFvk2 = receiveSk2.fullViewingKey(); IncomingViewingKey receiveIvk2 = receiveFvk2.inViewingKey(); - PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()).get(); + PaymentAddress receivePaymentAddress2 = receiveIvk2.address(new DiversifierT()) + .orElse(null); builder.addOutput(senderOvk, receivePaymentAddress2, 60, new byte[512]); ShieldedTRC20Parameters params = builder.build(true); @@ -3001,12 +3030,11 @@ public void verifyBurnWrongNF() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3072,12 +3100,11 @@ public void verifyBurnWrongRoot() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3144,12 +3171,11 @@ public void verifyBurnWrongCV() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3215,12 +3241,11 @@ public void verifyBurnWrongRk() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3286,12 +3311,11 @@ public void verifyBurnWrongProof() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3357,12 +3381,11 @@ public void verifyBurnWrongAuthoritySingature() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3428,12 +3451,11 @@ public void verifyBurnWrongBindingSingature() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3499,12 +3521,11 @@ public void verifyBurnWrongHash() throws ZksnarkException { SpendingKey senderSk = SpendingKey.random(); ExpandedSpendingKey senderExpsk = senderSk.expandedSpendingKey(); FullViewingKey senderFvk = senderSk.fullViewingKey(); - byte[] senderOvk = senderFvk.getOvk(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm = new byte[32]; JLibrustzcash.librustzcashSaplingGenerateR(rcm); - PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).get(); - + PaymentAddress senderPaymentAddress = senderIvk.address(DiversifierT.random()).orElse(null); + assertNotNull(senderPaymentAddress); { //for mint ShieldedTRC20ParametersBuilder mintBuilder = new ShieldedTRC20ParametersBuilder(); mintBuilder.setTransparentFromAmount(BigInteger.valueOf(value)); @@ -3560,21 +3581,19 @@ public void verifyBurnWrongHash() throws ZksnarkException { private Pair verifyTransfer(byte[] input) { transferContract.getEnergyForData(input); transferContract.setVmShouldEndInUs(System.nanoTime() / 1000 + 50 * 1000); - Pair ret = transferContract.execute(input); - return ret; + return transferContract.execute(input); } private IncrementalMerkleVoucherContainer addSimpleMerkleVoucherContainer( IncrementalMerkleTreeContainer tree, byte[][] cm) throws ZksnarkException { - for (int i = 0; i < cm.length; i++) { + for (byte[] bytes : cm) { PedersenHashCapsule compressCapsule = new PedersenHashCapsule(); - compressCapsule.setContent(ByteString.copyFrom(cm[i])); + compressCapsule.setContent(ByteString.copyFrom(bytes)); ShieldContract.PedersenHash a = compressCapsule.getInstance(); tree.append(a); } - IncrementalMerkleVoucherContainer voucher = tree.toVoucher(); - return voucher; + return tree.toVoucher(); } private byte[] decodePath(byte[] encodedPath) { @@ -3677,24 +3696,6 @@ private byte[] abiEncodeForMintWrongProof(ShieldedTRC20Parameters params, long v return mergedBytes; } - private byte[] abiEncodeForMintWrongBindingSignature(ShieldedTRC20Parameters params, long value, - byte[] frontier, long leafCount) { - byte[] mergedBytes; - ShieldContract.ReceiveDescription revDesc = params.getReceiveDescription(0); - mergedBytes = ByteUtil.merge( - revDesc.getNoteCommitment().toByteArray(), - revDesc.getValueCommitment().toByteArray(), - revDesc.getEpk().toByteArray(), - revDesc.getZkproof().toByteArray(), - Wallet.generateRandomBytes(64), - longTo32Bytes(value), - params.getMessageHash().toByteArray(), - frontier, - longTo32Bytes(leafCount) - ); - return mergedBytes; - } - private byte[] abiEncodeForMintWrongHash(ShieldedTRC20Parameters params, long value, byte[] frontier, long leafCount) { byte[] mergedBytes; @@ -4505,7 +4506,7 @@ private byte[] longTo32Bytes(long value) { } private long randomLong() { - return (long) Math.round(Math.random() * Long.MAX_VALUE / 2); + return round(random(true) * Long.MAX_VALUE / 2, true); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java b/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java new file mode 100644 index 00000000000..5c38ed90a3c --- /dev/null +++ b/framework/src/test/java/org/tron/common/runtime/vm/RepositoryTest.java @@ -0,0 +1,395 @@ +package org.tron.common.runtime.vm; + +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.Runtime; +import org.tron.common.runtime.TVMTestResult; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.WalletUtil; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.config.Parameter.ForkBlockVersionConsts; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction; + +@Slf4j +public class RepositoryTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private Repository rootRepository; + + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + + @Before + public void init() { + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + rootRepository.addBalance(Hex.decode(OWNER_ADDRESS), 30000000000000L); + rootRepository.commit(); + } + + /* pragma solidity ^0.4.0; + + contract A { + uint256 public n1; + uint256 public n2; + function callBcallA(address addr, uint256 _n1, uint256 _n2) public { + n1 = _n1; + string memory method = "callA(address,uint256)"; + bytes4 methodId = bytes4(keccak256(method)); + addr.call(methodId, address(this), _n2); + } + + function callBcallARevert(address addr, uint256 _n1, uint256 _n2) public { + n1 = _n1; + string memory method = "callARevert(address,uint256)"; + bytes4 methodId = bytes4(keccak256(method)); + addr.call(methodId, address(this), _n2); + } + + + function changeN(uint256 _n2) { + n2 = _n2; + } + + } + + contract B { + function callA(address addr, uint256 _n2) { + string memory method = "changeN(uint256)"; + bytes4 methodId = bytes4(keccak256(method)); + addr.call(methodId, _n2); + } + + function callARevert(address addr, uint256 _n2) { + string memory method = "changeN(uint256)"; + bytes4 methodId = bytes4(keccak256(method)); + addr.call(methodId, _n2); + revert(); + } + }*/ + + + @Test + @Ignore + public void loopCallTest() + throws ContractExeException, ReceiptCheckErrException, + VMIllegalException, ContractValidateException { + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + this.dbManager.getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); + this.dbManager.getDynamicPropertiesStore() + .saveLatestBlockHeaderNumber(CommonParameter.getInstance() + .getBlockNumForEnergyLimit() + 1); + + String contractA = "A"; + String contractB = "B"; + byte[] address = Hex.decode(OWNER_ADDRESS); + + String aABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"n1\",\"outputs\":[{\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":" + + "\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"n2\",\"outputs\":[{\"name\"" + + ":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":" + + "\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_n2\",\"type\":\"uint256\"}]," + + "\"name\":\"changeN\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\"" + + ",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":" + + "\"address\"},{\"name\":\"_n1\",\"type\":\"uint256\"},{\"name\":\"_n2\",\"type\":" + + "\"uint256\"}],\"name\":\"callBcallARevert\",\"outputs\":[],\"payable\":false," + + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"},{\"name\":\"_n1\",\"type\":" + + "\"uint256\"},{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callBcallA\"," + + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":" + + "\"function\"}]"; + + String bABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}," + + "{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callA\",\"outputs\":[],\"payable\"" + + ":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"},{\"name\":\"_n2\",\"type\":" + + "\"uint256\"}],\"name\":\"callARevert\",\"outputs\":[],\"payable\":false," + + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; + + String aCode = "608060405234801561001057600080fd5b506102c8806100206000396000f300608060405260043" + + "61061006c5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350" + + "4166336fe1f2581146100715780634aaa831d146100985780636aac216d146100ad578063a71d1d68146100c" + + "7578063b9d3e3ce146100fb575b600080fd5b34801561007d57600080fd5b5061008661012f565b604080519" + + "18252519081900360200190f35b3480156100a457600080fd5b50610086610135565b3480156100b95760008" + + "0fd5b506100c560043561013b565b005b3480156100d357600080fd5b506100c573fffffffffffffffffffff" + + "fffffffffffffffffff60043516602435604435610140565b34801561010757600080fd5b506100c573fffff" + + "fffffffffffffffffffffffffffffffffff6004351660243560443561024e565b60005481565b60015481565" + + "b600155565b6000828155604080518082018252601c8082527f63616c6c41526576657274286164647265737" + + "32c75696e7432353629000000006020830190815292519193928492918291908083835b602083106101a9578" + + "0518252601f19909201916020918201910161018a565b5181516000196020949094036101000a93909301928" + + "3169219169190911790526040805193909101839003832063ffffffff7c01000000000000000000000000000" + + "00000000000000000000000000000808304918216028552306004860152602485018a9052915190965073fff" + + "fffffffffffffffffffffffffffffffffffff8b16955090935060448084019360009350829003018183875af" + + "1505050505050505050565b600082815560408051808201825260168082527f63616c6c41286164647265737" + + "32c75696e7432353629000000000000000000006020830190815292519193928492918291908083836101a95" + + "600a165627a7a72305820f6164f67f8344af6aa83a5f724f6c3cb7d09905c4bc94729d1d72e9f11d0df1900" + + "29"; + + String bCode = "608060405234801561001057600080fd5b5061029f806100206000396000f300608060405260043" + + "6106100325763ffffffff60e060020a600035041663417c7cc581146100375780637a9a0e721461006a575b6" + + "00080fd5b34801561004357600080fd5b5061006873ffffffffffffffffffffffffffffffffffffffff60043" + + "51660243561009b565b005b34801561007657600080fd5b5061006873fffffffffffffffffffffffffffffff" + + "fffffffff60043516602435610187565b60408051808201825260108082527f6368616e67654e2875696e743" + + "23536290000000000000000000000000000000060208301908152925191926000928492909182918083835b6" + + "02083106101015780518252601f1990920191602091820191016100e2565b6001836020036101000a0380198" + + "25116818451168082178552505050505050905001915050604051809103902090508373fffffffffffffffff" + + "fffffffffffffffffffffff168160e060020a9004846040518263ffffffff1660e060020a028152600401808" + + "281526020019150506000604051808303816000875af15050505050505050565b60408051808201825260108" + + "082527f6368616e67654e2875696e74323536290000000000000000000000000000000060208301908152925" + + "191926000928492909182918083835b602083106101ed5780518252601f1990920191602091820191016101c" + + "e565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809" + + "103902090508373ffffffffffffffffffffffffffffffffffffffff168160e060020a9004846040518263fff" + + "fffff1660e060020a028152600401808281526020019150506000604051808303816000875af192505050506" + + "00080fd00a165627a7a723058209cb73b547b599b5d2a96ade83e03d656f8025f4ac7642f8b9aab37cc2574f" + + "8310029"; + + long value = 0; + long fee = 100000000; + long consumeUserResourcePercent = 0; + long engeryLiimt = 100000000; + + Transaction aTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractA, address, aABI, aCode, value, fee, consumeUserResourcePercent, + null, engeryLiimt); + Runtime runtime = TvmTestUtils.processTransactionAndReturnRuntime(aTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); + Assert.assertNull(runtime.getRuntimeError()); + + Transaction bTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractB, address, bABI, bCode, value, fee, consumeUserResourcePercent, + null, engeryLiimt); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(bTrx, + RepositoryImpl.createRoot(StoreFactory.getInstance()), null); + Assert.assertNull(runtime.getRuntimeError()); + + byte[] aAddress = WalletUtil.generateContractAddress(aTrx); + byte[] bAddress = WalletUtil.generateContractAddress(bTrx); + + // trigger contractA + // callBcallA(address,uint256,uint256) + // ,1,2 + // + String params1 = Hex.toHexString(new DataWord(bAddress).getData()) + + "000000000000000000000000000000000000000000000000000000000000000100000000000000000000000" + + "00000000000000000000000000000000000000002"; + + byte[] triggerData = TvmTestUtils + .parseAbi("callBcallARevert(address,uint256,uint256)", params1); + TVMTestResult result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, triggerData, 0, fee, dbManager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + // check result + // expected: n1 = 1; n2 = 0 + byte[] checkN1Data = TvmTestUtils.parseAbi("n1()", null); + byte[] checkN2Data = TvmTestUtils.parseAbi("n2()", null); + + TVMTestResult checkN1 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN1Data, 0, fee, dbManager, null); + TVMTestResult checkN2 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN2Data, 0, fee, dbManager, null); + + + Assert.assertArrayEquals(checkN1.getRuntime().getResult().getHReturn(), + new DataWord(1).getData()); + Assert.assertArrayEquals(checkN2.getRuntime().getResult().getHReturn(), + new DataWord(0).getData()); + + // trigger contractA + // callBcallA(address,uint256,uint256) + // ,100,1000 + String params2 = Hex.toHexString(new DataWord(bAddress).getData()) + + "000000000000000000000000000000000000000000000000000000000000006400000000000000000000000" + + "000000000000000000000000000000000000003e8"; + triggerData = TvmTestUtils.parseAbi("callBcallA(address,uint256,uint256)", params2); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, triggerData, 0, fee, dbManager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + checkN1 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN1Data, 0, fee, dbManager, null); + checkN2 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN2Data, 0, fee, dbManager, null); + Assert.assertArrayEquals(checkN1.getRuntime().getResult().getHReturn(), + new DataWord(100).getData()); + Assert.assertArrayEquals(checkN2.getRuntime().getResult().getHReturn(), + new DataWord(1000).getData()); + CommonParameter.setENERGY_LIMIT_HARD_FORK(false); + } + + @Test + public void loopCallTestOldVersion() + throws ContractExeException, ReceiptCheckErrException, + VMIllegalException, ContractValidateException { + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 0); + this.dbManager.getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); + + String contractA = "A"; + String contractB = "B"; + byte[] address = Hex.decode(OWNER_ADDRESS); + + String aABI = "[{\"constant\":true,\"inputs\":[],\"name\":\"n1\",\"outputs\":[{\"name\":\"\"," + + "\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":" + + "\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"n2\",\"outputs\":[{\"name\"" + + ":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\"" + + ":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_n2\",\"type\":\"uint256\"}]" + + ",\"name\":\"changeN\",\"outputs\":[],\"payable\":false,\"stateMutability\":" + + "\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":" + + "\"addr\",\"type\":\"address\"},{\"name\":\"_n1\",\"type\":\"uint256\"},{\"name\":" + + "\"_n2\",\"type\":\"uint256\"}],\"name\":\"callBcallARevert\",\"outputs\":[],\"payable\":" + + "false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false," + + "\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"},{\"name\":\"_n1\",\"type\"" + + ":\"uint256\"},{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callBcallA\"," + + "\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":" + + "\"function\"}]"; + String bABI = "[{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}," + + "{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callA\",\"outputs\":[]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}," + + "{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}," + + "{\"name\":\"_n2\",\"type\":\"uint256\"}],\"name\":\"callARevert\",\"outputs\":[]," + + "\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]"; + + String aCode = "608060405234801561001057600080fd5b506102c8806100206000396000f300608060405260043" + + "61061006c5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350" + + "4166336fe1f2581146100715780634aaa831d146100985780636aac216d146100ad578063a71d1d68146100c" + + "7578063b9d3e3ce146100fb575b600080fd5b34801561007d57600080fd5b5061008661012f565b604080519" + + "18252519081900360200190f35b3480156100a457600080fd5b50610086610135565b3480156100b95760008" + + "0fd5b506100c560043561013b565b005b3480156100d357600080fd5b506100c573fffffffffffffffffffff" + + "fffffffffffffffffff60043516602435604435610140565b34801561010757600080fd5b506100c573fffff" + + "fffffffffffffffffffffffffffffffffff6004351660243560443561024e565b60005481565b60015481565" + + "b600155565b6000828155604080518082018252601c8082527f63616c6c41526576657274286164647265737" + + "32c75696e7432353629000000006020830190815292519193928492918291908083835b602083106101a9578" + + "0518252601f19909201916020918201910161018a565b5181516000196020949094036101000a93909301928" + + "3169219169190911790526040805193909101839003832063ffffffff7c01000000000000000000000000000" + + "00000000000000000000000000000808304918216028552306004860152602485018a9052915190965073fff" + + "fffffffffffffffffffffffffffffffffffff8b16955090935060448084019360009350829003018183875af" + + "1505050505050505050565b600082815560408051808201825260168082527f63616c6c41286164647265737" + + "32c75696e7432353629000000000000000000006020830190815292519193928492918291908083836101a95" + + "600a165627a7a72305820f6164f67f8344af6aa83a5f724f6c3cb7d09905c4bc94729d1d72e9f11d0df1900" + + "29"; + + String bCode = "608060405234801561001057600080fd5b5061029f806100206000396000f300608060405260043" + + "6106100325763ffffffff60e060020a600035041663417c7cc581146100375780637a9a0e721461006a575b6" + + "00080fd5b34801561004357600080fd5b5061006873ffffffffffffffffffffffffffffffffffffffff60043" + + "51660243561009b565b005b34801561007657600080fd5b5061006873fffffffffffffffffffffffffffffff" + + "fffffffff60043516602435610187565b60408051808201825260108082527f6368616e67654e2875696e743" + + "23536290000000000000000000000000000000060208301908152925191926000928492909182918083835b6" + + "02083106101015780518252601f1990920191602091820191016100e2565b6001836020036101000a0380198" + + "25116818451168082178552505050505050905001915050604051809103902090508373fffffffffffffffff" + + "fffffffffffffffffffffff168160e060020a9004846040518263ffffffff1660e060020a028152600401808" + + "281526020019150506000604051808303816000875af15050505050505050565b60408051808201825260108" + + "082527f6368616e67654e2875696e74323536290000000000000000000000000000000060208301908152925" + + "191926000928492909182918083835b602083106101ed5780518252601f1990920191602091820191016101c" + + "e565b6001836020036101000a038019825116818451168082178552505050505050905001915050604051809" + + "103902090508373ffffffffffffffffffffffffffffffffffffffff168160e060020a9004846040518263fff" + + "fffff1660e060020a028152600401808281526020019150506000604051808303816000875af192505050506" + + "00080fd00a165627a7a723058209cb73b547b599b5d2a96ade83e03d656f8025f4ac7642f8b9aab37cc2574f" + + "8310029"; + + long value = 0; + long fee = 100000000; + long consumeUserResourcePercent = 0; + + Transaction aTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractA, address, aABI, aCode, value, fee, consumeUserResourcePercent, + null); + Repository rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + Runtime runtime = TvmTestUtils.processTransactionAndReturnRuntime(aTrx, rootRepository, null); + Assert.assertNull(runtime.getRuntimeError()); + + Transaction bTrx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + contractB, address, bABI, bCode, value, fee, consumeUserResourcePercent, + null); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(bTrx, rootRepository, null); + Assert.assertNull(runtime.getRuntimeError()); + + byte[] aAddress = WalletUtil.generateContractAddress(aTrx); + byte[] bAddress = WalletUtil.generateContractAddress(bTrx); + + // trigger contractA + // callBcallA(address,uint256,uint256) + // ,1,2 + // + String params1 = Hex.toHexString(new DataWord(bAddress).getData()) + + "000000000000000000000000000000000000000000000000000000000000000100000000000000000000000" + + "00000000000000000000000000000000000000002"; + + byte[] triggerData = TvmTestUtils + .parseAbi("callBcallARevert(address,uint256,uint256)", params1); + TVMTestResult result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, triggerData, 0, fee, dbManager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + + // check result + // expected: n1 = 1; n2 = 0 + byte[] checkN1Data = TvmTestUtils.parseAbi("n1()", null); + byte[] checkN2Data = TvmTestUtils.parseAbi("n2()", null); + + TVMTestResult checkN1 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN1Data, 0, fee, dbManager, null); + TVMTestResult checkN2 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN2Data, 0, fee, dbManager, null); + + + Assert.assertArrayEquals(checkN1.getRuntime().getResult().getHReturn(), + new DataWord(1).getData()); + Assert.assertArrayEquals(checkN2.getRuntime().getResult().getHReturn(), + new DataWord(2).getData()); + + // trigger contractA + // callBcallA(address,uint256,uint256) + // ,100,1000 + String params2 = Hex.toHexString(new DataWord(bAddress).getData()) + + "000000000000000000000000000000000000000000000000000000000000006400000000000000000000000" + + "000000000000000000000000000000000000003e8"; + triggerData = TvmTestUtils.parseAbi("callBcallA(address,uint256,uint256)", params2); + result = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, triggerData, 0, fee, dbManager, null); + Assert.assertNull(result.getRuntime().getRuntimeError()); + checkN1 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN1Data, 0, fee, dbManager, null); + checkN2 = TvmTestUtils + .triggerContractAndReturnTvmTestResult(Hex.decode(OWNER_ADDRESS), + aAddress, checkN2Data, 0, fee, dbManager, null); + Assert.assertArrayEquals(checkN1.getRuntime().getResult().getHReturn(), + new DataWord(100).getData()); + Assert + .assertArrayEquals(checkN2.getRuntime().getResult().getHReturn(), + new DataWord(1000).getData()); + CommonParameter.setENERGY_LIMIT_HARD_FORK(false); + } +} diff --git a/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java index 5fc95be728f..af95952ebf7 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/RewardBalanceTest.java @@ -3,13 +3,14 @@ import java.util.Collections; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.InternalTransaction; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.Base58; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.capsule.BlockCapsule; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -25,7 +26,6 @@ import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j public class RewardBalanceTest extends VMTestBase { @@ -149,7 +149,7 @@ public void testRewardBalance() null); byte[] factoryAddress = WalletUtil.generateContractAddress(trx); String factoryAddressStr = StringUtil.encode58Check(factoryAddress); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // Trigger contract method: rewardBalanceTest(address) @@ -168,7 +168,7 @@ public void testRewardBalance() InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - Program program = new Program(null, programInvoke, rootInternalTransaction); + Program program = new Program(null, null, programInvoke, rootInternalTransaction); byte[] result = program.getRewardBalance(new DataWord(Base58.decode(nonexistentAccount))) .getData(); @@ -188,7 +188,7 @@ public void testRewardBalance() InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); result = program.getRewardBalance(new DataWord(Base58.decode(factoryAddressStr))).getData(); Assert.assertEquals(Hex.toHexString(result), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -207,7 +207,7 @@ public void testRewardBalance() InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); result = program.getRewardBalance(new DataWord(Base58.decode(witnessAccount))).getData(); Assert.assertEquals(Hex.toHexString(result), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -226,7 +226,7 @@ public void testRewardBalance() InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); result = program.getRewardBalance(DataWord.ZERO()).getData(); Assert.assertEquals(Hex.toHexString(result), "0000000000000000000000000000000000000000000000000000000000000000"); @@ -245,7 +245,7 @@ public void testRewardBalance() InternalTransaction.ExecutorType.ET_PRE_TYPE, trx, 0, 0, blockCap.getInstance(), repository, System.nanoTime() / 1000, System.nanoTime() / 1000 + 50000, 3_000_000L); - program = new Program(null, programInvoke, rootInternalTransaction); + program = new Program(null, null, programInvoke, rootInternalTransaction); result = program.getRewardBalance(new DataWord(Base58.decode(factoryAddressStr))).getData(); Assert.assertEquals(Hex.toHexString(result), "0000000000000000000000000000000000000000000000000000000000000000"); diff --git a/framework/src/test/java/org/tron/common/runtime/vm/StorageTest.java b/framework/src/test/java/org/tron/common/runtime/vm/StorageTest.java index f4f339eb43e..8ae04761ac3 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/StorageTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/StorageTest.java @@ -3,27 +3,27 @@ import java.util.Arrays; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; -import org.testng.Assert; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.Deposit; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.WalletUtil; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.Transaction; @Slf4j public class StorageTest extends VMTestBase { - @Test public void writeAndCommit() { byte[] address = Hex.decode(OWNER_ADDRESS); @@ -32,25 +32,25 @@ public void writeAndCommit() { DataWord nullKey = new DataWord("nullkey".getBytes()); DataWord nullValue = new DataWord(0); - rootDeposit.putStorageValue(address, storageKey1, storageVal1); - rootDeposit.putStorageValue(address, nullKey, nullValue); + rootRepository.putStorageValue(address, storageKey1, storageVal1); + rootRepository.putStorageValue(address, nullKey, nullValue); // test cache - Assert.assertEquals(rootDeposit.getStorageValue(address, storageKey1), storageVal1); - Assert.assertEquals(rootDeposit.getStorageValue(address, nullKey), nullValue); - rootDeposit.commit(); + Assert.assertEquals(rootRepository.getStorageValue(address, storageKey1), storageVal1); + Assert.assertEquals(rootRepository.getStorageValue(address, nullKey), nullValue); + rootRepository.commit(); // use a new rootDeposit - Deposit deposit1 = DepositImpl.createRoot(manager); - Assert.assertEquals(deposit1.getStorageValue(address, storageKey1), storageVal1); - Assert.assertNull(deposit1.getStorageValue(address, nullKey)); + Repository repository1 = RepositoryImpl.createRoot(StoreFactory.getInstance()); + Assert.assertEquals(repository1.getStorageValue(address, storageKey1), storageVal1); + Assert.assertNull(repository1.getStorageValue(address, nullKey)); // delete key - deposit1.putStorageValue(address, storageKey1, nullValue); - Assert.assertNotNull(deposit1.getStorageValue(address, storageKey1)); - deposit1.commit(); - Deposit deposit2 = DepositImpl.createRoot(manager); - Assert.assertNull(deposit2.getStorageValue(address, storageKey1)); + repository1.putStorageValue(address, storageKey1, nullValue); + Assert.assertNotNull(repository1.getStorageValue(address, storageKey1)); + repository1.commit(); + Repository repository2 = RepositoryImpl.createRoot(StoreFactory.getInstance()); + Assert.assertNull(repository2.getStorageValue(address, storageKey1)); } @Test @@ -61,14 +61,17 @@ public void writeWithoutCommit() { DataWord nullKey = new DataWord("nullkey".getBytes()); DataWord nullValue = new DataWord(0); - rootDeposit.putStorageValue(address, storageKey1, storageVal1); - rootDeposit.putStorageValue(address, nullKey, nullValue); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, nullKey)); - rootDeposit.commit(); - Assert.assertEquals(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1), - storageVal1); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, nullKey)); + rootRepository.putStorageValue(address, storageKey1, storageVal1); + rootRepository.putStorageValue(address, nullKey, nullValue); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, nullKey)); + rootRepository.commit(); + Assert.assertEquals(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1), storageVal1); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, nullKey)); } /* @@ -128,7 +131,7 @@ public void contractWriteAndDeleteStorage() Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( contractName, address, ABI, code, value, fee, consumeUserResourcePercent, null); byte[] contractAddress = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); // write storage @@ -201,65 +204,77 @@ public void testParentChild() { DataWord storageParentVal1 = new DataWord("parent_val1".getBytes()); DataWord storageParentZeroKey = new DataWord("parent_zero_key1".getBytes()); - Deposit chlidDeposit = rootDeposit.newDepositChild(); + Repository childRepository = rootRepository.newRepositoryChild(); // write to root cache - rootDeposit.putStorageValue(address, storageParentKey1, storageParentVal1); - rootDeposit.putStorageValue(address, storageParentZeroKey, zeroValue); + rootRepository.putStorageValue(address, storageParentKey1, storageParentVal1); + rootRepository.putStorageValue(address, storageParentZeroKey, zeroValue); // write to child cache - chlidDeposit.putStorageValue(address, storageKey1, storageVal1); - chlidDeposit.putStorageValue(address, zeroKey, zeroValue); + childRepository.putStorageValue(address, storageKey1, storageVal1); + childRepository.putStorageValue(address, zeroKey, zeroValue); // check child cache - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageKey1), storageVal1); - Assert.assertEquals(chlidDeposit.getStorageValue(address, zeroKey), zeroValue); + Assert.assertEquals(childRepository.getStorageValue(address, storageKey1), storageVal1); + Assert.assertEquals(childRepository.getStorageValue(address, zeroKey), zeroValue); Assert - .assertEquals(chlidDeposit.getStorageValue(address, storageParentKey1), storageParentVal1); - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentZeroKey), zeroValue); + .assertEquals(childRepository.getStorageValue(address, storageParentKey1), + storageParentVal1); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentZeroKey), zeroValue); - chlidDeposit.putStorageValue(address, storageParentKey1, parentChangedVal); + childRepository.putStorageValue(address, storageParentKey1, parentChangedVal); // check root cache - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentKey1), storageParentVal1); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentKey1), + parentChangedVal); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentKey1), + storageParentVal1); - Assert.assertNull(rootDeposit.getStorageValue(address, storageKey1)); - Assert.assertNull(rootDeposit.getStorageValue(address, zeroKey)); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentZeroKey), zeroValue); + Assert.assertNull(rootRepository.getStorageValue(address, storageKey1)); + Assert.assertNull(rootRepository.getStorageValue(address, zeroKey)); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentZeroKey), zeroValue); // check db - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, zeroKey)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentKey1)); - Assert - .assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentZeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, zeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentZeroKey)); // commit child cache - chlidDeposit.commit(); + childRepository.commit(); // check root cache - Assert.assertEquals(rootDeposit.getStorageValue(address, storageKey1), storageVal1); - Assert.assertEquals(rootDeposit.getStorageValue(address, zeroKey), zeroValue); - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentZeroKey), zeroValue); + Assert.assertEquals(rootRepository.getStorageValue(address, storageKey1), storageVal1); + Assert.assertEquals(rootRepository.getStorageValue(address, zeroKey), zeroValue); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentKey1), + parentChangedVal); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentKey1), + parentChangedVal); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentZeroKey), zeroValue); // check db - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, zeroKey)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentKey1)); - Assert - .assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentZeroKey)); - - rootDeposit.commit(); - Assert.assertEquals(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1), - storageVal1); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, zeroKey)); - Assert.assertEquals(DepositImpl.createRoot(manager).getStorageValue(address, storageParentKey1), - parentChangedVal); - Assert - .assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentZeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, zeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentZeroKey)); + + rootRepository.commit(); + Assert.assertEquals(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1), storageVal1); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, zeroKey)); + Assert.assertEquals(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentKey1), parentChangedVal); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentZeroKey)); CommonParameter.setENERGY_LIMIT_HARD_FORK(false); } @@ -280,76 +295,87 @@ public void testParentChildOldVersion() { DataWord storageParentVal1 = new DataWord("parent_val1".getBytes()); DataWord storageParentZeroKey = new DataWord("parent_zero_key1".getBytes()); - Deposit chlidDeposit = rootDeposit.newDepositChild(); + Repository childRepository = rootRepository.newRepositoryChild(); // write to root cache - rootDeposit.putStorageValue(address, storageParentKey1, storageParentVal1); - rootDeposit.putStorageValue(address, storageParentZeroKey, zeroValue); + rootRepository.putStorageValue(address, storageParentKey1, storageParentVal1); + rootRepository.putStorageValue(address, storageParentZeroKey, zeroValue); // write to child cache - chlidDeposit.putStorageValue(address, storageKey1, storageVal1); - chlidDeposit.putStorageValue(address, zeroKey, zeroValue); + childRepository.putStorageValue(address, storageKey1, storageVal1); + childRepository.putStorageValue(address, zeroKey, zeroValue); // check child cache - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageKey1), storageVal1); - Assert.assertEquals(chlidDeposit.getStorageValue(address, zeroKey), zeroValue); - Assert - .assertEquals(chlidDeposit.getStorageValue(address, storageParentKey1), storageParentVal1); - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentZeroKey), zeroValue); + Assert.assertEquals(childRepository.getStorageValue(address, storageKey1), storageVal1); + Assert.assertEquals(childRepository.getStorageValue(address, zeroKey), zeroValue); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentKey1), + storageParentVal1); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentZeroKey), zeroValue); - chlidDeposit.putStorageValue(address, storageParentKey1, parentChangedVal); + childRepository.putStorageValue(address, storageParentKey1, parentChangedVal); // check root cache - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentKey1), + parentChangedVal); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentKey1), + parentChangedVal); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageKey1), storageVal1); - Assert.assertEquals(rootDeposit.getStorageValue(address, zeroKey), zeroValue); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentZeroKey), zeroValue); + Assert.assertEquals(rootRepository.getStorageValue(address, storageKey1), storageVal1); + Assert.assertEquals(rootRepository.getStorageValue(address, zeroKey), zeroValue); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentZeroKey), zeroValue); // check parent deposit == child deposit - Assert.assertEquals(rootDeposit.getStorageValue(address, storageKey1), - chlidDeposit.getStorageValue(address, storageKey1)); - Assert.assertEquals(rootDeposit.getStorageValue(address, zeroKey), - chlidDeposit.getStorageValue(address, zeroKey)); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentKey1), - chlidDeposit.getStorageValue(address, storageParentKey1)); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentZeroKey), - chlidDeposit.getStorageValue(address, storageParentZeroKey)); + Assert.assertEquals(rootRepository.getStorageValue(address, storageKey1), + childRepository.getStorageValue(address, storageKey1)); + Assert.assertEquals(rootRepository.getStorageValue(address, zeroKey), + childRepository.getStorageValue(address, zeroKey)); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentKey1), + childRepository.getStorageValue(address, storageParentKey1)); + Assert.assertEquals(rootRepository.getStorageValue(address, storageParentZeroKey), + childRepository.getStorageValue(address, storageParentZeroKey)); // check db - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, zeroKey)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentKey1)); - Assert - .assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentZeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, zeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentZeroKey)); // didn't commit child cache - // chlidDeposit.commit(); + // childRepository.commit(); // check root cache - Assert.assertEquals(rootDeposit.getStorageValue(address, storageKey1), storageVal1); - Assert.assertEquals(rootDeposit.getStorageValue(address, zeroKey), zeroValue); - Assert.assertEquals(rootDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); + Assert.assertEquals(rootRepository.getStorageValue(address, storageKey1), storageVal1); + Assert.assertEquals(rootRepository.getStorageValue(address, zeroKey), zeroValue); + Assert.assertEquals(rootRepository + .getStorageValue(address, storageParentKey1), parentChangedVal); - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentKey1), parentChangedVal); - Assert.assertEquals(chlidDeposit.getStorageValue(address, storageParentZeroKey), zeroValue); + Assert.assertEquals(childRepository + .getStorageValue(address, storageParentKey1), parentChangedVal); + Assert.assertEquals(childRepository.getStorageValue(address, storageParentZeroKey), zeroValue); // check db - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, zeroKey)); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentKey1)); - Assert - .assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentZeroKey)); - - rootDeposit.commit(); - Assert.assertEquals(DepositImpl.createRoot(manager).getStorageValue(address, storageKey1), - storageVal1); - Assert.assertNull(DepositImpl.createRoot(manager).getStorageValue(address, zeroKey)); - Assert.assertEquals(DepositImpl.createRoot(manager).getStorageValue(address, storageParentKey1), - parentChangedVal); - Assert - .assertNull(DepositImpl.createRoot(manager).getStorageValue(address, storageParentZeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, zeroKey)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentKey1)); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentZeroKey)); + + rootRepository.commit(); + Assert.assertEquals(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageKey1), storageVal1); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, zeroKey)); + Assert.assertEquals(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentKey1), parentChangedVal); + Assert.assertNull(RepositoryImpl.createRoot(StoreFactory.getInstance()) + .getStorageValue(address, storageParentZeroKey)); CommonParameter.setENERGY_LIMIT_HARD_FORK(false); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java index 4a588ae8646..8104a689cfa 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TimeBenchmarkTest.java @@ -1,58 +1,48 @@ package org.tron.common.runtime.vm; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.After; +import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j @Ignore -public class TimeBenchmarkTest { +public class TimeBenchmarkTest extends BaseTest { - private Manager dbManager; - private TronApplicationContext context; - private DepositImpl deposit; - private String dbPath = "output_TimeBenchmarkTest"; - private String OWNER_ADDRESS; - private Application AppT; + private RepositoryImpl repository; + private static final String OWNER_ADDRESS; private long totalBalance = 30_000_000_000_000L; + static { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + /** * Init data. */ @Before public void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - deposit.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); - deposit.commit(); + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + repository.addBalance(Hex.decode(OWNER_ADDRESS), totalBalance); + repository.commit(); } // pragma solidity ^0.4.2; @@ -136,23 +126,9 @@ public void timeBenchmark() long expectEnergyUsageTotal2 = 110; Assert.assertEquals(result.getReceipt().getEnergyUsageTotal(), expectEnergyUsageTotal2); - Assert.assertEquals(result.getRuntime().getResult().isRevert(), true); - Assert.assertTrue(result.getRuntime().getResult().getException() == null); + Assert.assertTrue(result.getRuntime().getResult().isRevert()); + Assert.assertNull(result.getRuntime().getResult().getException()); Assert.assertEquals(dbManager.getAccountStore().get(address).getBalance(), totalBalance - (expectEnergyUsageTotal + expectEnergyUsageTotal2) * 100); } - - /** - * Release resources. - */ - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java index 8f9232dee07..dbc9147de7f 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TransferFailedEnergyTest.java @@ -6,12 +6,13 @@ import lombok.Data; import lombok.ToString; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.runtime.ProgramResult; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.capsule.ReceiptCapsule; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -20,7 +21,6 @@ import org.tron.core.vm.config.ConfigLoader; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Result.contractResult; -import stest.tron.wallet.common.client.utils.AbiUtil; public class TransferFailedEnergyTest extends VMTestBase { /* @@ -281,7 +281,7 @@ public void testTransferFailedAfterAllowTvmConstantinopl() contractName, address, ABI, code, value, fee, consumeUserResourcePercent, null); byte[] addressWithSufficientBalance = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); for (TestCase testCase : testCasesAfterAllowTvmConstantinop) { @@ -292,7 +292,7 @@ public void testTransferFailedAfterAllowTvmConstantinopl() contractName, address, ABI, code, 0, fee, consumeUserResourcePercent, null); byte[] addressWithoutBalance = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); for (TestCase testCase : testCasesInsufficientBalance) { @@ -353,7 +353,7 @@ public void testTransferFailedBeforeAllowTvmConstantinopl() contractName, address, ABI, code, value, fee, consumeUserResourcePercent, null); byte[] addressWithSufficientBalance = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); for (TestCase testCase : testCasesBeforeAllowTvmConstantinop) { @@ -364,7 +364,7 @@ public void testTransferFailedBeforeAllowTvmConstantinopl() contractName, address, ABI, code, 0, fee, consumeUserResourcePercent, null); byte[] addressWithoutBalance = WalletUtil.generateContractAddress(trx); - runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootDeposit, null); + runtime = TvmTestUtils.processTransactionAndReturnRuntime(trx, rootRepository, null); Assert.assertNull(runtime.getRuntimeError()); for (TestCase testCase : testCasesInsufficientBalance) { @@ -383,12 +383,12 @@ private void checkResult(TestCase testCase, byte[] factoryAddress) factoryAddress, Hex.decode(hexInput), 0, fee, manager, null); ProgramResult programResult = result.getRuntime().getResult(); ReceiptCapsule receiptCapsule = result.getReceipt(); - Assert.assertEquals(receiptCapsule.getResult(), testCase.getReceiptResult(), - testCase.getMethod()); + Assert.assertEquals(testCase.getMethod(), + receiptCapsule.getResult(), testCase.getReceiptResult()); if (testCase.allEnergy) { - Assert.assertEquals(programResult.getEnergyUsed(), 1000000, testCase.getMethod()); + Assert.assertEquals(testCase.getMethod(), programResult.getEnergyUsed(), 1000000); } else { - Assert.assertTrue(programResult.getEnergyUsed() < allEnergy, testCase.getMethod()); + Assert.assertTrue(testCase.getMethod(), programResult.getEnergyUsed() < allEnergy); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java index 4d7fa13109d..ede47555f3f 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TransferToAccountTest.java @@ -1,24 +1,20 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.runtime.ProgramResult; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -27,9 +23,7 @@ import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionContext; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -37,15 +31,14 @@ import org.tron.core.exception.VMIllegalException; import org.tron.core.store.StoreFactory; import org.tron.core.vm.EnergyCost; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import stest.tron.wallet.common.client.utils.AbiUtil; @Slf4j -public class TransferToAccountTest { +public class TransferToAccountTest extends BaseTest { - private static final String dbPath = "output_TransferToAccountTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static final long TOTAL_SUPPLY = 1000_000_000L; @@ -57,25 +50,21 @@ public class TransferToAccountTest { private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; private static Runtime runtime; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; + private static RepositoryImpl repository; private static AccountCapsule ownerCapsule; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); - deposit.addBalance(Hex.decode(TRANSFER_TO), 10); - deposit.commit(); + } + + @Before + public void before() { + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); + repository.addBalance(Hex.decode(TRANSFER_TO), 10); + repository.commit(); ownerCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -85,20 +74,6 @@ public class TransferToAccountTest { ownerCapsule.setBalance(1000_1000_1000L); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - private long createAsset(String tokenName) { chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); chainBaseManager.getDynamicPropertiesStore().saveAllowTvmTransferTrc10(1); @@ -144,10 +119,10 @@ public void TransferTokenTest() // 1. Test deploy with tokenValue and tokenId */ long id = createAsset("testToken1"); byte[] contractAddress = deployTransferContract(id); - deposit.commit(); + repository.commit(); Assert.assertEquals(100, chainBaseManager.getAccountStore() - .get(contractAddress).getAssetMapV2().get(String.valueOf(id)).longValue()); + .get(contractAddress).getAssetV2MapForTest().get(String.valueOf(id)).longValue()); Assert.assertEquals(1000, chainBaseManager.getAccountStore().get(contractAddress).getBalance()); @@ -170,11 +145,11 @@ public void TransferTokenTest() Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(9, - chainBaseManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getAssetMapV2() + chainBaseManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getAssetV2MapForTest() .get(String.valueOf(id)).longValue()); Assert.assertEquals(100 + tokenValue - 9, chainBaseManager.getAccountStore().get(contractAddress) - .getAssetMapV2().get(String.valueOf(id)).longValue()); + .getAssetV2MapForTest().get(String.valueOf(id)).longValue()); long energyCostWhenExist = runtime.getResult().getEnergyUsed(); // 3.Test transferToken To Non-exist address @@ -190,10 +165,10 @@ public void TransferTokenTest() Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(100 + tokenValue * 2 - 18, - chainBaseManager.getAccountStore().get(contractAddress).getAssetMapV2() + chainBaseManager.getAccountStore().get(contractAddress).getAssetV2MapForTest() .get(String.valueOf(id)).longValue()); Assert.assertEquals(9, - chainBaseManager.getAccountStore().get(ecKey.getAddress()).getAssetMapV2() + chainBaseManager.getAccountStore().get(ecKey.getAddress()).getAssetV2MapForTest() .get(String.valueOf(id)).longValue()); long energyCostWhenNonExist = runtime.getResult().getEnergyUsed(); //4.Test Energy @@ -250,7 +225,6 @@ public void TransferTokenTest() // 9.Test transferToken Big Amount selectorStr = "transferTokenTo(address,trcToken,uint256)"; - ecKey = new ECKey(Utils.getRandom()); String params = "000000000000000000000000548794500882809695a8a687866e76d4271a1abc" + Hex.toHexString(new DataWord(id).getData()) + "0000000000000000000000000000000011111111111111111111111111111111"; @@ -318,10 +292,9 @@ private byte[] deployTransferContract(long id) long tokenValue = 100; long tokenId = id; - byte[] contractAddress = TvmTestUtils + return TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, tokenValue, tokenId, - deposit, null); - return contractAddress; + repository, null); } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java b/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java index 0a6e30f8897..0509cad1dc7 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/TransferTokenTest.java @@ -1,40 +1,33 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @Slf4j -public class TransferTokenTest { +public class TransferTokenTest extends BaseTest { - private static final String dbPath = "output_TransferTokenTest"; private static final String OWNER_ADDRESS; private static final String TRANSFER_TO; private static final long TOTAL_SUPPLY = 1000_000_000L; @@ -46,24 +39,22 @@ public class TransferTokenTest { private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; private static Runtime runtime; - private static Manager dbManager; - private static TronApplicationContext context; - private static Application appT; - private static DepositImpl deposit; + private static RepositoryImpl repository; private static AccountCapsule ownerCapsule; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TRANSFER_TO = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - dbManager = context.getBean(Manager.class); - deposit = DepositImpl.createRoot(dbManager); - deposit.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); - deposit.addBalance(Hex.decode(TRANSFER_TO), 10); - deposit.commit(); + } + + @Before + public void before() { + repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + repository.createAccount(Hex.decode(TRANSFER_TO), AccountType.Normal); + repository.addBalance(Hex.decode(TRANSFER_TO), 10); + repository.commit(); ownerCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -73,20 +64,6 @@ public class TransferTokenTest { ownerCapsule.setBalance(1000_1000_1000L); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - private long createAsset(String tokenName) { dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveAllowTvmTransferTrc10(1); @@ -116,13 +93,11 @@ private long createAsset(String tokenName) { /** * pragma solidity ^0.4.24; - * * contract tokenTest{ constructor() public payable{} // positive case function * TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ * toAddress.transferToken(amount,id); } function suicide(address toAddress) payable public{ * selfdestruct(toAddress); } function get(trcToken trc) public payable returns(uint256){ return * address(this).tokenBalance(trc); } } - * * 1. deploy 2. trigger and internal transaction 3. suicide (all token) */ @Test @@ -132,10 +107,10 @@ public void TransferTokenTest() /* 1. Test deploy with tokenValue and tokenId */ long id = createAsset("testToken1"); byte[] contractAddress = deployTransferTokenContract(id); - deposit.commit(); + repository.commit(); Assert.assertEquals(100, - dbManager.getAccountStore().get(contractAddress).getAssetMapV2().get(String.valueOf(id)) - .longValue()); + dbManager.getAccountStore().get(contractAddress) + .getAssetV2MapForTest().get(String.valueOf(id)).longValue()); Assert.assertEquals(1000, dbManager.getAccountStore().get(contractAddress).getBalance()); String selectorStr = "TransferTokenTo(address,trcToken,uint256)"; @@ -156,12 +131,12 @@ public void TransferTokenTest() triggerCallValue, feeLimit, tokenValue, id); runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction, dbManager, null); - org.testng.Assert.assertNull(runtime.getRuntimeError()); + Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(100 + tokenValue - 9, - dbManager.getAccountStore().get(contractAddress).getAssetMapV2().get(String.valueOf(id)) - .longValue()); - Assert.assertEquals(9, dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getAssetMapV2() - .get(String.valueOf(id)).longValue()); + dbManager.getAccountStore().get(contractAddress).getAssetV2MapForTest() + .get(String.valueOf(id)).longValue()); + Assert.assertEquals(9, dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)) + .getAssetV2MapForTest().get(String.valueOf(id)).longValue()); /* suicide test */ // create new token: testToken2 @@ -181,12 +156,12 @@ public void TransferTokenTest() triggerData2, triggerCallValue, feeLimit, 0, id); runtime = TvmTestUtils.processTransactionAndReturnRuntime(transaction2, dbManager, null); - org.testng.Assert.assertNull(runtime.getRuntimeError()); + Assert.assertNull(runtime.getRuntimeError()); Assert.assertEquals(100 + tokenValue - 9 + 9, - dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getAssetMapV2() + dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getAssetV2MapForTest() .get(String.valueOf(id)).longValue()); - Assert.assertEquals(99, dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)).getAssetMapV2() - .get(String.valueOf(id2)).longValue()); + Assert.assertEquals(99, dbManager.getAccountStore().get(Hex.decode(TRANSFER_TO)) + .getAssetV2MapForTest().get(String.valueOf(id2)).longValue()); } private byte[] deployTransferTokenContract(long id) @@ -216,7 +191,7 @@ private byte[] deployTransferTokenContract(long id) byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, tokenValue, tokenId, - deposit, null); + repository, null); return contractAddress; } @@ -278,7 +253,7 @@ private byte[] deployTransferTokenPerformanceContract(long id) byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, code, value, feeLimit, consumeUserResourcePercent, null, tokenValue, tokenId, - deposit, null); + repository, null); return contractAddress; } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java index 777166a0bc0..ee49bdca7f6 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMContractTestBase.java @@ -1,13 +1,14 @@ package org.tron.common.runtime.vm; -import java.io.File; +import java.io.IOException; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.After; import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.TronApplicationContext; import org.tron.common.runtime.Runtime; -import org.tron.common.utils.FileUtil; import org.tron.consensus.dpos.DposSlot; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.ChainBaseManager; @@ -26,8 +27,8 @@ @Slf4j public class VMContractTestBase { - - protected String dbPath; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); protected Runtime runtime; protected Manager manager; protected Repository rootRepository; @@ -50,9 +51,9 @@ public class VMContractTestBase { } @Before - public void init() { - dbPath = "output_" + this.getClass().getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + public void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); // TRdmP9bYvML7dGUX9Rbw2kZrE2TayPZmZX - 41abd4b9367799eaa3197fecb144eb71de1e049abc @@ -77,10 +78,5 @@ public void init() { public void destroy() { Args.clearParam(); context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VMTestBase.java b/framework/src/test/java/org/tron/common/runtime/vm/VMTestBase.java index 92febb89ab1..18209543f62 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VMTestBase.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VMTestBase.java @@ -1,20 +1,23 @@ package org.tron.common.runtime.vm; -import java.io.File; +import java.io.IOException; + import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; import org.junit.After; import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.TronApplicationContext; import org.tron.common.runtime.Runtime; -import org.tron.common.storage.Deposit; -import org.tron.common.storage.DepositImpl; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.Manager; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; @Slf4j @@ -22,34 +25,30 @@ public class VMTestBase { protected Manager manager; protected TronApplicationContext context; - protected String dbPath; - protected Deposit rootDeposit; + protected Repository rootRepository; protected String OWNER_ADDRESS; protected Runtime runtime; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + @Before - public void init() { - dbPath = "output_" + this.getClass().getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + public void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; manager = context.getBean(Manager.class); - rootDeposit = DepositImpl.createRoot(manager); - rootDeposit.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); - rootDeposit.addBalance(Hex.decode(OWNER_ADDRESS), 30000000000000L); - - rootDeposit.commit(); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(Hex.decode(OWNER_ADDRESS), AccountType.Normal); + rootRepository.addBalance(Hex.decode(OWNER_ADDRESS), 30000000000000L); + rootRepository.commit(); } @After public void destroy() { Args.clearParam(); context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } } } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java index 4ce516cd11f..a688f5f9a29 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/ValidateMultiSignContractTest.java @@ -1,75 +1,53 @@ package org.tron.common.runtime.vm; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.Hash; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.StringUtil; +import org.tron.common.utils.client.utils.AbiUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.store.StoreFactory; import org.tron.core.vm.PrecompiledContracts.ValidateMultiSign; import org.tron.core.vm.repository.Repository; import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; + @Slf4j -public class ValidateMultiSignContractTest { +public class ValidateMultiSignContractTest extends BaseTest { - private static final String dbPath = "output_ValidateMultiSignContract_test"; private static final String METHOD_SIGN = "validatemultisign(address,uint256,bytes32,bytes[])"; private static final byte[] longData; - private static TronApplicationContext context; - private static Application appT; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); - dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); - + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); longData = new byte[1000000]; Arrays.fill(longData, (byte) 2); } ValidateMultiSign contract = new ValidateMultiSign(); - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + @Before + public void before() { + dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); + dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); } @Test @@ -81,7 +59,7 @@ public void testAddressNonExist() { signs.add(Hex.toHexString(sign)); //Address non exist - Assert.assertEquals( + Assert.assertArrayEquals( validateMultiSign(StringUtil.encode58Check(key.getAddress()), 1, hash, signs) .getValue(), DataWord.ZERO().getData()); } @@ -116,7 +94,8 @@ public void testDifferentCase() { .build(); toAccount - .updatePermissions(toAccount.getPermissionById(0), null, Arrays.asList(activePermission)); + .updatePermissions(toAccount.getPermissionById(0), null, + Collections.singletonList(activePermission)); dbManager.getAccountStore().put(key.getAddress(), toAccount); //generate data @@ -140,21 +119,21 @@ public void testDifferentCase() { signs.add(Hex.toHexString(key1.sign(toSign).toByteArray())); signs.add(Hex.toHexString(key2.sign(toSign).toByteArray())); - Assert.assertEquals( + Assert.assertArrayEquals( validateMultiSign(StringUtil.encode58Check(key.getAddress()), permissionId, data, signs) .getValue(), DataWord.ONE().getData()); //weight not enough signs = new ArrayList<>(); signs.add(Hex.toHexString(key1.sign(toSign).toByteArray())); - Assert.assertEquals( + Assert.assertArrayEquals( validateMultiSign(StringUtil.encode58Check(key.getAddress()), permissionId, data, signs) .getValue(), DataWord.ZERO().getData()); //put wrong sign signs = new ArrayList<>(); signs.add(Hex.toHexString(key1.sign(toSign).toByteArray())); - Assert.assertEquals( + Assert.assertArrayEquals( validateMultiSign(StringUtil.encode58Check(key.getAddress()), permissionId, data, signs) .getValue(), DataWord.ZERO().getData()); @@ -162,7 +141,7 @@ public void testDifferentCase() { signs.add(Hex.toHexString(key1.sign(toSign).toByteArray())); signs.add(Hex.toHexString(new ECKey().sign(toSign).toByteArray())); - Assert.assertEquals( + Assert.assertArrayEquals( validateMultiSign(StringUtil.encode58Check(key.getAddress()), permissionId, data, signs) .getValue(), DataWord.ZERO().getData()); } diff --git a/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java b/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java index 2beedfb3f13..d6493ed8018 100644 --- a/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java +++ b/framework/src/test/java/org/tron/common/runtime/vm/VoteTest.java @@ -1,10 +1,10 @@ package org.tron.common.runtime.vm; +import static org.tron.common.math.Maths.max; import static org.tron.protos.Protocol.Transaction.Result.contractResult; import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT; import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -19,19 +19,20 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Ignore; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.TronApplicationContext; import org.tron.common.parameter.CommonParameter; import org.tron.common.runtime.Runtime; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TVMTestResult; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.Deposit; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.common.utils.WalletUtil; +import org.tron.common.utils.client.utils.AbiUtil; +import org.tron.common.utils.client.utils.DataWord; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -46,9 +47,9 @@ import org.tron.core.store.StoreFactory; import org.tron.core.vm.config.ConfigLoader; import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.DataWord; @Slf4j public class VoteTest { @@ -264,19 +265,20 @@ private static Consumer getSmallerConsumer(long expected) { return getConsumer("<", expected); } - private static String dbPath; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); private static TronApplicationContext context; private static Manager manager; private static MaintenanceManager maintenanceManager; private static ConsensusService consensusService; private static MortgageService mortgageService; private static byte[] owner; - private static Deposit rootDeposit; + private static Repository rootRepository; @Before public void init() throws Exception { - dbPath = "output_" + VoteTest.class.getName(); - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); CommonParameter.getInstance().setCheckFrozenTime(0); context = new TronApplicationContext(DefaultConfig.class); manager = context.getBean(Manager.class); @@ -286,10 +288,10 @@ public void init() throws Exception { mortgageService = context.getBean(MortgageService.class); owner = Hex.decode(Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"); - rootDeposit = DepositImpl.createRoot(manager); - rootDeposit.createAccount(owner, Protocol.AccountType.Normal); - rootDeposit.addBalance(owner, 900_000_000_000_000_000L); - rootDeposit.commit(); + rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(owner, Protocol.AccountType.Normal); + rootRepository.addBalance(owner, 900_000_000_000_000_000L); + rootRepository.commit(); ConfigLoader.disable = true; VMConfig.initVmHardFork(true); @@ -301,6 +303,7 @@ public void init() throws Exception { VMConfig.initAllowTvmVote(1); manager.getDynamicPropertiesStore().saveChangeDelegation(1); manager.getDynamicPropertiesStore().saveAllowTvmVote(1); + manager.getDynamicPropertiesStore().saveNewRewardAlgorithmEffectiveCycle(); } @After @@ -309,11 +312,6 @@ public void destroy() { VMConfig.initVmHardFork(false); Args.clearParam(); context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.error("Release resources failure."); - } } private byte[] deployContract(String contractName, String abi, String code) throws Exception { @@ -864,7 +862,8 @@ private void checkRewardAndWithdraw(byte[] contract, boolean isZero) throws Exce long rewardBySystem = mortgageService.queryReward(contract); long beginCycle = manager.getDelegationStore().getBeginCycle(contract); long currentCycle = manager.getDynamicPropertiesStore().getCurrentCycleNumber(); - long passedCycle = Math.max(0, currentCycle - beginCycle); + long passedCycle = max(0, currentCycle - beginCycle, + manager.getDynamicPropertiesStore().disableJavaLangMath()); Assert.assertTrue(isZero ? rewardBySystem == 0 : rewardBySystem > 0); triggerContract(contract, SUCCESS, getConsumer(">=", rewardBySystem) diff --git a/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java b/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java index f19f927c953..bf18b988f19 100644 --- a/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java +++ b/framework/src/test/java/org/tron/common/storage/leveldb/LevelDbDataSourceImplTest.java @@ -22,30 +22,41 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; +import java.io.IOException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; 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.junit.AfterClass; import org.junit.Assert; import org.junit.Before; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; import org.tron.core.config.args.Args; +import org.tron.core.db2.common.WrappedByteArray; +import org.tron.core.exception.TronError; @Slf4j public class LevelDbDataSourceImplTest { - private static final String dbPath = "output-levelDb-test"; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static LevelDbDataSourceImpl dataSourceTest; private byte[] value1 = "10000".getBytes(); @@ -68,23 +79,20 @@ public class LevelDbDataSourceImplTest { @AfterClass public static void destroy() { Args.clearParam(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } @Before - public void initDb() { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - dataSourceTest = new LevelDbDataSourceImpl(dbPath + File.separator, "test_levelDb"); + public void initDb() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + dataSourceTest = new LevelDbDataSourceImpl( + Args.getInstance().getOutputDirectory() + File.separator, "test_levelDb"); } @Test public void testPutGet() { dataSourceTest.resetDb(); - String key1 = "2c0937534dd1b3832d05d865e8e6f2bf23218300b33a992740d45ccab7d4f519"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSourceTest.initDB(); String value1 = "50000"; @@ -104,6 +112,13 @@ public void testReset() { Args.getInstance().getOutputDirectory(), "test_reset"); dataSource.resetDb(); assertEquals(0, dataSource.allKeys().size()); + assertEquals("LEVELDB", dataSource.getEngine()); + assertEquals("test_reset", dataSource.getName()); + assertEquals(Sets.newHashSet(), dataSource.getlatestValues(0)); + assertEquals(Collections.emptyMap(), dataSource.getNext(key1, 0)); + assertEquals(new ArrayList<>(), dataSource.getKeysNext(key1, 0)); + assertEquals(Sets.newHashSet(), dataSource.getValuesNext(key1, 0)); + assertEquals(Sets.newHashSet(), dataSource.getlatestValues(0)); dataSource.closeDB(); } @@ -113,9 +128,9 @@ public void testupdateByBatchInner() { Args.getInstance().getOutputDirectory(), "test_updateByBatch"); dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); String value1 = "50000"; - String key2 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757351"; + String key2 = PublicMethod.getRandomPrivateKey(); String value2 = "10000"; Map rows = new HashMap<>(); @@ -135,7 +150,7 @@ public void testdeleteData() { LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( Args.getInstance().getOutputDirectory(), "test_delete"); dataSource.initDB(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSource.deleteData(key); byte[] value = dataSource.getData(key); @@ -151,14 +166,14 @@ public void testallKeys() { dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757321"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); String value1 = "50000"; byte[] value = value1.getBytes(); dataSource.putData(key, value); - String key3 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757091"; + String key3 = PublicMethod.getRandomPrivateKey(); byte[] key2 = key3.getBytes(); String value3 = "30000"; @@ -257,25 +272,6 @@ public void getValuesNext() { dataSource.closeDB(); } - @Test - public void getValuesPrev() { - LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( - Args.getInstance().getOutputDirectory(), "test_getValuesPrev_key"); - dataSource.initDB(); - dataSource.resetDb(); - - putSomeKeyValue(dataSource); - Set seekKeyLimitNext = dataSource.getValuesPrev("0000000300".getBytes(), 2); - HashSet hashSet = Sets.newHashSet(ByteArray.toStr(value1), ByteArray.toStr(value2)); - seekKeyLimitNext.forEach(valeu -> { - Assert.assertTrue("getValuesPrev1", hashSet.contains(ByteArray.toStr(valeu))); - }); - seekKeyLimitNext = dataSource.getValuesPrev("0000000100".getBytes(), 2); - Assert.assertEquals("getValuesPrev2", 0, seekKeyLimitNext.size()); - dataSource.resetDb(); - dataSource.closeDB(); - } - @Test public void testGetTotal() { LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( @@ -312,4 +308,59 @@ public void getKeysNext() { dataSource.resetDb(); dataSource.closeDB(); } -} \ No newline at end of file + + @Test + public void prefixQueryTest() { + LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "test_prefixQuery"); + dataSource.initDB(); + dataSource.resetDb(); + + putSomeKeyValue(dataSource); + // put a kv that will not be queried. + byte[] key7 = "0000001".getBytes(); + byte[] value7 = "0000001v".getBytes(); + dataSource.putData(key7, value7); + + byte[] prefix = "0000000".getBytes(); + + List result = dataSource.prefixQuery(prefix) + .keySet() + .stream() + .map(WrappedByteArray::getBytes) + .map(ByteArray::toStr) + .collect(Collectors.toList()); + List list = Arrays.asList( + ByteArray.toStr(key1), + ByteArray.toStr(key2), + ByteArray.toStr(key3), + ByteArray.toStr(key4), + ByteArray.toStr(key5), + ByteArray.toStr(key6)); + + Assert.assertEquals(list.size(), result.size()); + list.forEach(entry -> Assert.assertTrue(result.contains(entry))); + + dataSource.resetDb(); + dataSource.closeDB(); + } + + @Test + public void initDbTest() { + makeExceptionDb("test_initDb"); + LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "test_initDb"); + TronError thrown = assertThrows(TronError.class, dataSource::initDB); + assertEquals(TronError.ErrCode.LEVELDB_INIT, thrown.getErrCode()); + } + + private void makeExceptionDb(String dbName) { + LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "test_initDb"); + dataSource.initDB(); + dataSource.closeDB(); + FileUtil.saveData(dataSource.getDbPath().toString() + "/CURRENT", + "...", Boolean.FALSE); + } + +} diff --git a/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java b/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java index e872b4ddfab..c6fce30e3af 100644 --- a/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java +++ b/framework/src/test/java/org/tron/common/storage/leveldb/RocksDbDataSourceImplTest.java @@ -4,32 +4,42 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; +import java.io.IOException; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; 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.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl; import org.tron.common.utils.ByteArray; import org.tron.common.utils.FileUtil; import org.tron.common.utils.PropUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.config.args.Args; +import org.tron.core.db2.common.WrappedByteArray; +import org.tron.core.exception.TronError; @Slf4j public class RocksDbDataSourceImplTest { - private static final String dbPath = "output-Rocks-test"; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static RocksDbDataSourceImpl dataSourceTest; private byte[] value1 = "10000".getBytes(); @@ -50,31 +60,21 @@ public class RocksDbDataSourceImplTest { */ @AfterClass public static void destroy() { - String directory = Args.getInstance().getStorage().getDbDirectory(); Args.clearParam(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - - if (FileUtil.deleteDir(new File(dbPath + directory))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } @BeforeClass - public static void initDb() { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-test-dbbackup.conf"); - dataSourceTest = new RocksDbDataSourceImpl(dbPath + File.separator, "test_rocksDb"); + public static void initDb() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString()}, "config-test-dbbackup.conf"); + dataSourceTest = new RocksDbDataSourceImpl( + Args.getInstance().getOutputDirectory() + File.separator, "test_rocksDb"); } @Test public void testPutGet() { dataSourceTest.resetDb(); - String key1 = "2c0937534dd1b3832d05d865e8e6f2bf23218300b33a992740d45ccab7d4f519"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSourceTest.initDB(); String value1 = "50000"; @@ -94,6 +94,13 @@ public void testReset() { Args.getInstance().getOutputDirectory(), "test_reset"); dataSource.resetDb(); assertEquals(0, dataSource.allKeys().size()); + assertEquals("ROCKSDB", dataSource.getEngine()); + assertEquals("test_reset", dataSource.getName()); + assertEquals(Sets.newHashSet(), dataSource.getlatestValues(0)); + assertEquals(Collections.emptyMap(), dataSource.getNext(key1, 0)); + assertEquals(new ArrayList<>(), dataSource.getKeysNext(key1, 0)); + assertEquals(Sets.newHashSet(), dataSource.getValuesNext(key1, 0)); + assertEquals(Sets.newHashSet(), dataSource.getlatestValues(0)); dataSource.closeDB(); } @@ -103,9 +110,9 @@ public void testupdateByBatchInner() { Args.getInstance().getOutputDirectory(), "test_updateByBatch"); dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); String value1 = "50000"; - String key2 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757351"; + String key2 = PublicMethod.getRandomPrivateKey(); String value2 = "10000"; Map rows = new HashMap<>(); @@ -125,7 +132,7 @@ public void testdeleteData() { RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( Args.getInstance().getOutputDirectory(), "test_delete"); dataSource.initDB(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757350"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); dataSource.deleteData(key); byte[] value = dataSource.getData(key); @@ -141,14 +148,14 @@ public void testallKeys() { dataSource.initDB(); dataSource.resetDb(); - String key1 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757321"; + String key1 = PublicMethod.getRandomPrivateKey(); byte[] key = key1.getBytes(); String value1 = "50000"; byte[] value = value1.getBytes(); dataSource.putData(key, value); - String key3 = "431cd8c8d5abe5cb5944b0889b32482d85772fbb98987b10fbb7f17110757091"; + String key3 = PublicMethod.getRandomPrivateKey(); byte[] key2 = key3.getBytes(); String value3 = "30000"; @@ -245,25 +252,6 @@ public void getValuesNext() { dataSource.closeDB(); } - @Test - public void getValuesPrev() { - RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( - Args.getInstance().getOutputDirectory(), "test_getValuesPrev_key"); - dataSource.initDB(); - dataSource.resetDb(); - - putSomeKeyValue(dataSource); - Set seekKeyLimitNext = dataSource.getValuesPrev("0000000300".getBytes(), 2); - HashSet hashSet = Sets.newHashSet(ByteArray.toStr(value1), ByteArray.toStr(value2)); - seekKeyLimitNext.forEach(value -> { - Assert.assertTrue("getValuesPrev1", hashSet.contains(ByteArray.toStr(value))); - }); - seekKeyLimitNext = dataSource.getValuesPrev("0000000100".getBytes(), 2); - Assert.assertEquals("getValuesPrev2", 0, seekKeyLimitNext.size()); - dataSource.resetDb(); - dataSource.closeDB(); - } - @Test public void testCheckOrInitEngine() { String dir = @@ -288,7 +276,9 @@ public void testCheckOrInitEngine() { try { dataSource.initDB(); } catch (Exception e) { - Assert.assertTrue(e.getMessage().contains("Failed to")); + Assert.assertEquals(String.format("failed to check database: %s, engine do not match", + "test_engine"), + e.getMessage()); } Assert.assertNull(dataSource.getDatabase()); PropUtil.writeProperty(enginePath, "ENGINE", "ROCKSDB"); @@ -360,4 +350,58 @@ public void getKeysNext() { dataSource.resetDb(); dataSource.closeDB(); } + + @Test + public void prefixQueryTest() { + RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "test_prefixQuery"); + dataSource.initDB(); + dataSource.resetDb(); + + putSomeKeyValue(dataSource); + // put a kv that will not be queried. + byte[] key7 = "0000001".getBytes(); + byte[] value7 = "0000001v".getBytes(); + dataSource.putData(key7, value7); + + byte[] prefix = "0000000".getBytes(); + + List result = dataSource.prefixQuery(prefix) + .keySet() + .stream() + .map(WrappedByteArray::getBytes) + .map(ByteArray::toStr) + .collect(Collectors.toList()); + List list = Arrays.asList( + ByteArray.toStr(key1), + ByteArray.toStr(key2), + ByteArray.toStr(key3), + ByteArray.toStr(key4), + ByteArray.toStr(key5), + ByteArray.toStr(key6)); + + Assert.assertEquals(list.size(), result.size()); + list.forEach(entry -> Assert.assertTrue(result.contains(entry))); + + dataSource.resetDb(); + dataSource.closeDB(); + } + + @Test + public void initDbTest() { + makeExceptionDb("test_initDb"); + RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "test_initDb"); + TronError thrown = assertThrows(TronError.class, dataSource::initDB); + assertEquals(TronError.ErrCode.ROCKSDB_INIT, thrown.getErrCode()); + } + + private void makeExceptionDb(String dbName) { + RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "test_initDb"); + dataSource.initDB(); + dataSource.closeDB(); + FileUtil.saveData(dataSource.getDbPath().toString() + "/CURRENT", + "...", Boolean.FALSE); + } } diff --git a/framework/src/test/java/org/tron/common/utils/ALockTest.java b/framework/src/test/java/org/tron/common/utils/ALockTest.java new file mode 100644 index 00000000000..d4501756daa --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ALockTest.java @@ -0,0 +1,27 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertNotNull; + +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; +import org.junit.Before; +import org.junit.Test; + +public class ALockTest { + private ALock aLock; + private Lock mockLock; + + @Before + public void setUp() { + mockLock = new ReentrantLock(); + aLock = new ALock(mockLock); + } + + @Test + public void testLockAndUnlock() { + aLock.lock(); + assertNotNull(aLock); + aLock.close(); + } + +} diff --git a/framework/src/test/java/org/tron/common/utils/BIUtilTest.java b/framework/src/test/java/org/tron/common/utils/BIUtilTest.java new file mode 100644 index 00000000000..d126eb2a6b1 --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/BIUtilTest.java @@ -0,0 +1,155 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import org.junit.Test; + +public class BIUtilTest { + + @Test + public void testIsLessThan() { + BigInteger valueA = BigInteger.valueOf(1); + BigInteger valueB = BigInteger.valueOf(2); + assertTrue(BIUtil.isLessThan(valueA, valueB)); + + valueA = BigInteger.valueOf(3); + valueB = BigInteger.valueOf(3); + assertFalse(BIUtil.isLessThan(valueA, valueB)); + + valueA = BigInteger.valueOf(4); + valueB = BigInteger.valueOf(2); + assertFalse(BIUtil.isLessThan(valueA, valueB)); + } + + @Test + public void testIsZero() { + BigInteger value = BigInteger.ZERO; + assertTrue(BIUtil.isZero(value)); + + value = BigInteger.valueOf(1); + assertFalse(BIUtil.isZero(value)); + + value = BigInteger.valueOf(-1); + assertFalse(BIUtil.isZero(value)); + } + + @Test + public void testIsEqual() { + BigInteger valueA = BigInteger.valueOf(1); + BigInteger valueB = BigInteger.valueOf(1); + assertTrue(BIUtil.isEqual(valueA, valueB)); + + valueA = BigInteger.valueOf(2); + valueB = BigInteger.valueOf(3); + assertFalse(BIUtil.isEqual(valueA, valueB)); + } + + @Test + public void testIsNotEqual() { + BigInteger valueA = BigInteger.valueOf(1); + BigInteger valueB = BigInteger.valueOf(2); + assertTrue(BIUtil.isNotEqual(valueA, valueB)); + + valueA = BigInteger.valueOf(3); + valueB = BigInteger.valueOf(3); + assertFalse(BIUtil.isNotEqual(valueA, valueB)); + } + + @Test + public void testIsMoreThan() { + BigInteger valueA = BigInteger.valueOf(3); + BigInteger valueB = BigInteger.valueOf(2); + assertTrue(BIUtil.isMoreThan(valueA, valueB)); + + valueA = BigInteger.valueOf(1); + valueB = BigInteger.valueOf(2); + assertFalse(BIUtil.isMoreThan(valueA, valueB)); + + valueA = BigInteger.valueOf(2); + valueB = BigInteger.valueOf(2); + assertFalse(BIUtil.isMoreThan(valueA, valueB)); + } + + @Test + public void testSum() { + BigInteger valueA = BigInteger.valueOf(5); + BigInteger valueB = BigInteger.valueOf(7); + BigInteger expected = BigInteger.valueOf(12); + assertEquals(expected, BIUtil.sum(valueA, valueB)); + } + + @Test + public void testToBI_byteArray() { + byte[] data = {1, 0, 0, 0, 0, 0, 0, 1}; // BigInteger(128) + BigInteger expected = new BigInteger(1, data); + assertEquals(expected, BIUtil.toBI(data)); + } + + @Test + public void testToBI_long() { + long data = 123456789L; + BigInteger expected = BigInteger.valueOf(data); + assertEquals(expected, BIUtil.toBI(data)); + } + + @Test + public void testIsPositive() { + BigInteger value = BigInteger.valueOf(1); + assertTrue(BIUtil.isPositive(value)); + + value = BigInteger.ZERO; + assertFalse(BIUtil.isPositive(value)); + + value = BigInteger.valueOf(-1); + assertFalse(BIUtil.isPositive(value)); + } + + @Test + public void testIsNotCovers() { + BigInteger covers = BigInteger.valueOf(5); + BigInteger value = BigInteger.valueOf(10); + assertTrue(BIUtil.isNotCovers(covers, value)); + + covers = BigInteger.valueOf(10); + value = BigInteger.valueOf(5); + assertFalse(BIUtil.isNotCovers(covers, value)); + + covers = BigInteger.valueOf(10); + value = BigInteger.valueOf(10); + assertFalse(BIUtil.isNotCovers(covers, value)); + } + + @Test + public void testMax() { + BigInteger first = BigInteger.valueOf(5); + BigInteger second = BigInteger.valueOf(10); + assertEquals(second, BIUtil.max(first, second)); + + first = BigInteger.valueOf(15); + second = BigInteger.valueOf(10); + assertEquals(first, BIUtil.max(first, second)); + + first = BigInteger.valueOf(10); + second = BigInteger.valueOf(10); + assertEquals(first, BIUtil.max(first, second)); + } + + @Test + public void testAddSafely() { + int a = Integer.MAX_VALUE; + int b = 1; + int expected = Integer.MAX_VALUE; + assertEquals(expected, BIUtil.addSafely(a, b)); + + a = Integer.MAX_VALUE - 1; + b = 2; + assertEquals(expected, BIUtil.addSafely(a, b)); + + a = 1; + expected = 3; + assertEquals(expected, BIUtil.addSafely(a, b)); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ByteArrayMapTest.java b/framework/src/test/java/org/tron/common/utils/ByteArrayMapTest.java new file mode 100644 index 00000000000..b367ade7e4f --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ByteArrayMapTest.java @@ -0,0 +1,173 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import lombok.Getter; +import org.junit.Before; +import org.junit.Test; + +public class ByteArrayMapTest { + + private ByteArrayMap byteArrayMap; + + @Before + public void setUp() { + byteArrayMap = new ByteArrayMap<>(); + } + + @Test + public void testPutAndGet() { + byte[] key = "key1".getBytes(); + String value = "value1"; + byteArrayMap.put(key, value); + assertEquals("Should return the correct value", value, byteArrayMap.get(key)); + } + + @Test + public void testSize() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + assertEquals("Should return the correct size", 2, byteArrayMap.size()); + } + + @Test + public void testRemove() { + byte[] key = "key".getBytes(); + String value = "value"; + byteArrayMap.put(key, value); + byteArrayMap.remove(key); + assertNull("Should return null after removal", byteArrayMap.get(key)); + } + + @Test + public void testContainsKey() { + byte[] key = "key".getBytes(); + byteArrayMap.put(key, "value"); + assertTrue("Should contain the key", byteArrayMap.containsKey(key)); + } + + @Test + public void testPutAll() { + Map mapToPut = createTestMap(); + byteArrayMap.putAll(mapToPut); + assertEquals("Should contain all entries after putAll", 2, byteArrayMap.size()); + assertEquals("Should return the correct value for key1", + "value1", byteArrayMap.get("key1".getBytes())); + assertEquals("Should return the correct value for key2", + "value2", byteArrayMap.get("key2".getBytes())); + + } + + @Test + public void testClear() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + assertFalse(byteArrayMap.isEmpty()); + byteArrayMap.clear(); + } + + @Test + public void testKeySet() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + Set set = byteArrayMap.keySet(); + assertTrue("Key set should contain key1", set.contains(key1)); + assertTrue("Key set should contain key2", set.contains(key2)); + } + + @Test + public void testValues() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + Collection values = byteArrayMap.values(); + assertTrue("Values should contain value1", values.contains("value1")); + assertTrue("Values should contain value1", byteArrayMap.containsValue("value1")); + assertTrue("Values should contain value2", values.contains("value2")); + } + + @Test + public void testEntrySet() { + byte[] key1 = "key1".getBytes(); + byte[] key2 = "key2".getBytes(); + byteArrayMap.put(key1, "value1"); + byteArrayMap.put(key2, "value2"); + Set> entrySet = byteArrayMap.entrySet(); + assertFalse(entrySet.isEmpty()); + assertEquals("Entry set size should be 2", 2, entrySet.size()); + assertThrows(Exception.class, () -> entrySet.contains(new Object())); + assertThrows(Exception.class, entrySet::toArray); + assertThrows(Exception.class, () -> entrySet.toArray(new Map.Entry[0])); + assertThrows(Exception.class, () -> entrySet.add(new MapEntry(key1, "value1"))); + assertThrows(Exception.class, () -> entrySet.remove(new MapEntry(key1, "value1"))); + assertThrows(Exception.class, () -> entrySet.containsAll(new HashSet<>())); + assertThrows(Exception.class, () -> entrySet.removeAll(new HashSet<>())); + assertThrows(Exception.class, () -> entrySet.addAll(new HashSet<>())); + assertThrows(Exception.class, () -> entrySet.retainAll(new HashSet<>())); + assertThrows(Exception.class, entrySet::clear); + } + + // Helper method to create a map for testing putAll + private Map createTestMap() { + Map map = new ByteArrayMap<>(); + map.put("key1".getBytes(), "value1"); + map.put("key2".getBytes(), "value2"); + return map; + } + + + @Test + public void test() { + Map map = new ByteArrayMap<>(); + Map testMap = createTestMap(); + assertNotEquals(map, testMap); + assertTrue(testMap.hashCode() <= 0); + assertNotNull(testMap.toString()); + } + + + @Getter + static class MapEntry implements Map.Entry { + K key; + V value; + + public MapEntry(K key, V value) { + this.key = key; + this.value = value; + } + + public V setValue(V o) { + throw new UnsupportedOperationException(); + } + + public boolean equals(Object o) { + if (o instanceof Map.Entry) { + Map.Entry other = (Map.Entry) o; + return Objects.equals(key, other.getKey()) && Objects.equals(value, other.getValue()); + } + return false; + } + + public int hashCode() { + return Objects.hashCode(key) ^ Objects.hashCode(value); + } + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ByteArraySetTest.java b/framework/src/test/java/org/tron/common/utils/ByteArraySetTest.java new file mode 100644 index 00000000000..22695f713a7 --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ByteArraySetTest.java @@ -0,0 +1,143 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import org.junit.Before; +import org.junit.Test; + +public class ByteArraySetTest { + + private ByteArraySet byteArraySet; + + @Before + public void setUp() { + byteArraySet = new ByteArraySet(); + } + + @Test + public void testSizeIsEmptyInitially() { + assertEquals(0, byteArraySet.size()); + } + + @Test + public void testIsEmptyInitially() { + assertTrue(byteArraySet.isEmpty()); + } + + @Test + public void testAddAndGetSize() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + assertEquals(1, byteArraySet.size()); + + byteArraySet.add(bytes2); + assertEquals(2, byteArraySet.size()); + } + + @Test + public void testContains() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + assertTrue(byteArraySet.contains(bytes1)); + assertFalse(byteArraySet.contains(bytes2)); + + byteArraySet.add(bytes2); + assertTrue(byteArraySet.contains(bytes2)); + + assertThrows(Exception.class, () -> byteArraySet.containsAll(new HashSet<>())); + assertThrows(Exception.class, () -> byteArraySet.retainAll(new HashSet<>())); + assertThrows(Exception.class, () -> byteArraySet.removeAll(new HashSet<>())); + assertThrows(Exception.class, () -> byteArraySet.equals(new ByteArraySet())); + assertThrows(Exception.class, () -> byteArraySet.hashCode()); + } + + @Test + public void testIterator() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + + Iterator iterator = byteArraySet.iterator(); + + assertTrue(iterator.hasNext()); + assertArrayEquals(bytes1, iterator.next()); + + assertTrue(iterator.hasNext()); + assertArrayEquals(bytes2, iterator.next()); + + assertFalse(iterator.hasNext()); + } + + @Test + public void testToArray() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + + byte[][] array = byteArraySet.toArray(new byte[0][]); + + assertEquals(2, array.length); + assertArrayEquals(bytes1, array[0]); + assertArrayEquals(bytes2, array[1]); + } + + @Test + public void testAddAll() { + List list = Arrays.asList( + new byte[]{1, 2, 3}, + new byte[]{4, 5, 6} + ); + + boolean result = byteArraySet.addAll(list); + + assertTrue(result); + assertEquals(2, byteArraySet.size()); + assertTrue(byteArraySet.contains(new byte[]{1, 2, 3})); + assertTrue(byteArraySet.contains(new byte[]{4, 5, 6})); + } + + @Test + public void testRemove() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + + boolean result = byteArraySet.remove(bytes1); + + assertTrue(result); + assertEquals(1, byteArraySet.size()); + assertFalse(byteArraySet.contains(bytes1)); + assertTrue(byteArraySet.contains(bytes2)); + } + + @Test + public void testClear() { + byte[] bytes1 = {1, 2, 3}; + byte[] bytes2 = {4, 5, 6}; + + byteArraySet.add(bytes1); + byteArraySet.add(bytes2); + assertTrue(byteArraySet.size() > 0); + + byteArraySet.clear(); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java b/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java index 226b00b8cb1..c0db8c4b418 100644 --- a/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java +++ b/framework/src/test/java/org/tron/common/utils/ByteArrayTest.java @@ -17,6 +17,12 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.ByteArray.fromHex; +import static org.tron.common.utils.ByteArray.jsonHexToInt; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; @@ -80,4 +86,33 @@ public void test2ToHexString() { assertEquals("ByteArray.toHexString is not equals Hex.toHexString", ByteArray.toHexString(bss), Hex.toHexString(bss)); } + + @Test + public void testFromObject_SerializableObject() { + String testString = "Hello, World!"; + byte[] result = ByteArray.fromObject(testString); + assertNotNull(result); + assertTrue(result.length > 0); + } + + @Test + public void testJsonHexToInt_ValidHex() { + try { + int result = jsonHexToInt("0x1A"); + assertEquals(26, result); + } catch (Exception e) { + fail("Exception should not have been thrown for valid hex string."); + } + assertThrows(Exception.class, () -> ByteArray.jsonHexToInt("1A")); + } + + @Test + public void testFromHexWithPrefix() { + String input = "0x1A3F"; + String expected = "1A3F"; + String result = fromHex(input); + assertEquals(expected, result); + String input1 = "1A3"; + assertEquals("01A3", fromHex(input1)); + } } diff --git a/framework/src/test/java/org/tron/common/utils/CollectionUtilsTest.java b/framework/src/test/java/org/tron/common/utils/CollectionUtilsTest.java new file mode 100644 index 00000000000..8b8ef35fb4b --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/CollectionUtilsTest.java @@ -0,0 +1,81 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Predicate; +import org.junit.Test; + +public class CollectionUtilsTest { + + @Test + public void testCollectList() { + List numbers = Arrays.asList("1", "2", "3"); + Function toInt = Integer::parseInt; + List integers = CollectionUtils.collectList(numbers, toInt); + assertEquals(Arrays.asList(1, 2, 3), integers); + } + + @Test + public void testCollectSet() { + List numbers = Arrays.asList("1", "2", "2", "3"); + Function toInt = Integer::parseInt; + Set integers = CollectionUtils.collectSet(numbers, toInt); + assertEquals(new HashSet<>(Arrays.asList(1, 2, 3)), integers); + } + + @Test + public void testTruncate() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List truncated = CollectionUtils.truncate(numbers, 3); + assertEquals(Arrays.asList(1, 2, 3), truncated); + } + + @Test + public void testTruncateNoLimit() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List truncated = CollectionUtils.truncate(numbers, 10); + assertEquals(numbers, truncated); + } + + @Test + public void testTruncateRandom() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List numbers1 = Arrays.asList(1, 2); + List truncated = CollectionUtils.truncateRandom(numbers, 3, 2); + List truncated1 = CollectionUtils.truncateRandom(numbers1, 3, 2); + assertEquals(2, truncated1.size()); + assertEquals(3, truncated.size()); + assertTrue(truncated.containsAll(Arrays.asList(1, 2, 3, 4, 5).subList(0, 2))); + // Last element could be 3, 4, or 5, so we just check that it's one of them + assertTrue(truncated.contains(3) || truncated.contains(4) || truncated.contains(5)); + } + + @Test + public void testTruncateRandomConfirmEqualLimit() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + List truncated = CollectionUtils.truncateRandom(numbers, 5, 5); + assertEquals(numbers, truncated); + } + + @Test + public void testSelectList() { + List numbers = Arrays.asList(1, 2, 3, 4, 5); + Predicate isEven = n -> n % 2 == 0; + List selected = CollectionUtils.selectList(numbers, isEven); + assertEquals(Arrays.asList(2, 4), selected); + } + + @Test + public void testSelectSet() { + List numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); + Predicate isEven = n -> n % 2 == 0; + Set selected = CollectionUtils.selectSet(numbers, isEven); + assertEquals(new HashSet<>(Arrays.asList(2, 4)), selected); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/FileUtilTest.java b/framework/src/test/java/org/tron/common/utils/FileUtilTest.java index 9aff1566ef3..126e0918520 100644 --- a/framework/src/test/java/org/tron/common/utils/FileUtilTest.java +++ b/framework/src/test/java/org/tron/common/utils/FileUtilTest.java @@ -1,11 +1,88 @@ package org.tron.common.utils; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.tron.common.utils.FileUtil.readData; + import java.io.File; +import java.io.FileWriter; import java.io.IOException; +import java.nio.file.FileVisitResult; +import java.nio.file.FileVisitor; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import org.junit.After; import org.junit.Assert; +import org.junit.Before; import org.junit.Test; public class FileUtilTest { + private Path tempDir; + + @Before + public void setUp() throws IOException { + tempDir = Files.createTempDirectory("testDir"); + + Files.createFile(tempDir.resolve("file1.txt")); + Files.createFile(tempDir.resolve("file2.txt")); + + Path subDir = Files.createDirectory(tempDir.resolve("subdir")); + Files.createFile(subDir.resolve("file3.txt")); + } + + @After + public void tearDown() throws IOException { + Files.walk(tempDir) + .sorted(Comparator.reverseOrder()) + .forEach(path -> { + try { + Files.delete(path); + } catch (IOException e) { + e.printStackTrace(); + } + }); + } + + @Test + public void testRecursiveList() throws IOException { + List files = FileUtil.recursiveList(tempDir.toString()); + + assertTrue(files.contains(tempDir.resolve("file1.txt").toString())); + assertTrue(files.contains(tempDir.resolve("file2.txt").toString())); + assertTrue(files.contains(tempDir.resolve("subdir").resolve("file3.txt").toString())); + + assertEquals(3, files.size()); + } + + @Test + public void testReadData_NormalFile() throws IOException { + Path tempFile = Files.createTempFile("testfile", ".txt"); + try (FileWriter writer = new FileWriter(tempFile.toFile())) { + writer.write("Hello, World!"); + } + + char[] buffer = new char[1024]; + int len = readData(tempFile.toString(), buffer); + + assertEquals(13, len); + assertArrayEquals("Hello, World!".toCharArray(), Arrays.copyOf(buffer, 13)); + } + + @Test + public void testReadData_IOException() { + char[] buffer = new char[1024]; + File dir = new File(System.getProperty("java.io.tmpdir")); + int len = readData(dir.getAbsolutePath(), buffer); + assertEquals(0, len); + } + @Test public void testCreateFileIfNotExists() { @@ -16,15 +93,15 @@ public void testCreateFileIfNotExists() { } catch (IOException e) { System.out.println("ignore this exception."); } - Assert.assertTrue(file1.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(existFile)); - Assert.assertTrue(file1.exists()); + assertTrue(file1.exists()); + assertTrue(FileUtil.createDirIfNotExists(existFile)); + assertTrue(file1.exists()); String notExistFile = "notexistsfile.txt"; File file2 = new File(notExistFile); - Assert.assertTrue(!file2.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(notExistFile)); - Assert.assertTrue(file2.exists()); + assertTrue(!file2.exists()); + assertTrue(FileUtil.createDirIfNotExists(notExistFile)); + assertTrue(file2.exists()); file1.delete(); file2.delete(); } @@ -34,16 +111,18 @@ public void testCreateDirIfNotExists() { String existDir = "existsdir"; File fileDir1 = new File(existDir); fileDir1.mkdir(); - Assert.assertTrue(fileDir1.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(existDir)); - Assert.assertTrue(fileDir1.exists()); + assertTrue(fileDir1.exists()); + assertTrue(FileUtil.createDirIfNotExists(existDir)); + assertTrue(fileDir1.exists()); String notExistDir = "notexistsdir"; File fileDir2 = new File(notExistDir); - Assert.assertTrue(!fileDir2.exists()); - Assert.assertTrue(FileUtil.createDirIfNotExists(notExistDir)); - Assert.assertTrue(fileDir2.exists()); + assertTrue(!fileDir2.exists()); + assertTrue(FileUtil.createDirIfNotExists(notExistDir)); + assertTrue(fileDir2.exists()); fileDir1.delete(); fileDir2.delete(); } + + } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java b/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java index ae006f21521..8681ff58270 100644 --- a/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java +++ b/framework/src/test/java/org/tron/common/utils/JsonUtilTest.java @@ -1,31 +1,80 @@ package org.tron.common.utils; -import java.util.ArrayList; -import java.util.List; -import org.junit.Assert; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.JsonUtil.json2Obj; +import static org.tron.common.utils.JsonUtil.obj2Json; + +import lombok.Data; import org.junit.Test; -import org.tron.common.overlay.discover.node.DBNode; -import org.tron.common.overlay.discover.node.DBNodeStats; -import org.tron.common.overlay.discover.node.Node; public class JsonUtilTest { + @Data + public static class A { + private String key; + private int value; + + public A() {} + + public A(String key, int value) { + this.key = key; + this.value = value; + } + } + @Test public void test() { - DBNode dbNode = new DBNode(); - DBNodeStats dbNodeStats = new DBNodeStats(Node.getNodeId(), "1.0.0.1", 1000, 100); - List nodes = new ArrayList(); - nodes.add(dbNodeStats); - dbNode.setNodes(nodes); + A a1 = new A(); + a1.setKey("abc"); + a1.setValue(100); + + String jsonString = obj2Json(a1); + + A a2 = JsonUtil.json2Obj(jsonString, A.class); + + assert a2 != null; + assertEquals("abc", a2.getKey()); + assertEquals(100, a2.getValue()); + assertNull(obj2Json(null)); + assertNull(json2Obj(null, null)); - String jsonString = JsonUtil.obj2Json(dbNode); - DBNode dbNode2 = JsonUtil.json2Obj(jsonString, DBNode.class); + } + + @Test + public void testObj2JsonWithCircularReference() { + Node node1 = new Node("Node1"); + Node node2 = new Node("Node2"); + node1.setNext(node2); + node2.setNext(node1); + + try { + obj2Json(node1); + fail("Expected a RuntimeException to be thrown"); + } catch (RuntimeException e) { + assertTrue(e.getCause() instanceof com.fasterxml.jackson.databind.JsonMappingException); + } + } + + @Test(expected = RuntimeException.class) + public void testInvalidJson() { + String invalidJson = "{invalid: json}"; + json2Obj(invalidJson, String.class); + } + + class Node { + private String name; + private org.tron.common.utils.JsonUtilTest.Node next; - dbNodeStats = dbNode2.getNodes().get(0); + public Node(String name) { + this.name = name; + } - Assert.assertEquals(dbNodeStats.getHost(), "1.0.0.1"); - Assert.assertEquals(dbNodeStats.getPort(), 1000); - Assert.assertEquals(dbNodeStats.getReputation(), 100); + public void setNext(org.tron.common.utils.JsonUtilTest.Node next) { + this.next = next; + } } } diff --git a/framework/src/test/java/org/tron/common/utils/PublicMethod.java b/framework/src/test/java/org/tron/common/utils/PublicMethod.java new file mode 100644 index 00000000000..63feab160d4 --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/PublicMethod.java @@ -0,0 +1,355 @@ +package org.tron.common.utils; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonParser; +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.Socket; +import java.util.Objects; +import java.util.Random; + +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; + +import org.tron.api.GrpcAPI; +import org.tron.api.WalletGrpc; +import org.tron.common.crypto.ECKey; +import org.tron.common.crypto.sm2.SM2; +import org.tron.common.crypto.sm2.SM2Signer; +import org.tron.common.utils.client.utils.TransactionUtils; +import org.tron.core.Wallet; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.SmartContractOuterClass; + +@Slf4j +public class PublicMethod { + + public static ECKey getRandomECKey(String privateKey) { + BigInteger priK = new BigInteger(privateKey, 16); + return ECKey.fromPrivate(priK); + } + + public static String getRandomPrivateKey() { + return Hex.toHexString(Objects + .requireNonNull(new ECKey(Utils.getRandom()).getPrivKeyBytes())); + } + + public static String getHexAddressByPrivateKey(String privateKey) { + return ByteArray.toHexString(getAddressByteByPrivateKey(privateKey)); + } + + public static byte[] getAddressByteByPrivateKey(String privateKey) { + return getRandomECKey(privateKey).getAddress(); + } + + public static String getPublicByPrivateKey(String privateKey) { + return Hex.toHexString(getRandomECKey(privateKey).getPubKey()); + } + + public static byte[] getPublicKeyFromPrivate(String privateKey) { + BigInteger tmpKey = new BigInteger(privateKey, 16); + return ECKey.publicKeyFromPrivate(tmpKey, true); + } + + public static String getSM2RandomPrivateKey() { + SM2 key = new SM2(Utils.getRandom()); + return Hex.toHexString( + Objects.requireNonNull(key.getPrivKeyBytes())); + } + + public static SM2 getSM2byPrivate(String privateKey) { + BigInteger priK = new BigInteger(privateKey, 16); + return SM2.fromPrivate(priK); + } + + public static String getSM2PublicByPrivateKey(String privateKey) { + return Hex.toHexString(getSM2byPrivate(privateKey).getPubKey()); + } + + public static String getSM2AddressByPrivateKey(String privateKey) { + return ByteArray + .toHexString(getSM2byPrivate(privateKey).getAddress()); + } + + public static byte[] getSM2PublicKeyFromPrivate(String privateKey) { + BigInteger tmpKey = new BigInteger(privateKey, 16); + return SM2.publicKeyFromPrivate(tmpKey, true); + } + + public static byte[] getSM2HashByPubKey(byte[] pubKey, String message) { + SM2 key = SM2.fromPublicOnly(pubKey); + SM2Signer signer = key.getSM2SignerForHash(); + return signer.generateSM3Hash(message.getBytes()); + } + + /** constructor. */ + public static SmartContractOuterClass.SmartContract.ABI jsonStr2Abi(String jsonStr) { + if (jsonStr == null) { + return null; + } + + JsonParser jsonParser = new JsonParser(); + JsonElement jsonElementRoot = jsonParser.parse(jsonStr); + JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); + SmartContractOuterClass.SmartContract.ABI.Builder abiBuilder = + SmartContractOuterClass.SmartContract.ABI.newBuilder(); + for (int index = 0; index < jsonRoot.size(); index++) { + JsonElement abiItem = jsonRoot.get(index); + boolean anonymous = + abiItem.getAsJsonObject().get("anonymous") != null + && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); + final boolean constant = + abiItem.getAsJsonObject().get("constant") != null + && abiItem.getAsJsonObject().get("constant").getAsBoolean(); + final String name = + abiItem.getAsJsonObject().get("name") != null + ? abiItem.getAsJsonObject().get("name").getAsString() + : null; + JsonArray inputs = + abiItem.getAsJsonObject().get("inputs") != null + ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() : null; + final JsonArray outputs = + abiItem.getAsJsonObject().get("outputs") != null + ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() : null; + String type = + abiItem.getAsJsonObject().get("type") != null + ? abiItem.getAsJsonObject().get("type").getAsString() : null; + final boolean payable = + abiItem.getAsJsonObject().get("payable") != null + && abiItem.getAsJsonObject().get("payable").getAsBoolean(); + final String stateMutability = + abiItem.getAsJsonObject().get("stateMutability") != null + ? abiItem.getAsJsonObject().get("stateMutability").getAsString() + : null; + if (type == null) { + logger.error("No type!"); + return null; + } + if (!type.equalsIgnoreCase("fallback") && null == inputs) { + logger.error("No inputs!"); + return null; + } + + SmartContractOuterClass.SmartContract.ABI.Entry.Builder entryBuilder = + SmartContractOuterClass.SmartContract.ABI.Entry.newBuilder(); + entryBuilder.setAnonymous(anonymous); + entryBuilder.setConstant(constant); + if (name != null) { + entryBuilder.setName(name); + } + + /* { inputs : optional } since fallback function not requires inputs*/ + if (inputs != null) { + for (int j = 0; j < inputs.size(); j++) { + JsonElement inputItem = inputs.get(j); + if (inputItem.getAsJsonObject().get("name") == null + || inputItem.getAsJsonObject().get("type") == null) { + logger.error("Input argument invalid due to no name or no type!"); + return null; + } + String inputName = inputItem.getAsJsonObject().get("name").getAsString(); + String inputType = inputItem.getAsJsonObject().get("type").getAsString(); + SmartContractOuterClass.SmartContract.ABI.Entry.Param.Builder paramBuilder + = SmartContractOuterClass.SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(inputName); + paramBuilder.setType(inputType); + entryBuilder.addInputs(paramBuilder.build()); + } + } + + /* { outputs : optional } */ + if (outputs != null) { + for (int k = 0; k < outputs.size(); k++) { + JsonElement outputItem = outputs.get(k); + if (outputItem.getAsJsonObject().get("name") == null + || outputItem.getAsJsonObject().get("type") == null) { + logger.error("Output argument invalid due to no name or no type!"); + return null; + } + String outputName = outputItem.getAsJsonObject().get("name").getAsString(); + String outputType = outputItem.getAsJsonObject().get("type").getAsString(); + SmartContractOuterClass.SmartContract.ABI.Entry.Param.Builder paramBuilder = + SmartContractOuterClass.SmartContract.ABI.Entry.Param.newBuilder(); + JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); + + paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); + paramBuilder.setName(outputName); + paramBuilder.setType(outputType); + entryBuilder.addOutputs(paramBuilder.build()); + } + } + + entryBuilder.setType(getEntryType(type)); + entryBuilder.setPayable(payable); + if (stateMutability != null) { + entryBuilder.setStateMutability(getStateMutability(stateMutability)); + } + + abiBuilder.addEntrys(entryBuilder.build()); + } + + return abiBuilder.build(); + } + + /** constructor. */ + public static SmartContractOuterClass.SmartContract.ABI.Entry.EntryType + getEntryType(String type) { + switch (type) { + case "constructor": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Constructor; + case "function": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Function; + case "event": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Event; + case "fallback": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Fallback; + case "error": + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.Error; + default: + return SmartContractOuterClass.SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; + } + } + + + /** constructor. */ + public static SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType + getStateMutability(String stateMutability) { + switch (stateMutability) { + case "pure": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.Pure; + case "view": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.View; + case "nonpayable": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; + case "payable": + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.Payable; + default: + return SmartContractOuterClass.SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; + } + } + + /** + * Convert to pub. + * @param priKey private key + * @return public addr + */ + public static byte[] getFinalAddress(String priKey) { + Wallet.setAddressPreFixByte((byte) 0x41); + ECKey key = ECKey.fromPrivate(new BigInteger(priKey, 16)); + return key.getAddress(); + } + + /** + * Transfer TRX. + * @param to addr receives the asset + * @param amount asset amount + * @param owner sender + * @param priKey private key of the sender + * @param blockingStubFull Grpc interface + * @return true or false + */ + public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, + WalletGrpc.WalletBlockingStub blockingStubFull) { + Wallet.setAddressPreFixByte((byte) 0x41); + ECKey temKey = null; + try { + BigInteger priK = new BigInteger(priKey, 16); + temKey = ECKey.fromPrivate(priK); + } catch (Exception ex) { + ex.printStackTrace(); + } + final ECKey ecKey = temKey; + + int times = 0; + while (times++ <= 2) { + + BalanceContract.TransferContract.Builder builder = + BalanceContract.TransferContract.newBuilder(); + com.google.protobuf.ByteString bsTo = com.google.protobuf.ByteString.copyFrom(to); + com.google.protobuf.ByteString bsOwner = ByteString.copyFrom(owner); + builder.setToAddress(bsTo); + builder.setOwnerAddress(bsOwner); + builder.setAmount(amount); + + BalanceContract.TransferContract contract = builder.build(); + Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); + if (transaction == null || transaction.getRawData().getContractCount() == 0) { + continue; + } + transaction = signTransaction(ecKey, transaction); + GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); + return response.getResult(); + } + return false; + } + + /** + * Sign TX. + * @param ecKey ecKey of the private key + * @param transaction transaction object + */ + public static Protocol.Transaction signTransaction(ECKey ecKey, + Protocol.Transaction transaction) { + if (ecKey == null || ecKey.getPrivKey() == null) { + return null; + } + transaction = TransactionUtils.setTimestamp(transaction); + return TransactionUtils.sign(transaction, ecKey); + } + + /** + * Broadcast TX. + * @param transaction transaction object + * @param blockingStubFull Grpc interface + */ + public static GrpcAPI.Return broadcastTransaction( + Protocol.Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { + int i = 10; + GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); + while (!response.getResult() && response.getCode() == GrpcAPI.Return.response_code.SERVER_BUSY + && i > 0) { + try { + Thread.sleep(300); + } catch (InterruptedException e) { + e.printStackTrace(); + } + i--; + response = blockingStubFull.broadcastTransaction(transaction); + } + return response; + } + + public static int chooseRandomPort() { + return chooseRandomPort(10240, 65000); + } + + public static int chooseRandomPort(int min, int max) { + int port = new Random().nextInt(max - min + 1) + min; + try { + while (!checkPortAvailable(port)) { + port = new Random().nextInt(max - min + 1) + min; + } + } catch (IOException e) { + return new Random().nextInt(max - min + 1) + min; + } + return port; + } + + private static boolean checkPortAvailable(int port) throws IOException { + InetAddress theAddress = InetAddress.getByName("127.0.0.1"); + try (Socket socket = new Socket(theAddress, port)) { + // only check + socket.getPort(); + } catch (IOException e) { + return true; + } + return false; + } +} 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 7bc922661cb..4de441d940d 100644 --- a/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java +++ b/framework/src/test/java/org/tron/common/utils/RandomGeneratorTest.java @@ -1,19 +1,42 @@ package org.tron.common.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.beust.jcommander.internal.Lists; import com.google.protobuf.ByteString; +import java.util.Arrays; 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; import org.tron.core.capsule.WitnessCapsule; @Slf4j -@Ignore public class RandomGeneratorTest { + private RandomGenerator randomGenerator; + + @Before + public void setUp() { + randomGenerator = new RandomGenerator<>(); + } + + @Test + public void testShufflePreservesElements() { + List list = Arrays.asList(1, 2, 3, 4, 5); + List shuffledList = randomGenerator.shuffle(list, System.currentTimeMillis()); + + assertEquals(list.size(), shuffledList.size()); + for (Integer num : list) { + assertTrue(shuffledList.contains(num)); + } + } + + @Ignore @Test public void shuffle() { final List witnessCapsuleListBefore = this.getWitnessList(); diff --git a/framework/src/test/java/org/tron/common/utils/SetAdapterTest.java b/framework/src/test/java/org/tron/common/utils/SetAdapterTest.java new file mode 100644 index 00000000000..1d53ea3dd1a --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/SetAdapterTest.java @@ -0,0 +1,114 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import org.junit.Before; +import org.junit.Test; + +public class SetAdapterTest { + + private Map delegate; + private SetAdapter setAdapter; + + @Before + public void setUp() { + delegate = new HashMap<>(); + setAdapter = new SetAdapter<>(delegate); + } + + @Test + public void testSizeInitiallyEmpty() { + assertEquals(0, setAdapter.size()); + } + + @Test + public void testIsEmptyInitially() { + assertTrue(setAdapter.isEmpty()); + } + + @Test + public void testContainsWhenEmpty() { + assertFalse(setAdapter.contains("test")); + } + + @Test + public void testAddAndGetSize() { + setAdapter.add("one"); + assertEquals(1, setAdapter.size()); + } + + @Test + public void testAddAndCheckContains() { + setAdapter.add("two"); + assertTrue(setAdapter.contains("two")); + } + + @Test + public void testRemoveAndCheckContains() { + setAdapter.add("three"); + assertTrue(setAdapter.contains("three")); + setAdapter.remove("three"); + assertFalse(setAdapter.contains("three")); + } + + @Test + public void testIterator() { + setAdapter.add("four"); + setAdapter.add("five"); + Set expected = new HashSet<>(Arrays.asList("four", "five")); + Set actual = new HashSet<>(setAdapter); // Convert to HashSet to ignore order + assertEquals(expected, actual); + } + + @Test + public void testToArray() { + setAdapter.add("six"); + setAdapter.add("seven"); + Object[] array = setAdapter.toArray(); + Arrays.sort(array); // Sorting to ignore order + assertArrayEquals(new String[]{"seven", "six"}, array); + } + + @Test + public void testToArrayWithGivenType() { + setAdapter.add("eight"); + String[] array = setAdapter.toArray(new String[0]); + Arrays.sort(array); // Sorting to ignore order + assertArrayEquals(new String[]{"eight"}, array); + } + + @Test + public void testAddAll() { + setAdapter.addAll(Arrays.asList("nine", "ten")); + assertTrue(setAdapter.containsAll(Arrays.asList("nine", "ten"))); + } + + @Test + public void testRemoveAll() { + setAdapter.addAll(Arrays.asList("eleven", "twelve")); + setAdapter.removeAll(Collections.singletonList("eleven")); + assertFalse(setAdapter.contains("eleven")); + assertTrue(setAdapter.contains("twelve")); + } + + @Test + public void testClear() { + setAdapter.addAll(Arrays.asList("thirteen", "fourteen")); + setAdapter.clear(); + assertTrue(setAdapter.isEmpty()); + } + + @Test(expected = RuntimeException.class) + public void testRetainAllThrowsException() { + setAdapter.retainAll(Collections.emptyList()); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java index a0164190b8c..0df72cc125d 100644 --- a/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java +++ b/framework/src/test/java/org/tron/common/utils/Sha256HashTest.java @@ -1,26 +1,56 @@ package org.tron.common.utils; +import static java.nio.file.Files.createTempFile; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import ch.qos.logback.core.util.FileUtil; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.IntStream; -import org.testng.Assert; -import org.testng.annotations.Test; +import org.apache.commons.io.FileUtils; +import org.junit.Assert; +import org.junit.Test; import org.tron.common.parameter.CommonParameter; public class Sha256HashTest { @Test - public void testHash() { + public void testHash() throws IOException { //Example from https://github.com/tronprotocol/tips/blob/master/TWP-001.md byte[] input = ByteArray.fromHexString("A0E11973395042BA3C0B52B4CDF4E15EA77818F275"); byte[] hash0 = Sha256Hash.hash(CommonParameter .getInstance().isECKeyCryptoEngine(), input); byte[] hash1 = Sha256Hash.hash(CommonParameter .getInstance().isECKeyCryptoEngine(), hash0); - Assert.assertEquals(hash0, ByteArray - .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084")); - Assert.assertEquals(hash1, ByteArray - .fromHexString("10AE21E887E8FE30C591A22A5F8BB20EB32B2A739486DC5F3810E00BBDB58C5C")); + assertEquals(Arrays.toString(hash0), Arrays.toString(ByteArray + .fromHexString("CD5D4A7E8BE869C00E17F8F7712F41DBE2DDBD4D8EC36A7280CD578863717084"))); + assertEquals(Arrays.toString(hash1), Arrays.toString(ByteArray + .fromHexString("10AE21E887E8FE30C591A22A5F8BB20EB32B2A739486DC5F3810E00BBDB58C5C"))); + + Sha256Hash sha256Hash = new Sha256Hash(1, new byte[32]); + assertNotNull(sha256Hash.toBigInteger()); + + Sha256Hash.create(true, ("byte1-1").getBytes(StandardCharsets.UTF_8)); + File testfile = createTempFile("testfile", ".txt").toFile(); + Sha256Hash.of(true, testfile); + Sha256Hash.createDouble(true, new byte[0]); + Sha256Hash.twiceOf(true, new byte[0]); + Sha256Hash.hashTwice(true, new byte[0]); + Sha256Hash.hashTwice(false, new byte[0]); + Sha256Hash.hashTwice(true, new byte[0], 0, 0); + Sha256Hash.hashTwice(false, new byte[0], 0, 0); + Sha256Hash.hash(false, new byte[0], 0, 0); + Sha256Hash.hashTwice(true, new byte[0], 0, 0, new byte[0], 0, 0); + Sha256Hash.hashTwice(false, new byte[0], 0, 0, new byte[0], 0, 0); + assertTrue(testfile.delete()); + + } @@ -40,7 +70,7 @@ public void testMultiThreadingHash() { countAll.incrementAndGet(); if (!Arrays.equals(hash, hash0)) { countFailed.incrementAndGet(); - Assert.assertTrue(false); + Assert.fail(); } } }); @@ -51,7 +81,7 @@ public void testMultiThreadingHash() { e.printStackTrace(); } }); - Assert.assertEquals(70000, countAll.get()); - Assert.assertEquals(0, countFailed.get()); + assertEquals(70000, countAll.get()); + assertEquals(0, countFailed.get()); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/common/utils/SlidingWindowCounterTest.java b/framework/src/test/java/org/tron/common/utils/SlidingWindowCounterTest.java new file mode 100644 index 00000000000..016b7ac611b --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/SlidingWindowCounterTest.java @@ -0,0 +1,63 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.junit.Before; +import org.junit.Test; + +public class SlidingWindowCounterTest { + + private SlidingWindowCounter counter; + + @Before + public void setUp() { + counter = new SlidingWindowCounter(3); + } + + @Test + public void testIncrease() { + counter.increase(); + counter.increase(); + counter.increase(); + assertEquals(3, counter.totalCount()); + counter.resizeWindow(5); + assertNotNull(counter.toString()); + } + + @Test + public void testTotalAndAdvance() { + counter.increase(); + counter.increase(); + counter.advance(); + counter.increase(); + int total = counter.totalAndAdvance(); + assertEquals(3, total); + assertEquals(3, counter.totalCount()); + } + + @Test + public void testTotalCount() { + counter.increase(); + counter.increase(); + counter.advance(); + assertEquals(2, counter.totalCount()); + } + + @Test + public void testCircularWindow() { + for (int i = 0; i < 3; i++) { + counter.increase(); + } + counter.increase(); + counter.advance(); + assertEquals(4, counter.totalCount()); + + counter.increase(); + counter.increase(); + counter.increase(); + int total = counter.totalAndAdvance(); + assertEquals(7, total); + assertEquals(7, counter.totalCount()); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java b/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java index b9188e96060..c98115af3f0 100644 --- a/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java +++ b/framework/src/test/java/org/tron/common/utils/TypeConversionTest.java @@ -17,9 +17,13 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.tron.common.utils.TypeConversion.bytesToHexString; import static org.tron.common.utils.TypeConversion.bytesToLong; import static org.tron.common.utils.TypeConversion.hexStringToBytes; +import static org.tron.common.utils.TypeConversion.increment; import static org.tron.common.utils.TypeConversion.longToBytes; import lombok.extern.slf4j.Slf4j; @@ -58,6 +62,14 @@ public void testHexStringToBytes() { //logger.info("hex string 7f to bytes is: {}", result); byte[] expected = new byte[]{127}; assertArrayEquals(expected, result); + assertNull(hexStringToBytes("test")); + } + @Test + public void testIncrementNormalCase() { + byte[] bytes = {1, 2, 3}; + boolean result = increment(bytes); + assertTrue(result); + assertArrayEquals(new byte[]{1, 2, 4}, bytes); } } diff --git a/framework/src/test/java/org/tron/common/utils/UtilsTest.java b/framework/src/test/java/org/tron/common/utils/UtilsTest.java new file mode 100644 index 00000000000..6a593a7684f --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/UtilsTest.java @@ -0,0 +1,74 @@ +package org.tron.common.utils; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +import java.nio.charset.Charset; +import java.security.SecureRandom; +import org.junit.Test; + +public class UtilsTest { + + @Test + public void testGetRandom() { + SecureRandom random = Utils.getRandom(); + assertNotNull("SecureRandom should not be null", random); + } + + @Test + public void testGetBytes() { + char[] chars = "hello".toCharArray(); + byte[] bytes = Utils.getBytes(chars); + + // Convert back to String to check if it's the same + String result = new String(bytes, Charset.forName("UTF-8")); + assertEquals("Converted bytes should match the original string", "hello", result); + } + + @Test + public void testGetIdShort() { + String longId = "12345678901234567890"; + String shortId = Utils.getIdShort(longId); + assertEquals("Short ID should be the first 8 characters of the long ID", "12345678", shortId); + + String nullId = Utils.getIdShort(null); + assertEquals("ID should be '' for null input", "", nullId); + } + + @Test + public void testClone() { + byte[] original = {1, 2, 3, 4, 5}; + byte[] clone = Utils.clone(original); + + assertArrayEquals("Clone should be equal to the original", original, clone); + + // Modify the clone to ensure it's a new array + clone[0] = 99; + assertNotEquals("Modifying the clone should not affect the original", original[0], clone[0]); + } + + @Test + public void testAlignLeft() { + String result = Utils.align("abc", '-', 10, false); + String result1 = Utils.align("abc", '-', 2, false); + assertEquals("abc-------", result); + assertEquals("abc", result1); + } + + @Test + public void testAlignRight() { + String result = Utils.align("abc", '-', 10, true); + assertEquals("-------abc", result); + } + + @Test + public void testRepeat() { + String result = Utils.repeat("a", 5); + assertEquals("aaaaa", result); + + result = Utils.repeat("abc", 3); + assertEquals("abcabcabc", result); + } +} diff --git a/framework/src/test/java/org/tron/common/utils/ValueTest.java b/framework/src/test/java/org/tron/common/utils/ValueTest.java new file mode 100644 index 00000000000..f7e4f415f5f --- /dev/null +++ b/framework/src/test/java/org/tron/common/utils/ValueTest.java @@ -0,0 +1,198 @@ +package org.tron.common.utils; + +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.assertTrue; +import static org.tron.common.utils.ByteUtil.EMPTY_BYTE_ARRAY; + +import java.math.BigInteger; +import java.util.Arrays; +import java.util.List; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Before; +import org.junit.Test; + +public class ValueTest { + + private Value value; + + @Before + public void setUp() { + value = new Value(); + value.init(new byte[100]); + } + + @Test + public void testAsObj() { + Object obj = new Object(); + value = new Value(obj); + assertEquals("asObj should return the encapsulated object", obj, value.asObj()); + } + + @Test + public void testAsList() { + Object[] array = { "element1", "element2" }; + value = new Value(array); + List list = value.asList(); + assertEquals(2, list.size()); + assertEquals("element1", list.get(0)); + } + + @Test + public void testAsInt() { + value = new Value(123); + assertEquals(123, value.asInt()); + assertEquals(0, new Value(new byte[0]).asInt()); + assertEquals(0, new Value("test").asInt()); + } + + @Test + public void testAsLong() { + value = new Value(123456789L); + assertEquals(123456789L, value.asLong()); + assertEquals(0L, new Value(new byte[0]).asLong()); + assertEquals(0L, new Value("TEST").asLong()); + } + + @Test + public void testAsBigInt() { + BigInteger bigInteger = new BigInteger("12345678901234567890"); + value = new Value(bigInteger); + assertEquals(bigInteger, value.asBigInt()); + } + + @Test + public void testAsString() { + value = new Value("test string"); + assertEquals("test string", value.asString()); + assertNotNull(new Value(new byte[0]).asString()); + assertEquals("", new Value(100).asString()); + assertNotNull(value.get(0)); + + } + + @Test + public void testAsBytes() { + byte[] bytes = { 0x01, 0x02, 0x03 }; + value = new Value(bytes); + assertArrayEquals("asBytes should return the correct byte array", bytes, value.asBytes()); + assertEquals(EMPTY_BYTE_ARRAY, new Value(100).asBytes()); + } + + @Test + public void testGet() { + List list = Arrays.asList("element1", "element2"); + value = new Value(list.toArray()); + Value element = value.get(0); + assertEquals("element1", element.asString()); + assertNotNull(value.get(2)); + } + + @Test(expected = Exception.class) + public void testGetNegativeIndex() { + value = new Value(new Object[] { "element1", "element2" }); + value.get(-1); + } + + @Test + public void testCmp() { + Value value1 = new Value("test"); + Value value2 = new Value("test"); + assertTrue("cmp should return true for equal values", value1.cmp(value2)); + } + + @Test + public void testIsList() { + value = new Value(new Object[] { "element1", "element2" }); + assertTrue("isList should return true for an array", value.isList()); + assertNotNull(value.toString()); + } + + @Test + public void testIsString() { + value = new Value("test string"); + assertTrue("isString should return true for a string", value.isString()); + } + + @Test + public void testIsInt() { + value = new Value(123); + assertTrue("isInt should return true for an integer", value.isInt()); + } + + @Test + public void testIsLong() { + value = new Value(123456789L); + assertTrue("isLong should return true for a long", value.isLong()); + } + + @Test + public void testIsBigInt() { + value = new Value(new BigInteger("12345678901234567890")); + assertTrue("isBigInt should return true for a BigInteger", value.isBigInt()); + } + + @Test + public void testIsBytes() { + byte[] bytes = { 0x01, 0x02, 0x03 }; + value = new Value(bytes); + assertTrue("isBytes should return true for a byte array", value.isBytes()); + } + + @Test + public void testIsReadableString() { + byte[] readableBytes = "Hello World".getBytes(); + value = new Value(readableBytes); + assertTrue(value.isReadableString()); + } + + @Test + public void testIsHexString() { + byte[] hexBytes = Hex.decode("48656c6c6f20576f726c64"); + value = new Value(hexBytes); + assertFalse("isHexString should return true for hex byte array", value.isHexString()); + } + + @Test + public void testIsHashCode() { + byte[] hashBytes = new byte[32]; + value = new Value(hashBytes); + assertTrue("isHashCode should return true for a 32 byte array", value.isHashCode()); + } + + @Test + public void testIsNull() { + value = new Value(null); + assertTrue("isNull should return true for null", value.isNull()); + } + + @Test + public void testIsEmpty() { + value = new Value(""); + assertTrue("isEmpty should return true for an empty string", value.isEmpty()); + } + + @Test + public void testLength() { + value = new Value("test string"); + assertEquals(11, value.length()); + } + + @Test + public void testToString() { + value = new Value("test string"); + assertEquals("test string", value.toString()); + } + + @Test + public void testCountBranchNodes() { + Object[] array = { new Value("element1"), new Value("element2") }; + value = new Value(array); + assertEquals(0, value.countBranchNodes()); + value = new Value(new byte[0]); + assertEquals(0, value.countBranchNodes()); + + } +} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/common/client/Configuration.java b/framework/src/test/java/org/tron/common/utils/client/Configuration.java similarity index 90% rename from framework/src/test/java/stest/tron/wallet/common/client/Configuration.java rename to framework/src/test/java/org/tron/common/utils/client/Configuration.java index 9d0cdd050c8..79dded303aa 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/Configuration.java +++ b/framework/src/test/java/org/tron/common/utils/client/Configuration.java @@ -1,6 +1,4 @@ -package stest.tron.wallet.common.client; - -import static org.apache.commons.lang3.StringUtils.isBlank; +package org.tron.common.utils.client; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; @@ -8,6 +6,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -22,7 +21,7 @@ public class Configuration { */ public static Config getByPath(final String configurationPath) { - if (isBlank(configurationPath)) { + if (StringUtils.isBlank(configurationPath)) { throw new IllegalArgumentException("Configuration path is required!"); } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/GrpcClient.java b/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/GrpcClient.java rename to framework/src/test/java/org/tron/common/utils/client/GrpcClient.java index 11482d4af83..139485e4e2b 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/GrpcClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/GrpcClient.java @@ -1,10 +1,11 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; import com.google.protobuf.ByteString; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import java.util.Optional; import java.util.concurrent.TimeUnit; + import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.AccountNetMessage; import org.tron.api.GrpcAPI.AccountPaginated; @@ -35,7 +36,6 @@ import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; import org.tron.protos.contract.WitnessContract; - public class GrpcClient { private ManagedChannel channelFull = null; @@ -46,7 +46,7 @@ public class GrpcClient { // public GrpcClient(String host, int port) { // channel = ManagedChannelBuilder.forAddress(host, port) - // .usePlaintext(true) + // .usePlaintext() // .build(); // blockingStub = WalletGrpc.newBlockingStub(channel); // } @@ -58,13 +58,13 @@ public class GrpcClient { public GrpcClient(String fullnode, String soliditynode) { if (!(fullnode.isEmpty())) { channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); } if (!(soliditynode.isEmpty())) { channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) + .usePlaintext() .build(); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); diff --git a/framework/src/test/java/stest/tron/wallet/common/client/Parameter.java b/framework/src/test/java/org/tron/common/utils/client/Parameter.java similarity index 89% rename from framework/src/test/java/stest/tron/wallet/common/client/Parameter.java rename to framework/src/test/java/org/tron/common/utils/client/Parameter.java index 8fead433c2e..f0531c95165 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/Parameter.java +++ b/framework/src/test/java/org/tron/common/utils/client/Parameter.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; public interface Parameter { @@ -11,4 +11,4 @@ interface CommonConstant { byte ADD_PRE_FIX_BYTE_MAINNET = (byte) 0x41; //41 + address byte ADD_PRE_FIX_BYTE_TESTNET = (byte) 0xa0; //a0 + address } -} \ No newline at end of file +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java similarity index 91% rename from framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java rename to framework/src/test/java/org/tron/common/utils/client/WalletClient.java index c4bd7ae29d3..9d9a68da49d 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/WalletClient.java +++ b/framework/src/test/java/org/tron/common/utils/client/WalletClient.java @@ -1,9 +1,10 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import com.typesafe.config.Config; import com.typesafe.config.ConfigObject; + import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; @@ -12,6 +13,7 @@ import java.util.List; import java.util.Map; import java.util.Optional; + import org.apache.commons.lang3.StringUtils; import org.bouncycastle.util.encoders.Hex; import org.slf4j.Logger; @@ -28,6 +30,9 @@ import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; +import org.tron.common.utils.client.Parameter.CommonConstant; +import org.tron.common.utils.client.utils.Base58; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.core.exception.CancelException; import org.tron.core.exception.CipherException; import org.tron.protos.Protocol.Account; @@ -45,9 +50,6 @@ import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.TransactionUtils; public class WalletClient { @@ -94,65 +96,6 @@ public WalletClient(final ECKey ecKey) { this.ecKey = ecKey; } - /** - * constructor. - */ - - public static boolean init(int itype) { - Config config = Configuration.getByPath("testng.conf"); - dbPath = config.getString("CityDb.DbPath"); - txtPath = System.getProperty("user.dir") + '/' + config.getString("CityDb.TxtPath"); - - String fullNodepathname = ""; - - if (1000 == itype) { - fullNodepathname = "checkfullnode.ip.list"; - } else { - fullNodepathname = "fullnode.ip.list"; - } - String fullNode = ""; - String solidityNode = ""; - if (config.hasPath("soliditynode.ip.list")) { - solidityNode = config.getStringList("soliditynode.ip.list").get(0); - } - if (config.hasPath(fullNodepathname)) { - fullNode = config.getStringList(fullNodepathname).get(itype); - } - if (config.hasPath("net.type") && "mainnet".equalsIgnoreCase(config.getString("net.type"))) { - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } else { - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_TESTNET); - } - rpcCli = new GrpcClient(fullNode, solidityNode); - return true; - } - - /** - * constructor. - */ - - public static GrpcClient init() { - //Config config = org.tron.core.config.Configuration.getByPath("config.conf"); - Config config = Configuration.getByPath("testng.conf"); - dbPath = config.getString("CityDb.DbPath"); - txtPath = System.getProperty("user.dir") + "/" + config.getString("CityDb.TxtPath"); - - String fullNode = ""; - String solidityNode = ""; - if (config.hasPath("soliditynode.ip.list")) { - solidityNode = config.getStringList("soliditynode.ip.list").get(0); - } - if (config.hasPath("fullnode.ip.list")) { - fullNode = config.getStringList("fullnode.ip.list").get(0); - } - if (config.hasPath("net.type") && "mainnet".equalsIgnoreCase(config.getString("net.type"))) { - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } else { - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_TESTNET); - } - return new GrpcClient(fullNode, solidityNode); - } - public static byte getAddressPreFixByte() { return addressPreFixByte; } @@ -246,7 +189,7 @@ public static Transaction createTransferAssetTransaction(byte[] to, byte[] asser public static Transaction participateAssetIssueTransaction(byte[] to, byte[] assertName, byte[] owner, long amount) { - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = + ParticipateAssetIssueContract contract = participateAssetIssueContract(to, assertName, owner, amount); return rpcCli.createParticipateAssetIssueTransaction(contract); } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/WitnessComparator.java b/framework/src/test/java/org/tron/common/utils/client/WitnessComparator.java similarity index 85% rename from framework/src/test/java/stest/tron/wallet/common/client/WitnessComparator.java rename to framework/src/test/java/org/tron/common/utils/client/WitnessComparator.java index c032fce9eff..43e10441c51 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/WitnessComparator.java +++ b/framework/src/test/java/org/tron/common/utils/client/WitnessComparator.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client; +package org.tron.common.utils.client; import java.util.Comparator; import org.tron.protos.Protocol.Witness; @@ -8,4 +8,4 @@ class WitnessComparator implements Comparator { public int compare(Object o1, Object o2) { return Long.compare(((Witness) o2).getVoteCount(), ((Witness) o1).getVoteCount()); } -} \ No newline at end of file +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/AbiUtil.java b/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java similarity index 96% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/AbiUtil.java rename to framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java index 9eb2bf3a8c0..1d780bfacd4 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/AbiUtil.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/AbiUtil.java @@ -1,4 +1,6 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; + +import static org.tron.common.math.Maths.abs; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; @@ -238,6 +240,16 @@ public static byte[] encodeInput(String methodSign, String input) { return pack(coders, items); } + public static String generateOccupationConstantPrivateKey() { + StringBuilder privateKey = new StringBuilder(); + String baseKey = "1234567890"; + for (int i = 0; i < 6; i++) { + privateKey.append(baseKey); + } + privateKey.append("1234"); + return privateKey.toString(); + } + public static void main(String[] args) { String method = "test(string,int2,string)"; String params = "asdf,3123,adf"; @@ -340,7 +352,7 @@ static class CoderNumber extends Coder { @Override byte[] encode(String value) { long n = Long.valueOf(value); - DataWord word = new DataWord(Math.abs(n)); + DataWord word = new DataWord(abs(n, true)); if (n < 0) { word.negate(); } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java similarity index 99% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java rename to framework/src/test/java/org/tron/common/utils/client/utils/Base58.java index 6fd13777927..2106b191af9 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Base58.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/Base58.java @@ -1,7 +1,8 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import java.io.UnsupportedEncodingException; import java.math.BigInteger; + import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.Commons; import org.tron.common.utils.Sha256Hash; @@ -240,4 +241,4 @@ public static byte[] decode58CheckForShield(String input) { } -} \ No newline at end of file +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ByteArrayWrapper.java b/framework/src/test/java/org/tron/common/utils/client/utils/ByteArrayWrapper.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/ByteArrayWrapper.java rename to framework/src/test/java/org/tron/common/utils/client/utils/ByteArrayWrapper.java index 7a41ed44b23..1775f28ac17 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ByteArrayWrapper.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/ByteArrayWrapper.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * Copyright (c) [2016] [ ] * This file is part of the ethereumJ library. @@ -19,6 +19,7 @@ import java.io.Serializable; import java.util.Arrays; + import org.bouncycastle.util.encoders.Hex; import org.tron.common.utils.FastByteComparisons; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/DataWord.java b/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/DataWord.java rename to framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java index e44ac34e765..f676ef6c8e4 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/DataWord.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/DataWord.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * Copyright (c) [2016] [ ] @@ -18,10 +18,13 @@ * along with the ethereumJ library. If not, see . */ +import static org.tron.common.math.Maths.signum; + import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.math.BigInteger; import java.nio.ByteBuffer; + import org.bouncycastle.util.Arrays; import org.bouncycastle.util.encoders.Hex; import org.tron.common.utils.ByteUtil; @@ -465,7 +468,7 @@ public int compareTo(DataWord o) { data, 0, data.length, o.getData(), 0, o.getData().length); // Convert result into -1, 0 or 1 as is the convention - return (int) Math.signum(result); + return (int) signum(result, true); } /** diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java similarity index 94% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java rename to framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java index 8ef8fecbd8e..a68bb616f11 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/HttpMethed.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/HttpMethed.java @@ -1,21 +1,17 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; +import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.google.protobuf.ByteString; -import io.netty.util.internal.StringUtil; - import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; - import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; @@ -27,12 +23,12 @@ import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import org.junit.Assert; -import org.testng.collections.Lists; +import org.springframework.mock.web.MockHttpServletRequest; import org.tron.api.GrpcAPI; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.Configuration; @Slf4j public class HttpMethed { @@ -40,10 +36,8 @@ public class HttpMethed { static HttpClient httpClient; static HttpPost httppost; static HttpResponse response; - static Integer connectionTimeout = - Configuration.getByPath("testng.conf").getInt("defaultParameter.httpConnectionTimeout"); - static Integer soTimeout = - Configuration.getByPath("testng.conf").getInt("defaultParameter.httpSoTimeout"); + static Integer connectionTimeout = 19000; + static Integer soTimeout = 18000; static String transactionString; static String transactionSignString; static JSONObject responseContent; @@ -52,8 +46,7 @@ public class HttpMethed { public static volatile Integer witnessNum; /** constructor. */ - private static volatile String httpnode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(1); + private static volatile String httpnode = "127.0.0.1:50052"; /** constructor. */ public static Integer getWitnessNum() { @@ -106,7 +99,7 @@ public static HttpResponse setAccountId( JsonObject userBaseObj2 = new JsonObject(); userBaseObj2.addProperty("account_id", accountId); userBaseObj2.addProperty( - "owner_address", Base58.encode58Check(PublicMethed.getFinalAddress(fromKey))); + "owner_address", Base58.encode58Check(PublicMethod.getFinalAddress(fromKey))); userBaseObj2.addProperty("visible", visable); response = createConnect(requestUrl, userBaseObj2); transactionString = EntityUtils.toString(response.getEntity()); @@ -1174,12 +1167,8 @@ public static HttpResponse unFreezeBalance( public static String gettransactionsign( String httpNode, String transactionString, String privateKey) { try { - String requestUrl = "http://" + httpNode + "/wallet/gettransactionsign"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("transaction", transactionString); - userBaseObj2.addProperty("privateKey", privateKey); - response = createConnect(requestUrl, userBaseObj2); - transactionSignString = EntityUtils.toString(response.getEntity()); + transactionSignString = TransactionUtils.getTransactionSign(transactionString, privateKey, + false); } catch (Exception e) { e.printStackTrace(); httppost.releaseConnection(); @@ -2229,18 +2218,33 @@ public static HttpResponse getNowBlockFromPbft(String httpSolidityNode) { public static void waitToProduceOneBlock(String httpNode) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - Integer currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + if (responseContent.containsKey("block_header")) { + responseContent = HttpMethed.parseStringContent( + responseContent.get("block_header").toString()); + } + if (responseContent.containsKey("raw_data")) { + responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); + } + Integer currentBlockNum = 0; + if (responseContent.containsKey("number")) { + currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); + } Integer nextBlockNum = 0; Integer times = 0; while (nextBlockNum <= currentBlockNum + 1 && times++ <= 10) { response = HttpMethed.getNowBlock(httpNode); responseContent = HttpMethed.parseResponseContent(response); - responseContent = - HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + if (responseContent.containsKey("block_header")) { + responseContent = HttpMethed.parseStringContent( + responseContent.get("block_header").toString()); + } + if (responseContent.containsKey("raw_data")) { + responseContent = HttpMethed.parseStringContent( + responseContent.get("raw_data").toString()); + } + if (responseContent.containsKey("number")) { + nextBlockNum = Integer.parseInt(responseContent.get("number").toString()); + } try { Thread.sleep(1200); } catch (InterruptedException e) { @@ -2968,36 +2972,6 @@ public static HttpResponse updateEnergyLimit( return response; } - /** constructor. */ - public static HttpResponse createAddress(String httpNode, String value) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createaddress"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("value", str2hex(value)); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse generateAddress(String httpNode) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/generateaddress"; - JsonObject userBaseObj2 = new JsonObject(); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - /** constructor. */ public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { try { @@ -3029,92 +3003,6 @@ public static HttpResponse validateAddress(String httpNode, String address) { return response; } - /** constructor. */ - public static HttpResponse easyTransfer( - String httpNode, String value, byte[] toAddress, Long amount) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransfer"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("passPhrase", str2hex(value)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse easyTransferByPrivate( - String httpNode, String privateKey, byte[] toAddress, Long amount) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("privateKey", privateKey); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("amount", amount); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse easyTransferAsset( - String httpNode, String value, byte[] toAddress, Long amount, String assetId) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferasset"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("passPhrase", str2hex(value)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("assetId", assetId); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse easyTransferAssetByPrivate( - String httpNode, String privateKey, byte[] toAddress, Long amount, String assetId) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/easytransferassetbyprivate"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("privateKey", privateKey); - userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress)); - userBaseObj2.addProperty("amount", amount); - userBaseObj2.addProperty("assetId", assetId); - response = createConnect(requestUrl, userBaseObj2); - logger.info(userBaseObj2.toString()); - transactionString = EntityUtils.toString(response.getEntity()); - logger.info(transactionString); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - /** constructor. */ public static HttpResponse getContractInfo(String httpNode, String contractAddress) { try { @@ -3229,97 +3117,7 @@ public static HttpResponse clearABiGetTxid( return response; } - /** constructor. */ - public static Optional generateShieldAddress(String httpnode) { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - String sk; - String d; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD; - try { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - sk = responseContent.getString("value"); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - d = responseContent.getString("d"); - - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - ak = responseContent.getString("value"); - - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - nk = responseContent.getString("value"); - - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - ivk = responseContent.getString("ivk"); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d); - responseContent = HttpMethed.parseResponseContent(response); - pkD = responseContent.getString("pkD"); - - addressInfo.setSk(ByteArray.fromHexString(sk)); - addressInfo.setD(new DiversifierT(ByteArray.fromHexString(d))); - addressInfo.setIvk(ByteArray.fromHexString(ivk)); - addressInfo.setOvk(ByteArray.fromHexString(ovk)); - addressInfo.setPkD(ByteArray.fromHexString(pkD)); - logger.info("sk:" + sk); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** constructor. */ - public static List addShieldOutputList( - String httpNode, - List shieldOutList, - String shieldToAddress, - String toAmountString, - String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - GrpcAPI.Note.Builder noteBuild = GrpcAPI.Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - - response = HttpMethed.getRcm(httpNode); - responseContent = HttpMethed.parseResponseContent(response); - String rcm = responseContent.getString("value"); - noteBuild.setRcm(ByteString.copyFrom(rcm.getBytes())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } /** constructor. */ public static HttpResponse getSpendingKey(String httpNode) { @@ -3421,19 +3219,6 @@ public static HttpResponse getIncomingViewingKey(String httpNode, String ak, Str return response; } - /** constructor. */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - /** constructor. */ public static HttpResponse getZenPaymentAddress(String httpNode, String ivk, String d) { try { @@ -3658,7 +3443,7 @@ public static Boolean getSpendResult( String jsonString = responseContent.toJSONString(); if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { + && responseContent.getString("message").equals("Input note has been spent"))) { return Boolean.TRUE; } else { return Boolean.FALSE; @@ -3713,7 +3498,7 @@ public static Boolean getSpendResultFromSolidity( String jsonString = responseContent.toJSONString(); if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { + && responseContent.getString("message").equals("Input note has been spent"))) { return Boolean.TRUE; } else { return Boolean.FALSE; @@ -3764,7 +3549,7 @@ public static Boolean getSpendResultFromPbft( String jsonString = responseContent.toJSONString(); if (jsonString.contains("result") && (responseContent.getString("result").equals("true") - && responseContent.getString("message").equals("Input note has been spent"))) { + && responseContent.getString("message").equals("Input note has been spent"))) { return Boolean.TRUE; } else { return Boolean.FALSE; @@ -4446,10 +4231,8 @@ public static HttpResponse sendShieldCoinWithoutAsk( public static void freedResource( String httpNode, byte[] fromAddress, byte[] toAddress, String fromKey) { long balance = HttpMethed.getBalance(httpNode, fromAddress); - // System.out.println("剩余资源:" + balance); sendCoin(httpNode, fromAddress, toAddress, balance - 50000, fromKey); balance = HttpMethed.getBalance(httpNode, fromAddress); - // System.out.println("之后资源:" + balance); } /** constructor. */ @@ -5089,4 +4872,11 @@ public static HttpResponse getTransactionFromPending(String httpNode, String txi } return response; } + + public static MockHttpServletRequest createRequest(String method) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod(method); + request.setCharacterEncoding("UTF-8"); + return request; + } } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JSONObjectWarp.java b/framework/src/test/java/org/tron/common/utils/client/utils/JSONObjectWarp.java old mode 100755 new mode 100644 similarity index 77% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/JSONObjectWarp.java rename to framework/src/test/java/org/tron/common/utils/client/utils/JSONObjectWarp.java index b482068f118..bab667dedf1 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JSONObjectWarp.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/JSONObjectWarp.java @@ -1,11 +1,11 @@ -package stest.tron.wallet.common.client.utils; - -import com.alibaba.fastjson.JSONObject; - -public class JSONObjectWarp extends JSONObject { - - public JSONObjectWarp put(String key, Object value) { - super.put(key, value); - return this; - } -} +package org.tron.common.utils.client.utils; + +import com.alibaba.fastjson.JSONObject; + +public class JSONObjectWarp extends JSONObject { + + public JSONObjectWarp put(String key, Object value) { + super.put(key, value); + return this; + } +} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Sm3Hash.java b/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Sm3Hash.java rename to framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java index 478bd280440..fde88385794 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Sm3Hash.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/Sha256Sm3Hash.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * Copyright 2011 Google Inc. @@ -16,9 +16,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -import static com.google.common.base.Preconditions.checkArgument; - +import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; @@ -31,6 +29,7 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; + import org.bouncycastle.crypto.digests.SM3Digest; import org.tron.common.utils.ByteArray; @@ -59,13 +58,13 @@ public class Sha256Sm3Hash implements Serializable, Comparable { public Sha256Sm3Hash(long num, byte[] hash) { byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); + Preconditions.checkArgument(rawHashBytes.length == LENGTH); this.bytes = rawHashBytes; } public Sha256Sm3Hash(long num, Sha256Sm3Hash hash) { byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); + Preconditions.checkArgument(rawHashBytes.length == LENGTH); this.bytes = rawHashBytes; } @@ -74,7 +73,7 @@ public Sha256Sm3Hash(long num, Sha256Sm3Hash hash) { */ @Deprecated public Sha256Sm3Hash(byte[] rawHashBytes) { - checkArgument(rawHashBytes.length == LENGTH); + Preconditions.checkArgument(rawHashBytes.length == LENGTH); this.bytes = rawHashBytes; } diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldAddressInfo.java b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldAddressInfo.java similarity index 98% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldAddressInfo.java rename to framework/src/test/java/org/tron/common/utils/client/utils/ShieldAddressInfo.java index 35332287e93..5d0de50c0b8 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldAddressInfo.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldAddressInfo.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import java.util.Arrays; import java.util.Optional; diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldNoteInfo.java b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldNoteInfo.java similarity index 97% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldNoteInfo.java rename to framework/src/test/java/org/tron/common/utils/client/utils/ShieldNoteInfo.java index 8691ac26abc..50fad817c56 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldNoteInfo.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/ShieldNoteInfo.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; import lombok.AllArgsConstructor; import lombok.Getter; @@ -78,4 +78,3 @@ public boolean decode(final String data) { } } - diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/TransactionUtils.java b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java similarity index 85% rename from framework/src/test/java/stest/tron/wallet/common/client/utils/TransactionUtils.java rename to framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java index cc2af15ec7b..b6226d01aae 100644 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/TransactionUtils.java +++ b/framework/src/test/java/org/tron/common/utils/client/utils/TransactionUtils.java @@ -1,4 +1,4 @@ -package stest.tron.wallet.common.client.utils; +package org.tron.common.utils.client.utils; /* * java-tron is free software: you can redistribute it and/or modify @@ -24,7 +24,13 @@ import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.exception.PermissionException; +import org.tron.core.exception.SignatureFormatException; +import org.tron.core.services.http.JsonFormat; +import org.tron.core.store.AccountStore; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract; import org.tron.protos.contract.AccountContract.AccountCreateContract; @@ -168,7 +174,6 @@ public static boolean validTransaction(Transaction signedTransaction) { */ public static Transaction sign(Transaction transaction, ECKey myKey) { - ByteString lockSript = ByteString.copyFrom(myKey.getAddress()); Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); byte[] hash = Sha256Hash.hash(CommonParameter @@ -185,6 +190,30 @@ public static Transaction sign(Transaction transaction, ECKey myKey) { return transaction; } + public static String getTransactionSign(String transaction, String priKey, + boolean selfType) { + byte[] privateKey = ByteArray.fromHexString(priKey); + Transaction.Builder builder = Transaction.newBuilder(); + try { + JsonFormat.merge(transaction, builder, selfType); + TransactionCapsule trx = new TransactionCapsule(builder.build()); + trx.sign(privateKey); + return JsonFormat.printToString(trx.getInstance(), selfType); + } catch (JsonFormat.ParseException e) { + logger.error("{}", e); + } + return null; + } + + public static TransactionCapsule addTransactionSign(Transaction transaction, String priKey, + AccountStore accountStore) + throws PermissionException, SignatureException, SignatureFormatException { + byte[] privateKey = ByteArray.fromHexString(priKey); + TransactionCapsule trx = new TransactionCapsule(transaction); + trx.addSign(privateKey, accountStore); + return trx; + } + /** * constructor. */ diff --git a/framework/src/test/java/org/tron/common/zksnark/ZksnarkClientTest.java b/framework/src/test/java/org/tron/common/zksnark/ZksnarkClientTest.java new file mode 100644 index 00000000000..21275d548a0 --- /dev/null +++ b/framework/src/test/java/org/tron/common/zksnark/ZksnarkClientTest.java @@ -0,0 +1,43 @@ +package org.tron.common.zksnark; + +import static org.junit.Assert.assertThrows; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import io.grpc.StatusRuntimeException; +import java.nio.charset.StandardCharsets; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.contract.BalanceContract; + +public class ZksnarkClientTest { + + public ZksnarkClient zksnarkClient; + + @Before + public void setUp() { + zksnarkClient = ZksnarkClient.getInstance(); + } + + @Test + public void testCheckZksnarkProof() { + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + Transaction transaction = Transaction.newBuilder().setRawData(Transaction.raw.newBuilder() + .setData(ByteString.copyFrom("transfer".getBytes(StandardCharsets.UTF_8))) + .addContract(Transaction.Contract.newBuilder().setParameter(Any.pack(transferContract)) + .setType(Transaction.Contract.ContractType.TransferContract))) + .addRet(Transaction.Result.newBuilder().setAssetIssueID("1234567").build()).build(); + byte[] b = ByteArray + .fromHexString("ded9c2181fd7ea468a7a7b1475defe90bb0fc0ca8d0f2096b0617465cea6568c"); + assertThrows(StatusRuntimeException.class, () -> zksnarkClient.checkZksnarkProof(transaction, b, + 10000L)); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java index d52643a4237..1faa70d59ee 100755 --- a/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java +++ b/framework/src/test/java/org/tron/core/BandwidthProcessorTest.java @@ -1,43 +1,44 @@ package org.tron.core; +import static org.junit.Assert.assertThrows; + import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; +import java.nio.charset.StandardCharsets; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.BandwidthProcessor; -import org.tron.core.db.Manager; import org.tron.core.db.TransactionTrace; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.store.StoreFactory; import org.tron.protos.Protocol; import org.tron.protos.Protocol.AccountType; +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.Protocol.Transaction.Result; +import org.tron.protos.Protocol.Transaction.raw; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; import org.tron.protos.contract.BalanceContract.TransferContract; @Slf4j -public class BandwidthProcessorTest { +public class BandwidthProcessorTest extends BaseTest { - private static final String dbPath = "output_bandwidth_test"; private static final String ASSET_NAME; private static final String ASSET_NAME_V2; private static final String OWNER_ADDRESS; @@ -50,16 +51,12 @@ public class BandwidthProcessorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static long START_TIME; - private static long END_TIME; + private static final long START_TIME; + private static final long END_TIME; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); ASSET_NAME = "test_token"; ASSET_NAME_V2 = "2"; OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -70,29 +67,6 @@ public class BandwidthProcessorTest { END_TIME = DateTime.now().getMillis(); } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -148,6 +122,8 @@ public void createCapsule() { AccountType.AssetIssue, chainBaseManager.getDynamicPropertiesStore().getAssetIssueFee()); + assetCapsule2.addAcquiredDelegatedFrozenBalanceForBandwidth(999999L); + chainBaseManager.getAccountStore().reset(); chainBaseManager.getAccountAssetStore().reset(); chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -155,9 +131,6 @@ public void createCapsule() { .put(toAccountCapsule.getAddress().toByteArray(), toAccountCapsule); chainBaseManager.getAccountStore().put(assetCapsule.getAddress().toByteArray(), assetCapsule); chainBaseManager.getAccountStore().put(assetCapsule2.getAddress().toByteArray(), assetCapsule2); - - chainBaseManager.getAccountAssetStore().put(ownerCapsule.getAddress().toByteArray(), - new AccountAssetCapsule(ownerCapsule.getAddress())); } private TransferAssetContract getTransferAssetContract() { @@ -486,9 +459,6 @@ public void testConsumeOwner() throws Exception { .get(ByteArray.fromHexString(OWNER_ADDRESS)); ownerCapsule.setFrozen(10_000_000L, 0L); - AccountAssetCapsule ownerAssetCapsule = chainBaseManager.getAccountAssetStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); - chainBaseManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); TransactionResultCapsule ret = new TransactionResultCapsule(); @@ -578,6 +548,32 @@ public void testUsingFee() throws Exception { dbManager.consumeBandwidth(trx, trace); } + @Test + public void testConsumeBandwidthTooBigTransactionResultException() { + TransferContract transferContract = + TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6666; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + Transaction transaction = Transaction.newBuilder().setRawData(raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract(Contract.newBuilder().setParameter(Any.pack(transferContract)) + .setType(ContractType.TransferContract))) + .addRet(Result.newBuilder().setAssetIssueID(sb.toString()).build()).build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + trx.setInBlock(false); + TransactionTrace trace = new TransactionTrace(trx, StoreFactory + .getInstance(), new RuntimeImpl()); + assertThrows( + "Too big transaction result, TxId %s, the result size is %d bytes, maxResultSize %d", + TooBigTransactionResultException.class, () -> dbManager.consumeBandwidth(trx, trace)); + } + /** * sameTokenName close, consume success assetIssueCapsule.getOwnerAddress() != * fromAccount.getAddress()) contract.getType() = TransferAssetContract @@ -685,6 +681,8 @@ public void sameTokenNameCloseConsumeSuccess() { Assert.assertFalse(e instanceof TooBigTransactionResultException); } catch (AccountResourceInsufficientException e) { Assert.assertFalse(e instanceof AccountResourceInsufficientException); + } catch (TooBigTransactionException e) { + Assert.fail(); } finally { chainBaseManager.getAccountStore().delete(ByteArray.fromHexString(OWNER_ADDRESS)); chainBaseManager.getAccountStore().delete(ByteArray.fromHexString(TO_ADDRESS)); @@ -791,6 +789,8 @@ public void sameTokenNameOpenConsumeSuccess() { Assert.assertFalse(e instanceof TooBigTransactionResultException); } catch (AccountResourceInsufficientException e) { Assert.assertFalse(e instanceof AccountResourceInsufficientException); + } catch (TooBigTransactionException e) { + Assert.fail(); } finally { chainBaseManager.getAccountStore().delete(ByteArray.fromHexString(OWNER_ADDRESS)); chainBaseManager.getAccountStore().delete(ByteArray.fromHexString(TO_ADDRESS)); @@ -860,9 +860,24 @@ public void sameTokenNameCloseTransferToAccountNotExist() { Assert.assertFalse(e instanceof TooBigTransactionResultException); } catch (AccountResourceInsufficientException e) { Assert.assertFalse(e instanceof AccountResourceInsufficientException); + } catch (TooBigTransactionException e) { + Assert.fail(); } finally { chainBaseManager.getAccountStore().delete(ByteArray.fromHexString(OWNER_ADDRESS)); chainBaseManager.getAccountStore().delete(ByteArray.fromHexString(TO_ADDRESS)); } } + + @Test + public void testCalculateGlobalNetLimit() { + chainBaseManager.getDynamicPropertiesStore().saveTotalNetWeight(6310L); + BandwidthProcessor processor = new BandwidthProcessor(chainBaseManager); + AccountCapsule accountCapsule = chainBaseManager.getAccountStore() + .get(ByteArray.fromHexString(ASSET_ADDRESS_V2)); + long netLimit = processor.calculateGlobalNetLimit(accountCapsule); + Assert.assertEquals(0, netLimit); + long netLimitV2 = processor + .calculateGlobalNetLimitV2(accountCapsule.getAllFrozenBalanceForBandwidth()); + Assert.assertTrue(netLimitV2 > 0); + } } diff --git a/framework/src/test/java/org/tron/core/BlockCapsuleTest.java b/framework/src/test/java/org/tron/core/BlockCapsuleTest.java deleted file mode 100644 index ad129c6d471..00000000000 --- a/framework/src/test/java/org/tron/core/BlockCapsuleTest.java +++ /dev/null @@ -1,23 +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 this program. If not, see . - */ - -package org.tron.core; - -import lombok.extern.slf4j.Slf4j; - -@Slf4j -public class BlockCapsuleTest { - -} diff --git a/framework/src/test/java/org/tron/core/BlockUtilTest.java b/framework/src/test/java/org/tron/core/BlockUtilTest.java index 25e998d7a70..b122c3082f7 100644 --- a/framework/src/test/java/org/tron/core/BlockUtilTest.java +++ b/framework/src/test/java/org/tron/core/BlockUtilTest.java @@ -69,9 +69,7 @@ public void testBlockUtil() { .fromHexString(blockCapsule2.getBlockId().toString()))) )).build()); - Assert.assertEquals(false, BlockUtil.isParentOf(blockCapsule1, blockCapsule2)); Assert.assertFalse(BlockUtil.isParentOf(blockCapsule1, blockCapsule2)); - Assert.assertEquals(true, BlockUtil.isParentOf(blockCapsule2, blockCapsule3)); Assert.assertTrue(BlockUtil.isParentOf(blockCapsule2, blockCapsule3)); } } diff --git a/framework/src/test/java/org/tron/core/CoreExceptionTest.java b/framework/src/test/java/org/tron/core/CoreExceptionTest.java new file mode 100644 index 00000000000..89feaba338c --- /dev/null +++ b/framework/src/test/java/org/tron/core/CoreExceptionTest.java @@ -0,0 +1,1161 @@ +package org.tron.core; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; +import static org.tron.core.exception.BadBlockException.TypeEnum.DEFAULT; +import static org.tron.core.exception.P2pException.TypeEnum.NO_SUCH_MESSAGE; +import static org.tron.core.exception.P2pException.TypeEnum.PARSE_MESSAGE_FAILED; +import static org.tron.core.exception.P2pException.TypeEnum.SYNC_FAILED; + +import org.junit.Test; +import org.tron.common.error.TronDBException; +import org.tron.core.exception.AccountResourceInsufficientException; +import org.tron.core.exception.BadBlockException; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.BadNumberBlockException; +import org.tron.core.exception.BadTransactionException; +import org.tron.core.exception.BalanceInsufficientException; +import org.tron.core.exception.CancelException; +import org.tron.core.exception.CipherException; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractSizeNotEqualToOneException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.EventBloomException; +import org.tron.core.exception.HeaderNotFound; +import org.tron.core.exception.HighFreqException; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.JsonRpcInternalException; +import org.tron.core.exception.JsonRpcInvalidParamsException; +import org.tron.core.exception.JsonRpcInvalidRequestException; +import org.tron.core.exception.JsonRpcMethodNotFoundException; +import org.tron.core.exception.JsonRpcTooManyResultException; +import org.tron.core.exception.NonCommonBlockException; +import org.tron.core.exception.NonUniqueObjectException; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.PermissionException; +import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.RevokingStoreIllegalStateException; +import org.tron.core.exception.SignatureFormatException; +import org.tron.core.exception.StoreException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TooBigTransactionResultException; +import org.tron.core.exception.TraitorPeerException; +import org.tron.core.exception.TransactionExpirationException; +import org.tron.core.exception.TronRuntimeException; +import org.tron.core.exception.TypeMismatchNamingException; +import org.tron.core.exception.UnLinkedBlockException; +import org.tron.core.exception.UnReachBlockException; +import org.tron.core.exception.VMIllegalException; +import org.tron.core.exception.ValidateScheduleException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.exception.ZkProofValidateException; +import org.tron.core.exception.ZksnarkException; + +public class CoreExceptionTest { + + @Test + public void testAccountResourceInsufficientExceptionMessage() { + String expectedMessage = "Account resources are insufficient"; + AccountResourceInsufficientException exception = + new AccountResourceInsufficientException(expectedMessage); + + assertEquals(expectedMessage, exception.getMessage()); + } + + @Test + public void testBadBlockExceptionWithNoMessageAndDefaultType() { + BadBlockException exception = new BadBlockException(); + + assertNull(exception.getMessage()); + + assertEquals(DEFAULT, exception.getType()); + } + + @Test + public void testBadBlockExceptionWithMessageAndDefaultType() { + String testMessage = "Block is bad due to some reason"; + + BadBlockException exception = new BadBlockException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertEquals(DEFAULT, exception.getType()); + } + + @Test + public void testBadBlockExceptionWithSpecificTypeAndMessage() { + String testMessage = "Failed to calculate Merkle root"; + + BadBlockException exception = new BadBlockException(CALC_MERKLE_ROOT_FAILED, testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertEquals(CALC_MERKLE_ROOT_FAILED, exception.getType()); + } + + @Test + public void testTypeEnumValues() { + assertEquals(Integer.valueOf(1), CALC_MERKLE_ROOT_FAILED.getValue()); + + assertEquals(Integer.valueOf(100), DEFAULT.getValue()); + } + + @Test + public void testBadItemExceptionDefaultConstructor() { + BadItemException exception = new BadItemException(); + assertNotNull(exception); + } + + @Test + public void testBadItemExceptionMessageConstructor() { + String expectedMessage = "This item is bad!"; + BadItemException exception = new BadItemException(expectedMessage); + assertEquals(expectedMessage, exception.getMessage()); + assertNull(exception.getCause()); + assertNotNull(exception); + } + + @Test + public void testBadItemExceptionMessageAndCauseConstructor() { + String expectedMessage = "This item is really bad!"; + Throwable expectedCause = new Throwable("Some underlying cause"); + BadItemException exception = new BadItemException(expectedMessage, expectedCause); + assertEquals(expectedMessage, exception.getMessage()); + assertEquals(expectedCause, exception.getCause()); + assertNotNull(exception); + } + + @Test + public void testBadNumberBlockExceptionDefaultConstructor() { + BadNumberBlockException exception = new BadNumberBlockException(); + assertNull(exception.getMessage()); + assertNotNull(exception); + } + + @Test + public void testBadNumberBlockExceptionMessageConstructor() { + String expectedMessage = "Number block is bad!"; + BadNumberBlockException exception = new BadNumberBlockException(expectedMessage); + assertEquals(expectedMessage, exception.getMessage()); + assertNotNull(exception); + } + + @Test + public void testBadTransactionExceptionDefaultConstructor() { + BadTransactionException exception = new BadTransactionException(); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + assertNotNull(exception); + } + + @Test + public void testBadTransactionExceptionMessageConstructor() { + String expectedMessage = "Transaction is bad!"; + BadTransactionException exception = new BadTransactionException(expectedMessage); + + assertEquals(expectedMessage, exception.getMessage()); + + assertNull(exception.getCause()); + + assertNotNull(exception); + } + + @Test + public void testBadTransactionExceptionMessageAndCauseConstructor() { + String expectedMessage = "Transaction failed due to an error"; + Throwable cause = new IllegalArgumentException("Invalid transaction data"); + + BadTransactionException exception = new BadTransactionException(expectedMessage, cause); + + assertEquals(expectedMessage, exception.getMessage()); + + assertEquals(cause, exception.getCause()); + + assertNotNull(exception); + } + + @Test + public void testBalanceInsufficientExceptionWithNoMessage() { + BalanceInsufficientException exception = new BalanceInsufficientException(); + assertNull(exception.getMessage()); + } + + @Test + public void testBalanceInsufficientExceptionWithMessage() { + String testMessage = "Balance is insufficient for this transaction"; + BalanceInsufficientException exception = new BalanceInsufficientException(testMessage); + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testCancelExceptionWithNoMessage() { + CancelException exception = new CancelException(); + + assertNull(exception.getMessage()); + } + + @Test + public void testCancelExceptionWithMessage() { + String testMessage = "Operation canceled by user"; + + CancelException exception = new CancelException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testCipherExceptionWithMessage() { + String testMessage = "Cipher operation failed"; + + CipherException exception = new CipherException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testCipherExceptionWithCause() { + Throwable testCause = new Throwable("Underlying error"); + + CipherException exception = new CipherException(testCause); + + assertSame(testCause, exception.getCause()); + + } + + @Test + public void testCipherExceptionWithMessageAndCause() { + String testMessage = "Cipher operation failed due to error"; + + Throwable testCause = new Throwable("Underlying error"); + CipherException exception = new CipherException(testMessage, testCause); + + assertEquals(testMessage, exception.getMessage()); + + assertSame(testCause, exception.getCause()); + } + + @Test + public void testContractExeExceptionWithNoMessage() { + ContractExeException exception = new ContractExeException(); + + assertNull(exception.getMessage()); + } + + @Test + public void testContractExeExceptionWithMessage() { + String testMessage = "Contract execution failed"; + + ContractExeException exception = new ContractExeException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testContractSizeNotEqualToOneExceptionWithNoMessage() { + ContractSizeNotEqualToOneException exception = new ContractSizeNotEqualToOneException(); + + assertNull(exception.getMessage()); + } + + @Test + public void testContractSizeNotEqualToOneExceptionWithMessage() { + String testMessage = "Contract size is not equal to one"; + + ContractSizeNotEqualToOneException exception = + new ContractSizeNotEqualToOneException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testContractValidateExceptionWithNoMessageOrThrowable() { + ContractValidateException exception = new ContractValidateException(); + + assertNull(exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testContractValidateExceptionWithMessage() { + String testMessage = "Contract validation failed"; + + ContractValidateException exception = new ContractValidateException(testMessage); + + assertEquals(testMessage, exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testContractValidateExceptionWithMessageAndThrowable() { + String testMessage = "Contract validation failed due to internal error"; + + Throwable cause = new RuntimeException("Internal error"); + + ContractValidateException exception = new ContractValidateException(testMessage, cause); + + assertEquals(testMessage, exception.getMessage()); + + assertSame(cause, exception.getCause()); + } + + @Test + public void testDupTransactionExceptionDefaultConstructor() { + DupTransactionException exception = new DupTransactionException(); + + assertNotNull(exception); + + } + + @Test + public void testDupTransactionExceptionMessageConstructor() { + String testMessage = "Duplicate Transaction Exception"; + DupTransactionException exception = new DupTransactionException(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testEventBloomExceptionDefaultConstructor() { + EventBloomException exception = new EventBloomException(); + + assertNotNull(exception); + + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testEventBloomExceptionMessageConstructor() { + String testMessage = "Event Bloom Exception occurred"; + EventBloomException exception = new EventBloomException(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + + assertNull(exception.getCause()); + } + + @Test + public void testEventBloomExceptionMessageAndCauseConstructor() { + String testMessage = "Event Bloom Exception with cause"; + Throwable testCause = new Throwable("Root cause"); + EventBloomException exception = new EventBloomException(testMessage, testCause); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + + assertEquals(testCause, exception.getCause()); + } + + @Test + public void testHeaderNotFoundDefaultConstructor() { + HeaderNotFound exception = new HeaderNotFound(); + + assertNotNull(exception); + + assertNull(exception.getMessage()); + } + + @Test + public void testHeaderNotFoundMessageConstructor() { + String testMessage = "Header not found"; + HeaderNotFound exception = new HeaderNotFound(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testHighFreqExceptionDefaultConstructor() { + HighFreqException exception = new HighFreqException(); + + assertNotNull("Exception object should not be null", exception); + + assertNull("Exception message should be null", exception.getMessage()); + } + + @Test + public void testHighFreqExceptionMessageConstructor() { + String testMessage = "High frequency error occurred"; + HighFreqException exception = new HighFreqException(testMessage); + + assertNotNull("Exception object should not be null", exception); + + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + } + + @Test + public void testItemNotFoundExceptionWithMessage() { + String testMessage = "Item not found"; + ItemNotFoundException exception = new ItemNotFoundException(testMessage); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", testMessage, + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testItemNotFoundExceptionDefaultConstructor() { + ItemNotFoundException exception = new ItemNotFoundException(); + + assertNotNull("Exception object should not be null", exception); + assertNull("Exception message should be null when no message is provided", + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testItemNotFoundExceptionWithMessageAndCause() { + String testMessage = "Item not found in database"; + Throwable testCause = new Throwable("Database error"); + ItemNotFoundException exception = new ItemNotFoundException(testMessage, testCause); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + assertEquals("Cause should match the provided Throwable", testCause, exception.getCause()); + } + + @Test + public void testJsonRpcInternalExceptionDefaultConstructor() { + JsonRpcInternalException exception = new JsonRpcInternalException(); + + assertNotNull("Exception object should not be null", exception); + assertNull("Exception message should be null when no message is provided", + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInternalExceptionWithMessage() { + String testMessage = "Internal JSON-RPC error occurred"; + JsonRpcInternalException exception = new JsonRpcInternalException(testMessage); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", testMessage, + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInternalExceptionWithMessageAndCause() { + String testMessage = "Internal JSON-RPC processing failed"; + Throwable testCause = new Throwable("Underlying system error"); + JsonRpcInternalException exception = new JsonRpcInternalException(testMessage, testCause); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + assertEquals("Cause should match the provided Throwable", testCause, exception.getCause()); + } + + @Test + public void testJsonRpcInvalidParamsExceptionDefaultConstructor() { + JsonRpcInvalidParamsException exception = new JsonRpcInvalidParamsException(); + + assertNotNull("Exception object should not be null", exception); + assertNull("Exception message should be null when no message is provided", + exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInvalidParamsExceptionWithMessage() { + String testMessage = "Invalid parameters provided"; + JsonRpcInvalidParamsException exception = new JsonRpcInvalidParamsException(testMessage); + + assertNotNull("Exception object should not be null", exception); + assertEquals("Exception message should match the provided message", + testMessage, exception.getMessage()); + assertNull("Cause should be null when not provided", exception.getCause()); + } + + @Test + public void testJsonRpcInvalidParamsExceptionWithMessageAndCause() { + String testMessage = "Parameter validation failed"; + Throwable testCause = new Throwable("Underlying validation error"); + JsonRpcInvalidParamsException e = new JsonRpcInvalidParamsException(testMessage, testCause); + + assertNotNull("Exception object should not be null", e); + assertEquals("Exception message should match the provided message", testMessage, + e.getMessage()); + assertEquals("Cause should match the provided Throwable", testCause, e.getCause()); + } + + @Test + public void testJsonRpcInvalidRequestExceptionDefaultConstructor() { + JsonRpcInvalidRequestException exception = new JsonRpcInvalidRequestException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcInvalidRequestExceptionConstructorWithMessage() { + String testMessage = "Invalid JSON-RPC request"; + JsonRpcInvalidRequestException exception = new JsonRpcInvalidRequestException(testMessage); + assertNotNull(exception); + assertEquals(testMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcInvalidRequestExceptionConstructorWithMessageAndCause() { + String testMessage = "Invalid JSON-RPC request with cause"; + Throwable testCause = new Throwable("Root cause"); + JsonRpcInvalidRequestException e = new JsonRpcInvalidRequestException(testMessage, testCause); + assertNotNull(e); + assertEquals(testMessage, e.getMessage()); + assertEquals(testCause, e.getCause()); + } + + @Test + public void testJsonRpcMethodNotFoundExceptionDefaultConstructor() { + JsonRpcMethodNotFoundException exception = new JsonRpcMethodNotFoundException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcMethodNotFoundExceptionConstructorWithMessage() { + String testMessage = "JSON-RPC method not found"; + JsonRpcMethodNotFoundException exception = new JsonRpcMethodNotFoundException(testMessage); + assertNotNull(exception); + assertEquals(testMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testJsonRpcMethodNotFoundExceptionConstructorWithMessageAndCause() { + String testMessage = "JSON-RPC method not found with cause"; + Throwable testCause = new Throwable("Root cause"); + JsonRpcMethodNotFoundException e = new JsonRpcMethodNotFoundException(testMessage, testCause); + assertNotNull(e); + assertEquals(testMessage, e.getMessage()); + assertEquals(testCause, e.getCause()); + } + + @Test + public void testJsonRpcTooManyResultExceptionDefaultConstructor() { + JsonRpcTooManyResultException exception = new JsonRpcTooManyResultException(); + assertNotNull("Exception object should not be null", exception); + assertNull(exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testJsonRpcTooManyResultExceptionWithMessage() { + String testMessage = "Too many results returned by JSON-RPC method"; + JsonRpcTooManyResultException exception = new JsonRpcTooManyResultException(testMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testJsonRpcTooManyResultExceptionWithMessageAndCause() { + String testMessage = "Too many results returned with cause"; + Throwable testCause = new Throwable("Root cause"); + JsonRpcTooManyResultException e = new JsonRpcTooManyResultException(testMessage, testCause); + assertNotNull("Exception object should not be null", e); + assertEquals("Message should match the provided message", testMessage, e.getMessage()); + assertEquals("Cause should match the provided cause", testCause, e.getCause()); + } + + @Test + public void testNonCommonBlockExceptionDefaultConstructor() { + NonCommonBlockException exception = new NonCommonBlockException(); + assertNotNull("Exception object should not be null", exception); + assertNull("Message should be null for default constructor", exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testNonCommonBlockExceptionWithMessage() { + String testMessage = "Block is not common"; + NonCommonBlockException exception = new NonCommonBlockException(testMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testNonCommonBlockExceptionWithMessageAndCause() { + String testMessage = "Block is not common due to some error"; + Throwable testCause = new Throwable("Root cause of the error"); + NonCommonBlockException exception = new NonCommonBlockException(testMessage, testCause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertEquals("Cause should match the provided cause", testCause, exception.getCause()); + } + + @Test + public void testDefaultConstructor() { + NonUniqueObjectException exception = new NonUniqueObjectException(); + assertNotNull("Exception object should not be null", exception); + assertNull("Message should be null for default constructor", exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testConstructorWithMessage() { + String testMessage = "Object is not unique"; + NonUniqueObjectException exception = new NonUniqueObjectException(testMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testConstructorWithMessageAndCause() { + String testMessage = "Object is not unique due to a conflict"; + Throwable testCause = new Throwable("Conflict error"); + NonUniqueObjectException exception = new NonUniqueObjectException(testMessage, testCause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the provided message", testMessage, exception.getMessage()); + assertEquals("Cause should match the provided cause", testCause, exception.getCause()); + } + + @Test + public void testConstructorWithCauseOnly() { + Throwable testCause = new Throwable("Root cause of non-uniqueness"); + NonUniqueObjectException exception = new NonUniqueObjectException(testCause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should be empty string when only cause is provided", "", + exception.getMessage()); + assertEquals("Cause should match the provided cause", testCause, exception.getCause()); + } + + @Test + public void testConstructorWithTypeEnumAndErrMsg() { + P2pException exception = new P2pException(NO_SUCH_MESSAGE, "Test error message"); + assertNotNull("Exception should not be null", exception); + assertEquals("Error message should match", "Test error message", exception.getMessage()); + assertEquals("Exception type should be NO_SUCH_MESSAGE", NO_SUCH_MESSAGE, exception.getType()); + } + + @Test + public void testConstructorWithTypeEnumAndThrowable() { + Throwable cause = new Throwable("Cause of the error"); + P2pException exception = new P2pException(PARSE_MESSAGE_FAILED, cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Cause should match", cause, exception.getCause()); + } + + @Test + public void testConstructorWithTypeEnumErrMsgAndThrowable() { + Throwable cause = new Throwable("Cause of the error"); + P2pException exception = new P2pException(SYNC_FAILED, "Test error message", cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Error message should match", + "Test error message", exception.getMessage()); + assertEquals("Cause should match", cause, exception.getCause()); + assertEquals("Exception type should be SYNC_FAILED", SYNC_FAILED, exception.getType()); + } + + @Test + public void testP2pExceptionTypeEnumValues() { + assertNotNull(NO_SUCH_MESSAGE.toString()); + assertEquals("NO_SUCH_MESSAGE value should be 1", + Integer.valueOf(1), NO_SUCH_MESSAGE.getValue()); + assertEquals("NO_SUCH_MESSAGE desc should be 'no such message'", + "no such message", NO_SUCH_MESSAGE.getDesc()); + + assertEquals("DEFAULT value should be 100", Integer.valueOf(100), + P2pException.TypeEnum.DEFAULT.getValue()); + assertEquals("DEFAULT desc should be 'default exception'", + "default exception", P2pException.TypeEnum.DEFAULT.getDesc()); + } + + @Test + public void testPermissionExceptionDefaultConstructor() { + PermissionException exception = new PermissionException(); + assertNotNull(exception); + } + + @Test + public void testPermissionExceptionWithMessage() { + String errorMessage = "You do not have sufficient permissions to perform this operation"; + PermissionException exception = new PermissionException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testReceiptCheckErrExceptionDefaultConstructor() { + ReceiptCheckErrException exception = new ReceiptCheckErrException(); + assertNotNull("Exception object should not be null", exception); + assertNull("Message should be null for default constructor", exception.getMessage()); + assertNull("Cause should be null for default constructor", exception.getCause()); + } + + @Test + public void testReceiptCheckErrExceptionConstructorWithMessage() { + String errorMessage = "Receipt check failed due to invalid data"; + ReceiptCheckErrException exception = new ReceiptCheckErrException(errorMessage); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the input message", errorMessage, exception.getMessage()); + assertNull("Cause should be null when only message is provided", exception.getCause()); + } + + @Test + public void testReceiptCheckErrExceptionConstructorWithMessageAndCause() { + String errorMessage = "Receipt check error"; + Throwable cause = new Throwable("Underlying database error"); + ReceiptCheckErrException exception = new ReceiptCheckErrException(errorMessage, cause); + assertNotNull("Exception object should not be null", exception); + assertEquals("Message should match the input message", errorMessage, exception.getMessage()); + assertEquals("Cause should match the input cause", cause, exception.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionDefaultConstructor() { + RevokingStoreIllegalStateException exception = new RevokingStoreIllegalStateException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithMessage() { + String errorMessage = "Invalid state for revoking store"; + RevokingStoreIllegalStateException e = new RevokingStoreIllegalStateException(errorMessage); + assertNotNull("Exception should not be null", e); + assertEquals("Message should match the input message", errorMessage, e.getMessage()); + assertNull("Cause should be null", e.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithMessageAndCause() { + String errorMessage = "Error occurred during revocation"; + Throwable cause = new Throwable("Database connection failed"); + RevokingStoreIllegalStateException e = + new RevokingStoreIllegalStateException(errorMessage, cause); + assertNotNull("Exception should not be null", e); + assertEquals("Message should match the input message", errorMessage, e.getMessage()); + assertEquals("Cause should match the input cause", cause, e.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithCauseOnly() { + Throwable cause = new Throwable("Unknown error"); + RevokingStoreIllegalStateException exception = new RevokingStoreIllegalStateException(cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should be empty string", "", exception.getMessage()); + assertEquals("Cause should match the input cause", cause, exception.getCause()); + } + + @Test + public void testRevokingStoreIllegalStateExceptionConstructorWithActiveSession() { + int activeSession = 0; + RevokingStoreIllegalStateException e = new RevokingStoreIllegalStateException(activeSession); + assertNotNull("Exception should not be null", e); + assertEquals("Message should indicate activeSession is not greater than 0", + "activeSession 0 has to be greater than 0", e.getMessage()); + } + + @Test + public void testSignatureFormatExceptionDefaultConstructor() { + SignatureFormatException exception = new SignatureFormatException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + } + + @Test + public void testSignatureFormatExceptionWithMessage() { + String errorMessage = "Invalid signature format"; + SignatureFormatException exception = new SignatureFormatException(errorMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match the provided error message", + errorMessage, exception.getMessage()); + } + + @Test + public void testStoreExceptionDefaultConstructor() { + StoreException exception = new StoreException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testStoreExceptionWithMessage() { + String errorMessage = "Store error occurred"; + StoreException exception = new StoreException(errorMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match the provided error message", + errorMessage, exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testStoreExceptionWithMessageAndCause() { + String errorMessage = "Store error occurred"; + Throwable cause = new Throwable("Root cause"); + StoreException exception = new StoreException(errorMessage, cause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match the provided error message", + errorMessage, exception.getMessage()); + assertEquals("Cause should match the provided cause", cause, exception.getCause()); + } + + @Test + public void testStoreExceptionWithCause() { + Throwable cause = new Throwable("Root cause"); + StoreException exception = new StoreException(cause); + assertNotNull("Exception should not be null", exception); + } + + + @Test + public void testTaposExceptionDefaultConstructor() { + TaposException exception = new TaposException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTaposExceptionWithMessage() { + String errorMessage = "Tapos error occurred"; + TaposException exception = new TaposException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTaposExceptionWithMessageAndCause() { + String errorMessage = "Tapos error occurred"; + Throwable cause = new Throwable("Root cause"); + TaposException exception = new TaposException(errorMessage, cause); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTooBigTransactionExceptionDefaultConstructor() { + TooBigTransactionException exception = new TooBigTransactionException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + } + + @Test + public void testTooBigTransactionExceptionWithMessage() { + String errorMessage = "Transaction is too big"; + TooBigTransactionException exception = new TooBigTransactionException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testTooBigTransactionResultExceptionDefaultConstructor() { + TooBigTransactionResultException exception = new TooBigTransactionResultException(); + assertNotNull(exception); + assertEquals("too big transaction result", + exception.getMessage()); + } + + @Test + public void testTooBigTransactionResultExceptionWithMessage() { + String customMessage = "Custom error message for too big transaction result"; + TooBigTransactionResultException e = new TooBigTransactionResultException(customMessage); + assertNotNull(e); + assertEquals(customMessage, e.getMessage()); + } + + @Test + public void testTraitorPeerExceptionDefaultConstructor() { + TraitorPeerException exception = new TraitorPeerException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTraitorPeerExceptionWithMessage() { + String errorMessage = "Peer is a traitor"; + TraitorPeerException exception = new TraitorPeerException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTraitorPeerExceptionWithMessageAndCause() { + String errorMessage = "Peer is a traitor and caused an error"; + Throwable cause = new Throwable("Underlying cause"); + TraitorPeerException exception = new TraitorPeerException(errorMessage, cause); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTransactionExpirationExceptionDefaultConstructor() { + TransactionExpirationException exception = new TransactionExpirationException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + } + + @Test + public void testTransactionExpirationExceptionWithMessage() { + String errorMessage = "Transaction has expired"; + TransactionExpirationException exception = new TransactionExpirationException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + } + + @Test + public void testTronRuntimeExceptionDefaultConstructor() { + TronRuntimeException exception = new TronRuntimeException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTronRuntimeExceptionWithMessage() { + String errorMessage = "An error occurred"; + TronRuntimeException exception = new TronRuntimeException(errorMessage); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testTronRuntimeExceptionWithMessageAndCause() { + String errorMessage = "An error occurred due to a cause"; + Throwable cause = new Throwable("Underlying cause"); + TronRuntimeException exception = new TronRuntimeException(errorMessage, cause); + assertNotNull(exception); + assertEquals(errorMessage, exception.getMessage()); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTronRuntimeExceptionWithCause() { + Throwable cause = new Throwable("Underlying cause without message"); + TronRuntimeException exception = new TronRuntimeException(cause); + assertEquals(cause, exception.getCause()); + } + + @Test + public void testTypeMismatchNamingException_WithRequiredAndActualTypes() { + try { + throw new TypeMismatchNamingException("someName", String.class, Integer.class); + } catch (TypeMismatchNamingException e) { + assertEquals("Object of type [class java.lang.Integer] available at store location " + + "[someName] is not assignable to [java.lang.String]", e.getMessage()); + assertEquals(String.class, e.getRequiredType()); + assertEquals(Integer.class, e.getActualType()); + } + } + + @Test + public void testTypeMismatchNamingException_WithExplanation() { + try { + throw new TypeMismatchNamingException("Custom explanation"); + } catch (TypeMismatchNamingException e) { + assertEquals("Custom explanation", e.getMessage()); + assertNull(e.getRequiredType()); + assertNull(e.getActualType()); + } + } + + @Test + public void testUnLinkedBlockExceptionDefaultConstructor() { + UnLinkedBlockException exception = new UnLinkedBlockException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testUnLinkedBlockExceptionWithMessage() { + String testMessage = "This block is not linked"; + UnLinkedBlockException exception = new UnLinkedBlockException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testUnLinkedBlockExceptionWithMessageAndCause() { + String testMessage = "This block is not linked due to an error"; + Throwable testCause = new Throwable("Cause of the error"); + UnLinkedBlockException exception = new UnLinkedBlockException(testMessage, testCause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertEquals("Cause should match", testCause, exception.getCause()); + } + + @Test + public void testUnReachBlockExceptionDefaultConstructor() { + UnReachBlockException exception = new UnReachBlockException(); + assertNotNull(exception); + assertNull(exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testUnReachBlockExceptionWithMessage() { + String testMessage = "Block is unreachable"; + UnReachBlockException exception = new UnReachBlockException(testMessage); + assertNotNull(exception); + assertEquals(testMessage, exception.getMessage()); + assertNull(exception.getCause()); + } + + @Test + public void testUnReachBlockExceptionWithMessageAndCause() { + String testMessage = "Block is unreachable due to an error"; + Throwable testCause = new Throwable("Cause of the error"); + UnReachBlockException exception = new UnReachBlockException(testMessage, testCause); + assertNotNull(exception); + assertEquals(testCause, exception.getCause()); + } + + @Test + public void testValidateScheduleExceptionDefaultConstructor() { + ValidateScheduleException exception = new ValidateScheduleException(); + + assertNotNull(exception); + + assertNull(exception.getMessage()); + } + + @Test + public void testValidateScheduleExceptionConstructorWithMessage() { + String testMessage = "Schedule validation failed"; + + ValidateScheduleException exception = new ValidateScheduleException(testMessage); + + assertNotNull(exception); + + assertEquals(testMessage, exception.getMessage()); + } + + @Test + public void testValidateSignatureExceptionDefaultConstructor() { + ValidateSignatureException exception = new ValidateSignatureException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + } + + @Test + public void testValidateSignatureExceptionConstructorWithMessage() { + String testMessage = "Signature validation failed"; + ValidateSignatureException exception = new ValidateSignatureException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + } + + @Test + public void testVMIllegalExceptionDefaultConstructor() { + VMIllegalException exception = new VMIllegalException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + } + + @Test + public void testVMIllegalExceptionConstructorWithMessage() { + String testMessage = "VM operation is illegal"; + VMIllegalException exception = new VMIllegalException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + } + + @Test + public void testZkProofValidateExceptionWithFirstValidatedTrue() { + String testMessage = "Zero-knowledge proof validation failed, but first part was validated"; + boolean firstValidated = true; + + ZkProofValidateException exception = new ZkProofValidateException(testMessage, firstValidated); + + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertTrue("firstValidated should be true", exception.isFirstValidated()); + } + + @Test + public void testZkProofValidateExceptionWithFirstValidatedFalse() { + String testMessage = "Zero-knowledge proof validation failed, first part not validated"; + boolean firstValidated = false; + + ZkProofValidateException exception = new ZkProofValidateException(testMessage, firstValidated); + exception.setFirstValidated(true); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertTrue("firstValidated should be true", exception.isFirstValidated()); + } + + @Test + public void testZksnarkExceptionNoMessage() { + ZksnarkException exception = new ZksnarkException(); + assertNotNull("Exception should not be null", exception); + assertNull(exception.getMessage()); + } + + @Test + public void testZksnarkExceptionWithMessage() { + String testMessage = "Zksnark validation failed"; + ZksnarkException exception = new ZksnarkException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + } + + @Test + public void testTronDBExceptionNoArgs() { + TronDBException exception = new TronDBException(); + assertNotNull("Exception should not be null", exception); + assertNull("Message should be null", exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testTronDBExceptionWithMessage() { + String testMessage = "Database error occurred"; + TronDBException exception = new TronDBException(testMessage); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertNull("Cause should be null", exception.getCause()); + } + + @Test + public void testTronDBExceptionWithMessageAndThrowable() { + String testMessage = "Database error with specific cause"; + Throwable testCause = new Throwable("Root cause"); + TronDBException exception = new TronDBException(testMessage, testCause); + assertNotNull("Exception should not be null", exception); + assertEquals("Message should match", testMessage, exception.getMessage()); + assertEquals("Cause should match", testCause, exception.getCause()); + } + + @Test + public void testTronDBExceptionWithThrowable() { + Throwable testCause = new Throwable("Root cause without message"); + TronDBException exception = new TronDBException(testCause); + assertNotNull("Exception should not be null", exception); + assertEquals("Cause should match", testCause, exception.getCause()); + } +} diff --git a/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java b/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java index e787fe16e96..4bcef1e148c 100644 --- a/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java +++ b/framework/src/test/java/org/tron/core/CreateCommonTransactionTest.java @@ -1,6 +1,6 @@ package org.tron.core; -import static stest.tron.wallet.common.client.WalletClient.decodeFromBase58Check; +import static org.tron.common.utils.client.WalletClient.decodeFromBase58Check; import com.google.protobuf.Any; import com.google.protobuf.ByteString; @@ -16,14 +16,14 @@ public class CreateCommonTransactionTest { - private static String fullnode = "127.0.0.1:50051"; + private static final String FULL_NODE = "127.0.0.1:50051"; /** * for example create UpdateBrokerageContract */ public static void testCreateUpdateBrokerageContract() { WalletBlockingStub walletStub = WalletGrpc - .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build()); + .newBlockingStub(ManagedChannelBuilder.forTarget(FULL_NODE).usePlaintext().build()); UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); updateBrokerageContract.setOwnerAddress( ByteString.copyFrom(decodeFromBase58Check("TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz"))) diff --git a/framework/src/test/java/org/tron/core/EnergyProcessorTest.java b/framework/src/test/java/org/tron/core/EnergyProcessorTest.java index b66b79ba07f..1e9064cb998 100755 --- a/framework/src/test/java/org/tron/core/EnergyProcessorTest.java +++ b/framework/src/test/java/org/tron/core/EnergyProcessorTest.java @@ -1,69 +1,36 @@ package org.tron.core; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.AdaptiveResourceLimitConstants; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.args.Args; import org.tron.core.db.EnergyProcessor; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; +import org.tron.protos.contract.Common; @Slf4j -public class EnergyProcessorTest { +public class EnergyProcessorTest extends BaseTest { - private static final String dbPath = "EnergyProcessorTest"; private static final String ASSET_NAME; private static final String CONTRACT_PROVIDER_ADDRESS; private static final String USER_ADDRESS; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); ASSET_NAME = "test_token"; CONTRACT_PROVIDER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; USER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -130,7 +97,63 @@ public void testUseContractCreatorEnergy() throws Exception { Assert.assertEquals(1526647838000L, ownerCapsuleNew.getAccountResource().getLatestConsumeTimeForEnergy()); Assert.assertEquals(10000L, ownerCapsuleNew.getAccountResource().getEnergyUsage()); + } + @Test + public void testUseEnergyInWindowSizeV2() throws Exception { + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(10000L); + dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(2849288700L); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(CONTRACT_PROVIDER_ADDRESS)); + ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 300); + ownerCapsule.setWindowOptimized(Common.ResourceCode.ENERGY, false); + ownerCapsule.setLatestConsumeTimeForEnergy(9999L); + ownerCapsule.setEnergyUsage(70021176L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + EnergyProcessor processor = + new EnergyProcessor(dbManager.getDynamicPropertiesStore(), dbManager.getAccountStore()); + long energy = 2345L; + long now = 9999L; + for (int i = 0; i < 1000; i++) { + processor.useEnergy(ownerCapsule, energy, now); + } + processor.useEnergy(ownerCapsule, energy, now); + Assert.assertEquals(72368521, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(300, ownerCapsule.getWindowSize(Common.ResourceCode.ENERGY)); + Assert.assertFalse(ownerCapsule.getWindowOptimized(Common.ResourceCode.ENERGY)); + + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 300); + ownerCapsule.setWindowOptimized(Common.ResourceCode.ENERGY, false); + ownerCapsule.setLatestConsumeTimeForEnergy(9999L); + ownerCapsule.setEnergyUsage(70021176L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + for (int i = 0; i < 1000; i++) { + processor.useEnergy(ownerCapsule, energy, now); + } + processor.useEnergy(ownerCapsule, energy, now); + + Assert.assertEquals(72368521L, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(1224, ownerCapsule.getWindowSize(Common.ResourceCode.ENERGY)); + Assert.assertEquals(1224919, ownerCapsule.getWindowSizeV2(Common.ResourceCode.ENERGY)); + Assert.assertTrue(ownerCapsule.getWindowOptimized(Common.ResourceCode.ENERGY)); + + ownerCapsule.setNewWindowSize(Common.ResourceCode.ENERGY, 300); + ownerCapsule.setWindowOptimized(Common.ResourceCode.ENERGY, false); + ownerCapsule.setLatestConsumeTimeForEnergy(9999L); + ownerCapsule.setEnergyUsage(70021176L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + for (int i = 0; i < 1000; i++) { + processor.useEnergy(ownerCapsule, energy, now); + now++; + } + Assert.assertEquals(15844971L, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(2086, ownerCapsule.getWindowSize(Common.ResourceCode.ENERGY)); + Assert.assertEquals(2086556, ownerCapsule.getWindowSizeV2(Common.ResourceCode.ENERGY)); } @Test diff --git a/framework/src/test/java/org/tron/core/ForkControllerTest.java b/framework/src/test/java/org/tron/core/ForkControllerTest.java new file mode 100644 index 00000000000..0b43db3e534 --- /dev/null +++ b/framework/src/test/java/org/tron/core/ForkControllerTest.java @@ -0,0 +1,262 @@ +package org.tron.core; + +import com.google.protobuf.ByteString; +import java.io.IOException; +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; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ForkController; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.Parameter; +import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol; + +public class ForkControllerTest { + private static ChainBaseManager chainBaseManager; + private static DynamicPropertiesStore dynamicPropertiesStore; + private static final ForkController forkController = ForkController.instance(); + private static TronApplicationContext context; + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + private static long ENERGY_LIMIT_BLOCK_NUM = 4727890L; + + @Before + public void init() throws IOException { + Args.setParam(new String[]{"-d", + temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + dynamicPropertiesStore = context.getBean(DynamicPropertiesStore.class); + chainBaseManager = context.getBean(ChainBaseManager.class); + forkController.init(chainBaseManager); + } + + @Test + public void testPass() { + boolean flag = forkController.pass(Parameter.ForkBlockVersionEnum.ENERGY_LIMIT); + Assert.assertFalse(flag); + + dynamicPropertiesStore.saveLatestBlockHeaderNumber(ENERGY_LIMIT_BLOCK_NUM); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.ENERGY_LIMIT); + Assert.assertTrue(flag); + + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertFalse(flag); + + byte[] stats = new byte[3]; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertFalse(flag); + + stats[0] = 1; + stats[1] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertFalse(flag); + + stats[2] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_3_5); + Assert.assertTrue(flag); + + stats = new byte[5]; + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertFalse(flag); + + stats[0] = 1; + stats[1] = 1; + stats[2] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertFalse(flag); + + stats[3] = 1; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertFalse(flag); + + dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(1596780000000L); + flag = forkController.pass(Parameter.ForkBlockVersionEnum.VERSION_4_4); + Assert.assertTrue(flag); + } + + @Test + public void testReset() { + List list = new ArrayList<>(); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + list.add(ByteString.copyFrom(getBytes(0))); + + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + + byte[] stats1 = {1, 1, 1, 1, 1}; + byte[] stats2 = {1, 1, 1, 1, 0}; + byte[] stats3 = {1, 1, 1, 0, 0}; + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats1); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue(), stats3); + + dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(1596780000000L); + forkController.reset(); + + byte[] bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue()); + Assert.assertEquals(getSum(bytes), 5); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(getSum(bytes), 0); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(getSum(bytes), 4); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(getSum(bytes), 0); + list.add(ByteString.copyFrom(new byte[32])); + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + forkController.reset(); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(bytes.length, 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(bytes.length, 6); + } + + @Test + public void testUpdate() { + List list = new ArrayList<>(); + list.add(ByteString.copyFrom(getBytes(1))); + list.add(ByteString.copyFrom(getBytes(2))); + list.add(ByteString.copyFrom(getBytes(3))); + list.add(ByteString.copyFrom(getBytes(4))); + list.add(ByteString.copyFrom(getBytes(5))); + + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + + byte[] stats1 = {1, 1, 1, 1, 1}; + byte[] stats2 = {1, 1, 1, 1, 0}; + byte[] stats3 = {1, 1, 1, 0, 0}; + + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_5.getValue(), stats1); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue(), stats2); + dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue(), stats3); + + BlockCapsule blockCapsule = getBlock(1, Parameter.ForkBlockVersionEnum.VERSION_3_5); + + forkController.update(blockCapsule); + + byte[] bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(0, bytes[0]); + + blockCapsule = getBlock(1, Parameter.ForkBlockVersionEnum.VERSION_4_5); + forkController.update(blockCapsule); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(0, bytes[0]); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(1, bytes[0]); + + blockCapsule = getBlock(4, Parameter.ForkBlockVersionEnum.VERSION_4_5); + forkController.update(blockCapsule); + blockCapsule = getBlock(5, Parameter.ForkBlockVersionEnum.VERSION_4_5); + + dynamicPropertiesStore.saveLatestBlockHeaderTimestamp(1596780000000L); + forkController.update(blockCapsule); + + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_3_6.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_3.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(getSum(bytes), 4); + + blockCapsule = getBlock(1, Parameter.ForkBlockVersionEnum.VERSION_4_3); + forkController.update(blockCapsule); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_4.getValue()); + Assert.assertEquals(getSum(bytes), 5); + bytes = dynamicPropertiesStore + .statsByVersion(Parameter.ForkBlockVersionEnum.VERSION_4_5.getValue()); + Assert.assertEquals(getSum(bytes), 4); + } + + private BlockCapsule getBlock(int i, Parameter.ForkBlockVersionEnum versionEnum) { + org.tron.protos.Protocol.BlockHeader.raw rawData = + org.tron.protos.Protocol.BlockHeader.raw.newBuilder() + .setVersion(versionEnum.getValue()) + .setWitnessAddress(ByteString.copyFrom(getBytes(i))) + .build(); + + Protocol.BlockHeader blockHeader = Protocol.BlockHeader.newBuilder() + .setRawData(rawData).build(); + + Protocol.Block block = Protocol.Block.newBuilder().setBlockHeader(blockHeader).build(); + + return new BlockCapsule(block); + } + + private int getSum(byte[] bytes) { + int sum = 0; + for (byte aByte : bytes) { + sum += aByte; + } + return sum; + } + + private byte[] getBytes(int i) { + byte[] bytes = new byte[21]; + bytes[i] = 1; + return bytes; + } + + @After + public void removeDb() { + Args.clearParam(); + context.destroy(); + } + +} diff --git a/framework/src/test/java/org/tron/core/ShieldWalletTest.java b/framework/src/test/java/org/tron/core/ShieldWalletTest.java new file mode 100644 index 00000000000..f8d5db1a44c --- /dev/null +++ b/framework/src/test/java/org/tron/core/ShieldWalletTest.java @@ -0,0 +1,460 @@ +package org.tron.core; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.tron.core.zen.ZksnarkInitService.librustzcashInitZksnarkParams; + +import java.math.BigInteger; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.api.GrpcAPI.PrivateParameters; +import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk; +import org.tron.api.GrpcAPI.PrivateShieldedTRC20Parameters; +import org.tron.api.GrpcAPI.PrivateShieldedTRC20ParametersWithoutAsk; +import org.tron.api.GrpcAPI.ShieldedAddressInfo; +import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.services.http.JsonFormat; +import org.tron.core.services.http.JsonFormat.ParseException; + + +public class ShieldWalletTest extends BaseTest { + + @Resource + private Wallet wallet; + + static { + Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testCreateShieldedTransaction1() { + librustzcashInitZksnarkParams(); + String transactionStr1 = new String(ByteArray.fromHexString( + "0x7b0a20202020227472616e73706172656e745f66726f6d5f61646472657373223a202234433930413" + + "73241433344414546324536383932343545463430303839443634314345414337373433323433414233" + + "31333136303030222c0a202020202266726f6d5f616d6f756e74223a203130303030303030302c0a202" + + "02020226f766b223a223566643165636466643637396232616461333337623235306231303234373138" + + "6633316439636237316361653664666363396131613637626134373033643863222c0a2020202022736" + + "869656c6465645f7265636569766573223a205b0a20202020202020207b0a2020202020202020202020" + + "20226e6f7465223a207b0a202020202020202020202020202020202276616c7565223a2039303030303" + + "030302c0a20202020202020202020202020202020227061796d656e745f61646472657373223a20227a" + + "74726f6e3179616d336a723270746d79706c707030747978387974707a36736a64786364657a306a333" + + "36673636d656a76376e6863346171336d766b687275726772777671653932636a6c68356b3367222c0a" + + "202020202020202020202020202020202272636d223a202237323330353362636266656364663564613" + + "63663313861623033373634373665663330386336316237616265383931623263303165393033626362" + + "3837633065222c0a20202020202020202020202020202020226d656d6f223a20223232323232220a202" + + "0202020202020202020207d0a20202020202020207d0a202020205d0a7d")); + PrivateParameters.Builder builder1 = PrivateParameters.newBuilder(); + try { + JsonFormat.merge(transactionStr1, builder1, false); + } catch (ParseException e) { + Assert.fail(); + } + + try { + TransactionCapsule transactionCapsule = wallet.createShieldedTransaction(builder1.build()); + Assert.assertNotNull(transactionCapsule); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testCreateShieldedTransaction2() { + librustzcashInitZksnarkParams(); + String transactionStr2 = new String(ByteArray.fromHexString( + "7b0a202020202261736b223a20223938666430333136376632333437623534643737323338343137663" + + "6373038643537323939643938376362613838353564653037626532346236316464653064222c0a2020" + + "2020226e736b223a2022643063623330653764306634653435333535363134333463303462616339316" + + "63039643230653664366234363361623031626534663531386230363839653039222c0a20202020226f" + + "766b223a202235666431656364666436373962326164613333376232353062313032343731386633316" + + "439636237316361653664666363396131613637626134373033643863222c0a2020202022736869656c" + + "6465645f7370656e6473223a205b0a20202020202020207b200a090909226e6f7465223a207b0a20202" + + "0202020202020202020202020202276616c7565223a2039303030303030302c0a202020202020202020" + + "20202020202020227061796d656e745f61646472657373223a20227a74726f6e3179616d336a7232707" + + "46d79706c707030747978387974707a36736a64786364657a306a33336673636d656a76376e68633461" + + "71336d766b687275726772777671653932636a6c68356b3367222c0a202020202020202020202020202" + + "020202272636d223a202237323330353362636266656364663564613636633138616230333736343736" + + "656633303863363162376162653839316232633031653930336263623837633065222c0a20202020202" + + "020202020202020202020226d656d6f223a20223232323232220a2020202020202020202020207d2c0a" + + "20202020202020202020202022616c706861223a2022323936656531633532633933663734306433616" + + "23162373265366463663561626231643666343965643865646236663334656633666462366537366335" + + "353063222c0a20202020202020202020202022766f7563686572223a207b0a202020202020202020202" + + "0202274726565223a207b0a20202020202020202020202020202020226c656674223a207b0a20202020" + + "2020202020202020202020202020202022636f6e74656e74223a2022346565653236313963343862613" + + "26264303235303235363330636430313362616361663337653961323162323965333938393735623763" + + "653864363436613265220a202020202020202020202020202020207d2c0a20202020202020202020202" + + "020202020227269676874223a207b0a202020202020202020202020202020202020202022636f6e7465" + + "6e74223a202235333863326139313537313333356334666138383866396234336239666164643931633" + + "334666366326265666130333931353932613564366535343539623537220a2020202020202020202020" + + "20202020207d0a2020202020202020202020207d2c0a202020202020202020202020227274223a20226" + + "33539376436633235663131623938613638303034343838393138386638613934616237393265353432" + + "32313461386636346632363334616535346535353531220a20202020202020207d2c0a2020202020202" + + "020202020202270617468223a2022323032306232656564303331643464366134663032613039376638" + + "30623534636331353431643431363363366236663539373166383862366534316433356335333831343" + + "23031323933356631346236373635303962383165623439656632356633393236396564373233303932" + + "33386234633134353830333534346236343664636136326432306531663334623033346434613363643" + + "23835353765323930376562663939306339313866363465636235306139346630316436666461356361" + + "35633765663732323032386537623834316463626334376363656236396437636238643934323435666" + + "23763623262613361376136626331386631336639343566376462643665326132306135313232633038" + + "66663963313631643963613666633436323037333339366337643764333865386565343863646233626" + + "56137653232333031333465643661323064326531363432633961343632323239323839653562306533" + + "62376639303038653033303163626239333338356565306532316461323534353037336362353832303" + + "13664363235323936383937316138336461383532316436353338326536316630313736363436643737" + + "31633931353238653332373665653435333833653461323066656530653532383032636230633436623" + + "16562346433373663363236393766343735396636633839313766613335323537313230326664373738" + + "66643731323230346336393337643738663432363835663834623433616433623762303066383132383" + + "53636326638356336613638656631316436326164316133656530383530323030373639353537626336" + + "38326231626633303836343666643062323265363438653862396539386635376532396635616634306" + + "63665646238333365326334393230303865656162306331336162643630363965363331303139376266" + + "38306639633165613664653738666431396362616532346434613532306536636633303233323038643" + + "56661343365356131306431313630356163373433306261316635643831666231623638643239613634" + + "30343035373637373439653834313532373637333230366163613834343864383236336535343764356" + + "66632393530653265643338333965393938643331636263366163396664353762633630303262313539" + + "32313632306364316338646266366533616363376138303433396263343936326366323562396463653" + + "76338393666336135626437303830336663356130653333636630303230366564623136643031393037" + + "62373539393737643736353064616437653365633034396166316133643837353338306236393763383" + + "63263396563356435316332303165613636373566393535316565623964666161613932343762633938" + + "35383237306433643361346335616661373137376139383464356564316265323435313230643661636" + + "46564663935663630386530396661353366623433646364303939303437353732366335313331323130" + + "63396535636165616239376630653634326632306264373462323561616362393233373861383731626" + + "63237643232356366633236626163613334346131656133356664643934353130663364313537303832" + + "63323031623737646163346432346662373235386333633532383730346335393433306236333037313" + + "86265633438363432313833373032316366373564616236353132306563363737313134633237323036" + + "66356465626331633165643636663935653262313838356461356237626533643733366231646539383" + + "53739343733303438323034373737633837373661336231653639623733613632666137303166613466" + + "37613632383264396165653263376136623832653739333764373038316332336332306261343962363" + + "53966626430623733333432313165613661396439646631383563373537653730616138316461353632" + + "66623931326238346634396263653732323034336666353435376631336239323662363164663535326" + + "43465343032656536646331343633663939613533356639613731333433393236346435623631366232" + + "30376239396162646333373330393931636339323734373237643764383264323863623739346564626" + + "33730333462346630303533666637633462363830343434323064366336333961633234623436626431" + + "39333431633931623133666463616233313538316464616637663134313133333661323731663364306" + + "16135323831333230386163396366396333393165336664343238393164323732333861383161386135" + + "63316433613732623162636265613863663434613538636537333839363133323039313264383262326" + + "33262636132333166373165666366363137333766626630613038626566613034313632313561656566" + + "35336538626236643233333930613230653131306465363563393037623964656134616530626438336" + + "13462306135316265613137353634366136346331326234633966393331623263623331623439323064" + + "38323833333836656632656630376562646262343338336331326137333961393533613464366530643" + + "66662313133396134303336643639336266626236633230666665396663303366313862313736633939" + + "38383036343339666630626238616431393361666462323762326363626338383835363931366464383" + + "03465333432303831376465333661623264353766656230373736333462636137373831396338653062" + + "64323938633034663666656430653661383363633133353663613135353230346565653236313963343" + + "86261326264303235303235363330636430313362616361663337653961323162323965333938393735" + + "62376365386436343661326530313030303030303030303030303030220a20202020202020207d0a202" + + "020205d2c0a2020202022736869656c6465645f7265636569766573223a205b0a20202020202020207b" + + "0a202020202020202020202020226e6f7465223a207b0a2020202020202020202020202020202022766" + + "16c7565223a2038303030303030302c0a20202020202020202020202020202020227061796d656e745f" + + "61646472657373223a20227a74726f6e31356b657a70736d71303568336d616a6e6c7a6834306772796" + + "a6d676d3630783265686a7967633771387336376d6c753835376375747177613334386e76706765706e" + + "35786b336735727278222c0a202020202020202020202020202020202272636d223a202237323330353" + + "36263626665636466356461363663313861623033373634373665663330386336316237616265383931" + + "6232633031653930336263623837633065222c0a20202020202020202020202020202020226d656d6f2" + + "23a2022313131313131313131220a2020202020202020202020207d0a20202020202020207d0a202020" + + "205d2c0a202020202276697369626c6522203a20747275650a7d")); + PrivateParameters.Builder builder2 = PrivateParameters.newBuilder(); + try { + JsonFormat.merge(transactionStr2, builder2, true); + } catch (ParseException e) { + Assert.fail(); + } + + try { + TransactionCapsule transactionCapsule = wallet.createShieldedTransaction(builder2.build()); + Assert.assertNotNull(transactionCapsule); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testCreateShieldedTransactionWithoutSpendAuthSig() { + librustzcashInitZksnarkParams(); + String transactionStr3 = new String(ByteArray.fromHexString( + "7b0a2020202022616b223a2022373161643638633466353035373464356164333735343863626538363" + + "63031663732393662393161306362303535353733313462373830383437323730326465222c0a202020" + + "20226e736b223a202264306362333065376430663465343533353536313433346330346261633931663" + + "039643230653664366234363361623031626534663531386230363839653039222c0a20202020226f76" + + "6b223a20223566643165636466643637396232616461333337623235306231303234373138663331643" + + "9636237316361653664666363396131613637626134373033643863222c0a2020202022736869656c64" + + "65645f7370656e6473223a205b0a20202020202020207b0a202020202020202020202020226e6f74652" + + "23a207b0a202020202020202020202020202020202276616c7565223a2039303030303030302c0a2020" + + "2020202020202020202020202020227061796d656e745f61646472657373223a20227a74726f6e31796" + + "16d336a723270746d79706c707030747978387974707a36736a64786364657a306a33336673636d656a" + + "76376e6863346171336d766b687275726772777671653932636a6c68356b3367222c0a2020202020202" + + "02020202020202020202272636d223a2022373233303533626362666563646635646136366331386162" + + "30333736343736656633303863363162376162653839316232633031653930336263623837633065222" + + "c0a20202020202020202020202020202020226d656d6f223a20223232323232220a2020202020202020" + + "202020207d2c0a20202020202020202020202022616c706861223a20223239366565316335326339336" + + "63734306433616231623732653664636635616262316436663439656438656462366633346566336664" + + "62366537366335353063222c0a20202020202020202020202022766f7563686572223a207b0a2020202" + + "02020202020202020202020202274726565223a207b0a20202020202020202020202020202020202020" + + "20226c656674223a207b0a20202020202020202020202020202020202020202020202022636f6e74656" + + "e74223a2022346565653236313963343862613262643032353032353633306364303133626163616633" + + "37653961323162323965333938393735623763653864363436613265220a20202020202020202020202" + + "020202020202020207d2c0a2020202020202020202020202020202020202020227269676874223a207b" + + "0a20202020202020202020202020202020202020202020202022636f6e74656e74223a2022353338633" + + "26139313537313333356334666138383866396234336239666164643931633334666366326265666130" + + "333931353932613564366535343539623537220a20202020202020202020202020202020202020207d0" + + "a202020202020202020202020202020207d2c0a20202020202020202020202020202020227274223a20" + + "22633539376436633235663131623938613638303034343838393138386638613934616237393265353" + + "43232313461386636346632363334616535346535353531220a2020202020202020202020207d2c0a20" + + "20202020202020202020202270617468223a20223230323062326565643033316434643661346630326" + + "13039376638306235346363313534316434313633633662366635393731663838623665343164333563" + + "35333831343230313239333566313462363736353039623831656234396566323566333932363965643" + + "73233303932333862346331343538303335343462363436646361363264323065316633346230333464" + + "34613363643238353537653239303765626639393063393138663634656362353061393466303164366" + + "66461356361356337656637323230323865376238343164636263343763636562363964376362386439" + + "34323435666237636232626133613761366263313866313366393435663764626436653261323061353" + + "13232633038666639633136316439636136666334363230373333393663376437643338653865653438" + + "63646233626561376532323330313334656436613230643265313634326339613436323232393238396" + + "53562306533623766393030386530333031636262393333383565653065323164613235343530373363" + + "62353832303136643632353239363839373161383364613835323164363533383265363166303137363" + + "63436643737316339313532386533323736656534353338336534613230666565306535323830326362" + + "30633436623165623464333736633632363937663437353966366338393137666133353235373132303" + + "26664373738666437313232303463363933376437386634323638356638346234336164336237623030" + + "66383132383536363266383563366136386566313164363261643161336565303835303230303736393" + + "53537626336383262316266333038363436666430623232653634386538623965393866353765323966" + + "35616634306636656462383333653263343932303038656561623063313361626436303639653633313" + + "03139376266383066396331656136646537386664313963626165323464346135323065366366333032" + + "33323038643566613433653561313064313136303561633734333062613166356438316662316236386" + + "43239613634303430353736373734396538343135323736373332303661636138343438643832363365" + + "35343764356666323935306532656433383339653939386433316362633661633966643537626336303" + + "03262313539323136323063643163386462663665336163633761383034333962633439363263663235" + + "62396463653763383936663361356264373038303366633561306533336366303032303665646231366" + + "43031393037623735393937376437363530646164376533656330343961663161336438373533383062" + + "36393763383632633965633564353163323031656136363735663935353165656239646661616139323" + + "43762633938353832373064336433613463356166613731373761393834643565643162653234353132" + + "30643661636465646639356636303865303966613533666234336463643039393034373537323663353" + + "13331323130633965356361656162393766306536343266323062643734623235616163623932333738" + + "61383731626632376432323563666332366261636133343461316561333566646439343531306633643" + + "13537303832633230316237376461633464323466623732353863336335323837303463353934333062" + + "36333037313862656334383634323138333730323163663735646162363531323065633637373131346" + + "33237323036663564656263316331656436366639356532623138383564613562376265336437333662" + + "31646539383537393437333034383230343737376338373736613362316536396237336136326661373" + + "03166613466376136323832643961656532633761366238326537393337643730383163323363323062" + + "61343962363539666264306237333334323131656136613964396466313835633735376537306161383" + + "16461353632666239313262383466343962636537323230343366663534353766313362393236623631" + + "64663535326434653430326565366463313436336639396135333566396137313334333932363464356" + + "23631366232303762393961626463333733303939316363393237343732376437643832643238636237" + + "39346564626337303334623466303035336666376334623638303434343230643663363339616332346" + + "23436626431393334316339316231336664636162333135383164646166376631343131333336613237" + + "31663364306161353238313332303861633963663963333931653366643432383931643237323338613" + + "83161386135633164336137326231626362656138636634346135386365373338393631333230393132" + + "64383262326332626361323331663731656663663631373337666266306130386265666130343136323" + + "13561656566353365386262366432333339306132306531313064653635633930376239646561346165" + + "30626438336134623061353162656131373536343661363463313262346339663933316232636233316" + + "23439323064383238333338366566326566303765626462623433383363313261373339613935336134" + + "64366530643666623131333961343033366436393362666262366332306666653966633033663138623" + + "13736633939383830363433396666306262386164313933616664623237623263636263383838353639" + + "31366464383034653334323038313764653336616232643537666562303737363334626361373738313" + + "96338653062643239386330346636666564306536613833636331333536636131353532303465656532" + + "36313963343862613262643032353032353633306364303133626163616633376539613231623239653" + + "3393839373562376365386436343661326530313030303030303030303030303030220a202020202020" + + "20207d0a202020205d2c0a2020202022736869656c6465645f7265636569766573223a205b0a2020202" + + "0202020207b0a202020202020202020202020226e6f7465223a207b0a20202020202020202020202020" + + "2020202276616c7565223a2038303030303030302c0a202020202020202020202020202020202270617" + + "96d656e745f61646472657373223a20227a74726f6e31356b657a70736d71303568336d616a6e6c7a68" + + "34306772796a6d676d3630783265686a7967633771387336376d6c753835376375747177613334386e7" + + "6706765706e35786b336735727278222c0a202020202020202020202020202020202272636d223a2022" + + "37323330353362636266656364663564613636633138616230333736343736656633303863363162376" + + "162653839316232633031653930336263623837633065222c0a20202020202020202020202020202020" + + "226d656d6f223a2022313131313131313131220a2020202020202020202020207d0a202020202020202" + + "07d0a202020205d2c0a202020202276697369626c65223a20747275650a7d")); + PrivateParametersWithoutAsk.Builder builder3 = PrivateParametersWithoutAsk.newBuilder(); + try { + JsonFormat.merge(transactionStr3, builder3, false); + } catch (ParseException e) { + Assert.fail(); + } + + try { + TransactionCapsule transactionCapsule = wallet.createShieldedTransactionWithoutSpendAuthSig( + builder3.build()); + Assert.assertNotNull(transactionCapsule); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testGetNewShieldedAddress() { + librustzcashInitZksnarkParams(); + try { + ShieldedAddressInfo shieldedAddressInfo = wallet.getNewShieldedAddress(); + Assert.assertNotNull(shieldedAddressInfo); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testCreateShieldedContractParameters() throws ContractExeException { + librustzcashInitZksnarkParams(); + Args.getInstance().setFullNodeAllowShieldedTransactionArgs(true); + Wallet wallet1 = spy(new Wallet()); + + doReturn(BigInteger.valueOf(1).toByteArray()) + .when(wallet1).getShieldedContractScalingFactor( + ByteArray.fromHexString("4144007979359ECAC395BBD3CEF8060D3DF2DC3F01")); + String parameter = new String(ByteArray.fromHexString( + "7b0a202020202261736b223a22633235313365396533303834393439333262643832653063653533363" + + "63264313734323164393062373261383437316130613132623835353261333336653032222c0a202020" + + "20226e736b223a223463366266336464346130363433643230623632386637653435393830633565313" + + "8376630376135316436663365383661616631616239313663303765623064222c0a20202020226f766b" + + "223a2231376135386439613530353864613665343263613132636432383964306136616131363962393" + + "236633138653139626361353138623864366638363734653433222c0a202020202266726f6d5f616d6f" + + "756e74223a22313030222c0a2020202022736869656c6465645f7265636569766573223a5b0a2020202" + + "0202020207b0a202020202020202020202020226e6f7465223a7b0a2020202020202020202020202020" + + "20202276616c7565223a3130302c0a20202020202020202020202020202020227061796d656e745f616" + + "46472657373223a227a74726f6e317939397536656a71656e757076666b70356736713679716b703061" + + "34346334386374613064643567656a7471613476323768716132636768667664786e6d6e65683671717" + + "1303366613735222c0a202020202020202020202020202020202272636d223a22313662366635653430" + + "34343461623765656162313161653636313363323766333531313739373165666138376237313536306" + + "235383133383239633933393064220a2020202020202020202020207d0a20202020202020207d0a2020" + + "20205d2c0a2020202022736869656c6465645f54524332305f636f6e74726163745f616464726573732" + + "23a22343134343030373937393335394543414333393542424433434546383036304433444632444333" + + "463031220a7d")); + PrivateShieldedTRC20Parameters.Builder builder = PrivateShieldedTRC20Parameters.newBuilder(); + try { + JsonFormat.merge(parameter, builder, false); + } catch (ParseException e) { + Assert.fail(); + } + + try { + ShieldedTRC20Parameters shieldedTRC20Parameters = wallet1.createShieldedContractParameters( + builder.build()); + Assert.assertNotNull(shieldedTRC20Parameters); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testCreateShieldedContractParameters2() throws ContractExeException { + librustzcashInitZksnarkParams(); + Args.getInstance().setFullNodeAllowShieldedTransactionArgs(true); + Wallet wallet1 = spy(new Wallet()); + + doReturn(BigInteger.valueOf(1).toByteArray()) + .when(wallet1).getShieldedContractScalingFactor( + ByteArray.fromHexString("4144007979359ECAC395BBD3CEF8060D3DF2DC3F01")); + String parameter = new String(ByteArray.fromHexString( + "7b0a202020202261736b223a2263323531336539653330383439343933326264383265306365353336" + + "363264313734323164393062373261383437316130613132623835353261333336653032222c0a202" + + "02020226e736b223a2234633662663364643461303634336432306236323866376534353938306335" + + "653138376630376135316436663365383661616631616239313663303765623064222c0a202020202" + + "26f766b223a2231376135386439613530353864613665343263613132636432383964306136616131" + + "363962393236633138653139626361353138623864366638363734653433222c0a202020202266726" + + "f6d5f616d6f756e74223a22313030222c0a2020202022736869656c6465645f726563656976657322" + + "3a5b0a20202020202020207b0a202020202020202020202020226e6f7465223a7b0a2020202020202" + + "02020202020202020202276616c7565223a3130302c0a202020202020202020202020202020202270" + + "61796d656e745f61646472657373223a22222c0a202020202020202020202020202020202272636d2" + + "23a223136623666356534303434346162376565616231316165363631336332376633353131373937" + + "3165666138376237313536306235383133383239633933393064220a2020202020202020202020207" + + "d0a20202020202020207d0a202020205d2c0a2020202022736869656c6465645f54524332305f636f" + + "6e74726163745f61646472657373223a2234313434303037393739333539454341433339354242443" + + "3434546383036304433444632444333463031220a7d")); + + PrivateShieldedTRC20Parameters.Builder builder = PrivateShieldedTRC20Parameters.newBuilder(); + try { + JsonFormat.merge(parameter, builder, false); + } catch (ParseException e) { + Assert.fail(); + } + + try { + wallet1.createShieldedContractParameters(builder.build()); + Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("PaymentAddress in ReceiveNote should not be empty", + e.getMessage()); + } + + String parameter2 = new String(ByteArray.fromHexString( + "7b0a202020202261736b223a2263323531336539653330383439343933326264383265306365353336" + + "363264313734323164393062373261383437316130613132623835353261333336653032222c0a202" + + "02020226e736b223a2234633662663364643461303634336432306236323866376534353938306335" + + "653138376630376135316436663365383661616631616239313663303765623064222c0a202020202" + + "26f766b223a2231376135386439613530353864613665343263613132636432383964306136616131" + + "363962393236633138653139626361353138623864366638363734653433222c0a202020202266726" + + "f6d5f616d6f756e74223a22313030222c0a2020202022736869656c6465645f7370656e6473223a5b" + + "0a20202020202020207b0a202020202020202020202020226e6f7465223a7b0a20202020202020202" + + "0202020202020202276616c7565223a3130302c0a2020202020202020202020202020202022706179" + + "6d656e745f61646472657373223a22222c0a202020202020202020202020202020202272636d223a2" + + "231366236663565343034343461623765656162313161653636313363323766333531313739373165" + + "666138376237313536306235383133383239633933393064220a2020202020202020202020207d0a2" + + "0202020202020207d0a202020205d2c0a2020202022736869656c6465645f54524332305f636f6e74" + + "726163745f61646472657373223a22343134343030373937393335394543414333393542424433434" + + "546383036304433444632444333463031220a7d")); + + builder = PrivateShieldedTRC20Parameters.newBuilder(); + try { + JsonFormat.merge(parameter2, builder, false); + } catch (ParseException e) { + Assert.fail(); + } + + try { + wallet1.createShieldedContractParameters(builder.build()); + Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("PaymentAddress in SpendNote should not be empty", + e.getMessage()); + } + } + + @Test + public void testCreateShieldedContractParametersWithoutAsk() throws ContractExeException { + librustzcashInitZksnarkParams(); + Args.getInstance().setFullNodeAllowShieldedTransactionArgs(true); + + Wallet wallet1 = spy(new Wallet()); + doReturn(BigInteger.valueOf(1).toByteArray()) + .when(wallet1).getShieldedContractScalingFactor( + ByteArray.fromHexString("4144007979359ECAC395BBD3CEF8060D3DF2DC3F01")); + String parameter = new String(ByteArray.fromHexString( + "7b0a2020202022616b223a2230656261373361343865323934396561356461613133626365663466646" + + "633613561613966336232363830363763663831313233333938613833386665336363222c0a20202020" + + "226e736b223a22346336626633646434613036343364323062363238663765343539383063356531383" + + "76630376135316436663365383661616631616239313663303765623064222c0a20202020226f766b22" + + "3a223137613538643961353035386461366534326361313263643238396430613661613136396239323" + + "6633138653139626361353138623864366638363734653433222c0a202020202266726f6d5f616d6f75" + + "6e74223a22313030222c0a2020202022736869656c6465645f7265636569766573223a5b0a202020202" + + "02020207b0a202020202020202020202020226e6f7465223a7b0a202020202020202020202020202020" + + "202276616c7565223a3130302c0a20202020202020202020202020202020227061796d656e745f61646" + + "472657373223a227a74726f6e317939397536656a71656e757076666b70356736713679716b70306134" + + "346334386374613064643567656a7471613476323768716132636768667664786e6d6e6568367171713" + + "03366613735222c0a202020202020202020202020202020202272636d223a2231366236663565343034" + + "34346162376565616231316165363631336332376633353131373937316566613837623731353630623" + + "5383133383239633933393064220a2020202020202020202020207d0a20202020202020207d0a202020" + + "205d2c0a2020202022736869656c6465645f54524332305f636f6e74726163745f61646472657373223" + + "a2234313434303037393739333539454341433339354242443343454638303630443344463244433346" + + "3031220a7d")); + PrivateShieldedTRC20ParametersWithoutAsk.Builder builder = + PrivateShieldedTRC20ParametersWithoutAsk.newBuilder(); + try { + JsonFormat.merge(parameter, builder, false); + } catch (ParseException e) { + Assert.fail(); + } + + try { + ShieldedTRC20Parameters shieldedTRC20Parameters = + wallet1.createShieldedContractParametersWithoutAsk(builder.build()); + Assert.assertNotNull(shieldedTRC20Parameters); + } catch (Exception e) { + Assert.fail(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java index ba407b42e0b..2c97473b6c3 100644 --- a/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java +++ b/framework/src/test/java/org/tron/core/ShieldedTRC20BuilderTest.java @@ -3,21 +3,18 @@ import static org.tron.core.zksnark.LibrustzcashTest.librustzcashInitZksnarkParams; import com.google.protobuf.ByteString; -import java.io.File; import java.math.BigInteger; import java.util.Arrays; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.tuple.Pair; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.tron.api.GrpcAPI; import org.tron.api.GrpcAPI.BytesMessage; import org.tron.api.GrpcAPI.PrivateShieldedTRC20Parameters; @@ -25,27 +22,25 @@ import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; import org.tron.api.GrpcAPI.ShieldedTRC20TriggerContractParameters; import org.tron.api.GrpcAPI.SpendAuthSigParameters; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.WalletClient; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; import org.tron.common.zksnark.LibrustzcashParam; import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.PedersenHashCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.BlockGenerate; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.vm.PrecompiledContracts.VerifyBurnProof; import org.tron.core.vm.PrecompiledContracts.VerifyMintProof; import org.tron.core.vm.PrecompiledContracts.VerifyTransferProof; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; import org.tron.core.zen.address.FullViewingKey; @@ -56,17 +51,12 @@ import org.tron.core.zen.note.Note; import org.tron.protos.contract.ShieldContract; import org.tron.protos.contract.ShieldContract.SpendDescription; -import stest.tron.wallet.common.client.WalletClient; @Slf4j -public class ShieldedTRC20BuilderTest extends BlockGenerate { - - private static String dbPath = "output_Shielded_TRC20_Api_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; - private String privateKey = "650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812"; - private String pubAddress = "TFsrP7YcSSRwHzLPwaCnXyTKagHs8rXKNJ"; +public class ShieldedTRC20BuilderTest extends BaseTest { + @Resource + private Wallet wallet; + private String priKey = PublicMethod.getRandomPrivateKey(); private static final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; private static final byte[] SHIELDED_CONTRACT_ADDRESS; private static final byte[] DEFAULT_OVK; @@ -74,12 +64,11 @@ public class ShieldedTRC20BuilderTest extends BlockGenerate { private static final byte[] PUBLIC_TO_ADDRESS; static { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-test-mainnet.conf"); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, "config-test-mainnet.conf"); SHIELDED_CONTRACT_ADDRESS = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); DEFAULT_OVK = ByteArray .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - FullNodeHttpApiService.librustzcashInitZksnarkParams(); + ZksnarkInitService.librustzcashInitZksnarkParams(); PUBLIC_TO_ADDRESS = WalletClient.decodeFromBase58Check(PUBLIC_TO_ADDRESS_STR); } @@ -87,25 +76,6 @@ public class ShieldedTRC20BuilderTest extends BlockGenerate { VerifyTransferProof transferContract = new VerifyTransferProof(); VerifyBurnProof burnContract = new VerifyBurnProof(); - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); - dbManager.getDynamicPropertiesStore().saveAllowShieldedTRC20Transaction(1); - dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Before public void before() { } @@ -121,7 +91,7 @@ public void createShieldedContractParametersForMint() for (int countNum = 0; countNum < totalCountNum; countNum++) { GrpcAPI.PrivateShieldedTRC20Parameters mintPrivateParam1 = mintParams( - privateKey, value, SHIELDED_CONTRACT_ADDRESS_STR, null); + priKey, value, SHIELDED_CONTRACT_ADDRESS_STR, null); GrpcAPI.ShieldedTRC20Parameters trc20MintParams = wallet .createShieldedContractParameters(mintPrivateParam1); @@ -132,7 +102,7 @@ public void createShieldedContractParametersForMint() Assert.assertEquals(1, result[31]); //update frontier and leafCount - + int slot = result[63]; if (slot == 0) { System.arraycopy(inputData, 0, frontier, 0, 32); @@ -159,7 +129,7 @@ public void createShieldedContractParametersForTransfer1to1() IncrementalMerkleTreeContainer tree = new IncrementalMerkleTreeContainer( new IncrementalMerkleTreeCapsule()); for (int countNum = 0; countNum < totalCountNum; countNum++) { - SpendingKey senderSk = SpendingKey.decode(privateKey); + SpendingKey senderSk = SpendingKey.decode(priKey); FullViewingKey senderFvk = senderSk.fullViewingKey(); IncomingViewingKey senderIvk = senderFvk.inViewingKey(); byte[] rcm1 = new byte[32]; @@ -2203,7 +2173,6 @@ public void createShieldedContractParametersWithoutAskForBurn1to2() @Test public void getTriggerInputForForMint() throws Exception { librustzcashInitZksnarkParams(); - byte[] callerAddress = WalletClient.decodeFromBase58Check(pubAddress); SpendingKey sk = SpendingKey.random(); ExpandedSpendingKey expsk = sk.expandedSpendingKey(); byte[] ovk = expsk.getOvk(); @@ -2273,7 +2242,7 @@ public void testScanShieldedTRC20NotesByIvk() throws Exception { int statNum = 1; int endNum = 100; librustzcashInitZksnarkParams(); - SpendingKey sk = SpendingKey.decode(privateKey); + SpendingKey sk = SpendingKey.decode(priKey); FullViewingKey fvk = sk.fullViewingKey(); byte[] ivk = fvk.inViewingKey().value; @@ -2289,7 +2258,7 @@ public void testScanShieldedTRC20NotesByIvk() throws Exception { public void testscanShieldedTRC20NotesByOvk() throws Exception { int statNum = 9200; int endNum = 9240; - SpendingKey sk = SpendingKey.decode(privateKey); + SpendingKey sk = SpendingKey.decode(priKey); FullViewingKey fvk = sk.fullViewingKey(); GrpcAPI.DecryptNotesTRC20 scannedNotes = wallet.scanShieldedTRC20NotesByOvk( @@ -2300,12 +2269,12 @@ public void testscanShieldedTRC20NotesByOvk() throws Exception { } } - @Test(expected = IllegalArgumentException.class) + @Test(expected = ZksnarkException.class) public void isShieldedTRC20ContractNoteSpent() throws Exception { int statNum = 9200; int endNum = 9240; librustzcashInitZksnarkParams(); - SpendingKey sk = SpendingKey.decode(privateKey); + SpendingKey sk = SpendingKey.decode(priKey); FullViewingKey fvk = sk.fullViewingKey(); byte[] ivk = fvk.inViewingKey().value; diff --git a/framework/src/test/java/org/tron/core/StorageMarketTest.java b/framework/src/test/java/org/tron/core/StorageMarketTest.java deleted file mode 100644 index 039f919c9f4..00000000000 --- a/framework/src/test/java/org/tron/core/StorageMarketTest.java +++ /dev/null @@ -1,295 +0,0 @@ -package org.tron.core; - -import static org.tron.core.config.Parameter.ChainConstant.TRANSFER_FEE; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import java.io.File; -import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.db.StorageMarket; -import org.tron.protos.Protocol.AccountType; -import org.tron.protos.contract.StorageContract.BuyStorageContract; - -@Slf4j -public class StorageMarketTest { - - private static final String dbPath = "output_storage_market_test"; - private static final String OWNER_ADDRESS; - private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static final String OWNER_ACCOUNT_INVALID; - private static final long initBalance = 10_000_000_000_000_000L; - private static Manager dbManager; - private static StorageMarket storageMarket; - private static TronApplicationContext context; - - static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - OWNER_ACCOUNT_INVALID = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - storageMarket = new StorageMarket(dbManager.getAccountStore(), - dbManager.getDynamicPropertiesStore()); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - /** - * create temp Capsule test need. - */ - @Before - public void createAccountCapsule() { - AccountCapsule ownerCapsule = - new AccountCapsule( - ByteString.copyFromUtf8("owner"), - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), - AccountType.Normal, - initBalance); - dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); - - dbManager.getDynamicPropertiesStore().saveTotalStorageReserved( - 128L * 1024 * 1024 * 1024); - dbManager.getDynamicPropertiesStore().saveTotalStoragePool(100_000_000_000000L); - dbManager.getDynamicPropertiesStore().saveTotalStorageTax(0); - - dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); - } - - private Any getContract(String ownerAddress, long quant) { - return Any.pack( - BuyStorageContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) - .setQuant(quant) - .build()); - } - - @Test - public void testBuyStorage() { - long currentPool = dbManager.getDynamicPropertiesStore().getTotalStoragePool(); - long currentReserved = dbManager.getDynamicPropertiesStore().getTotalStorageReserved(); - Assert.assertEquals(currentPool, 100_000_000_000000L); - Assert.assertEquals(currentReserved, 128L * 1024 * 1024 * 1024); - - AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - - long quant = 2_000_000_000_000L; // 2 million trx - storageMarket.buyStorage(owner, quant); - - Assert.assertEquals(owner.getBalance(), initBalance - quant - - TRANSFER_FEE); - Assert.assertEquals(2694881440L, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - 2694881440L, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + quant, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - } - - @Test - public void testBuyStorage2() { - long currentPool = dbManager.getDynamicPropertiesStore().getTotalStoragePool(); - long currentReserved = dbManager.getDynamicPropertiesStore().getTotalStorageReserved(); - Assert.assertEquals(currentPool, 100_000_000_000000L); - Assert.assertEquals(currentReserved, 128L * 1024 * 1024 * 1024); - - AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - - long quant = 1_000_000_000_000L; // 1 million trx - - storageMarket.buyStorage(owner, quant); - - Assert.assertEquals(owner.getBalance(), initBalance - quant - - TRANSFER_FEE); - Assert.assertEquals(1360781717L, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - 1360781717L, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + quant, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - storageMarket.buyStorage(owner, quant); - - Assert.assertEquals(owner.getBalance(), initBalance - 2 * quant - - TRANSFER_FEE); - Assert.assertEquals(2694881439L, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - 2694881439L, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + 2 * quant, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - } - - - @Test - public void testBuyStorageBytes() { - long currentPool = dbManager.getDynamicPropertiesStore().getTotalStoragePool(); - long currentReserved = dbManager.getDynamicPropertiesStore().getTotalStorageReserved(); - Assert.assertEquals(currentPool, 100_000_000_000000L); - Assert.assertEquals(currentReserved, 128L * 1024 * 1024 * 1024); - - AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - - long bytes = 2694881440L; // 2 million trx - storageMarket.buyStorageBytes(owner, bytes); - - Assert.assertEquals(owner.getBalance(), initBalance - 2_000_000_000_000L - - TRANSFER_FEE); - Assert.assertEquals(bytes, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - bytes, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + 2_000_000_000_000L, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - } - - @Test - public void testBuyStorageBytes2() { - long currentPool = dbManager.getDynamicPropertiesStore().getTotalStoragePool(); - long currentReserved = dbManager.getDynamicPropertiesStore().getTotalStorageReserved(); - Assert.assertEquals(currentPool, 100_000_000_000000L); - Assert.assertEquals(currentReserved, 128L * 1024 * 1024 * 1024); - - AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - - long bytes1 = 1360781717L; - - storageMarket.buyStorageBytes(owner, bytes1); - - Assert.assertEquals(owner.getBalance(), initBalance - 1_000_000_000_000L - - TRANSFER_FEE); - Assert.assertEquals(bytes1, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - bytes1, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + 1_000_000_000_000L, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - long bytes2 = 1334099723L; - storageMarket.buyStorageBytes(owner, bytes2); - Assert.assertEquals(owner.getBalance(), initBalance - 2 * 1_000_000_000_000L - - TRANSFER_FEE); - Assert.assertEquals(bytes1 + bytes2, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - (bytes1 + bytes2), - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + 2 * 1_000_000_000_000L, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - } - - @Test - public void testSellStorage() { - long currentPool = dbManager.getDynamicPropertiesStore().getTotalStoragePool(); - long currentReserved = dbManager.getDynamicPropertiesStore().getTotalStorageReserved(); - Assert.assertEquals(currentPool, 100_000_000_000000L); - Assert.assertEquals(currentReserved, 128L * 1024 * 1024 * 1024); - - AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - - long quant = 2_000_000_000_000L; // 2 million trx - storageMarket.buyStorage(owner, quant); - - Assert.assertEquals(owner.getBalance(), initBalance - quant - - TRANSFER_FEE); - Assert.assertEquals(2694881440L, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - 2694881440L, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + quant, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - long bytes = 2694881440L; - storageMarket.sellStorage(owner, bytes); - - Assert.assertEquals(owner.getBalance(), initBalance); - Assert.assertEquals(0, owner.getStorageLimit()); - Assert.assertEquals(currentReserved, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(100_000_000_000_000L, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - } - - @Test - public void testSellStorage2() { - long currentPool = dbManager.getDynamicPropertiesStore().getTotalStoragePool(); - long currentReserved = dbManager.getDynamicPropertiesStore().getTotalStorageReserved(); - Assert.assertEquals(currentPool, 100_000_000_000000L); - Assert.assertEquals(currentReserved, 128L * 1024 * 1024 * 1024); - - AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - - long quant = 2_000_000_000_000L; // 2 million trx - storageMarket.buyStorage(owner, quant); - - Assert.assertEquals(owner.getBalance(), initBalance - quant - - TRANSFER_FEE); - Assert.assertEquals(2694881440L, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - 2694881440L, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + quant, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - long bytes1 = 2694881440L - 1360781717L; // 1 million trx - long bytes2 = 1360781717L; // 1 million trx - - storageMarket.sellStorage(owner, bytes1); - - Assert.assertEquals(owner.getBalance(), initBalance - 1_000_000_000_000L); - Assert.assertEquals(1360781717L, owner.getStorageLimit()); - Assert.assertEquals(currentReserved - 1360781717L, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool + 1_000_000_000_000L, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - storageMarket.sellStorage(owner, bytes2); - - Assert.assertEquals(owner.getBalance(), initBalance); - Assert.assertEquals(0, owner.getStorageLimit()); - Assert.assertEquals(currentReserved, - dbManager.getDynamicPropertiesStore().getTotalStorageReserved()); - Assert.assertEquals(currentPool, - dbManager.getDynamicPropertiesStore().getTotalStoragePool()); - - } - - -} diff --git a/framework/src/test/java/org/tron/core/WalletMockTest.java b/framework/src/test/java/org/tron/core/WalletMockTest.java new file mode 100644 index 00000000000..098ba9aee61 --- /dev/null +++ b/framework/src/test/java/org/tron/core/WalletMockTest.java @@ -0,0 +1,1322 @@ +package org.tron.core; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.protobuf.LazyStringArrayList; +import com.google.protobuf.ProtocolStringList; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.tron.api.GrpcAPI; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteUtil; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.client.WalletClient; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.ContractStateCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.db.Manager; +import org.tron.core.db.TransactionStore; +import org.tron.core.exception.AccountResourceInsufficientException; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.HeaderNotFound; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TronException; +import org.tron.core.exception.VMIllegalException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.exception.ZksnarkException; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.message.adv.TransactionMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.store.AbiStore; +import org.tron.core.store.AccountStore; +import org.tron.core.store.CodeStore; +import org.tron.core.store.ContractStateStore; +import org.tron.core.store.ContractStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.TransactionHistoryStore; +import org.tron.core.store.TransactionRetStore; +import org.tron.core.zen.ShieldedTRC20ParametersBuilder; +import org.tron.core.zen.address.DiversifierT; +import org.tron.core.zen.address.ExpandedSpendingKey; +import org.tron.core.zen.address.KeyIo; +import org.tron.core.zen.address.PaymentAddress; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.ShieldContract; +import org.tron.protos.contract.SmartContractOuterClass; + + +public class WalletMockTest { + + @Before + public void init() { + CommonParameter.PARAMETER.setMinEffectiveConnection(0); + } + + @After + public void clearMocks() { + Mockito.clearAllCaches(); + } + + @Test + public void testSetTransactionNullException() throws Exception { + Wallet wallet = new Wallet(); + TransactionCapsule transactionCapsuleMock + = mock(TransactionCapsule.class); + + Method privateMethod = Wallet.class.getDeclaredMethod( + "setTransaction", TransactionCapsule.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, transactionCapsuleMock); + } + + @Test + public void testCreateTransactionCapsuleWithoutValidateWithTimeoutNullException() + throws Exception { + Wallet wallet = new Wallet(); + com.google.protobuf.Message message = + mock(com.google.protobuf.Message.class); + Protocol.Transaction.Contract.ContractType contractType = + mock(Protocol.Transaction.Contract.ContractType.class); + long timeout = 100L; + + try (MockedConstruction mocked = mockConstruction(TransactionCapsule.class, + (mock, context) -> { + when(mock.getInstance()).thenReturn(Protocol.Transaction.newBuilder().build()); + })) { + Method privateMethod = Wallet.class.getDeclaredMethod( + "createTransactionCapsuleWithoutValidateWithTimeout", + com.google.protobuf.Message.class, + Protocol.Transaction.Contract.ContractType.class, + long.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, message, contractType, timeout); + } + } + + @Test + public void testCreateTransactionCapsuleWithoutValidateWithTimeout() + throws Exception { + Wallet wallet = new Wallet(); + com.google.protobuf.Message message = + mock(com.google.protobuf.Message.class); + Protocol.Transaction.Contract.ContractType contractType = + mock(Protocol.Transaction.Contract.ContractType.class); + long timeout = 100L; + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + + try (MockedConstruction mocked = mockConstruction(TransactionCapsule.class, + (mock, context) -> { + when(mock.getInstance()).thenReturn(Protocol.Transaction.newBuilder().build()); + })) { + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + when(chainBaseManagerMock.getHeadBlockId()).thenReturn(blockId); + + Method privateMethod = Wallet.class.getDeclaredMethod( + "createTransactionCapsuleWithoutValidateWithTimeout", + com.google.protobuf.Message.class, + Protocol.Transaction.Contract.ContractType.class, + long.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, message, contractType, timeout); + } + } + + + @Test + public void testBroadcastTransactionBlockUnsolidified() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(true); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.BLOCK_UNSOLIDIFIED, ret.getCode()); + } + + @Test + public void testBroadcastTransactionNoConnection() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + List peerConnections = new ArrayList<>(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("minEffectiveConnection"); + field2.setAccessible(true); + field2.set(wallet, 10); + + when(tronNetDelegateMock.getActivePeer()).thenReturn(peerConnections); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.NO_CONNECTION, ret.getCode()); + } + + @Test + public void testBroadcastTransactionConnectionNotEnough() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + List peerConnections = new ArrayList<>(); + PeerConnection p1 = new PeerConnection(); + PeerConnection p2 = new PeerConnection(); + peerConnections.add(p1); + peerConnections.add(p2); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("minEffectiveConnection"); + field2.setAccessible(true); + field2.set(wallet, 10); + when(tronNetDelegateMock.getActivePeer()).thenReturn(peerConnections); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.NOT_ENOUGH_EFFECTIVE_CONNECTION, + ret.getCode()); + } + + @Test + public void testBroadcastTransactionTooManyPending() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(true); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.SERVER_BUSY, ret.getCode()); + } + + @Test + public void testBroadcastTransactionAlreadyExists() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + trx.setTime(System.currentTimeMillis()); + Sha256Hash txID = trx.getTransactionId(); + + Cache transactionIdCache = CacheBuilder + .newBuilder().maximumSize(10) + .expireAfterWrite(1, TimeUnit.HOURS).recordStats().build(); + transactionIdCache.put(txID, true); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(managerMock.getTransactionIdCache()).thenReturn(transactionIdCache); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, true); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.DUP_TRANSACTION_ERROR, + ret.getCode()); + } + + + @Test + public void testBroadcastTransactionNoContract() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock + = mock(DynamicPropertiesStore.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(dynamicPropertiesStoreMock); + when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field4 = wallet.getClass().getDeclaredField("chainBaseManager"); + field4.setAccessible(true); + field4.set(wallet, chainBaseManagerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, false); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR, + ret.getCode()); + } + + @Test + public void testBroadcastTransactionOtherException() throws Exception { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock + = mock(DynamicPropertiesStore.class); + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(dynamicPropertiesStoreMock); + when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field4 = wallet.getClass().getDeclaredField("chainBaseManager"); + field4.setAccessible(true); + field4.set(wallet, chainBaseManagerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, false); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + + assertEquals(GrpcAPI.Return.response_code.OTHER_ERROR, ret.getCode()); + } + + private Protocol.Transaction getExampleTrans() { + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6666; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + return Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract( + Protocol.Transaction.Contract.newBuilder() + .setParameter(Any.pack(transferContract)) + .setType(Protocol.Transaction.Contract.ContractType.TransferContract))) + .build(); + } + + private void mockEnv(Wallet wallet, TronException tronException) throws Exception { + TronNetDelegate tronNetDelegateMock = mock(TronNetDelegate.class); + Manager managerMock = mock(Manager.class); + ChainBaseManager chainBaseManagerMock + = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock + = mock(DynamicPropertiesStore.class); + + when(tronNetDelegateMock.isBlockUnsolidified()).thenReturn(false); + when(managerMock.isTooManyPending()).thenReturn(false); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(dynamicPropertiesStoreMock); + when(dynamicPropertiesStoreMock.supportVM()).thenReturn(false); + + doThrow(tronException).when(managerMock).pushTransaction(any()); + + Field field = wallet.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(wallet, tronNetDelegateMock); + + Field field2 = wallet.getClass().getDeclaredField("dbManager"); + field2.setAccessible(true); + field2.set(wallet, managerMock); + + Field field4 = wallet.getClass().getDeclaredField("chainBaseManager"); + field4.setAccessible(true); + field4.set(wallet, chainBaseManagerMock); + + Field field3 = wallet.getClass().getDeclaredField("trxCacheEnable"); + field3.setAccessible(true); + field3.set(wallet, false); + } + + @Test + public void testBroadcastTransactionValidateSignatureException() throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new ValidateSignatureException()); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.SIGERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateContractExeException() throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new ContractExeException()); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.CONTRACT_EXE_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateAccountResourceInsufficientException() + throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new AccountResourceInsufficientException("")); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.BANDWITH_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateDupTransactionException() + throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new DupTransactionException("")); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.DUP_TRANSACTION_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateTaposException() throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new TaposException("")); + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.TAPOS_ERROR, ret.getCode()); + } + + } + + @Test + public void testBroadcastTransactionValidateTooBigTransactionException() + throws Exception { + try (MockedConstruction mocked = mockConstruction(TransactionMessage.class, + (mock, context) -> { + + })) { + Wallet wallet = new Wallet(); + Protocol.Transaction transaction = getExampleTrans(); + mockEnv(wallet, new TooBigTransactionException("")); + + GrpcAPI.Return ret = wallet.broadcastTransaction(transaction); + assertEquals(GrpcAPI.Return.response_code.TOO_BIG_TRANSACTION_ERROR, ret.getCode()); + } + + } + + @Test + public void testGetBlockByNum() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockByNum(anyLong()); + + Protocol.Block block = wallet.getBlockByNum(0L); + assertNull(block); + } + + @Test + public void testGetBlockCapsuleByNum() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockByNum(anyLong()); + + BlockCapsule blockCapsule = wallet.getBlockCapsuleByNum(0L); + assertNull(blockCapsule); + } + + @Test + public void testGetTransactionCountByBlockNum() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockByNum(anyLong()); + + long count = wallet.getTransactionCountByBlockNum(0L); + assertEquals(count, 0L); + } + + @Test + public void testGetTransactionById() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = null; + Protocol.Transaction transaction = wallet.getTransactionById(transactionId); + assertNull(transaction); + } + + @Test + public void testGetTransactionById2() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new BadItemException()).when(transactionStoreMock).get(any()); + + Protocol.Transaction transaction = wallet.getTransactionById(transactionId); + assertNull(transaction); + } + + @Test + public void testGetTransactionById3() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + TransactionCapsule transactionCapsuleMock = mock(TransactionCapsule.class); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(transactionStoreMock.get(any())).thenReturn(transactionCapsuleMock); + when(transactionCapsuleMock.getInstance()).thenReturn(transaction); + + Protocol.Transaction transactionRet = wallet.getTransactionById(transactionId); + assertEquals(transaction, transactionRet); + } + + @Test + public void testGetTransactionCapsuleById() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = null; + TransactionCapsule transactionCapsule = wallet.getTransactionCapsuleById(transactionId); + assertNull(transactionCapsule); + } + + @Test + public void testGetTransactionCapsuleById1() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new BadItemException()).when(transactionStoreMock).get(any()); + + TransactionCapsule transactionCapsule = wallet.getTransactionCapsuleById(transactionId); + assertNull(transactionCapsule); + } + + @Test + public void testGetTransactionInfoById() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = null; + Protocol.TransactionInfo transactionInfo = wallet.getTransactionInfoById(transactionId); + assertNull(transactionInfo); + } + + @Test + public void testGetTransactionInfoById1() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionRetStore transactionRetStoreMock = mock(TransactionRetStore.class); + + when(chainBaseManagerMock.getTransactionRetStore()).thenReturn(transactionRetStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + doThrow(new BadItemException()).when(transactionRetStoreMock).getTransactionInfo(any()); + + Protocol.TransactionInfo transactionInfo = wallet.getTransactionInfoById(transactionId); + assertNull(transactionInfo); + } + + @Test + public void testGetTransactionInfoById2() throws Exception { + Wallet wallet = new Wallet(); + ByteString transactionId = ByteString.empty(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + TransactionRetStore transactionRetStoreMock = mock(TransactionRetStore.class); + TransactionHistoryStore transactionHistoryStoreMock = + mock(TransactionHistoryStore.class); + + when(chainBaseManagerMock.getTransactionRetStore()) + .thenReturn(transactionRetStoreMock); + when(chainBaseManagerMock.getTransactionHistoryStore()) + .thenReturn(transactionHistoryStoreMock); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(transactionRetStoreMock.getTransactionInfo(any())).thenReturn(null); + doThrow(new BadItemException()).when(transactionHistoryStoreMock).get(any()); + + Protocol.TransactionInfo transactionInfo = wallet.getTransactionInfoById(transactionId); + assertNull(transactionInfo); + } + + @Test + public void testGetProposalById() throws Exception { + Wallet wallet = new Wallet(); + ByteString proposalId = null; + Protocol.Proposal proposal = wallet.getProposalById(proposalId); + assertNull(proposal); + } + + @Test + public void testGetMemoFeePrices() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found MEMO_FEE_HISTORY")) + .when(dynamicPropertiesStoreMock).getMemoFeeHistory(); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + GrpcAPI.PricesResponseMessage responseMessage = wallet.getMemoFeePrices(); + assertNull(responseMessage); + } + + @Test + public void testGetEnergyFeeByTime() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + long now = System.currentTimeMillis(); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found ENERGY_PRICE_HISTORY")) + .when(dynamicPropertiesStoreMock).getEnergyPriceHistory(); + when(dynamicPropertiesStoreMock.getEnergyFee()).thenReturn(10L); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + long energyFee = wallet.getEnergyFee(now); + assertEquals(energyFee, 10L); + } + + @Test + public void testGetEnergyPrices() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found ENERGY_PRICE_HISTORY")) + .when(dynamicPropertiesStoreMock).getEnergyPriceHistory(); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + GrpcAPI.PricesResponseMessage pricesResponseMessage = wallet.getEnergyPrices(); + assertNull(pricesResponseMessage); + } + + @Test + public void testGetBandwidthPrices() throws Exception { + Wallet wallet = new Wallet(); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + DynamicPropertiesStore dynamicPropertiesStoreMock = + mock(DynamicPropertiesStore.class); + + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStoreMock); + doThrow(new IllegalArgumentException("not found BANDWIDTH_PRICE_HISTORY")) + .when(dynamicPropertiesStoreMock).getBandwidthPriceHistory(); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + + GrpcAPI.PricesResponseMessage pricesResponseMessage = wallet.getBandwidthPrices(); + assertNull(pricesResponseMessage); + } + + @Test + public void testCheckBlockIdentifier() { + Wallet wallet = new Wallet(); + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .build(); + blockIdentifier = blockIdentifier.getDefaultInstanceForType(); + + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier1 = + blockIdentifier; + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkBlockIdentifier(blockIdentifier1); + }); + + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier2 = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setNumber(-1L) + .build(); + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkBlockIdentifier(blockIdentifier2); + }); + + BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier3 = + BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() + .setHash(ByteString.copyFrom("".getBytes(StandardCharsets.UTF_8))) + .build(); + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkBlockIdentifier(blockIdentifier3); + }); + } + + @Test + public void testCheckAccountIdentifier() { + Wallet wallet = new Wallet(); + BalanceContract.AccountIdentifier accountIdentifier = + BalanceContract.AccountIdentifier.newBuilder().build(); + accountIdentifier = accountIdentifier.getDefaultInstanceForType(); + + BalanceContract.AccountIdentifier accountIdentifier2 = accountIdentifier; + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkAccountIdentifier(accountIdentifier2); + }); + + BalanceContract.AccountIdentifier accountIdentifier1 + = BalanceContract.AccountIdentifier.newBuilder().build(); + + assertThrows(IllegalArgumentException.class, () -> { + wallet.checkAccountIdentifier(accountIdentifier1); + }); + } + + @Test + public void testGetTriggerInputForShieldedTRC20Contract() { + Wallet wallet = new Wallet(); + GrpcAPI.ShieldedTRC20TriggerContractParameters.Builder triggerParam = + GrpcAPI.ShieldedTRC20TriggerContractParameters + .newBuilder(); + GrpcAPI.ShieldedTRC20Parameters shieldedTRC20Parameters = + GrpcAPI.ShieldedTRC20Parameters.newBuilder().build(); + GrpcAPI.BytesMessage bytesMessage = + GrpcAPI.BytesMessage.newBuilder().build(); + + triggerParam.setShieldedTRC20Parameters(shieldedTRC20Parameters); + triggerParam.addSpendAuthoritySignature(bytesMessage); + + CommonParameter commonParameterMock = mock(Args.class); + try (MockedStatic mockedStatic = mockStatic(CommonParameter.class)) { + when(CommonParameter.getInstance()).thenReturn(commonParameterMock); + when(commonParameterMock.isFullNodeAllowShieldedTransactionArgs()).thenReturn(true); + + assertThrows(ZksnarkException.class, () -> { + wallet.getTriggerInputForShieldedTRC20Contract(triggerParam.build()); + }); + } + } + + @Test + public void testGetTriggerInputForShieldedTRC20Contract1() + throws ZksnarkException, ContractValidateException { + Wallet wallet = new Wallet(); + ShieldContract.SpendDescription spendDescription = + ShieldContract.SpendDescription.newBuilder().build(); + GrpcAPI.ShieldedTRC20TriggerContractParameters.Builder triggerParam = + GrpcAPI.ShieldedTRC20TriggerContractParameters + .newBuilder(); + GrpcAPI.ShieldedTRC20Parameters shieldedTRC20Parameters = + GrpcAPI.ShieldedTRC20Parameters.newBuilder() + .addSpendDescription(spendDescription) + .setParameterType("transfer") + .build(); + GrpcAPI.BytesMessage bytesMessage = + GrpcAPI.BytesMessage.newBuilder().build(); + + triggerParam.setShieldedTRC20Parameters(shieldedTRC20Parameters); + triggerParam.addSpendAuthoritySignature(bytesMessage); + + CommonParameter commonParameterMock = mock(Args.class); + try (MockedStatic mockedStatic = mockStatic(CommonParameter.class)) { + when(CommonParameter.getInstance()).thenReturn(commonParameterMock); + when(commonParameterMock.isFullNodeAllowShieldedTransactionArgs()).thenReturn(true); + + GrpcAPI.BytesMessage reponse = + wallet.getTriggerInputForShieldedTRC20Contract(triggerParam.build()); + assertNotNull(reponse); + } + + } + + @Test + public void testGetShieldedContractScalingFactorException() throws Exception { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + when(walletMock.createTransactionCapsule(any(), any())) + .thenReturn(new TransactionCapsule(transaction)); + + try { + when(walletMock.getShieldedContractScalingFactor(contractAddress)).thenCallRealMethod(); + } catch (Exception e) { + assertNotNull(e); + } + } + + @Test + public void testGetShieldedContractScalingFactorRuntimeException() + throws VMIllegalException, HeaderNotFound, ContractValidateException, ContractExeException { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + when(walletMock.triggerConstantContract(any(),any(),any(),any())).thenReturn(transaction); + when(walletMock.getShieldedContractScalingFactor(any())).thenCallRealMethod(); + + assertThrows(ContractExeException.class, () -> { + walletMock.getShieldedContractScalingFactor(contractAddress); + }); + } + + @Test + public void testGetShieldedContractScalingFactorSuccess() + throws Exception { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + when(walletMock.triggerConstantContract(any(),any(),any(),any())) + .thenReturn(transaction); + when(walletMock.createTransactionCapsule(any(), any())) + .thenReturn(new TransactionCapsule(transaction)); + when(walletMock.getShieldedContractScalingFactor(any())).thenCallRealMethod(); + try { + byte[] listBytes = walletMock.getShieldedContractScalingFactor(contractAddress); + assertNotNull(listBytes); + } catch (Exception e) { + assertNull(e); + } + } + + @Test + public void testGetShieldedContractScalingFactorContractExeException() + throws Exception { + Wallet walletMock = mock(Wallet.class); + byte[] contractAddress = "".getBytes(StandardCharsets.UTF_8); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + doThrow(new ContractExeException("")) + .when(walletMock).triggerConstantContract(any(),any(),any(),any()); + when(walletMock.createTransactionCapsule(any(), any())) + .thenReturn(new TransactionCapsule(transaction)); + when(walletMock.getShieldedContractScalingFactor(any())).thenCallRealMethod(); + + assertThrows(ContractExeException.class, () -> { + walletMock.getShieldedContractScalingFactor(contractAddress); + }); + } + + @Test + public void testCheckBigIntegerRange() { + Wallet wallet = new Wallet(); + + assertThrows( + Exception.class, + () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkBigIntegerRange", BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, new BigInteger("-1")); + } + ); + } + + @Test + public void testCheckPublicAmount() throws ContractExeException { + Wallet walletMock = mock(Wallet.class); + + byte[] address = "".getBytes(StandardCharsets.UTF_8); + BigInteger fromAmount = new BigInteger("10"); + BigInteger toAmount = new BigInteger("10"); + doThrow(new ContractExeException("")).when(walletMock).getShieldedContractScalingFactor(any()); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkPublicAmount", + byte[].class, BigInteger.class, BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(walletMock, address, fromAmount, toAmount); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractExeException); + } + + @Test + public void testCheckPublicAmount1() throws ContractExeException { + Wallet walletMock = mock(Wallet.class); + + byte[] address = "".getBytes(StandardCharsets.UTF_8); + BigInteger fromAmount = new BigInteger("300"); + BigInteger toAmount = new BigInteger("255"); + + byte[] scalingFactorBytes = ByteUtil.bigIntegerToBytes(new BigInteger("-1")); + + when(walletMock.getShieldedContractScalingFactor(any())).thenReturn(scalingFactorBytes); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkPublicAmount", + byte[].class, BigInteger.class, BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(walletMock, address, fromAmount, toAmount); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractValidateException); + } + + @Test + public void testCheckPublicAmount2() throws ContractExeException { + Wallet walletMock = mock(Wallet.class); + + byte[] address = "".getBytes(StandardCharsets.UTF_8); + BigInteger fromAmount = new BigInteger("300"); + BigInteger toAmount = new BigInteger("255"); + + byte[] scalingFactorBytes = ByteUtil.bigIntegerToBytes(new BigInteger("-1")); + try (MockedStatic mockedStatic = mockStatic(ByteUtil.class)) { + when(ByteUtil.bytesToBigInteger(any())).thenReturn(new BigInteger("-1")); + when(walletMock.getShieldedContractScalingFactor(any())).thenReturn(scalingFactorBytes); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "checkPublicAmount", + byte[].class, BigInteger.class, BigInteger.class); + privateMethod.setAccessible(true); + privateMethod.invoke(walletMock, address, fromAmount, toAmount); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractValidateException); + } + + } + + @Test + public void testGetShieldedTRC20Nullifier() { + Wallet wallet = new Wallet(); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + long pos = 100L; + byte[] ak = "ak".getBytes(StandardCharsets.UTF_8); + byte[] nk = "nk".getBytes(StandardCharsets.UTF_8); + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(null); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20Nullifier", + GrpcAPI.Note.class, long.class, byte[].class, + byte[].class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + note, pos, ak, nk); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ZksnarkException); + } + } + + @Test + public void testGetShieldedTRC20LogType() { + Wallet wallet = new Wallet(); + Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder().build(); + byte[] contractAddress = "contractAddress".getBytes(StandardCharsets.UTF_8); + LazyStringArrayList topicsList = new LazyStringArrayList(); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20LogType", + Protocol.TransactionInfo.Log.class, + byte[].class, + ProtocolStringList.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + log, + contractAddress, + topicsList); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ZksnarkException); + } + + @Test + public void testGetShieldedTRC20LogType1() { + Wallet wallet = new Wallet(); + final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; + byte[] contractAddress = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); + + byte[] addressWithoutPrefix = new byte[20]; + System.arraycopy(contractAddress, 1, addressWithoutPrefix, 0, 20); + Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom(addressWithoutPrefix)) + .build(); + + LazyStringArrayList topicsList = new LazyStringArrayList(); + try { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20LogType", + Protocol.TransactionInfo.Log.class, + byte[].class, + ProtocolStringList.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + log, + contractAddress, + topicsList); + } catch (Exception e) { + assertTrue(false); + } + } + + + @Test + public void testGetShieldedTRC20LogType2() { + Wallet wallet = new Wallet(); + final String SHIELDED_CONTRACT_ADDRESS_STR = "TGAmX5AqVUoXCf8MoHxbuhQPmhGfWTnEgA"; + byte[] contractAddress = WalletClient.decodeFromBase58Check(SHIELDED_CONTRACT_ADDRESS_STR); + + byte[] addressWithoutPrefix = new byte[20]; + System.arraycopy(contractAddress, 1, addressWithoutPrefix, 0, 20); + Protocol.TransactionInfo.Log log = Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom(addressWithoutPrefix)) + .addTopics(ByteString.copyFrom("topic".getBytes())) + .build(); + + LazyStringArrayList topicsList = new LazyStringArrayList(); + topicsList.add("topic"); + try { + Method privateMethod = Wallet.class.getDeclaredMethod( + "getShieldedTRC20LogType", + Protocol.TransactionInfo.Log.class, + byte[].class, + ProtocolStringList.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + log, + contractAddress, + topicsList); + } catch (Exception e) { + assertTrue(false); + } + } + + @Test + public void testBuildShieldedTRC20InputWithAK() throws ZksnarkException { + Wallet wallet = new Wallet(); + ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder("transfer"); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + GrpcAPI.SpendNoteTRC20 spendNote = GrpcAPI.SpendNoteTRC20.newBuilder() + .setNote(note) + .setAlpha(ByteString.copyFrom("alpha".getBytes())) + .setRoot(ByteString.copyFrom("root".getBytes())) + .setPath(ByteString.copyFrom("path".getBytes())) + .setPos(0L) + .build(); + byte[] ak = "ak".getBytes(StandardCharsets.UTF_8); + byte[] nk = "nk".getBytes(StandardCharsets.UTF_8); + + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(null); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Wallet.class.getDeclaredMethod( + "buildShieldedTRC20InputWithAK", + ShieldedTRC20ParametersBuilder.class, + GrpcAPI.SpendNoteTRC20.class, + byte[].class, byte[].class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + builder, + spendNote, + ak, nk); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ZksnarkException); + } + + } + + @Test + public void testBuildShieldedTRC20InputWithAK1() throws Exception { + Wallet wallet = new Wallet(); + ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder("transfer"); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + GrpcAPI.SpendNoteTRC20 spendNote = GrpcAPI.SpendNoteTRC20.newBuilder() + .setNote(note) + .setAlpha(ByteString.copyFrom("alpha".getBytes())) + .setRoot(ByteString.copyFrom("root".getBytes())) + .setPath(ByteString.copyFrom("path".getBytes())) + .setPos(0L) + .build(); + byte[] ak = "ak".getBytes(StandardCharsets.UTF_8); + byte[] nk = "nk".getBytes(StandardCharsets.UTF_8); + PaymentAddress paymentAddress = mock(PaymentAddress.class); + DiversifierT diversifierT = mock(DiversifierT.class); + + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(paymentAddress); + when(paymentAddress.getD()).thenReturn(diversifierT); + when(paymentAddress.getPkD()).thenReturn("pkd".getBytes()); + + Method privateMethod = Wallet.class.getDeclaredMethod( + "buildShieldedTRC20InputWithAK", + ShieldedTRC20ParametersBuilder.class, + GrpcAPI.SpendNoteTRC20.class, + byte[].class, byte[].class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + builder, + spendNote, + ak, nk); + } + + } + + @Test + public void testBuildShieldedTRC20Input() throws Exception { + Wallet wallet = new Wallet(); + ShieldedTRC20ParametersBuilder builder = new ShieldedTRC20ParametersBuilder("transfer"); + GrpcAPI.Note note = GrpcAPI.Note.newBuilder() + .setValue(100) + .setPaymentAddress("address") + .setRcm(ByteString.copyFrom("rcm".getBytes(StandardCharsets.UTF_8))) + .setMemo(ByteString.copyFrom("memo".getBytes(StandardCharsets.UTF_8))) + .build(); + GrpcAPI.SpendNoteTRC20 spendNote = GrpcAPI.SpendNoteTRC20.newBuilder() + .setNote(note) + .setAlpha(ByteString.copyFrom("alpha".getBytes())) + .setRoot(ByteString.copyFrom("root".getBytes())) + .setPath(ByteString.copyFrom("path".getBytes())) + .setPos(0L) + .build(); + ExpandedSpendingKey expandedSpendingKey = mock(ExpandedSpendingKey.class); + PaymentAddress paymentAddress = mock(PaymentAddress.class); + DiversifierT diversifierT = mock(DiversifierT.class); + + try (MockedStatic keyIoMockedStatic = mockStatic(KeyIo.class)) { + when(KeyIo.decodePaymentAddress(any())).thenReturn(paymentAddress); + when(paymentAddress.getD()).thenReturn(diversifierT); + when(paymentAddress.getPkD()).thenReturn("pkd".getBytes()); + Method privateMethod = Wallet.class.getDeclaredMethod( + "buildShieldedTRC20Input", + ShieldedTRC20ParametersBuilder.class, + GrpcAPI.SpendNoteTRC20.class, + ExpandedSpendingKey.class); + privateMethod.setAccessible(true); + privateMethod.invoke(wallet, + builder, + spendNote, + expandedSpendingKey); + } + } + + @Test + public void testGetContractInfo() throws Exception { + Wallet wallet = new Wallet(); + GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() + .setValue(ByteString.copyFrom("test".getBytes())) + .build(); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + AccountStore accountStore = mock(AccountStore.class); + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(chainBaseManagerMock.getAccountStore()).thenReturn(accountStore); + when(accountStore.get(any())).thenReturn(null); + + SmartContractOuterClass.SmartContractDataWrapper smartContractDataWrapper = + wallet.getContractInfo(bytesMessage); + assertNull(smartContractDataWrapper); + } + + @Test + public void testGetContractInfo1() throws Exception { + Wallet wallet = new Wallet(); + GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder() + .setValue(ByteString.copyFrom("test".getBytes())) + .build(); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + AccountStore accountStore = mock(AccountStore.class); + ContractStore contractStore = mock(ContractStore.class); + AbiStore abiStore = mock(AbiStore.class); + CodeStore codeStore = mock(CodeStore.class); + ContractStateStore contractStateStore = mock(ContractStateStore.class); + DynamicPropertiesStore dynamicPropertiesStore = mock(DynamicPropertiesStore.class); + + AccountCapsule accountCapsule = mock(AccountCapsule.class); + ContractCapsule contractCapsule = mock(ContractCapsule.class); + ContractStateCapsule contractStateCapsule = new ContractStateCapsule(10L); + + Field field = wallet.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(wallet, chainBaseManagerMock); + when(chainBaseManagerMock.getAccountStore()).thenReturn(accountStore); + when(chainBaseManagerMock.getContractStore()).thenReturn(contractStore); + when(chainBaseManagerMock.getAbiStore()).thenReturn(abiStore); + when(chainBaseManagerMock.getCodeStore()).thenReturn(codeStore); + when(chainBaseManagerMock.getContractStateStore()).thenReturn(contractStateStore); + when(chainBaseManagerMock.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStore); + + when(accountStore.get(any())).thenReturn(accountCapsule); + when(contractStore.get(any())).thenReturn(contractCapsule); + when(contractCapsule.generateWrapper()) + .thenReturn(SmartContractOuterClass.SmartContractDataWrapper.newBuilder().build()); + when(abiStore.get(any())).thenReturn(null); + when(codeStore.get(any())).thenReturn(null); + when(contractStateStore.get(any())).thenReturn(contractStateCapsule); + when(dynamicPropertiesStore.getCurrentCycleNumber()).thenReturn(100L); + + SmartContractOuterClass.SmartContractDataWrapper smartContractDataWrapper = + wallet.getContractInfo(bytesMessage); + assertNotNull(smartContractDataWrapper); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/WalletTest.java b/framework/src/test/java/org/tron/core/WalletTest.java index 4c0ff5ed6c4..831490fdca1 100644 --- a/framework/src/test/java/org/tron/core/WalletTest.java +++ b/framework/src/test/java/org/tron/core/WalletTest.java @@ -20,46 +20,63 @@ import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static stest.tron.wallet.common.client.utils.PublicMethed.decode58Check; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; +import javax.annotation.Resource; +import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.joda.time.DateTime; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Ignore; import org.junit.Test; +import org.tron.api.GrpcAPI; +import org.tron.api.GrpcAPI.AccountNetMessage; import org.tron.api.GrpcAPI.AssetIssueList; import org.tron.api.GrpcAPI.BlockList; import org.tron.api.GrpcAPI.ExchangeList; +import org.tron.api.GrpcAPI.NumberMessage; +import org.tron.api.GrpcAPI.PricesResponseMessage; import org.tron.api.GrpcAPI.ProposalList; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; +import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Utils; +import org.tron.core.actuator.DelegateResourceActuator; +import org.tron.core.actuator.FreezeBalanceActuator; +import org.tron.core.actuator.UnfreezeBalanceV2Actuator; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.CodeCapsule; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionInfoCapsule; -import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; +import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.exception.NonUniqueObjectException; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.utils.ProposalUtil.ProposalType; import org.tron.core.utils.TransactionUtil; +import org.tron.core.vm.config.ConfigLoader; +import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.program.Program; import org.tron.protos.Protocol; -import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.BlockHeader; import org.tron.protos.Protocol.BlockHeader.raw; @@ -70,25 +87,25 @@ import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.TransactionInfo; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; +import org.tron.protos.contract.BalanceContract; import org.tron.protos.contract.BalanceContract.TransferContract; +import org.tron.protos.contract.Common; +import org.tron.protos.contract.SmartContractOuterClass; @Slf4j -public class WalletTest { +public class WalletTest extends BaseTest { public static final String ACCOUNT_ADDRESS_ONE = "121212a9cf"; public static final String ACCOUNT_ADDRESS_TWO = "232323a9cf"; public static final String ACCOUNT_ADDRESS_THREE = "343434a9cf"; public static final String ACCOUNT_ADDRESS_FOUR = "454545a9cf"; public static final String ACCOUNT_ADDRESS_FIVE = "565656a9cf"; - public static final String ACCOUNT_ADDRESS_SIX = "12344349cf"; public static final long BLOCK_NUM_ONE = 1; public static final long BLOCK_NUM_TWO = 2; 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 CYCLE_NUM_ONE = 1; - public static final long CYCLE_NUM_TWO = 2; 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(); @@ -99,16 +116,13 @@ public class WalletTest { public static final long BLOCK_WITNESS_THREE = 14; public static final long BLOCK_WITNESS_FOUR = 15; public static final long BLOCK_WITNESS_FIVE = 16; - //private static DeferredTransaction deferredTransaction; 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(); - private static TronApplicationContext context; - private static Wallet wallet; - private static ChainBaseManager chainBaseManager; - private static String dbPath = "output_wallet_test"; + @Resource + private Wallet wallet; private static Block block1; private static Block block2; private static Block block3; @@ -119,32 +133,44 @@ public class WalletTest { private static Transaction transaction3; private static Transaction transaction4; private static Transaction transaction5; - private static Transaction transaction6; private static AssetIssueCapsule Asset1; + private static AssetIssueCapsule Asset2; + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final long initBalance = 43_200_000_000L; + private static boolean init; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; } - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); - chainBaseManager = context.getBean(ChainBaseManager.class); + @Before + public void before() { + initAccountCapsule(); + if (init) { + return; + } initTransaction(); initBlock(); - chainBaseManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(5); + chainBaseManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(BLOCK_NUM_FIVE); + chainBaseManager.getDynamicPropertiesStore().saveLatestSolidifiedBlockNum(BLOCK_NUM_TWO); + chainBaseManager.getDelegatedResourceStore().reset(); + init = true; } /** * initTransaction. */ - private static void initTransaction() { + private void initTransaction() { transaction1 = getBuildTransaction( getBuildTransferContract(ACCOUNT_ADDRESS_ONE, ACCOUNT_ADDRESS_TWO), TRANSACTION_TIMESTAMP_ONE, BLOCK_NUM_ONE); addTransactionToStore(transaction1); + // solidified transaction2 = getBuildTransaction( getBuildTransferContract(ACCOUNT_ADDRESS_TWO, ACCOUNT_ADDRESS_THREE), TRANSACTION_TIMESTAMP_TWO, BLOCK_NUM_TWO); @@ -164,20 +190,48 @@ private static void initTransaction() { getBuildTransferContract(ACCOUNT_ADDRESS_FIVE, ACCOUNT_ADDRESS_ONE), TRANSACTION_TIMESTAMP_FIVE, BLOCK_NUM_FIVE); addTransactionToStore(transaction5); + } - transaction6 = getBuildTransaction( - getBuildTransferContract(ACCOUNT_ADDRESS_ONE, ACCOUNT_ADDRESS_SIX), - TRANSACTION_TIMESTAMP_FIVE, BLOCK_NUM_FIVE); - addTransactionToStore(transaction5); + private void initAccountCapsule() { + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + AccountCapsule receiverCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + + byte[] dbKey = DelegatedResourceCapsule.createDbKey( + ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS)); + byte[] dbKeyV2 = DelegatedResourceCapsule.createDbKeyV2( + ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), + false); + chainBaseManager.getDelegatedResourceStore().delete(dbKey); + chainBaseManager.getDelegatedResourceStore().delete(dbKeyV2); + chainBaseManager.getDelegatedResourceAccountIndexStore() + .delete(ByteArray.fromHexString(OWNER_ADDRESS)); + + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0L); } - private static void addTransactionToStore(Transaction transaction) { + private void addTransactionToStore(Transaction transaction) { TransactionCapsule transactionCapsule = new TransactionCapsule(transaction); chainBaseManager.getTransactionStore() .put(transactionCapsule.getTransactionId().getBytes(), transactionCapsule); } - private static void addTransactionInfoToStore(Transaction transaction) { + private void addTransactionInfoToStore(Transaction transaction) { TransactionInfoCapsule transactionInfo = new TransactionInfoCapsule(); byte[] trxId = transaction.getRawData().toByteArray(); transactionInfo.setId(trxId); @@ -188,11 +242,11 @@ private static void addTransactionInfoToStore(Transaction transaction) { private static Transaction getBuildTransaction( TransferContract transferContract, long transactionTimestamp, long refBlockNum) { return Transaction.newBuilder().setRawData( - Transaction.raw.newBuilder().setTimestamp(transactionTimestamp) - .setRefBlockNum(refBlockNum) - .addContract( - Contract.newBuilder().setType(ContractType.TransferContract) - .setParameter(Any.pack(transferContract)).build()).build()) + Transaction.raw.newBuilder().setTimestamp(transactionTimestamp) + .setRefBlockNum(refBlockNum) + .addContract( + Contract.newBuilder().setType(ContractType.TransferContract) + .setParameter(Any.pack(transferContract)).build()).build()) .build(); } @@ -205,7 +259,7 @@ private static TransferContract getBuildTransferContract(String ownerAddress, St /** * initBlock. */ - private static void initBlock() { + private void initBlock() { block1 = getBuildBlock(BLOCK_TIMESTAMP_ONE, BLOCK_NUM_ONE, BLOCK_WITNESS_ONE, ACCOUNT_ADDRESS_ONE, transaction1, transaction2); @@ -233,29 +287,38 @@ private static void initBlock() { addTransactionInfoToStore(transaction5); } - private static void addBlockToStore(Block block) { + private void addBlockToStore(Block block) { BlockCapsule blockCapsule = new BlockCapsule(block); + chainBaseManager.getBlockIndexStore().put(blockCapsule.getBlockId()); chainBaseManager.getBlockStore().put(blockCapsule.getBlockId().getBytes(), blockCapsule); } private static Block getBuildBlock(long timestamp, long num, long witnessId, String witnessAddress, Transaction transaction, Transaction transactionNext) { return Block.newBuilder().setBlockHeader(BlockHeader.newBuilder().setRawData( - raw.newBuilder().setTimestamp(timestamp).setNumber(num).setWitnessId(witnessId) - .setWitnessAddress(ByteString.copyFrom(ByteArray.fromHexString(witnessAddress))) - .build()).build()).addTransactions(transaction).addTransactions(transactionNext) + raw.newBuilder().setTimestamp(timestamp).setNumber(num).setWitnessId(witnessId) + .setWitnessAddress(ByteString.copyFrom(ByteArray.fromHexString(witnessAddress))) + .build()).build()).addTransactions(transaction).addTransactions(transactionNext) .build(); } - private static void buildAssetIssue() { + private void buildAssetIssue() { AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); + builder.setOwnerAddress(ByteString.copyFromUtf8("Address1")); builder.setName(ByteString.copyFromUtf8("Asset1")); Asset1 = new AssetIssueCapsule(builder.build()); chainBaseManager.getAssetIssueStore().put(Asset1.createDbKey(), Asset1); + + AssetIssueContract.Builder builder2 = AssetIssueContract.newBuilder(); + builder2.setOwnerAddress(ByteString.copyFromUtf8("Address2")); + builder2.setName(ByteString.copyFromUtf8("Asset2")); + builder2.setId("id2"); + Asset2 = new AssetIssueCapsule(builder2.build()); + chainBaseManager.getAssetIssueV2Store().put(Asset2.getId().getBytes(), Asset2); } - private static void buildProposal() { + private void buildProposal() { Proposal.Builder builder = Proposal.newBuilder(); builder.setProposalId(1L).setProposerAddress(ByteString.copyFromUtf8("Address1")); ProposalCapsule proposalCapsule = new ProposalCapsule(builder.build()); @@ -267,7 +330,7 @@ private static void buildProposal() { chainBaseManager.getDynamicPropertiesStore().saveLatestProposalNum(2L); } - private static void buildExchange() { + private void buildExchange() { Exchange.Builder builder = Exchange.newBuilder(); builder.setExchangeId(1L).setCreatorAddress(ByteString.copyFromUtf8("Address1")); ExchangeCapsule ExchangeCapsule = new ExchangeCapsule(builder.build()); @@ -281,13 +344,6 @@ private static void buildExchange() { } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - @Test public void testWallet() { Wallet wallet1 = new Wallet(); @@ -296,7 +352,7 @@ public void testWallet() { .getAddress())); logger.info("wallet2 address = {}", ByteArray.toHexString(wallet2 .getAddress())); - assertFalse(wallet1.getAddress().equals(wallet2.getAddress())); + assertNotEquals(wallet1.getAddress(), wallet2.getAddress()); } @Test @@ -313,7 +369,6 @@ public void testGetAddress() { @Test public void testGetEcKey() { ECKey ecKey = new ECKey(Utils.getRandom()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); Wallet wallet1 = new Wallet(ecKey); logger.info("ecKey address = {}", ByteArray.toHexString(ecKey .getAddress())); @@ -326,6 +381,7 @@ public void testGetEcKey() { public void ss() { for (int i = 0; i < 4; i++) { ECKey ecKey = new ECKey(Utils.getRandom()); + assertNotNull(ecKey); System.out.println(i + 1); System.out.println("privateKey:" + ByteArray.toHexString(ecKey.getPrivKeyBytes())); System.out.println("publicKey:" + ByteArray.toHexString(ecKey.getPubKey())); @@ -444,22 +500,67 @@ public void getBlockByLatestNum() { public void getPaginatedAssetIssueList() { buildAssetIssue(); AssetIssueList assetList1 = wallet.getAssetIssueList(0, 100); - Assert.assertTrue("get Asset1", - assetList1.getAssetIssue(0).getName().equals(Asset1.getName())); + assertEquals("get Asset1", assetList1.getAssetIssue(0).getName(), Asset1.getName()); try { - assetList1.getAssetIssue(1); + assertNotNull(assetList1.getAssetIssue(1)); } catch (Exception e) { Assert.assertTrue("AssetIssueList1 size should be 1", true); } AssetIssueList assetList2 = wallet.getAssetIssueList(0, 0); try { - assetList2.getAssetIssue(0); + assertNotNull(assetList2.getAssetIssue(0)); } catch (Exception e) { Assert.assertTrue("AssetIssueList2 size should be 0", true); } } + @Test + public void testGetAssetIssueByAccount() { + buildAssetIssue(); + // + AssetIssueList assetIssueList = wallet.getAssetIssueByAccount( + ByteString.copyFromUtf8("Address1")); + Assert.assertEquals(1, assetIssueList.getAssetIssueCount()); + } + + @Test + public void testGetAssetIssueList() { + buildAssetIssue(); + // + AssetIssueList assetIssueList = wallet.getAssetIssueList(); + Assert.assertEquals(1, assetIssueList.getAssetIssueCount()); + } + + @Test + public void testGetAssetIssueListByName() { + buildAssetIssue(); + // + AssetIssueList assetIssueList = wallet.getAssetIssueListByName( + ByteString.copyFromUtf8("Asset1")); + Assert.assertEquals(1, assetIssueList.getAssetIssueCount()); + } + + @Test + public void testGetAssetIssueById() { + buildAssetIssue(); + // + AssetIssueContract assetIssueContract = wallet.getAssetIssueById("id2"); + Assert.assertNotNull(assetIssueContract); + } + + @Test + public void testGetAccountNet() { + ByteString addressByte = ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + accountCapsule.setBalance(1000_000_000L); + dbManager.getChainBaseManager().getAccountStore() + .put(accountCapsule.createDbKey(), accountCapsule); + AccountNetMessage accountNetMessage = wallet.getAccountNet(addressByte); + Assert.assertNotNull(accountNetMessage); + } + @Test public void getPaginatedProposalList() { buildProposal(); @@ -493,6 +594,16 @@ public void getPaginatedProposalList() { } + @Test + public void testGetProposalById() { + buildProposal(); + // + Proposal proposal = wallet.getProposalById(ByteString.copyFrom(ByteArray.fromLong(1L))); + Assert.assertNotNull(proposal); + proposal = wallet.getProposalById(ByteString.copyFrom(ByteArray.fromLong(3L))); + Assert.assertNull(proposal); + } + @Test public void getPaginatedExchangeList() { buildExchange(); @@ -503,6 +614,56 @@ public void getPaginatedExchangeList() { exchangeList.getExchangesList().get(1).getCreatorAddress().toStringUtf8()); } + @Test + public void testGetExchangeById() { + buildExchange(); + // + Exchange exchange = wallet.getExchangeById(ByteString.copyFrom(ByteArray.fromLong(1L))); + Assert.assertNotNull(exchange); + exchange = wallet.getExchangeById(ByteString.copyFrom(ByteArray.fromLong(3L))); + Assert.assertNull(exchange); + } + + @Test + public void testGetExchangeList() { + buildExchange(); + // + ExchangeList exchangeList = wallet.getExchangeList(); + Assert.assertEquals(2, exchangeList.getExchangesCount()); + } + + @Test + public void getBlock() { + GrpcAPI.BlockReq req = GrpcAPI.BlockReq.getDefaultInstance(); + Block block = wallet.getBlock(req); + assertNotNull(block); + try { + req = req.toBuilder().setIdOrNum("-1").build(); + wallet.getBlock(req); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + } + try { + req = req.toBuilder().setIdOrNum("hash000001").build(); + wallet.getBlock(req); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + } + req = GrpcAPI.BlockReq.newBuilder().setIdOrNum("0").build(); + block = wallet.getBlock(req); + req = req.toBuilder().setDetail(true).build(); + assertEquals(block, wallet.getBlock(req).toBuilder().clearTransactions().build()); + req = req.toBuilder().clearDetail() + .setIdOrNum(new BlockCapsule(block).getBlockId().toString()).build(); + assertEquals(block, wallet.getBlock(req)); + } + + @Test + public void testGetNextMaintenanceTime() { + NumberMessage numberMessage = wallet.getNextMaintenanceTime(); + Assert.assertEquals(0, numberMessage.getNum()); + } + //@Test public void testChainParameters() { @@ -522,7 +683,615 @@ public void testChainParameters() { }); - System.out.printf(builder.build().toString()); + System.out.print(builder.build()); + } + + @Test + public void testGetDelegatedResource() { + long frozenBalance = 1_000_000_000L; + long duration = 3; + FreezeBalanceActuator actuator = new FreezeBalanceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForCpu(OWNER_ADDRESS, RECEIVER_ADDRESS, frozenBalance, duration)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + + GrpcAPI.DelegatedResourceList delegatedResourceList = wallet.getDelegatedResource( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + + Assert.assertEquals(1L, delegatedResourceList.getDelegatedResourceCount()); + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + delegatedResourceList.getDelegatedResource(0).getFrom()); + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + delegatedResourceList.getDelegatedResource(0).getTo()); + Assert.assertEquals(frozenBalance, + delegatedResourceList.getDelegatedResource(0).getFrozenBalanceForEnergy()); + Assert.assertEquals(0L, + delegatedResourceList.getDelegatedResource(0).getFrozenBalanceForBandwidth()); + Assert.assertEquals(0L, + delegatedResourceList.getDelegatedResource(0).getExpireTimeForBandwidth()); + } catch (Exception e) { + Assert.fail(); + } + } + + + @Test + public void testGetDelegatedResourceAccountIndex() { + long frozenBalance = 1_000_000_000L; + long duration = 3; + FreezeBalanceActuator actuator = new FreezeBalanceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForCpu(OWNER_ADDRESS, RECEIVER_ADDRESS, frozenBalance, duration)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + + Protocol.DelegatedResourceAccountIndex delegatedResourceAccountIndex = + wallet.getDelegatedResourceAccountIndex( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + delegatedResourceAccountIndex.getAccount()); + Assert.assertEquals(1L, delegatedResourceAccountIndex.getToAccountsCount()); + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + delegatedResourceAccountIndex.getToAccounts(0)); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + private Any getDelegatedContractForCpu(String ownerAddress, String receiverAddress, + long frozenBalance, + long duration) { + return Any.pack( + BalanceContract.FreezeBalanceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(receiverAddress))) + .setFrozenBalance(frozenBalance) + .setFrozenDuration(duration) + .setResource(Common.ResourceCode.ENERGY) + .build()); + } + + private void freezeBandwidthForOwner() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.addFrozenBalanceForBandwidthV2(initBalance); + ownerCapsule.setNetUsage(0L); + ownerCapsule.setEnergyUsage(0L); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(0L); + dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(0L); + dbManager.getDynamicPropertiesStore().addTotalNetWeight(initBalance / TRX_PRECISION); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + } + + private void freezeCpuForOwner() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.addFrozenBalanceForEnergyV2(initBalance); + ownerCapsule.setNetUsage(0L); + ownerCapsule.setEnergyUsage(0L); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(0L); + dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(0L); + dbManager.getDynamicPropertiesStore().addTotalEnergyWeight(initBalance / TRX_PRECISION); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + } + + private Any getDelegateContractForBandwidth(String ownerAddress, String receiveAddress, + long unfreezeBalance) { + return getLockedDelegateContractForBandwidth(ownerAddress, receiveAddress, + unfreezeBalance, false); + } + + private Any getLockedDelegateContractForBandwidth(String ownerAddress, String receiveAddress, + long unfreezeBalance, boolean lock) { + return Any.pack(BalanceContract.DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(receiveAddress))) + .setBalance(unfreezeBalance) + .setResource(BANDWIDTH) + .setLock(lock) + .build()); + } + + @Test + public void testGetDelegatedResourceV2() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + freezeBandwidthForOwner(); + + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(Transaction.Result.code.SUCESS, ret.getInstance().getRet()); + + GrpcAPI.DelegatedResourceList delegatedResourceList = wallet.getDelegatedResourceV2( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + + Protocol.Account account = Protocol.Account.newBuilder() + .setAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build(); + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addAssetV2("testv2".getBytes(), 1L); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + wallet.getAccount(account); + wallet.getProposalList(); + wallet.getWitnessList(); + Assert.assertEquals(1L, delegatedResourceList.getDelegatedResourceCount()); + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + delegatedResourceList.getDelegatedResource(0).getFrom()); + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + delegatedResourceList.getDelegatedResource(0).getTo()); + Assert.assertEquals(delegateBalance, + delegatedResourceList.getDelegatedResource(0).getFrozenBalanceForBandwidth()); + Assert.assertEquals(0L, + delegatedResourceList.getDelegatedResource(0).getExpireTimeForBandwidth()); + Assert.assertEquals(0L, + delegatedResourceList.getDelegatedResource(0).getFrozenBalanceForEnergy()); + Assert.assertEquals(0L, + delegatedResourceList.getDelegatedResource(0).getExpireTimeForEnergy()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testGetDelegatedResourceAccountIndexV2() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + freezeBandwidthForOwner(); + + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(Transaction.Result.code.SUCESS, ret.getInstance().getRet()); + + Protocol.DelegatedResourceAccountIndex delegatedResourceAccountIndex = + wallet.getDelegatedResourceAccountIndexV2( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + delegatedResourceAccountIndex.getAccount()); + Assert.assertEquals(1L, delegatedResourceAccountIndex.getToAccountsCount()); + Assert.assertEquals(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + delegatedResourceAccountIndex.getToAccounts(0)); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testGetCanDelegatedMaxSizeBandWidth() { + freezeBandwidthForOwner(); + + GrpcAPI.CanDelegatedMaxSizeResponseMessage message = wallet.getCanDelegatedMaxSize( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + BANDWIDTH.getNumber()); + Assert.assertEquals(initBalance - 280L, message.getMaxSize()); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testGetCanDelegatedMaxSizeBandWidth2() { + chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(86401); + freezeBandwidthForOwner(); + GrpcAPI.CanDelegatedMaxSizeResponseMessage message = wallet.getCanDelegatedMaxSize( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + BANDWIDTH.getNumber()); + Assert.assertEquals(initBalance - 284L, message.getMaxSize()); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testGetCanDelegatedMaxSizeEnergy() { + freezeCpuForOwner(); + + GrpcAPI.CanDelegatedMaxSizeResponseMessage message = wallet.getCanDelegatedMaxSize( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + Common.ResourceCode.ENERGY.getNumber()); + Assert.assertEquals(initBalance, message.getMaxSize()); + + } + + private Any getContractForBandwidthV2(String ownerAddress, long unfreezeBalance) { + return Any.pack( + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(ownerAddress)) + ) + .setUnfreezeBalance(unfreezeBalance) + .setResource(BANDWIDTH) + .build() + ); + } + + @Test + public void testGetAvailableUnfreezeCount() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + + long frozenBalance = 43_200_000_00L; + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(1000); + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + long unfreezeBalance = frozenBalance - 100; + + Assert.assertEquals(frozenBalance, accountCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(Transaction.Result.code.SUCESS, ret.getInstance().getRet()); + + GrpcAPI.GetAvailableUnfreezeCountResponseMessage message = + wallet.getAvailableUnfreezeCount( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + Assert.assertEquals(31, message.getCount()); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testGetCanWithdrawUnfreezeAmount() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + + AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); + Protocol.Account.UnFreezeV2 unFreezeV2_1 = Protocol.Account.UnFreezeV2.newBuilder() + .setType(BANDWIDTH).setUnfreezeAmount(16_000_000L).setUnfreezeExpireTime(1).build(); + Protocol.Account.UnFreezeV2 unFreezeV2_2 = Protocol.Account.UnFreezeV2.newBuilder() + .setType(ENERGY).setUnfreezeAmount(16_000_000L).setUnfreezeExpireTime(1).build(); + Protocol.Account.UnFreezeV2 unFreezeV2_3 = Protocol.Account.UnFreezeV2.newBuilder() + .setType(ENERGY).setUnfreezeAmount(0).setUnfreezeExpireTime(Long.MAX_VALUE).build(); + accountCapsule.addUnfrozenV2(unFreezeV2_1); + accountCapsule.addUnfrozenV2(unFreezeV2_2); + accountCapsule.addUnfrozenV2(unFreezeV2_3); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + GrpcAPI.CanWithdrawUnfreezeAmountResponseMessage message = + wallet.getCanWithdrawUnfreezeAmount( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + System.currentTimeMillis()); + Assert.assertEquals(16_000_000L * 2, message.getAmount()); + } + + @Test + public void testGetMemoFeePrices() { + PricesResponseMessage memeFeeList = wallet.getMemoFeePrices(); + Assert.assertEquals("0:0", memeFeeList.getPrices()); + } + + @Test + public void testGetChainParameters() { + Protocol.ChainParameters params = wallet.getChainParameters(); + //getTotalEnergyAverageUsage & getTotalEnergyCurrentLimit have not ProposalType. + Assert.assertEquals(ProposalType.values().length + 2, params.getChainParameterCount()); + } + + @Test + public void testGetAccountById() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.setAccountId(ByteString.copyFromUtf8("1001").toByteArray()); + chainBaseManager.getAccountIdIndexStore().put(ownerCapsule); + Protocol.Account account = wallet.getAccountById( + Protocol.Account.newBuilder().setAccountId(ByteString.copyFromUtf8("1001")).build()); + Assert.assertEquals(ownerCapsule.getAddress(), account.getAddress()); + } + + @Test + public void testGetAccountResource() { + GrpcAPI.AccountResourceMessage accountResource = + wallet.getAccountResource(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + Assert.assertEquals( + chainBaseManager.getDynamicPropertiesStore().getFreeNetLimit(), + accountResource.getFreeNetLimit()); + Assert.assertEquals(0, accountResource.getFreeNetUsed()); + } + + @Test + public void testGetAssetIssueByName() { + String assetName = "My_asset"; + String id = "10001"; + AssetIssueCapsule assetCapsule = new AssetIssueCapsule(ByteArray.fromHexString(OWNER_ADDRESS), + id, assetName, "abbr", 1_000_000_000_000L, 6); + chainBaseManager.getAssetIssueStore().put(assetCapsule.createDbKey(), assetCapsule); + chainBaseManager.getAssetIssueV2Store().put(assetCapsule.createDbV2Key(), assetCapsule); + try { + AssetIssueContract assetIssue = + wallet.getAssetIssueByName(ByteString.copyFromUtf8(assetName)); + Assert.assertEquals(ByteString.copyFromUtf8(assetName), assetIssue.getName()); + Assert.assertEquals(id, assetIssue.getId()); + chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); + assetIssue = wallet.getAssetIssueByName(ByteString.copyFromUtf8(assetName)); + Assert.assertEquals(ByteString.copyFromUtf8(assetName), assetIssue.getName()); + Assert.assertEquals(id, assetIssue.getId()); + } catch (NonUniqueObjectException e) { + Assert.fail(e.getMessage()); + } + chainBaseManager.getAssetIssueStore().delete(assetCapsule.createDbKey()); + chainBaseManager.getAssetIssueV2Store().delete(assetCapsule.createDbV2Key()); + chainBaseManager.getDynamicPropertiesStore().saveAllowSameTokenName(0); + } + + @Test + @SneakyThrows + public void testTriggerConstant() { + boolean preDebug = CommonParameter.getInstance().debug; + CommonParameter.getInstance().debug = true; + ConfigLoader.disable = true; + VMConfig.initAllowTvmTransferTrc10(1); + VMConfig.initAllowTvmConstantinople(1); + VMConfig.initAllowTvmShangHai(1); + + String contractAddress = + Wallet.getAddressPreFixString() + "1A622D84ed49f01045f5f1a5AfcEb9c57e9cC3cc"; + + AccountCapsule accountCap = new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(contractAddress)), + Protocol.AccountType.Normal); + dbManager.getAccountStore().put(accountCap.createDbKey(), accountCap); + + SmartContractOuterClass.SmartContract smartContract = + SmartContractOuterClass.SmartContract.newBuilder().build(); + ContractCapsule contractCap = new ContractCapsule(smartContract); + dbManager.getContractStore().put(ByteArray.fromHexString(contractAddress), contractCap); + + String codeString = "608060405234801561000f575f80fd5b50d3801561001b575f80fd5b50d280156100" + + "27575f80fd5b506004361061004c575f3560e01c80638da5cb5b14610050578063f8a8fd6d1461006e57" + + "5b5f80fd5b61005861008c565b6040516100659190610269565b60405180910390f35b6100766100af565b" + + "6040516100839190610269565b60405180910390f35b5f8054906101000a900473ffffffffffffffffffff" + + "ffffffffffffffffffff1681565b5f60017fbe0166938e2ea2f3f3e0746fdaf46e25c4d8de37ce56d70400" + + "cf284c80d47bbe601b7f10afab946e2be82aa3e4280cf24e2cab294911c3beb06ca9dd7ead06081265d07f" + + "1e1855bcdc3ed57c6f3c3874cde035782427d1236e2d819bd16c75676ecc003a6040515f81526020016040" + + "52604051610133949392919061038f565b6020604051602081039080840390855afa158015610153573d5f" + + "803e3d5ffd5b505050602060405103515f806101000a81548173ffffffffffffffffffffffffffffffffff" + + "ffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550734c95a52686a9b3" + + "ff9cf787b94b8549a988334c5773ffffffffffffffffffffffffffffffffffffffff165f8054906101000a" + + "900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffff" + + "ffff1614610205575f80fd5b5f8054906101000a900473ffffffffffffffffffffffffffffffffffffffff" + + "16905090565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6102538261" + + "022a565b9050919050565b61026381610249565b82525050565b5f60208201905061027c5f83018461025a" + + "565b92915050565b5f819050919050565b5f819050919050565b5f815f1b9050919050565b5f6102b96102" + + "b46102af84610282565b610294565b61028b565b9050919050565b6102c98161029f565b82525050565b5f" + + "819050919050565b5f60ff82169050919050565b5f819050919050565b5f6103076103026102fd846102cf" + + "565b6102e4565b6102d8565b9050919050565b610317816102ed565b82525050565b5f819050919050565b" + + "5f61034061033b6103368461031d565b610294565b61028b565b9050919050565b61035081610326565b82" + + "525050565b5f819050919050565b5f61037961037461036f84610356565b610294565b61028b565b905091" + + "9050565b6103898161035f565b82525050565b5f6080820190506103a25f8301876102c0565b6103af6020" + + "83018661030e565b6103bc6040830185610347565b6103c96060830184610380565b9594505050505056fe" + + "a26474726f6e58221220e967690f9c06386434cbe4d8dd6dce394130f190d17621cbd4ae4cabdef4ad7964" + + "736f6c63430008140033"; + CodeCapsule codeCap = new CodeCapsule(ByteArray.fromHexString(codeString)); + dbManager.getCodeStore().put(ByteArray.fromHexString(contractAddress), codeCap); + + SmartContractOuterClass.TriggerSmartContract contract = + SmartContractOuterClass.TriggerSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(contractAddress))) + .setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(contractAddress))) + .setData(ByteString.copyFrom(ByteArray.fromHexString("f8a8fd6d"))) + .build(); + TransactionCapsule trxCap = wallet.createTransactionCapsule(contract, + ContractType.TriggerSmartContract); + + GrpcAPI.TransactionExtention.Builder trxExtBuilder = GrpcAPI.TransactionExtention.newBuilder(); + GrpcAPI.Return.Builder retBuilder = GrpcAPI.Return.newBuilder(); + + Transaction tx = wallet.triggerConstantContract(contract, trxCap, trxExtBuilder, retBuilder); + Assert.assertEquals(Transaction.Result.code.SUCESS, tx.getRet(0).getRet()); + + VMConfig.initAllowTvmTransferTrc10(0); + VMConfig.initAllowTvmConstantinople(0); + VMConfig.initAllowTvmShangHai(0); + ConfigLoader.disable = false; + CommonParameter.getInstance().debug = preDebug; + } + + @Test + @SneakyThrows + public void testEstimateEnergy() { + dbManager.getDynamicPropertiesStore().put("ALLOW_TVM_TRANSFER_TRC10".getBytes(), + new BytesCapsule(ByteArray.fromHexString("0x01"))); + String contractAddress = "0x1A622D84ed49f01045f5f1a5AfcEb9c57e9cC3ca"; + + SmartContractOuterClass.SmartContract smartContract = + SmartContractOuterClass.SmartContract.newBuilder().build(); + ContractCapsule capsule = new ContractCapsule(smartContract); + dbManager.getContractStore().put(ByteArray.fromHexString(contractAddress), capsule); + + String codeString = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d28015" + + "61002a57600080fd5b50600436106100495760003560e01c806385bb7d69146100555761004a565b5b61" + + "0052610073565b50005b61005d610073565b60405161006a91906100b9565b60405180910390f35b6000" + + "80600090505b60028110156100a657808261009091906100d4565b915060018161009f91906100d4565b" + + "905061007b565b5090565b6100b38161012a565b82525050565b60006020820190506100ce6000830184" + + "6100aa565b92915050565b60006100df8261012a565b91506100ea8361012a565b9250827fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffff0382111561011f5761011e61013456" + + "5b5b828201905092915050565b6000819050919050565b7f4e487b710000000000000000000000000000" + + "0000000000000000000000000000600052601160045260246000fdfea26474726f6e58221220f3d01983" + + "23c67293b97323c101e294e6d2cac7fb29555292675277e11c275a4b64736f6c63430008060033"; + CodeCapsule codeCapsule = new CodeCapsule(ByteArray.fromHexString(codeString)); + dbManager.getCodeStore().put(ByteArray.fromHexString(contractAddress), codeCapsule); + + SmartContractOuterClass.TriggerSmartContract contract = + SmartContractOuterClass.TriggerSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setContractAddress(ByteString.copyFrom( + ByteArray.fromHexString( + contractAddress))) + .build(); + TransactionCapsule trxCap = wallet.createTransactionCapsule(contract, + ContractType.TriggerSmartContract); + + GrpcAPI.TransactionExtention.Builder trxExtBuilder = GrpcAPI.TransactionExtention.newBuilder(); + GrpcAPI.Return.Builder retBuilder = GrpcAPI.Return.newBuilder(); + GrpcAPI.EstimateEnergyMessage.Builder estimateBuilder + = GrpcAPI.EstimateEnergyMessage.newBuilder(); + + Args.getInstance().setEstimateEnergy(false); + try { + wallet.estimateEnergy( + contract, trxCap, trxExtBuilder, retBuilder, estimateBuilder); + Assert.fail(); + } catch (ContractValidateException exception) { + assertEquals("this node does not support estimate energy", exception.getMessage()); + } + + Args.getInstance().setEstimateEnergy(true); + + wallet.estimateEnergy( + contract, trxCap, trxExtBuilder, retBuilder, estimateBuilder); + GrpcAPI.EstimateEnergyMessage message = estimateBuilder.build(); + Assert.assertTrue(message.getEnergyRequired() > 0); + } + + @Test + @SneakyThrows + public void testEstimateEnergyOutOfTime() { + dbManager.getDynamicPropertiesStore().put("ALLOW_TVM_TRANSFER_TRC10".getBytes(), + new BytesCapsule(ByteArray.fromHexString("0x01"))); + + String contractAddress = "0x1A622D84ed49f01045f5f1a5AfcEb9c57e9cC3ca"; + + SmartContractOuterClass.SmartContract smartContract = + SmartContractOuterClass.SmartContract.newBuilder().build(); + ContractCapsule capsule = new ContractCapsule(smartContract); + dbManager.getContractStore().put(ByteArray.fromHexString(contractAddress), capsule); + + String codeString = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d28015" + + "61002a57600080fd5b50600436106100495760003560e01c806385bb7d69146100555761004a565b5b61" + + "0052610073565b50005b61005d610073565b60405161006a91906100ae565b60405180910390f35b6000" + + "80600090505b64e8d4a5100081101561009b57808261009491906100c9565b915061007b565b5090565b" + + "6100a88161011f565b82525050565b60006020820190506100c3600083018461009f565b92915050565b" + + "60006100d48261011f565b91506100df8361011f565b9250827fffffffffffffffffffffffffffffffff" + + "ffffffffffffffffffffffffffffffff0382111561011457610113610129565b5b828201905092915050" + + "565b6000819050919050565b7f4e487b7100000000000000000000000000000000000000000000000000" + + "000000600052601160045260246000fdfea26474726f6e58221220a7e1a6e6d17684029015a0b593b634" + + "40f77e7eb8abd4297a3063e59f28086bf464736f6c63430008060033"; + CodeCapsule codeCapsule = new CodeCapsule(ByteArray.fromHexString(codeString)); + dbManager.getCodeStore().put(ByteArray.fromHexString(contractAddress), codeCapsule); + + SmartContractOuterClass.TriggerSmartContract contract = + SmartContractOuterClass.TriggerSmartContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setContractAddress(ByteString.copyFrom( + ByteArray.fromHexString( + contractAddress))) + .build(); + TransactionCapsule trxCap = wallet.createTransactionCapsule(contract, + ContractType.TriggerSmartContract); + + GrpcAPI.TransactionExtention.Builder trxExtBuilder = GrpcAPI.TransactionExtention.newBuilder(); + GrpcAPI.Return.Builder retBuilder = GrpcAPI.Return.newBuilder(); + GrpcAPI.EstimateEnergyMessage.Builder estimateBuilder + = GrpcAPI.EstimateEnergyMessage.newBuilder(); + + Args.getInstance().setEstimateEnergy(true); + + try { + wallet.estimateEnergy( + contract, trxCap, trxExtBuilder, retBuilder, estimateBuilder); + Assert.fail("EstimateEnergy should throw exception!"); + } catch (Program.OutOfTimeException ignored) { + Assert.assertTrue(true); + } + } + + @Test + public void testListNodes() { + try { + wallet.listNodes(); + } catch (Exception e) { + Assert.assertTrue(e instanceof NullPointerException); + } + Args.getInstance().setP2pDisable(true); + GrpcAPI.NodeList nodeList = wallet.listNodes(); + assertEquals(0, nodeList.getNodesList().size()); + } + + /** + * We calculate the size of the structure and conclude that + * delegate_balance = 1000_000L; => 277 + * delegate_balance = 1000_000_000L; => 279 + * delegate_balance = 1000_000_000_000L => 280 + *

+ * We initialize account information as follows + * account balance = 1000_000_000_000L + * account frozen_balance = 1000_000_000L + *

+ * then estimateConsumeBandWidthSize cost 279 + *

+ * so we have following result: + * TransactionUtil.estimateConsumeBandWidthSize( + * dynamicStore,ownerCapsule.getBalance()) ===> false + * TransactionUtil.estimateConsumeBandWidthSize( + * dynamicStore,ownerCapsule.getFrozenV2BalanceForBandwidth()) ===> true + *

+ * This test case is used to verify the above conclusions + */ + @Test + public void testGetCanDelegatedMaxSizeBandWidth123() { + long frozenBalance = 1000_000_000L; + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + ownerCapsule.setNetUsage(0L); + ownerCapsule.setEnergyUsage(0L); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(0L); + dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(0L); + dbManager.getDynamicPropertiesStore().addTotalNetWeight( + frozenBalance / TRX_PRECISION + 43100000000L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + GrpcAPI.CanDelegatedMaxSizeResponseMessage message = wallet.getCanDelegatedMaxSize( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + BANDWIDTH.getNumber()); + Assert.assertEquals(frozenBalance / TRX_PRECISION - 279, + message.getMaxSize() / TRX_PRECISION); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testGetSolidBlock() { + long blkNum = wallet.getSolidBlockNum(); + Assert.assertEquals(BLOCK_NUM_TWO, blkNum); + + Block block = wallet.getSolidBlock(); + assertEquals(block2, block); } } diff --git a/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java index b5d1d7e0ac0..69bac08c3e6 100644 --- a/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/AccountPermissionUpdateActuatorTest.java @@ -1,30 +1,23 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -37,9 +30,8 @@ import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; @Slf4j -public class AccountPermissionUpdateActuatorTest { +public class AccountPermissionUpdateActuatorTest extends BaseTest { - private static final String dbPath = "output_transfer_test"; private static final String OWNER_ADDRESS; private static final String WITNESS_ADDRESS; private static final String KEY_ADDRESS; @@ -58,14 +50,9 @@ public class AccountPermissionUpdateActuatorTest { private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; private static final String KEY_ADDRESS_INVALID = "bbbb"; - public static Application AppT; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; WITNESS_ADDRESS = Wallet.getAddressPreFixString() + "8CFC572CC20CA18B636BDD93B4FB15EA84CC2B4E"; KEY_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -98,35 +85,14 @@ public class AccountPermissionUpdateActuatorTest { .setWeight(KEY_WEIGHT).build(); } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); - dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { + dbManager.getDynamicPropertiesStore().saveAllowMultiSign(1); + dbManager.getDynamicPropertiesStore().saveTotalSignNum(5); + AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), ByteString.copyFromUtf8("owner"), AccountType.Normal); @@ -199,27 +165,23 @@ private void processAndCheckInvalid(AccountPermissionUpdateActuator actuator, actuator.execute(ret); fail(failMsg); - } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); + } catch (ContractValidateException | RuntimeException e) { + Assert.assertTrue(true); Assert.assertEquals(expectedMsg, e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); - } catch (RuntimeException e) { - Assert.assertTrue(e instanceof RuntimeException); - Assert.assertEquals(expectedMsg, e.getMessage()); + Assert.fail(); } } @Test public void successUpdatePermissionKey() { - String ownerAddress = OWNER_ADDRESS; String keyAddress = KEY_ADDRESS; // step 1, init addDefaultPermission(); // step2, check init data - byte[] owner_name_array = ByteArray.fromHexString(ownerAddress); + byte[] owner_name_array = ByteArray.fromHexString(OWNER_ADDRESS); ByteString address = ByteString.copyFrom(owner_name_array); AccountCapsule owner = dbManager.getAccountStore().get(owner_name_array); @@ -227,7 +189,7 @@ public void successUpdatePermissionKey() { Permission activePermission = AccountCapsule.createDefaultActivePermission(address, dbManager.getDynamicPropertiesStore()); - Assert.assertEquals(owner.getInstance().getActivePermissionCount(), 1); + Assert.assertEquals(1, owner.getInstance().getActivePermissionCount()); Permission ownerPermission1 = owner.getInstance().getOwnerPermission(); Permission activePermission1 = owner.getInstance().getActivePermission(0); @@ -274,21 +236,19 @@ public void successUpdatePermissionKey() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); // step 4, check result after update operation owner = dbManager.getAccountStore().get(owner_name_array); - Assert.assertEquals(owner.getInstance().getActivePermissionCount(), 1); + Assert.assertEquals(1, owner.getInstance().getActivePermissionCount()); ownerPermission1 = owner.getInstance().getOwnerPermission(); activePermission1 = owner.getInstance().getActivePermission(0); Assert.assertEquals(ownerPermission1, ownerPermission); Assert.assertEquals(activePermission1, activePermission); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -329,8 +289,7 @@ public void invalidTransactionResultCapsule() { AccountPermissionUpdateActuator actuator = new AccountPermissionUpdateActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContract(OWNER_ADDRESS)); - TransactionResultCapsule ret = null; - processAndCheckInvalid(actuator, ret, "TransactionResultCapsule is null", + processAndCheckInvalid(actuator, null, "TransactionResultCapsule is null", "TransactionResultCapsule is null"); } @@ -398,7 +357,7 @@ public void activeToMany() { for (int i = 0; i <= 8; i++) { activeList.add(activePermission); } - + assertNotNull(activeList); AccountPermissionUpdateActuator actuator = new AccountPermissionUpdateActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContract(address, ownerPermission, null, null)); @@ -964,12 +923,12 @@ public void checkAvailableContractTypeCorrespondingToCode() { // 7fff1fc0037e0000000000000000000000000000000000000000000000000000, // and it should call the addSystemContractAndSetPermission to add new contract // type - // When you add a new contact, you can add its to contractType, + // When you add a new contact, you can add it to contractType, // as '|| contractType = ContractType.XXX', // and you will get the value from the output, // then update the value to checkAvailableContractType // and checkActiveDefaultOperations - String validContractType = "7fff1fc0037e3800000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0037ef80f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { @@ -996,7 +955,7 @@ public void checkActiveDefaultOperationsCorrespondingToCode() { // 7fff1fc0033e0000000000000000000000000000000000000000000000000000, // and it should call the addSystemContractAndSetPermission to add new contract // type - String validContractType = "7fff1fc0033e3800000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0033ef80f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { @@ -1019,7 +978,7 @@ public void checkActiveDefaultOperationsCorrespondingToCode() { @Test public void checkAvailableContractType() { - String validContractType = "7fff1fc0037e3900000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0037ef90f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { @@ -1040,7 +999,7 @@ public void checkAvailableContractType() { @Test public void checkActiveDefaultOperations() { - String validContractType = "7fff1fc0033e3900000000000000000000000000000000000000000000000000"; + String validContractType = "7fff1fc0033ef90f000000000000000000000000000000000000000000000000"; byte[] availableContractType = new byte[32]; for (ContractType contractType : ContractType.values()) { diff --git a/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java b/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java index fe17d7ae7c4..b8c2bd4fef9 100644 --- a/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ActuatorConstantTest.java @@ -1,59 +1,32 @@ package org.tron.core.actuator; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @Slf4j(topic = "actuator") -public class ActuatorConstantTest { - - private static final String dbPath = "output_actuatorConstant_test"; - public static Application AppT; - private static TronApplicationContext context; +public class ActuatorConstantTest extends BaseTest { /** * Init . */ @BeforeClass public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } @Test - public void variablecheck() { + public void variableCheck() { ActuatorConstant actuator = new ActuatorConstant(); Assert.assertEquals("Account[", actuator.ACCOUNT_EXCEPTION_STR); Assert.assertEquals("Witness[", actuator.WITNESS_EXCEPTION_STR); Assert.assertEquals("Proposal[", actuator.PROPOSAL_EXCEPTION_STR); Assert.assertEquals("] not exists", actuator.NOT_EXIST_STR); - Assert.assertTrue(actuator instanceof ActuatorConstant); } } diff --git a/framework/src/test/java/org/tron/core/actuator/ActuatorFactoryTest.java b/framework/src/test/java/org/tron/core/actuator/ActuatorFactoryTest.java new file mode 100644 index 00000000000..8258fbf9a3e --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/ActuatorFactoryTest.java @@ -0,0 +1,71 @@ +package org.tron.core.actuator; + +import com.google.protobuf.ByteString; +import java.util.List; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.contract.BalanceContract.TransferContract; + +public class ActuatorFactoryTest extends BaseTest { + + private static final String OWNER_ADDRESS = Wallet.getAddressPreFixString() + + "548794500882809695a8a687866e76d4271a1abc"; + private static final String TO_ADDRESS = Wallet.getAddressPreFixString() + + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + + static { + Args.setParam( + new String[] { + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + private TransferContract getContract(long count, String owneraddress, String toaddress) { + return TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(owneraddress))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(toaddress))) + .setAmount(count) + .build(); + } + + @Before + public void createCapsule() { + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + AccountType.Normal, + 10000L); + AccountCapsule toAccountCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("toAccount"), + ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS)), + AccountType.Normal, + 10L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + dbManager.getAccountStore().put(toAccountCapsule.getAddress().toByteArray(), toAccountCapsule); + } + + + @Test + public void testCreateActuator() { + TransferContract contract = getContract(10L, OWNER_ADDRESS, TO_ADDRESS); + TransactionCapsule trx = new TransactionCapsule(contract, + chainBaseManager.getAccountStore()); + List actList = ActuatorFactory.createActuator(trx, chainBaseManager); + + Assert.assertEquals(1, actList.size()); + } + +} diff --git a/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java index 728e46dd569..77c24c28797 100755 --- a/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/AssetIssueActuatorTest.java @@ -1,35 +1,27 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -39,9 +31,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply; @Slf4j -public class AssetIssueActuatorTest { +public class AssetIssueActuatorTest extends BaseTest { - private static final String dbPath = "output_assetIssue_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_SECOND; private static final String NAME = "trx-my"; @@ -51,60 +42,22 @@ public class AssetIssueActuatorTest { private static final String DESCRIPTION = "myCoin"; private static final String URL = "tron-my.com"; private static final String ASSET_NAME_SECOND = "asset_name2"; - private static TronApplicationContext context; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; private static long now = 0; private static long startTime = 0; private static long endTime = 0; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ADDRESS_SECOND = Wallet .getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { - - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule( - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS_SECOND))); - dbManager.getAccountAssetStore().put(ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put(ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, dbManager.getDynamicPropertiesStore().getAssetIssueFee()); @@ -169,7 +122,7 @@ public void SameTokenNameCloseAssetIssueSuccess() { Assert.assertEquals(6, assetIssueCapsule.getPrecision()); Assert.assertEquals(NUM, assetIssueCapsule.getNum()); Assert.assertEquals(TRX_NUM, assetIssueCapsule.getTrxNum()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); // check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); AssetIssueCapsule assetIssueCapsuleV2 = dbManager.getAssetIssueV2Store() @@ -178,7 +131,7 @@ public void SameTokenNameCloseAssetIssueSuccess() { Assert.assertEquals(0, assetIssueCapsuleV2.getPrecision()); Assert.assertEquals(NUM, assetIssueCapsuleV2.getNum()); Assert.assertEquals(TRX_NUM, assetIssueCapsuleV2.getTrxNum()); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { @@ -222,7 +175,7 @@ public void oldNotUpdateAssetIssueSuccess() { Assert.assertEquals(6, assetIssueCapsuleV2.getPrecision()); Assert.assertEquals(NUM, assetIssueCapsuleV2.getNum()); Assert.assertEquals(TRX_NUM, assetIssueCapsuleV2.getTrxNum()); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { @@ -265,7 +218,7 @@ public void SameTokenNameOpenAssetIssueSuccess() { Assert.assertEquals(6, assetIssueCapsuleV2.getPrecision()); Assert.assertEquals(NUM, assetIssueCapsuleV2.getNum()); Assert.assertEquals(TRX_NUM, assetIssueCapsuleV2.getTrxNum()); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { @@ -732,8 +685,8 @@ public void assetNameTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get("testname0123456789abcdefghijgklm").longValue(), - TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest() + .get("testname0123456789abcdefghijgklm").longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -769,7 +722,7 @@ public void assetNameTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get("0").longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get("0").longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -891,7 +844,7 @@ public void urlTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -927,7 +880,7 @@ public void urlTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -963,7 +916,7 @@ public void urlTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1048,7 +1001,7 @@ public void descriptionTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1084,7 +1037,7 @@ public void descriptionTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1120,7 +1073,7 @@ public void descriptionTest() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMap().get(NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(NAME).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1505,7 +1458,7 @@ public void issueTimeTest() { .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); Assert.assertEquals(account.getAssetIssuedName().toStringUtf8(), NAME); - Assert.assertEquals(account.getAssetMap().size(), 1); + Assert.assertEquals(account.getAssetMapForTest().size(), 1); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1789,7 +1742,7 @@ public void IssueSameTokenNameAssert() { Assert.assertEquals(owner.getBalance(), 0L); Assert.assertEquals(dbManager.getAccountStore().getBlackhole().getBalance(), blackholeBalance + dbManager.getDynamicPropertiesStore().getAssetIssueFee()); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), TOTAL_SUPPLY); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); diff --git a/framework/src/test/java/org/tron/core/actuator/CancelAllUnfreezeV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/CancelAllUnfreezeV2ActuatorTest.java new file mode 100644 index 00000000000..fc2dad88420 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/CancelAllUnfreezeV2ActuatorTest.java @@ -0,0 +1,206 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.fail; +import static org.tron.protos.Protocol.Transaction.Result.code.SUCESS; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +@Slf4j +public class CancelAllUnfreezeV2ActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "aaaa"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 10_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + @Before + public void setUp() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + AccountCapsule receiverCapsule = new AccountCapsule(ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), Protocol.AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + } + + @Test + public void testCancelAllUnfreezeV2() { + long now = System.currentTimeMillis(); + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 1000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 2000000L, -1); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 3000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 4000000L, 100); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, 100); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + + assertEquals(SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + Map cancelUnfreezeV2AmountMap = ret.getInstance() + .getCancelUnfreezeV2AmountMap(); + assertEquals(2000000L, ret.getInstance().getWithdrawExpireAmount()); + assertEquals(0, owner.getUnfrozenV2List().size()); + assertEquals(8000000L, cancelUnfreezeV2AmountMap.get("BANDWIDTH").longValue()); + assertEquals(8000000L, cancelUnfreezeV2AmountMap.get("ENERGY").longValue()); + assertEquals(0, cancelUnfreezeV2AmountMap.get("TRON_POWER").longValue()); + } catch (ContractValidateException | ContractExeException e) { + fail(); + } + } + + @Test + public void testNullTransactionResultCapsule() { + long now = System.currentTimeMillis(); + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 1000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 2000000L, -1); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 3000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, now + 14 * 24 * 3600 * 1000); + accountCapsule.addUnfrozenV2List(BANDWIDTH, 4000000L, 100); + accountCapsule.addUnfrozenV2List(ENERGY, 4000000L, 100); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + try { + actuator.validate(); + } catch (ContractValidateException e) { + fail(); + } + assertThrows(ActuatorConstant.TX_RESULT_NULL, + RuntimeException.class, () -> actuator.execute(null)); + } + + @Test + public void testInvalidOwnerAddress() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2ContractInvalidAddress()); + assertThrows("Invalid address", ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidOwnerAccount() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2ContractInvalidAccount()); + assertThrows("Account[" + OWNER_ACCOUNT_INVALID + "] does not exist", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidOwnerUnfreezeV2List() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + assertThrows("no unfreezeV2 list to cancel", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidCancelAllUnfreezeV2Contract() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(null); + assertThrows(ActuatorConstant.CONTRACT_NOT_EXIST, + ContractValidateException.class, actuator::validate); + } + + @Test + public void testInvalidAccountStore() { + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(null).setAny(getCancelAllUnfreezeV2Contract()); + assertThrows(ActuatorConstant.STORE_NOT_EXIST, + ContractValidateException.class, actuator::validate); + } + + @Test + public void testSupportAllowCancelAllUnfreezeV2() { + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(0); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getCancelAllUnfreezeV2Contract()); + assertThrows( + "Not support CancelAllUnfreezeV2 transaction, need to be opened by the committee", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testErrorContract() { + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + CancelAllUnfreezeV2Actuator actuator = new CancelAllUnfreezeV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getErrorContract()); + assertThrows( + "contract type error, expected type [CancelAllUnfreezeV2Contract], " + + "real type[WithdrawExpireUnfreezeContract]", + ContractValidateException.class, actuator::validate); + } + + private Any getCancelAllUnfreezeV2Contract() { + return Any.pack(BalanceContract.CancelAllUnfreezeV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build() + ); + } + + private Any getErrorContract() { + return Any.pack(BalanceContract.WithdrawExpireUnfreezeContract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build() + ); + } + + private Any getCancelAllUnfreezeV2ContractInvalidAddress() { + return Any.pack(BalanceContract.CancelAllUnfreezeV2Contract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS_INVALID))).build()); + } + + private Any getCancelAllUnfreezeV2ContractInvalidAccount() { + return Any.pack(BalanceContract.CancelAllUnfreezeV2Contract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ACCOUNT_INVALID))).build() + ); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java index a5341c22c3c..3a23151f6bc 100644 --- a/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ClearABIContractActuatorTest.java @@ -1,43 +1,34 @@ package org.tron.core.actuator; import static junit.framework.TestCase.fail; -import static stest.tron.wallet.common.client.utils.PublicMethed.jsonStr2Abi; +import static org.tron.common.utils.PublicMethod.jsonStr2Abi; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; -import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol; import org.tron.protos.contract.AssetIssueContractOuterClass; import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; - @Slf4j -public class ClearABIContractActuatorTest { +public class ClearABIContractActuatorTest extends BaseTest { - private static final String dbPath = "output_clearabicontract_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String SECOND_ACCOUNT_ADDRESS; @@ -50,12 +41,9 @@ public class ClearABIContractActuatorTest { "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\"" + ":\"constructor\"}]"); private static final ABI TARGET_ABI = ABI.getDefaultInstance(); - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -63,34 +51,12 @@ public class ClearABIContractActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - VMConfig.initAllowTvmConstantinople(1); - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { + dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); // address in accountStore and the owner of contract AccountCapsule accountCapsule = new AccountCapsule( diff --git a/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java index 11c8f7754fc..f756f3dd087 100755 --- a/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/CreateAccountActuatorTest.java @@ -1,27 +1,21 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -30,19 +24,15 @@ import org.tron.protos.contract.AssetIssueContractOuterClass; @Slf4j -public class CreateAccountActuatorTest { +public class CreateAccountActuatorTest extends BaseTest { - private static final String dbPath = "output_CreateAccount_test"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; private static final String INVALID_ACCOUNT_ADDRESS; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -50,32 +40,6 @@ public class CreateAccountActuatorTest { INVALID_ACCOUNT_ADDRESS = Wallet.getAddressPreFixString() + "12344500882809695a8a687866"; } - /** - * 548794500882809695a8a687866e76d4271a1abc Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java new file mode 100644 index 00000000000..95577f46e50 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/DelegateResourceActuatorTest.java @@ -0,0 +1,890 @@ +package org.tron.core.actuator; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; +import static org.tron.protos.contract.Common.ResourceCode.TRON_POWER; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; + +@Slf4j +public class DelegateResourceActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "aaaa"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 1000_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + /** + * create temp Capsule test need. + */ + @Before + public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(0L); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(owner), + AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + AccountCapsule receiverCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(receiver), + AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + + // clear delegate + dbManager.getDelegatedResourceStore().delete(DelegatedResourceCapsule.createDbKeyV2( + owner, receiver, false)); + dbManager.getDelegatedResourceStore().delete(DelegatedResourceCapsule.createDbKeyV2( + owner, receiver, true)); + dbManager.getDelegatedResourceAccountIndexStore().unDelegateV2(owner, receiver); + } + + public void freezeBandwidthForOwner() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.addFrozenBalanceForBandwidthV2(initBalance); + dbManager.getDynamicPropertiesStore().addTotalNetWeight(initBalance / TRX_PRECISION); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + } + + public void freezeCpuForOwner() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.addFrozenBalanceForEnergyV2(initBalance); + dbManager.getDynamicPropertiesStore().addTotalEnergyWeight(initBalance / TRX_PRECISION); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + } + + private Any getDelegateContractForBandwidth(String ownerAddress, String receiveAddress, + long unfreezeBalance) { + return getLockedDelegateContractForBandwidth(ownerAddress, receiveAddress, + unfreezeBalance, false); + } + + private Any getLockedDelegateContractForBandwidth(String ownerAddress, String receiveAddress, + long unfreezeBalance, boolean lock) { + return Any.pack(DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(receiveAddress))) + .setBalance(unfreezeBalance) + .setResource(BANDWIDTH) + .setLock(lock) + .build()); + } + + private Any getMaxDelegateLockPeriodContractForBandwidth(long unfreezeBalance, long lockPeriod) { + return Any.pack(DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(unfreezeBalance) + .setResource(BANDWIDTH) + .setLock(true) + .setLockPeriod(lockPeriod) + .build()); + } + + private Any getMaxDelegateLockPeriodContractForEnergy(long unfreezeBalance, long lockPeriod) { + return Any.pack(DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(unfreezeBalance) + .setResource(ENERGY) + .setLock(true) + .setLockPeriod(lockPeriod) + .build()); + } + + private Any getDelegateContractForCpu(long unfreezeBalance) { + return Any.pack( + DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(unfreezeBalance) + .setResource(ENERGY) + .build()); + } + + private Any getDelegateContractForTronPower(long unfreezeBalance) { + return Any.pack( + DelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(unfreezeBalance) + .setResource(TRON_POWER) + .build()); + } + + @Test + public void testDelegateResourceWithNoFreeze() { + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth( + OWNER_ADDRESS, + RECEIVER_ADDRESS, + 1_000_000_000L)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", + e.getMessage()); + } catch (ContractExeException e) { + fail(); + } + + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForCpu(1_000_000_000L)); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals( + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void testDelegateBandwidthWithUsage() { + freezeBandwidthForOwner(); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + DynamicPropertiesStore dynamicPropertiesStore = dbManager.getDynamicPropertiesStore(); + ownerCapsule.setNetUsage(dynamicPropertiesStore.getTotalNetLimit() / 4); + ownerCapsule.setLatestConsumeTime(dbManager.getChainBaseManager().getHeadSlot()); + dbManager.getAccountStore().put(owner, ownerCapsule); + + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, initBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void testDelegateCpuWithUsage() { + freezeCpuForOwner(); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + DynamicPropertiesStore dynamicPropertiesStore = dbManager.getDynamicPropertiesStore(); + ownerCapsule.setEnergyUsage(dynamicPropertiesStore.getTotalEnergyCurrentLimit() / 4); + ownerCapsule.setLatestConsumeTimeForEnergy(dbManager.getChainBaseManager().getHeadSlot()); + dbManager.getAccountStore().put(owner, ownerCapsule); + + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForCpu(initBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals( + "delegateBalance must be less than or equal to available FreezeEnergyV2 balance", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + + @Test + public void testDelegateResourceWithContractAddress() { + freezeBandwidthForOwner(); + AccountCapsule receiverCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + AccountType.Contract, + initBalance); + dbManager.getAccountStore().put(ByteArray.fromHexString(RECEIVER_ADDRESS), receiverCapsule); + + + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, 1_000_000_000L)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + } catch (ContractValidateException e) { + assertEquals("Do not allow delegate resources to contract addresses", e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void testDelegateResourceToSelf() { + freezeBandwidthForOwner(); + + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, OWNER_ADDRESS, 1_000_000_000L)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + } catch (ContractValidateException e) { + assertEquals("receiverAddress must not be the same as ownerAddress", e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void testDelegateResourceForBandwidth() { + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + long totalNetWeightBefore = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(owner); + + assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(initBalance - delegateBalance, + ownerCapsule.getFrozenV2BalanceForBandwidth()); + assertEquals(initBalance, ownerCapsule.getTronPower()); + + AccountCapsule receiverCapsule = + dbManager.getAccountStore().get(receiver); + assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + assertEquals(0L, receiverCapsule.getTronPower()); + + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), false)); + + assertEquals(delegateBalance, delegatedResourceCapsule.getFrozenBalanceForBandwidth()); + long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + assertEquals(totalNetWeightBefore, totalNetWeightAfter); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + assertTrue(ownerIndexCapsule.getToAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); + + DelegatedResourceAccountIndexCapsule receiveCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + assertEquals(0, receiveCapsule.getToAccountsList().size()); + assertEquals(1, receiveCapsule.getFromAccountsList().size()); + assertTrue(receiveCapsule.getFromAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); + + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void testLockedDelegateResourceForBandwidth() { + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getLockedDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, + delegateBalance, true)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + long totalNetWeightBefore = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(owner); + + assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(initBalance - delegateBalance, + ownerCapsule.getFrozenV2BalanceForBandwidth()); + assertEquals(initBalance, ownerCapsule.getTronPower()); + + AccountCapsule receiverCapsule = + dbManager.getAccountStore().get(receiver); + assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + assertEquals(0L, receiverCapsule.getTronPower()); + + //check DelegatedResource + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), true)); + assertNull(delegatedResourceCapsule); + assertNotNull(lockedResourceCapsule); + assertNotEquals(0, lockedResourceCapsule.getExpireTimeForBandwidth()); + assertEquals(delegateBalance, lockedResourceCapsule.getFrozenBalanceForBandwidth()); + long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + assertEquals(totalNetWeightBefore, totalNetWeightAfter); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + assertTrue(ownerIndexCapsule.getToAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); + + DelegatedResourceAccountIndexCapsule receiveCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + assertEquals(0, receiveCapsule.getToAccountsList().size()); + assertEquals(1, receiveCapsule.getFromAccountsList().size()); + assertTrue(receiveCapsule.getFromAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); + + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void testMaxDelegateLockPeriodForBandwidthWrongLockPeriod1() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(86401); + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 370 * 24 * 3600)); + assertThrows("The lock period of delegate resources cannot exceed 1 year!", + ContractValidateException.class, actuator::validate); + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testMaxDelegateLockPeriodForBandwidthWrongLockPeriod2() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 30)); + assertThrows("The lock period for bandwidth this time cannot be less than the remaining" + + " time[60000s] of the last lock period for bandwidth!", + ContractValidateException.class, actuator1::validate); + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testMaxDelegateLockPeriodForBandwidth() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(50_000L); + freezeBandwidthForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForBandwidth( + delegateBalance, 60)); + + TransactionResultCapsule ret1 = new TransactionResultCapsule(); + try { + actuator1.validate(); + actuator1.execute(ret1); + assertEquals(code.SUCESS, ret1.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), true)); + long expireTimeForBandwidth = lockedResourceCapsule.getExpireTimeForBandwidth(); + assertEquals(50_000L + 60 * 3 * 1000, expireTimeForBandwidth); + assertTrue(expireTimeForBandwidth > 60_000); + } + + @Test + public void testMaxDelegateLockPeriodForEnergy() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(50_000L); + freezeCpuForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 60)); + + TransactionResultCapsule ret1 = new TransactionResultCapsule(); + try { + actuator1.validate(); + actuator1.execute(ret1); + assertEquals(code.SUCESS, ret1.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule + .createDbKeyV2(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS), true)); + assertTrue(lockedResourceCapsule.getExpireTimeForEnergy() > 60_000); + } + + @Test + public void testMaxDelegateLockPeriodForEnergyWrongLockPeriod2() { + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + freezeCpuForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 60)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + + DelegateResourceActuator actuator1 = new DelegateResourceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getMaxDelegateLockPeriodContractForEnergy( + delegateBalance, 30)); + assertThrows("The lock period for energy this time cannot be less than the remaining" + + " time[60000s] of the last lock period for energy!", + ContractValidateException.class, actuator1::validate); + } + + @Test + public void testDelegateResourceForCpu() { + freezeCpuForOwner(); + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForCpu(delegateBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + long totalEnergyWeightBefore = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(owner); + + assertEquals(initBalance, ownerCapsule.getBalance()); + assertEquals(0L, ownerCapsule.getFrozenBalance()); + assertEquals(0L, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + assertEquals(initBalance, ownerCapsule.getTronPower()); + + AccountCapsule receiverCapsule = + dbManager.getAccountStore().get(receiver); + assertEquals(0L, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + assertEquals(0L, receiverCapsule.getTronPower()); + + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + + assertEquals(0L, delegatedResourceCapsule.getFrozenBalanceForBandwidth()); + assertEquals(delegateBalance, delegatedResourceCapsule.getFrozenBalanceForEnergy()); + + long totalEnergyWeightAfter = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); + assertEquals(totalEnergyWeightBefore, totalEnergyWeightAfter); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + assertTrue(ownerIndexCapsule.getToAccountsList() + .contains(ByteString.copyFrom(receiver))); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + assertEquals(1, + receiverIndexCapsule.getFromAccountsList().size()); + assertTrue(receiverIndexCapsule.getFromAccountsList() + .contains(ByteString.copyFrom(owner))); + + } catch (ContractValidateException | ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void delegateLessThanZero() { + long delegateBalance = -1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals("delegateBalance must be greater than or equal to 1 TRX", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void delegateTronPower() { + long delegateBalance = 1_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForTronPower(delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals("ResourceCode error, valid ResourceCode[BANDWIDTH、ENERGY]", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + + @Test + public void delegateMoreThanBalance() { + long delegateBalance = 11_000_000_000L; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void invalidOwnerAddress() { + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS_INVALID, RECEIVER_ADDRESS, 1_000_000_000L)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + assertEquals("Invalid address", e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void invalidReceiverAddress() { + freezeBandwidthForOwner(); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, OWNER_ADDRESS_INVALID, 1_000_000_000L)); + assertThrows("Invalid receiverAddress", ContractValidateException.class, actuator::validate); + } + + @Test + public void invalidOwnerAccount() { + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ACCOUNT_INVALID, RECEIVER_ADDRESS, 1_000_000_000L)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", + e.getMessage()); + } catch (ContractExeException e) { + fail(e.getMessage()); + } + } + + @Test + public void commonErrorCheck() { + freezeBandwidthForOwner(); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + ActuatorTest actuatorTest = new ActuatorTest(actuator, dbManager); + actuatorTest.noContract(); + + Any invalidContractTypes = Any.pack(AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .build()); + actuatorTest.setInvalidContract(invalidContractTypes); + actuatorTest.setInvalidContractTypeMsg("contract type error", + "contract type error,expected type [DelegateResourceContract],real type["); + actuatorTest.invalidContractType(); + + actuatorTest.setContract( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, 1_000_000_000L)); + actuatorTest.nullTransationResult(); + + actuatorTest.setNullDBManagerMsg("No account store or dynamic store!"); + actuatorTest.nullDBManger(); + } + + @Test + public void testSupportDelegateResource() { + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(0); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, + RECEIVER_ADDRESS, + 1_000_000_000L)); + assertThrows( + "No support for resource delegate", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testSupportUnfreezeDelay() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0); + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegateContractForBandwidth( + OWNER_ADDRESS, + RECEIVER_ADDRESS, + 1_000_000_000L)); + assertThrows( + "Not support Delegate resource transaction, need to be opened by the committee", + ContractValidateException.class, actuator::validate); + } + + @Test + public void testErrorContract() { + DelegateResourceActuator actuator = new DelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getErrorContract()); + assertThrows( + "contract type error, expected type [DelegateResourceContract], " + + "real type[WithdrawExpireUnfreezeContract]", + ContractValidateException.class, actuator::validate); + } + + private Any getErrorContract() { + return Any.pack(BalanceContract.WithdrawExpireUnfreezeContract.newBuilder().setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))).build() + ); + } + + + /** + * We calculate the size of the structure and conclude that + * delegate_balance = 1000_000L; => 277 + * delegate_balance = 1000_000_000L; => 279 + * delegate_balance = 1000_000_000_000L => 280 + * + * We initialize account information as follows + * account balance = 1000_000_000_000L + * account frozen_balance = 1000_000_000L + * + * then estimateConsumeBandWidthSize cost 279 + * + * so we have following result: + * TransactionUtil.estimateConsumeBandWidthSize( + * dynamicStore,ownerCapsule.getBalance()) ===> false + * TransactionUtil.estimateConsumeBandWidthSize( + * dynamicStore,ownerCapsule.getFrozenV2BalanceForBandwidth()) ===> true + * + * This test case is used to verify the above conclusions + */ + @Test + public void testDelegateResourceNoFreeze123() { + long frozenBalance = 1000_000_000L; + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + ownerCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + dbManager.getDynamicPropertiesStore().addTotalNetWeight( + frozenBalance / TRX_PRECISION + 43100000000L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + long delegateBalance = frozenBalance - 279 * TRX_PRECISION; + //long delegateBalance = initBalance; + DelegateResourceActuator actuator = new DelegateResourceActuator(); + TransactionCapsule transactionCapsule = new TransactionCapsule( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance), + Protocol.Transaction.Contract.ContractType.DelegateResourceContract + ); + transactionCapsule.setTransactionCreate(true); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegateContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS, delegateBalance)); + actuator.setTx(transactionCapsule); + + boolean bSuccess = true; + try { + actuator.validate(); + } catch (ContractValidateException e) { + assertEquals( + "delegateBalance must be less than or equal to available FreezeBandwidthV2 balance", + e.getMessage()); + bSuccess = false; + } + Assert.assertEquals(true, bSuccess); + } + +} diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java index 517d64a3b6f..179ba56e7ed 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeCreateActuatorTest.java @@ -1,31 +1,24 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -37,53 +30,23 @@ @Slf4j -public class ExchangeCreateActuatorTest { +public class ExchangeCreateActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeCreate_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -92,18 +55,6 @@ public static void destroy() { @Before public void initTest() { - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_FIRST))); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_SECOND))); - dbManager.getAccountAssetStore().put(ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put(ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - - AccountCapsule ownerAccountFirstCapsule = new AccountCapsule( ByteString.copyFromUtf8(ACCOUNT_NAME_FIRST), @@ -174,8 +125,8 @@ public void sameTokenNameCloseSuccessExchangeCreate() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -206,7 +157,7 @@ public void sameTokenNameCloseSuccessExchangeCreate() { Assert.assertEquals(secondTokenBalance, exchangeCapsule.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L - 1024_000000L, accountCapsule.getBalance()); Assert.assertEquals(0L, assetMap.get(firstTokenId).longValue()); Assert.assertEquals(0L, assetMap.get(secondTokenId).longValue()); @@ -229,7 +180,7 @@ public void sameTokenNameCloseSuccessExchangeCreate() { Assert.assertEquals(secondTokenBalance, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map getAssetV2Map = accountCapsule.getAssetMapV2(); + Map getAssetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L - 1024_000000L, accountCapsule.getBalance()); Assert.assertEquals(0L, getAssetV2Map.get(firstTokenId).longValue()); Assert.assertEquals(0L, getAssetV2Map.get(secondTokenId).longValue()); @@ -265,7 +216,7 @@ public void sameTokenNameCloseSuccessExchangeCreate2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.setBalance(200_000_000_000000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L, true); dbManager.getAccountStore().put(ownerAddress, accountCapsule); ExchangeCreateActuator actuator = new ExchangeCreateActuator(); @@ -292,7 +243,7 @@ public void sameTokenNameCloseSuccessExchangeCreate2() { Assert.assertEquals(secondTokenBalance, exchangeCapsule.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(200_000_000_000000L - 1024_000000L - firstTokenBalance, accountCapsule.getBalance()); Assert.assertEquals(100_000_000L, assetMap.get(secondTokenId).longValue()); @@ -313,7 +264,7 @@ public void sameTokenNameCloseSuccessExchangeCreate2() { Assert.assertEquals(secondTokenBalance, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map getAssetV2Map = accountCapsule.getAssetMapV2(); + Map getAssetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(200_000_000_000000L - 1024_000000L - firstTokenBalance, accountCapsule.getBalance()); Assert.assertEquals(100_000_000L, getAssetV2Map.get(secondTokenId).longValue()); @@ -383,7 +334,7 @@ public void oldNotUpdateSuccessExchangeCreate2() { Assert.assertEquals(secondTokenBalance, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map getAssetV2Map = accountCapsule.getAssetMapV2(); + Map getAssetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(200_000_000_000000L - 1024_000000L - firstTokenBalance, accountCapsule.getBalance()); Assert.assertEquals(100_000_000L, getAssetV2Map.get(secondTokenId).longValue()); @@ -459,15 +410,14 @@ public void sameTokenNameOpenSuccessExchangeCreate() { Assert.assertEquals(id, exchangeCapsuleV2.getID()); Assert.assertEquals(1000000, exchangeCapsuleV2.getCreateTime()); - Assert - .assertTrue(Arrays.equals(firstTokenId.getBytes(), exchangeCapsuleV2.getFirstTokenId())); + Assert.assertArrayEquals(firstTokenId.getBytes(), exchangeCapsuleV2.getFirstTokenId()); Assert.assertEquals(firstTokenId, ByteArray.toStr(exchangeCapsuleV2.getFirstTokenId())); Assert.assertEquals(firstTokenBalance, exchangeCapsuleV2.getFirstTokenBalance()); Assert.assertEquals(secondTokenId, ByteArray.toStr(exchangeCapsuleV2.getSecondTokenId())); Assert.assertEquals(secondTokenBalance, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map getAssetV2Map = accountCapsule.getAssetMapV2(); + Map getAssetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L - 1024_000000L, accountCapsule.getBalance()); Assert.assertEquals(0L, getAssetV2Map.get(firstTokenId).longValue()); Assert.assertEquals(0L, getAssetV2Map.get(secondTokenId).longValue()); @@ -537,7 +487,7 @@ public void sameTokenNameOpenSuccessExchangeCreate2() { Assert.assertEquals(secondTokenBalance, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map getAssetV2Map = accountCapsule.getAssetMapV2(); + Map getAssetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(200_000_000_000000L - 1024_000000L - firstTokenBalance, accountCapsule.getBalance()); Assert.assertEquals(100_000_000L, getAssetV2Map.get(secondTokenId).longValue()); @@ -760,8 +710,8 @@ public void sameTokenNameCloseNoEnoughBalance() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(1000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -798,8 +748,8 @@ public void sameTokenNameOpenNoEnoughBalance() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(1000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -835,8 +785,8 @@ public void sameTokenNameCloseSameTokens() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -872,8 +822,8 @@ public void sameTokenNameOpenSameTokens() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -909,8 +859,8 @@ public void sameTokenNameCloseLessToken() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 1000); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 1000, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -947,8 +897,8 @@ public void sameTokenNameOpenLessToken() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 1000); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 1000, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -984,8 +934,8 @@ public void sameTokenNameCloseMoreThanBalanceLimit() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1022,8 +972,8 @@ public void sameTokenNameOpenMoreThanBalanceLimit() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1060,7 +1010,7 @@ public void sameTokenNameCloseBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.setBalance(firstTokenBalance + 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L, false); dbManager.getAccountStore().put(ownerAddress, accountCapsule); ExchangeCreateActuator actuator = new ExchangeCreateActuator(); @@ -1097,7 +1047,7 @@ public void sameTokenNameOpenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.setBalance(firstTokenBalance + 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L, false); dbManager.getAccountStore().put(ownerAddress, accountCapsule); ExchangeCreateActuator actuator = new ExchangeCreateActuator(); @@ -1132,8 +1082,8 @@ public void sameTokenNameCloseFirstTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance - 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance - 1000L, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1170,8 +1120,8 @@ public void sameTokenNameOpenFirstTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance - 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance - 1000L, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1208,7 +1158,7 @@ public void sameTokenNameCloseBalanceNotEnough2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.setBalance(secondTokenBalance + 1000L); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 200_000_000L, false); dbManager.getAccountStore().put(ownerAddress, accountCapsule); ExchangeCreateActuator actuator = new ExchangeCreateActuator(); @@ -1245,7 +1195,7 @@ public void sameTokenNameOpenBalanceNotEnough2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.setBalance(secondTokenBalance + 1000L); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 200_000_000L, false); dbManager.getAccountStore().put(ownerAddress, accountCapsule); ExchangeCreateActuator actuator = new ExchangeCreateActuator(); @@ -1280,8 +1230,8 @@ public void sameTokenNameCloseSecondTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 90_000_000L); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 90_000_000L, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1318,8 +1268,8 @@ public void sameTokenNameOpenSecondTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 90_000_000L); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 90_000_000L, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1355,7 +1305,7 @@ public void sameTokenNameCloseSecondTokenNotExist() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1392,7 +1342,7 @@ public void sameTokenNameOpenSecondTokenNotExist() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenBalance, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1438,7 +1388,7 @@ public void commonErrorCheck() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.setBalance(200_000_000_000000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), 200_000_000L, true); dbManager.getAccountStore().put(ownerAddress, accountCapsule); actuatorTest.setContract(getContract( diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java index 9f792e871ef..7aef11ed793 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeInjectActuatorTest.java @@ -1,32 +1,25 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -38,53 +31,23 @@ @Slf4j -public class ExchangeInjectActuatorTest { +public class ExchangeInjectActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeInject_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -92,19 +55,6 @@ public static void destroy() { */ @Before public void initTest() { - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_FIRST))); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_SECOND))); - dbManager.getAccountAssetStore().put( - ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put( - ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - AccountCapsule ownerAccountFirstCapsule = new AccountCapsule( ByteString.copyFromUtf8(ACCOUNT_NAME_FIRST), @@ -240,8 +190,8 @@ public void SameTokenNameCloseSuccessExchangeInject() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -278,7 +228,7 @@ public void SameTokenNameCloseSuccessExchangeInject() { Assert.assertEquals(600000000L, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(0L, assetMap.get(firstTokenId).longValue()); Assert.assertEquals(0L, assetMap.get(secondTokenId).longValue()); @@ -372,7 +322,7 @@ public void OldNotUpdateSuccessExchangeInject() { Assert.assertEquals(600000000L, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMapV2(); + Map assetMap = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(0L, assetMap.get(String.valueOf(1)).longValue()); Assert.assertEquals(0L, assetMap.get(String.valueOf(2)).longValue()); @@ -460,7 +410,7 @@ public void SameTokenNameOpenSuccessExchangeInject() { Assert.assertEquals(600000000L, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(0L, assetV2Map.get(firstTokenId).longValue()); Assert.assertEquals(0L, assetV2Map.get(secondTokenId).longValue()); @@ -501,7 +451,7 @@ public void SameTokenNameCloseSuccessExchangeInject2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(firstTokenQuant); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -538,7 +488,7 @@ public void SameTokenNameCloseSuccessExchangeInject2() { Assert.assertEquals(11_000_000L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(0L, accountCapsule.getBalance()); Assert.assertEquals(3_000_000L, assetMap.get(secondTokenId).longValue()); @@ -614,7 +564,7 @@ public void SameTokenNameOpenSuccessExchangeInject2() { Assert.assertEquals(11_000_000L, exchangeV2Capsule.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(0L, accountCapsule.getBalance()); Assert.assertEquals(3_000_000L, assetV2Map.get(secondTokenId).longValue()); @@ -781,8 +731,8 @@ public void SameTokenNameCloseExchangeNotExist() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -869,8 +819,8 @@ public void SameTokenNameCloseAccountIsNotCreator() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -960,7 +910,7 @@ public void SameTokenNameCloseTokenIsNotInExchange() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(firstTokenQuant); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1045,8 +995,8 @@ public void SameTokenNameCloseTokenBalanceZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1149,8 +1099,8 @@ public void SameTokenNameCloseTokenQuantLessThanZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000L, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1237,7 +1187,7 @@ public void SameTokenNameCloseCalculatedTokenQuantLessThanZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(firstTokenQuant); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1323,7 +1273,7 @@ public void SameTokenNameCloseTokenBalanceGreaterThanBalanceLimit() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(firstTokenQuant); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1408,7 +1358,7 @@ public void SameTokenNameCloseBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(firstTokenQuant - 1); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1495,8 +1445,8 @@ public void SameTokenNameCloseTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant - 1); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant - 1, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1583,7 +1533,7 @@ public void SameTokenNameCloseBalanceNotEnough2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(399_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1668,8 +1618,8 @@ public void SameTokenNameCloseAnotherTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant - 1); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant - 1, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1835,8 +1785,8 @@ public void sameTokennullTransationResult() { TransactionResultCapsule ret = null; byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java index bb2dd131683..d39706e0699 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeTransactionActuatorTest.java @@ -1,33 +1,26 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import junit.framework.TestCase; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -39,53 +32,23 @@ @Slf4j -public class ExchangeTransactionActuatorTest { +public class ExchangeTransactionActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeTransaction_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -93,19 +56,6 @@ public static void destroy() { */ @Before public void initTest() { - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_FIRST))); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_SECOND))); - dbManager.getAccountAssetStore().put( - ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put( - ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - AccountCapsule ownerAccountFirstCapsule = new AccountCapsule( ByteString.copyFromUtf8(ACCOUNT_NAME_FIRST), @@ -247,7 +197,7 @@ public void SameTokenNameCloseSuccessExchangeTransaction() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get("def")); @@ -293,7 +243,7 @@ public void SameTokenNameCloseSuccessExchangeTransaction() { Assert.assertEquals(9999001L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetMap = accountCapsule.getAssetMap(); + assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L - quant, accountCapsule.getBalance()); Assert.assertEquals(999L, assetMap.get("abc").longValue()); @@ -325,7 +275,7 @@ public void oldNotUpdateSuccessExchangeTransaction() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get("def")); @@ -372,7 +322,7 @@ public void oldNotUpdateSuccessExchangeTransaction() { Assert.assertEquals(9999001L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetMap = accountCapsule.getAssetMapV2(); + assetMap = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L - quant, accountCapsule.getBalance()); Assert.assertEquals(999L, assetMap.get("1").longValue()); @@ -404,7 +354,7 @@ public void SameTokenNameOpenSuccessExchangeTransaction() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get("456")); @@ -445,7 +395,7 @@ public void SameTokenNameOpenSuccessExchangeTransaction() { Assert.assertEquals(9999001L, exchangeV2Capsule.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetV2Map = accountCapsule.getAssetMapV2(); + assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L - quant, accountCapsule.getBalance()); Assert.assertEquals(999L, assetV2Map.get("123").longValue()); @@ -480,8 +430,8 @@ public void SameTokenNameCloseSuccessExchangeTransaction2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -528,7 +478,7 @@ public void SameTokenNameCloseSuccessExchangeTransaction2() { Assert.assertEquals(199998001L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetMap = accountCapsule.getAssetMap(); + assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(9000L, assetMap.get("abc").longValue()); Assert.assertEquals(1999L, assetMap.get("def").longValue()); @@ -563,7 +513,7 @@ public void SameTokenNameOpenSuccessExchangeTransaction2() { AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -605,7 +555,7 @@ public void SameTokenNameOpenSuccessExchangeTransaction2() { Assert.assertEquals(199998001L, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetV2Map = accountCapsule.getAssetMapV2(); + assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(9000L, assetV2Map.get("123").longValue()); Assert.assertEquals(1999L, assetV2Map.get("456").longValue()); @@ -638,8 +588,8 @@ public void SameTokenNameCloseInvalidAddress() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, false); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -685,7 +635,7 @@ public void SameTokenNameOpenInvalidAddress() { accountCapsule.addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -729,8 +679,8 @@ public void SameTokenNameCloseNoEnoughBalance() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, false); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); @@ -779,8 +729,8 @@ public void SameTokenNameOpenNoEnoughBalance() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); @@ -829,8 +779,8 @@ public void SameTokenNameCloseNoAccount() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -877,7 +827,7 @@ public void SameTokenNameOpenNoAccount() { accountCapsule.addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -920,8 +870,8 @@ public void SameTokenNameCloseExchangeNotExist() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -966,7 +916,7 @@ public void SameTokenNameOpenExchangeNotExist() { AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1009,8 +959,8 @@ public void SameTokenNameCloseTokenIsNotInExchange() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1056,7 +1006,7 @@ public void SameTokenNameOpenTokenIsNotInExchange() { accountCapsule .addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1099,8 +1049,8 @@ public void SameTokenNameCloseTokenBalanceZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1154,7 +1104,7 @@ public void SameTokenNameOpenTokenBalanceZero() { accountCapsule .addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1205,8 +1155,8 @@ public void SameTokenNameCloseTokenQuantLessThanZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1252,7 +1202,7 @@ public void SameTokenNameOpenTokenQuantLessThanZero() { accountCapsule .addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1295,8 +1245,8 @@ public void SameTokenNameCloseTokenBalanceGreaterThanBalanceLimit() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), 10000); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), 10000, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1342,7 +1292,7 @@ public void SameTokenNameOpenTokenBalanceGreaterThanBalanceLimit() { accountCapsule .addAssetAmountV2(tokenId.getBytes(), 10000, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1385,7 +1335,7 @@ public void SameTokenNameCloseBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); accountCapsule.setBalance(quant - 1); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1428,7 +1378,7 @@ public void SameTokenNameOpenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); accountCapsule.setBalance(quant - 1); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1471,8 +1421,8 @@ public void SameTokenNameCloseTokenBalanceNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), quant - 1); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), quant - 1, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1517,7 +1467,7 @@ public void SameTokenNameOpenTokenBalanceNotEnough() { AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); accountCapsule.addAssetAmountV2(tokenId.getBytes(), quant - 1, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1552,6 +1502,7 @@ public void SameTokenNameOpenTokenBalanceNotEnough() { @Test public void SameTokenNameCloseTokenRequiredNotEnough() { dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(0); + final boolean useStrictMath = dbManager.getDynamicPropertiesStore().allowStrictMath(); InitExchangeBeforeSameTokenNameActive(); long exchangeId = 2; String tokenId = "abc"; @@ -1560,8 +1511,8 @@ public void SameTokenNameCloseTokenRequiredNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(tokenId.getBytes(), quant); - Map assetMap = accountCapsule.getAssetMap(); + accountCapsule.addAssetAmount(tokenId.getBytes(), quant, true); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1570,7 +1521,7 @@ public void SameTokenNameCloseTokenRequiredNotEnough() { try { ExchangeCapsule exchangeCapsule = dbManager.getExchangeStore() .get(ByteArray.fromLong(exchangeId)); - expected = exchangeCapsule.transaction(tokenId.getBytes(), quant); + expected = exchangeCapsule.transaction(tokenId.getBytes(), quant, useStrictMath); } catch (ItemNotFoundException e) { fail(); } @@ -1605,6 +1556,7 @@ public void SameTokenNameCloseTokenRequiredNotEnough() { @Test public void SameTokenNameOpenTokenRequiredNotEnough() { dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); + final boolean useStrictMath = dbManager.getDynamicPropertiesStore().allowStrictMath(); InitExchangeSameTokenNameActive(); long exchangeId = 2; String tokenId = "123"; @@ -1616,7 +1568,7 @@ public void SameTokenNameOpenTokenRequiredNotEnough() { accountCapsule .addAssetAmountV2(tokenId.getBytes(), quant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(20000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(buyTokenId)); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1625,7 +1577,7 @@ public void SameTokenNameOpenTokenRequiredNotEnough() { try { ExchangeCapsule exchangeCapsuleV2 = dbManager.getExchangeV2Store() .get(ByteArray.fromLong(exchangeId)); - expected = exchangeCapsuleV2.transaction(tokenId.getBytes(), quant); + expected = exchangeCapsuleV2.transaction(tokenId.getBytes(), quant, useStrictMath); } catch (ItemNotFoundException e) { fail(); } diff --git a/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java index da23051a3c9..5c5536f873c 100644 --- a/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ExchangeWithdrawActuatorTest.java @@ -1,33 +1,26 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Arrays; import java.util.Map; import junit.framework.TestCase; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -39,53 +32,23 @@ @Slf4j -public class ExchangeWithdrawActuatorTest { +public class ExchangeWithdrawActuatorTest extends BaseTest { - private static final String dbPath = "output_ExchangeWithdraw_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; private static final String OWNER_ADDRESS_SECOND; - private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -111,11 +74,6 @@ public void initTest() { dbManager.getAccountStore() .put(ownerAccountSecondCapsule.getAddress().toByteArray(), ownerAccountSecondCapsule); - dbManager.getAccountAssetStore().put(ownerAccountFirstCapsule.getAddress().toByteArray(), - new AccountAssetCapsule(ownerAccountFirstCapsule.getAddress())); - dbManager.getAccountAssetStore().put(ownerAccountSecondCapsule.getAddress().toByteArray(), - new AccountAssetCapsule(ownerAccountSecondCapsule.getAddress())); - dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1000000); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(10); dbManager.getDynamicPropertiesStore().saveNextMaintenanceTime(2000000); @@ -278,7 +236,7 @@ public void SameTokenNameCloseSuccessExchangeWithdraw() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(firstTokenId)); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -314,7 +272,7 @@ public void SameTokenNameCloseSuccessExchangeWithdraw() { Assert.assertEquals(0L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetMap = accountCapsule.getAssetMap(); + assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(firstTokenQuant, assetMap.get(firstTokenId).longValue()); Assert.assertEquals(secondTokenQuant, assetMap.get(secondTokenId).longValue()); @@ -352,7 +310,7 @@ public void oldNotUpdateSuccessExchangeWithdraw() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(firstTokenId)); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -389,7 +347,7 @@ public void oldNotUpdateSuccessExchangeWithdraw() { Assert.assertEquals(0L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetMap = accountCapsule.getAssetMapV2(); + assetMap = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(firstTokenQuant, assetMap.get(String.valueOf(1)).longValue()); Assert.assertEquals(secondTokenQuant, assetMap.get(String.valueOf(2)).longValue()); @@ -426,7 +384,7 @@ public void SameTokenNameOpenSuccessExchangeWithdraw() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(firstTokenId)); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); @@ -458,7 +416,7 @@ public void SameTokenNameOpenSuccessExchangeWithdraw() { Assert.assertEquals(0L, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetV2Map = accountCapsule.getAssetMapV2(); + assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(firstTokenQuant, assetV2Map.get(firstTokenId).longValue()); Assert.assertEquals(secondTokenQuant, assetV2Map.get(secondTokenId).longValue()); @@ -493,7 +451,7 @@ public void SameTokenNameCloseSuccessExchangeWithdraw2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -530,7 +488,7 @@ public void SameTokenNameCloseSuccessExchangeWithdraw2() { Assert.assertEquals(0L, exchangeCapsule2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetMap = accountCapsule.getAssetMap(); + assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(firstTokenQuant + 10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(10_000_000L, assetMap.get(secondTokenId).longValue()); @@ -564,7 +522,7 @@ public void SameTokenNameOpenSuccessExchangeWithdraw2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); @@ -595,7 +553,7 @@ public void SameTokenNameOpenSuccessExchangeWithdraw2() { Assert.assertEquals(0L, exchangeCapsuleV2.getSecondTokenBalance()); accountCapsule = dbManager.getAccountStore().get(ownerAddress); - assetV2Map = accountCapsule.getAssetMapV2(); + assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(firstTokenQuant + 10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(10_000_000L, assetV2Map.get(secondTokenId).longValue()); @@ -629,7 +587,7 @@ public void SameTokenNameCloseInvalidAddress() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(firstTokenId)); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -672,7 +630,7 @@ public void SameTokenNameOpenInvalidAddress() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(firstTokenId)); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); @@ -716,7 +674,7 @@ public void SameTokenNameCloseNoAccount() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(firstTokenId)); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -761,7 +719,7 @@ public void SameTokenNameOpenNoAccount() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(firstTokenId)); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); @@ -805,7 +763,7 @@ public void SameTokenNameCloseExchangeNotExist() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(firstTokenId)); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -849,7 +807,7 @@ public void SameTokenNameOpenExchangeNotExist() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(firstTokenId)); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); @@ -893,8 +851,8 @@ public void SameTokenNameCloseAccountIsNotCreator() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -985,7 +943,7 @@ public void SameTokenNameCloseTokenIsNotInExchange() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(firstTokenQuant); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1072,8 +1030,8 @@ public void SameTokenNameCloseTokenBalanceZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), firstTokenQuant, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1178,8 +1136,8 @@ public void SameTokenNameCloseTokenQuantLessThanZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000L, true); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, true); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1269,8 +1227,8 @@ public void SameTokenNameCloseTnotherTokenQuantLessThanZero() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000L); - accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant); + accountCapsule.addAssetAmount(firstTokenId.getBytes(), 1000L, false); + accountCapsule.addAssetAmount(secondTokenId.getBytes(), secondTokenQuant, false); accountCapsule.setBalance(10000_000000L); dbManager.getAccountStore().put(ownerAddress, accountCapsule); @@ -1580,7 +1538,7 @@ public void SameTokenNameCloseExchangeBalanceIsNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(firstTokenId)); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -1624,7 +1582,7 @@ public void SameTokenNameOpenExchangeBalanceIsNotEnough() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(firstTokenId)); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); @@ -1668,7 +1626,7 @@ public void SameTokenNameCloseExchangeBalanceIsNotEnough2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetMap = accountCapsule.getAssetMap(); + Map assetMap = accountCapsule.getAssetMapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetMap.get(secondTokenId)); @@ -1711,7 +1669,7 @@ public void SameTokenNameOpenExchangeBalanceIsNotEnough2() { byte[] ownerAddress = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Map assetV2Map = accountCapsule.getAssetMapV2(); + Map assetV2Map = accountCapsule.getAssetV2MapForTest(); Assert.assertEquals(10000_000000L, accountCapsule.getBalance()); Assert.assertEquals(null, assetV2Map.get(secondTokenId)); diff --git a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java index b2e84d39095..18eef50c36f 100644 --- a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceActuatorTest.java @@ -5,16 +5,15 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; +import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; +import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.Utils; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -22,10 +21,8 @@ import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ChainConstant; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -35,52 +32,22 @@ import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class FreezeBalanceActuatorTest { +public class FreezeBalanceActuatorTest extends BaseTest { - private static final String dbPath = "output_freeze_balance_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -169,7 +136,7 @@ public void testFreezeBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -177,10 +144,8 @@ public void testFreezeBalanceForBandwidth() { - TRANSFER_FEE); Assert.assertEquals(owner.getFrozenBalance(), frozenBalance); Assert.assertEquals(frozenBalance, owner.getTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -196,7 +161,7 @@ public void testFreezeBalanceForEnergy() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -205,10 +170,8 @@ public void testFreezeBalanceForEnergy() { Assert.assertEquals(0L, owner.getFrozenBalance()); Assert.assertEquals(frozenBalance, owner.getEnergyFrozenBalance()); Assert.assertEquals(frozenBalance, owner.getTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -238,9 +201,9 @@ public void testFreezeDelegatedBalanceForBandwidthWithContractAddress() { actuator.validate(); actuator.execute(ret); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), "Do not allow delegate resources to contract addresses"); + Assert.assertEquals("Do not allow delegate resources to contract addresses", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -259,7 +222,7 @@ public void testFreezeDelegatedBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -290,9 +253,8 @@ public void testFreezeDelegatedBalanceForBandwidth() { Assert .assertEquals(0, delegatedResourceAccountIndexCapsuleOwner.getFromAccountsList().size()); Assert.assertEquals(1, delegatedResourceAccountIndexCapsuleOwner.getToAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsuleReceiver = dbManager .getDelegatedResourceAccountIndexStore().get(ByteArray.fromHexString(RECEIVER_ADDRESS)); @@ -301,16 +263,77 @@ public void testFreezeDelegatedBalanceForBandwidth() { Assert .assertEquals(1, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void testMultiFreezeDelegatedBalanceForBandwidth() { + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + dbManager.getDynamicPropertiesStore().saveAllowDelegateOptimization(1L); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(10000L); + long frozenBalance = 1_000_000_000L; + long duration = 3; + final int RECEIVE_COUNT = 100; + String[] RECEIVE_ADDRESSES = new String[RECEIVE_COUNT + 1]; + + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = + new DelegatedResourceAccountIndexCapsule( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + for (int i = 0; i < RECEIVE_COUNT + 1; i++) { + ECKey ecKey = new ECKey(Utils.getRandom()); + RECEIVE_ADDRESSES[i] = ByteArray.toHexString(ecKey.getAddress()); + if (i != RECEIVE_COUNT) { + ownerIndexCapsule.addToAccount(ByteString.copyFrom(ecKey.getAddress())); + } + } + dbManager.getDelegatedResourceAccountIndexStore().put( + ByteArray.fromHexString(OWNER_ADDRESS), ownerIndexCapsule); + AccountCapsule receiverCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVE_ADDRESSES[RECEIVE_COUNT])), + AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + FreezeBalanceActuator actuator = new FreezeBalanceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForBandwidth( + OWNER_ADDRESS, RECEIVE_ADDRESSES[RECEIVE_COUNT], frozenBalance, duration)); + try { + ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getIndex(ByteArray.fromHexString(OWNER_ADDRESS)); + List beforeList = ownerIndexCapsule.getToAccountsList(); + actuator.validate(); + actuator.execute(ret); + + //check DelegatedResourceAccountIndex convert + ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + Assert.assertNull(ownerIndexCapsule); + + ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getIndex(ByteArray.fromHexString(OWNER_ADDRESS)); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + List tmpList = ownerIndexCapsule.getToAccountsList(); + Assert.assertEquals(RECEIVE_COUNT + 1, ownerIndexCapsule.getToAccountsList().size()); + for (int i = 0; i < RECEIVE_COUNT; i++) { + Assert.assertEquals(beforeList.get(i), tmpList.get(i)); + } + Assert.assertEquals(RECEIVE_ADDRESSES[RECEIVE_COUNT], + ByteArray.toHexString(tmpList.get(RECEIVE_COUNT).toByteArray())); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail("con not reach here"); } + dbManager.getDynamicPropertiesStore().saveAllowDelegateOptimization(0L); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(10000L); } @Test @@ -327,7 +350,7 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenActive() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -362,9 +385,8 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenActive() { Assert .assertEquals(0, delegatedResourceAccountIndexCapsuleOwner.getFromAccountsList().size()); Assert.assertEquals(1, delegatedResourceAccountIndexCapsuleOwner.getToAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleOwner.getToAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)))); DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsuleReceiver = dbManager .getDelegatedResourceAccountIndexStore().get(ByteArray.fromHexString(RECEIVER_ADDRESS)); @@ -373,14 +395,11 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenActive() { Assert .assertEquals(1, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - Assert.assertEquals(true, - delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() - .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); + Assert.assertTrue(delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList() + .contains(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -398,7 +417,7 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenClose() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(owner.getBalance(), initBalance - frozenBalance @@ -418,10 +437,8 @@ public void testFreezeDelegatedBalanceForCpuSameNameTokenClose() { Assert.assertEquals(totalEnergyWeightBefore + frozenBalance / 1000_000L, totalEnergyWeightAfter); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -439,10 +456,9 @@ public void freezeLessThanZero() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenBalance must be positive", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -460,10 +476,10 @@ public void freezeMoreThanBalance() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("frozenBalance must be less than accountBalance", e.getMessage()); + Assert.assertEquals( + "frozenBalance must be less than or equal to accountBalance", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -482,12 +498,9 @@ public void invalidOwnerAddress() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Invalid address", e.getMessage()); - } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -506,11 +519,10 @@ public void invalidOwnerAccount() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -531,11 +543,10 @@ public void durationLessThanMin() { } catch (ContractValidateException e) { long minFrozenTime = dbManager.getDynamicPropertiesStore().getMinFrozenTime(); long maxFrozenTime = dbManager.getDynamicPropertiesStore().getMaxFrozenTime(); - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenDuration must be less than " + maxFrozenTime + " days " + "and more than " + minFrozenTime + " days", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -555,11 +566,10 @@ public void durationMoreThanMax() { } catch (ContractValidateException e) { long minFrozenTime = dbManager.getDynamicPropertiesStore().getMinFrozenTime(); long maxFrozenTime = dbManager.getDynamicPropertiesStore().getMaxFrozenTime(); - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenDuration must be less than " + maxFrozenTime + " days " + "and more than " + minFrozenTime + " days", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -577,10 +587,10 @@ public void lessThan1TrxTest() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("frozenBalance must be more than 1TRX", e.getMessage()); + Assert.assertEquals("frozenBalance must be greater than or equal to 1 TRX", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -604,10 +614,9 @@ public void frozenNumTest() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("frozenCount must be 0 or 1", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -623,10 +632,8 @@ public void moreThanFrozenNumber() { try { actuator.validate(); actuator.execute(ret); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } try { actuator.validate(); @@ -634,11 +641,10 @@ public void moreThanFrozenNumber() { fail("cannot run here."); } catch (ContractValidateException e) { long maxFrozenNumber = ChainConstant.MAX_FROZEN_NUMBER; - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("max frozen number is: " + maxFrozenNumber, e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -679,16 +685,14 @@ public void testFreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(-1L, owner.getInstance().getOldTronPower()); Assert.assertEquals(0L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -712,16 +716,14 @@ public void testFreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); Assert.assertEquals(100L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -745,18 +747,15 @@ public void testFreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); Assert.assertEquals(frozenBalance + 100L, owner.getAllTronPower()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } - } diff --git a/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java new file mode 100644 index 00000000000..86b0e3143ab --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/FreezeBalanceV2ActuatorTest.java @@ -0,0 +1,405 @@ +package org.tron.core.actuator; + +import static junit.framework.TestCase.fail; +import static org.tron.core.config.Parameter.ChainConstant.TRANSFER_FEE; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.config.Parameter.ChainConstant; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.Common.ResourceCode; + +@Slf4j +public class FreezeBalanceV2ActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "aaaa"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 10_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + /** + * create temp Capsule test need. + */ + @Before + public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + AccountCapsule receiverCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), + AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + } + + private Any getContractV2ForBandwidth(String ownerAddress, long frozenBalance) { + return Any.pack( + BalanceContract.FreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setFrozenBalance(frozenBalance) + .setResource(ResourceCode.BANDWIDTH) + .build()); + } + + private Any getContractForCpuV2(String ownerAddress, long frozenBalance) { + return Any.pack( + BalanceContract.FreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setFrozenBalance(frozenBalance) + .setResource(ResourceCode.ENERGY) + .build()); + } + + + private Any getContractForTronPowerV2(String ownerAddress, long frozenBalance) { + return Any.pack( + BalanceContract.FreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setFrozenBalance(frozenBalance) + .setResource(ResourceCode.TRON_POWER) + .build()); + } + + private Any getDelegatedContractForBandwidthV2(String ownerAddress, + long frozenBalance) { + return Any.pack( + BalanceContract.FreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + //.setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(receiverAddress))) + .setFrozenBalance(frozenBalance) + .build()); + } + + private Any getDelegatedContractForCpuV2(String ownerAddress, + long frozenBalance) { + return Any.pack( + BalanceContract.FreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + //.setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(receiverAddress))) + .setFrozenBalance(frozenBalance) + .setResource(ResourceCode.ENERGY) + .build()); + } + + @Test + public void testFreezeBalanceForBandwidth() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(owner.getBalance(), initBalance - frozenBalance + - TRANSFER_FEE); + Assert.assertEquals(owner.getFrozenV2BalanceForBandwidth(), frozenBalance); + Assert.assertEquals(frozenBalance, owner.getTronPower()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void testFreezeBalanceForEnergy() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForCpuV2(OWNER_ADDRESS, frozenBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(owner.getBalance(), initBalance - frozenBalance + - TRANSFER_FEE); + Assert.assertEquals(0L, owner.getAllFrozenBalanceForBandwidth()); + Assert.assertEquals(frozenBalance, owner.getAllFrozenBalanceForEnergy()); + Assert.assertEquals(frozenBalance, owner.getTronPower()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + + + @Test + public void freezeLessThanZero() { + long frozenBalance = -1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + Assert.assertEquals("frozenBalance must be positive", e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void freezeMoreThanBalance() { + long frozenBalance = 11_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertEquals("frozenBalance must be less than or equal to accountBalance", + e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void invalidOwnerAddress() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ADDRESS_INVALID, frozenBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + Assert.assertEquals("Invalid address", e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + + } + + @Test + public void invalidOwnerAccount() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ACCOUNT_INVALID, frozenBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", + e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void lessThan1TrxTest() { + long frozenBalance = 1; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertEquals("frozenBalance must be greater than or equal to 1 TRX", + e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + } + + //@Test + public void moreThanFrozenNumber() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceActuator actuator = new FreezeBalanceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + long maxFrozenNumber = ChainConstant.MAX_FROZEN_NUMBER; + Assert.assertEquals("max frozen number is: " + maxFrozenNumber, e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + } + + + @Test + public void commonErrorCheck() { + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + ActuatorTest actuatorTest = new ActuatorTest(actuator, dbManager); + actuatorTest.noContract(); + + Any invalidContractTypes = Any.pack(AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .build()); + actuatorTest.setInvalidContract(invalidContractTypes); + actuatorTest.setInvalidContractTypeMsg("contract type error", + "contract type error,expected type [FreezeBalanceV2Contract],real type["); + actuatorTest.invalidContractType(); + + long frozenBalance = 1_000_000_000L; + actuatorTest.setContract(getContractV2ForBandwidth(OWNER_ADDRESS, frozenBalance)); + actuatorTest.nullTransationResult(); + + actuatorTest.setNullDBManagerMsg("No account store or dynamic store!"); + actuatorTest.nullDBManger(); + } + + + @Test + public void testFreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + chainBaseManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + actuator.setChainBaseManager(chainBaseManager) + .setAny(getContractForCpuV2(OWNER_ADDRESS, frozenBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(-1L, owner.getInstance().getOldTronPower()); + Assert.assertEquals(0L, owner.getAllTronPower()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + + + @Test + public void testFreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + chainBaseManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + actuator.setChainBaseManager(chainBaseManager) + .setAny(getContractForCpuV2(OWNER_ADDRESS, frozenBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + AccountCapsule owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + owner.setFrozenForEnergy(100L,0L); + chainBaseManager.getAccountStore().put(ByteArray.fromHexString(OWNER_ADDRESS),owner); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); + Assert.assertEquals(100L, owner.getAllTronPower()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + + + @Test + public void testFreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel() { + long frozenBalance = 1_000_000_000L; + FreezeBalanceV2Actuator actuator = new FreezeBalanceV2Actuator(); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + chainBaseManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + actuator.setChainBaseManager(chainBaseManager) + .setAny(getContractForTronPowerV2(OWNER_ADDRESS, frozenBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + AccountCapsule owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + owner.setFrozenForEnergy(100L,0L); + chainBaseManager.getAccountStore().put(ByteArray.fromHexString(OWNER_ADDRESS),owner); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + owner = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(100L, owner.getInstance().getOldTronPower()); + Assert.assertEquals(100L, owner.getTronPower()); + Assert.assertEquals(frozenBalance + 100, owner.getAllTronPower()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java index 6ec03786345..b5c3427f529 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketCancelOrderActuatorTest.java @@ -1,24 +1,17 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; - import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.MarketAccountOrderCapsule; @@ -26,9 +19,7 @@ import org.tron.core.capsule.MarketOrderIdListCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -47,9 +38,8 @@ @Slf4j -public class MarketCancelOrderActuatorTest { +public class MarketCancelOrderActuatorTest extends BaseTest { - private static final String dbPath = "output_MarketCancelOrder_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -59,12 +49,9 @@ public class MarketCancelOrderActuatorTest { private static final String TOKEN_ID_ONE = String.valueOf(1L); private static final String TOKEN_ID_TWO = String.valueOf(2L); private static final String TRX = "_"; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -74,50 +61,19 @@ public class MarketCancelOrderActuatorTest { } /** - * Init data. + * create temp Capsule test need. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void initTest() { dbManager.getDynamicPropertiesStore().saveAllowMarketTransaction(1L); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1000000); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(10); dbManager.getDynamicPropertiesStore().saveNextMaintenanceTime(2000000); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - /** - * create temp Capsule test need. - */ - @Before - public void initTest() { byte[] ownerAddressFirstBytes = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); byte[] ownerAddressSecondBytes = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom(ownerAddressFirstBytes)); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule(ByteString.copyFrom(ownerAddressSecondBytes)); - - dbManager.getAccountAssetStore().put(ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put(ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - AccountCapsule ownerAccountFirstCapsule = new AccountCapsule( ByteString.copyFromUtf8(ACCOUNT_NAME_FIRST), @@ -233,7 +189,7 @@ public void invalidOwnerAddress() { try { actuator.validate(); - fail("Invalid address"); + Assert.fail("Invalid address"); } catch (ContractValidateException e) { Assert.assertEquals("Invalid address", e.getMessage()); } @@ -253,7 +209,7 @@ public void notExistAccount() { try { actuator.validate(); - fail("Account does not exist!"); + Assert.fail("Account does not exist!"); } catch (ContractValidateException e) { Assert.assertEquals("Account does not exist!", e.getMessage()); } @@ -272,7 +228,7 @@ public void notExistOrder() { OWNER_ADDRESS_FIRST, orderId)); try { actuator.validate(); - fail("orderId not exists"); + Assert.fail("orderId not exists"); } catch (ContractValidateException e) { Assert.assertEquals("orderId not exists", e.getMessage()); } @@ -306,7 +262,7 @@ public void orderNotActive() throws Exception { try { actuator.validate(); - fail("Order is not active!"); + Assert.fail("Order is not active!"); } catch (ContractValidateException e) { Assert.assertEquals("Order is not active!", e.getMessage()); } @@ -341,7 +297,7 @@ public void notBelongToTheAccount() throws Exception { try { actuator.validate(); actuator.execute(ret); - fail("Order does not belong to the account!"); + Assert.fail("Order does not belong to the account!"); } catch (ContractValidateException e) { Assert.assertEquals("Order does not belong to the account!", e.getMessage()); } catch (ContractExeException e) { @@ -383,7 +339,7 @@ public void noEnoughBalance() throws Exception { try { actuator.validate(); actuator.execute(ret); - fail("No enough balance !"); + Assert.fail("No enough balance !"); } catch (ContractValidateException e) { Assert.assertEquals("No enough balance !", e.getMessage()); } catch (ContractExeException e) { @@ -420,7 +376,7 @@ public void validateSuccess() throws Exception { try { actuator.validate(); } catch (ContractValidateException e) { - fail("validateSuccess error"); + Assert.fail("validateSuccess error"); } } @@ -514,7 +470,7 @@ public void multipleOrdersAtThisPrice1() throws Exception { dbManager.getDynamicPropertiesStore().getMarketCancelFee() + accountCapsule.getBalance()); //check token number return - Assert.assertEquals(100L,accountCapsule.getAssetMapV2().get(TOKEN_ID_ONE).longValue()); + Assert.assertEquals(100L,accountCapsule.getAssetV2MapForTest().get(TOKEN_ID_ONE).longValue()); //check accountOrder accountOrderCapsule = marketAccountStore.get(ByteArray.fromHexString(OWNER_ADDRESS_FIRST)); @@ -691,7 +647,7 @@ public void onlyOneOrderAtThisPriceAndHasMultiplePrices() throws Exception { +accountCapsule.getBalance()); //check token number return - Assert.assertEquals(100L, accountCapsule.getAssetMapV2().get(TOKEN_ID_ONE).longValue()); + Assert.assertEquals(100L, accountCapsule.getAssetV2MapForTest().get(TOKEN_ID_ONE).longValue()); //check accountOrder accountOrderCapsule = marketAccountStore.get(ByteArray.fromHexString(OWNER_ADDRESS_FIRST)); @@ -775,7 +731,7 @@ public void onlyOneOrderAtThisPriceAndHasOnlyOnePrice() throws Exception { +accountCapsule.getBalance()); //check token number return - Assert.assertEquals(100L,accountCapsule.getAssetMapV2().get(TOKEN_ID_ONE).longValue()); + Assert.assertEquals(100L,accountCapsule.getAssetV2MapForTest().get(TOKEN_ID_ONE).longValue()); //check accountOrder accountOrderCapsule = marketAccountStore.get(ByteArray.fromHexString(OWNER_ADDRESS_FIRST)); diff --git a/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java index 9713f779b95..0e938cdb025 100644 --- a/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/MarketSellAssetActuatorTest.java @@ -1,25 +1,20 @@ package org.tron.core.actuator; -import static org.testng.Assert.fail; +import static org.junit.Assert.fail; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.MarketAccountOrderCapsule; @@ -27,9 +22,7 @@ import org.tron.core.capsule.MarketOrderIdListCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -47,9 +40,8 @@ @Slf4j -public class MarketSellAssetActuatorTest { +public class MarketSellAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_MarketSellAsset_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -59,12 +51,9 @@ public class MarketSellAssetActuatorTest { private static final String TOKEN_ID_ONE = String.valueOf(1L); private static final String TOKEN_ID_TWO = String.valueOf(2L); private static final String TRX = "_"; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -74,51 +63,19 @@ public class MarketSellAssetActuatorTest { } /** - * Init data. + * create temp Capsule test need. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void initTest() { dbManager.getDynamicPropertiesStore().saveAllowMarketTransaction(1L); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1000000); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(10); dbManager.getDynamicPropertiesStore().saveNextMaintenanceTime(2000000); - } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - /** - * create temp Capsule test need. - */ - @Before - public void initTest() { byte[] ownerAddressFirstBytes = ByteArray.fromHexString(OWNER_ADDRESS_FIRST); byte[] ownerAddressSecondBytes = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom( - ByteArray.fromHexString(OWNER_ADDRESS_FIRST))); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule( - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS_SECOND))); - dbManager.getAccountAssetStore().put(ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put(ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - AccountCapsule ownerAccountFirstCapsule = new AccountCapsule( ByteString.copyFromUtf8(ACCOUNT_NAME_FIRST), @@ -552,7 +509,7 @@ public void exceedMakerBuyOrderNumLimit() throws Exception { dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); Assert.assertEquals(sellTokenQuant * orderNum, - (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -618,7 +575,8 @@ private void prepareAccount(String sellTokenId, String buyTokenId, accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); } @@ -760,7 +718,8 @@ public void noBuyAddFirstSellOrder2() throws Exception { dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); long balanceBefore = accountCapsule.getBalance(); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); MarketSellAssetActuator actuator = new MarketSellAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( @@ -782,7 +741,7 @@ public void noBuyAddFirstSellOrder2() throws Exception { accountCapsule = dbManager.getAccountStore().get(ownerAddress); Assert.assertEquals(balanceBefore, dbManager.getDynamicPropertiesStore().getMarketSellFee() + accountCapsule.getBalance()); - Assert.assertEquals(0L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(0L, (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -840,7 +799,8 @@ public void noBuyAddFirstSellOrder3() throws Exception { dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); long balanceBefore = accountCapsule.getBalance(); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); MarketSellAssetActuator actuator = new MarketSellAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny(getContract( @@ -862,7 +822,8 @@ public void noBuyAddFirstSellOrder3() throws Exception { accountCapsule = dbManager.getAccountStore().get(ownerAddress); Assert.assertEquals(balanceBefore, dbManager.getDynamicPropertiesStore().getMarketSellFee() + accountCapsule.getBalance()); - Assert.assertEquals(0L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(0L, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -921,7 +882,8 @@ public void noBuyAddMultiSellOrder1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1006,7 +968,8 @@ public void noBuyAddMultiSellOrderSamePrice1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1092,7 +1055,8 @@ public void hasBuyAddFirstSellOrderNotMatch1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book //add three order with different price by the same account @@ -1124,7 +1088,8 @@ public void hasBuyAddFirstSellOrderNotMatch1() throws Exception { //check balance and token accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Assert.assertEquals(0L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(0L, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -1185,7 +1150,8 @@ public void hasBuySellAddSellOrderNotMatch1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1227,7 +1193,8 @@ public void hasBuySellAddSellOrderNotMatch1() throws Exception { //check balance and token accountCapsule = dbManager.getAccountStore().get(ownerAddress); // Assert.assertTrue(accountCapsule.getAssetMapV2().get(sellTokenId) == 0L); - Assert.assertEquals(0L, accountCapsule.getAssetMapV2().get(sellTokenId).longValue()); + Assert.assertEquals(0L, + accountCapsule.getAssetV2MapForTest().get(sellTokenId).longValue()); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -1296,7 +1263,8 @@ public long doMatchTimeTest(int num) throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1340,7 +1308,8 @@ public void matchAll2SamePriceBuyOrders1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1381,12 +1350,15 @@ public void matchAll2SamePriceBuyOrders1() throws Exception { //check balance and token accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Assert.assertEquals(0L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); - Assert.assertEquals(200L, (long) accountCapsule.getAssetMapV2().get(buyTokenId)); + Assert.assertEquals(0L, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); + Assert.assertEquals(200L, + (long) accountCapsule.getAssetV2MapForTest().get(buyTokenId)); byte[] makerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule makerAccountCapsule = dbManager.getAccountStore().get(makerAddress); - Assert.assertEquals(400L, (long) makerAccountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(400L, + (long) makerAccountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -1488,7 +1460,8 @@ public void partMatchMakerBuyOrders1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); //get storeDB instance ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); @@ -1523,12 +1496,15 @@ public void partMatchMakerBuyOrders1() throws Exception { //check balance and token accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Assert.assertEquals(0L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); - Assert.assertEquals(200L, (long) accountCapsule.getAssetMapV2().get(buyTokenId)); + Assert.assertEquals(0L, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); + Assert.assertEquals(200L, + (long) accountCapsule.getAssetV2MapForTest().get(buyTokenId)); byte[] makerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule makerAccountCapsule = dbManager.getAccountStore().get(makerAddress); - Assert.assertEquals(500L, (long) makerAccountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(500L, + (long) makerAccountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -1632,7 +1608,8 @@ public void partMatchTakerBuyOrders1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1667,12 +1644,15 @@ public void partMatchTakerBuyOrders1() throws Exception { //check balance and token accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Assert.assertEquals(0L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); - Assert.assertEquals(250L, (long) accountCapsule.getAssetMapV2().get(buyTokenId)); + Assert.assertEquals(0L, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); + Assert.assertEquals(250L, + (long) accountCapsule.getAssetV2MapForTest().get(buyTokenId)); byte[] makerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule makerAccountCapsule = dbManager.getAccountStore().get(makerAddress); - Assert.assertEquals(800L, (long) makerAccountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(800L, + (long) makerAccountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -1750,7 +1730,8 @@ public void partMatchMakerLeftNotEnoughBuyOrders1() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book @@ -1782,12 +1763,15 @@ public void partMatchMakerLeftNotEnoughBuyOrders1() throws Exception { //check balance and token accountCapsule = dbManager.getAccountStore().get(ownerAddress); - Assert.assertEquals(1L, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); - Assert.assertEquals(100L, (long) accountCapsule.getAssetMapV2().get(buyTokenId)); + Assert.assertEquals(1L, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); + Assert.assertEquals(100L, + (long) accountCapsule.getAssetV2MapForTest().get(buyTokenId)); byte[] makerAddress = ByteArray.fromHexString(OWNER_ADDRESS_SECOND); AccountCapsule makerAccountCapsule = dbManager.getAccountStore().get(makerAddress); - Assert.assertEquals(200L, (long) makerAccountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(200L, + (long) makerAccountCapsule.getAssetV2MapForTest().get(sellTokenId)); //check accountOrder MarketAccountOrderCapsule accountOrderCapsule = marketAccountStore.get(ownerAddress); @@ -1858,7 +1842,8 @@ public void exceedMaxMatchNumLimit() throws Exception { accountCapsule.addAssetAmountV2(sellTokenId.getBytes(), sellTokenQuant, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore()); dbManager.getAccountStore().put(ownerAddress, accountCapsule); - Assert.assertEquals(sellTokenQuant, (long) accountCapsule.getAssetMapV2().get(sellTokenId)); + Assert.assertEquals(sellTokenQuant, + (long) accountCapsule.getAssetV2MapForTest().get(sellTokenId)); // Initialize the order book 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 23cf410a1fc..88db0791b0a 100755 --- a/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ParticipateAssetIssueActuatorTest.java @@ -2,28 +2,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import org.joda.time.DateTime; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -32,10 +22,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -public class ParticipateAssetIssueActuatorTest { +public class ParticipateAssetIssueActuatorTest extends BaseTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - private static final String dbPath = "output_participateAsset_test"; private static final String OWNER_ADDRESS; private static final String TO_ADDRESS; private static final String TO_ADDRESS_2; @@ -50,13 +38,10 @@ public class ParticipateAssetIssueActuatorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; + private static long AMOUNT = TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1234"; TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; TO_ADDRESS_2 = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e048892"; @@ -64,48 +49,12 @@ public class ParticipateAssetIssueActuatorTest { NOT_EXIT_ADDRESS = Wallet.getAddressPreFixString() + "B56446E617E924805E4D6CA021D341FEF6E2013B"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - - chainBaseManager.getDynamicPropertiesStore().saveTokenIdNum(1000000); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @Before public void createCapsule() { - AccountAssetCapsule ownerAddressFirstAsset = - new AccountAssetCapsule(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); - AccountAssetCapsule ownerAddressSecondAsset = - new AccountAssetCapsule(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))); - AccountAssetCapsule ownerAddressSecondAsset2 = - new AccountAssetCapsule(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS_2))); - dbManager.getAccountAssetStore().put(ownerAddressFirstAsset.getAddress().toByteArray(), - ownerAddressFirstAsset); - dbManager.getAccountAssetStore().put(ownerAddressSecondAsset.getAddress().toByteArray(), - ownerAddressSecondAsset); - dbManager.getAccountAssetStore().put(ownerAddressSecondAsset2.getAddress().toByteArray(), - ownerAddressSecondAsset2); + chainBaseManager.getDynamicPropertiesStore().saveTokenIdNum(1000000); AccountCapsule ownerCapsule = new AccountCapsule( @@ -349,16 +298,16 @@ public void sameTokenNameCloseRightAssetIssue() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE - 1000); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE + 1000); //V1 - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), (1000L) / TRX_NUM * NUM); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), - TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM); + + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), AMOUNT); //V2 long tokenId = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenId)).longValue(), (1000L) / TRX_NUM * NUM); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), - TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM); + Assert.assertEquals(toAccount.getAssetV2MapForTest() + .get(String.valueOf(tokenId)).longValue(), AMOUNT); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -393,14 +342,14 @@ public void OldNotUpdateSuccessAssetIssue() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE - 1000); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE + 1000); //V1 data not update - Assert.assertNull(owner.getAssetMap().get(ASSET_NAME)); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertNull(owner.getAssetMapForTest().get(ASSET_NAME)); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); //V2 long tokenId = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenId)).longValue(), (1000L) / TRX_NUM * NUM); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), - TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM); + Assert.assertEquals(toAccount.getAssetV2MapForTest() + .get(String.valueOf(tokenId)).longValue(), AMOUNT); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -433,14 +382,14 @@ public void sameTokenNameOpenRightAssetIssue() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE - 1000); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE + 1000); // V1, data is not exist - Assert.assertNull(owner.getAssetMap().get(ASSET_NAME)); - Assert.assertNull(toAccount.getAssetMap().get(ASSET_NAME)); + Assert.assertNull(owner.getAssetMapForTest().get(ASSET_NAME)); + Assert.assertNull(toAccount.getAssetMapForTest().get(ASSET_NAME)); //V2 long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(id)).longValue(), - (1000L) / TRX_NUM * NUM); + Assert.assertEquals(owner.getAssetV2MapForTest() + .get(String.valueOf(id)).longValue(), (1000L) / TRX_NUM * NUM); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -474,8 +423,8 @@ public void sameTokenNameCloseAssetIssueTimeRight() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -508,8 +457,8 @@ public void sameTokenNameOpenAssetIssueTimeRight() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -541,8 +490,9 @@ public void sameTokenNameCloseAssetIssueTimeLeft() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest() + .get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -575,9 +525,9 @@ public void sameTokenNameOpenAssetIssueTimeLeft() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), - TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest() + .get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -604,10 +554,10 @@ public void sameTokenNameCloseExchangeDevisibleTest() { AccountCapsule toAccount = chainBaseManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), (999L * NUM) / TRX_NUM); Assert.assertEquals( - toAccount.getAssetMap().get(ASSET_NAME).longValue(), + toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY - (999L * NUM) / TRX_NUM); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -638,10 +588,10 @@ public void sameTokenNameOpenExchangeDevisibleTest() { AccountCapsule toAccount = chainBaseManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), (999L * NUM) / TRX_NUM); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY - (999L * NUM) / TRX_NUM); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -676,8 +626,8 @@ public void sameTokenNameCloseNegativeAmountTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -712,9 +662,9 @@ public void sameTokenNameOpenNegativeAmountTest() { Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), - TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest() + .get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -746,8 +696,8 @@ public void sameTokenNameCloseZeroAmountTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -782,9 +732,9 @@ public void sameTokenNameOpenZeroAmountTest() { Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), - TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest() + .get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -818,8 +768,8 @@ public void sameTokenNameCloseNoExitOwnerTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -855,8 +805,8 @@ public void sameTokenNameOpenNoExitOwnerTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -894,8 +844,8 @@ public void sameTokenNameCloseNoExitToTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -935,8 +885,8 @@ public void sameTokenNameOpenNoExitToTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -974,8 +924,8 @@ public void sameTokenNameCloseParticipateAssetSelf() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1014,8 +964,8 @@ public void sameTokenNameOpenParticipateAssetSelf() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -1050,8 +1000,8 @@ public void sameTokenNameCloseParticipateAssetToThird() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1087,8 +1037,8 @@ public void sameTokenNameOpenParticipateAssetToThird() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -1144,9 +1094,9 @@ public void assetNameTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE - 1000); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE + 1000); - Assert.assertEquals(owner.getAssetMap().get(assetName).longValue(), + Assert.assertEquals(owner.getAssetMapForTest().get(assetName).longValue(), (1000L) / TRX_NUM * NUM); - Assert.assertEquals(toAccount.getAssetMap().get(assetName).longValue(), + Assert.assertEquals(toAccount.getAssetMapForTest().get(assetName).longValue(), TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -1176,9 +1126,9 @@ public void assetNameTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE - 2000); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE + 2000); - Assert.assertEquals(owner.getAssetMap().get(assetName).longValue(), + Assert.assertEquals(owner.getAssetMapForTest().get(assetName).longValue(), (1000L) / TRX_NUM * NUM); - Assert.assertEquals(toAccount.getAssetMap().get(assetName).longValue(), + Assert.assertEquals(toAccount.getAssetMapForTest().get(assetName).longValue(), TOTAL_SUPPLY - (1000L) / TRX_NUM * NUM); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -1219,8 +1169,8 @@ public void sameTokenNameCloseNotEnoughTrxTest() { Assert.assertEquals(owner.getBalance(), 100); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1260,8 +1210,8 @@ public void sameTokenNameOpenNotEnoughTrxTest() { Assert.assertEquals(owner.getBalance(), 100); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -1280,7 +1230,7 @@ public void sameTokenNameCloseNotEnoughAssetTest() { AccountCapsule toAccount = chainBaseManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); toAccount.reduceAssetAmount(ByteString.copyFromUtf8(ASSET_NAME).toByteArray(), - TOTAL_SUPPLY - 10000); + TOTAL_SUPPLY - 10000, true); chainBaseManager.getAccountStore().put(toAccount.getAddress().toByteArray(), toAccount); ParticipateAssetIssueActuator actuator = new ParticipateAssetIssueActuator(); actuator.setChainBaseManager(chainBaseManager).setAny(getContract(1)); @@ -1301,8 +1251,8 @@ public void sameTokenNameCloseNotEnoughAssetTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), 10000); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), 10000); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1347,9 +1297,9 @@ public void sameTokenNameOpenNotEnoughAssetTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), 10000); + toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), 10000); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1382,8 +1332,8 @@ public void sameTokenNameCloseNoneExistAssetTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1419,8 +1369,8 @@ public void sameTokenNameOpenNoneExistAssetTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -1463,8 +1413,8 @@ public void sameTokenNameCloseAddOverflowTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), Long.MAX_VALUE); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), Long.MAX_VALUE); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } } @@ -1507,9 +1457,9 @@ public void sameTokenNameOpenAddOverflowTest() { Assert.assertEquals(owner.getBalance(), OWNER_BALANCE); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), Long.MAX_VALUE); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } } @@ -1554,8 +1504,8 @@ public void sameTokenNameCloseMultiplyOverflowTest() { Assert.assertEquals(owner.getBalance(), 100000000000000L); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); - Assert.assertTrue(isNullOrZero(owner.getAssetMap().get(ASSET_NAME))); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); + Assert.assertTrue(isNullOrZero(owner.getAssetMapForTest().get(ASSET_NAME))); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1604,8 +1554,8 @@ public void sameTokenNameOpenMultiplyOverflowTest() { Assert.assertEquals(owner.getBalance(), 100000000000000L); Assert.assertEquals(toAccount.getBalance(), TO_BALANCE); long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(owner.getAssetMapV2().get(String.valueOf(id)))); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(id)).longValue(), + Assert.assertTrue(isNullOrZero(owner.getAssetV2MapForTest().get(String.valueOf(id)))); + Assert.assertEquals(toAccount.getAssetV2MapForTest().get(String.valueOf(id)).longValue(), TOTAL_SUPPLY); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); diff --git a/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java index 5ca4d7abfcf..2e8e78306a9 100644 --- a/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ProposalApproveActuatorTest.java @@ -4,17 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -22,9 +18,7 @@ import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -35,10 +29,8 @@ import org.tron.protos.contract.ProposalContract; @Slf4j +public class ProposalApproveActuatorTest extends BaseTest { -public class ProposalApproveActuatorTest { - - private static final String dbPath = "output_ProposalApprove_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -46,12 +38,9 @@ public class ProposalApproveActuatorTest { private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -60,28 +49,6 @@ public class ProposalApproveActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java index 56bf9504730..7210fe8d074 100644 --- a/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ProposalCreateActuatorTest.java @@ -1,29 +1,29 @@ package org.tron.core.actuator; import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertThrows; +import static org.tron.core.Constant.CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE; +import static org.tron.core.Constant.CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE; +import static org.tron.core.config.Parameter.ChainConstant.ONE_YEAR_BLOCK_NUMBERS; import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.mockito.Mockito; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.ForkController; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -33,10 +33,8 @@ import org.tron.protos.contract.ProposalContract.ProposalCreateContract; @Slf4j +public class ProposalCreateActuatorTest extends BaseTest { -public class ProposalCreateActuatorTest { - - private static final String dbPath = "output_ProposalCreate_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -44,43 +42,15 @@ public class ProposalCreateActuatorTest { private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_NOACCOUNT = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; - OWNER_ADDRESS_BALANCENOTSUFFIENT = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } /** @@ -315,6 +285,50 @@ public void invalidPara() { Assert.assertEquals("This value[REMOVE_THE_POWER_OF_THE_GR] is only allowed to be 1", e.getMessage()); } + // verify Proposal No. 78 + paras = new HashMap<>(); + paras.put(78L, 10L); + actuator = new ProposalCreateActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setForkUtils(dbManager.getChainBaseManager().getForkController()) + .setAny(getContract(OWNER_ADDRESS_FIRST, paras)); + assertThrows( + "Bad chain parameter id [MAX_DELEGATE_LOCK_PERIOD]", + ContractValidateException.class, actuator::validate); + + actuator = new ProposalCreateActuator(); + ForkController forkController = Mockito.mock(ForkController.class); + Mockito.when(forkController.pass(Mockito.any())).thenReturn(true); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setForkUtils(forkController) + .setAny(getContract(OWNER_ADDRESS_FIRST, paras)); + dbManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(86400L); + long maxDelegateLockPeriod = dbManager.getDynamicPropertiesStore().getMaxDelegateLockPeriod(); + assertThrows( + "This value[MAX_DELEGATE_LOCK_PERIOD] is only allowed to be greater than " + + maxDelegateLockPeriod + " and less than or equal to " + ONE_YEAR_BLOCK_NUMBERS + "!", + ContractValidateException.class, actuator::validate); + + // verify Proposal No. 82 + paras = new HashMap<>(); + paras.put(82L, 0L); + actuator = new ProposalCreateActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setForkUtils(dbManager.getChainBaseManager().getForkController()) + .setAny(getContract(OWNER_ADDRESS_FIRST, paras)); + assertThrows( + "Bad chain parameter id [ALLOW_ENERGY_ADJUSTMENT]", + ContractValidateException.class, actuator::validate); + + actuator = new ProposalCreateActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setForkUtils(forkController) + .setAny(getContract(OWNER_ADDRESS_FIRST, paras)); + assertThrows( + "This value[MAX_CREATE_ACCOUNT_TX_SIZE] is only allowed to be greater than or equal " + + "to " + CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE + " and less than or equal to " + + CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE + "!", + ContractValidateException.class, actuator::validate); } /** diff --git a/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java index e8d7829f90c..dfd34cb620e 100644 --- a/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ProposalDeleteActuatorTest.java @@ -4,17 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -22,9 +18,7 @@ import org.tron.core.capsule.ProposalCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ItemNotFoundException; @@ -35,10 +29,8 @@ import org.tron.protos.contract.ProposalContract; @Slf4j +public class ProposalDeleteActuatorTest extends BaseTest { -public class ProposalDeleteActuatorTest { - - private static final String dbPath = "output_ProposalApprove_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -46,12 +38,9 @@ public class ProposalDeleteActuatorTest { private static final String URL = "https://tron.network/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -60,28 +49,6 @@ public class ProposalDeleteActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1aed"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java index 018ae6401bc..e93d9ecf333 100644 --- a/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/SetAccountIdActuatorTest.java @@ -2,23 +2,17 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -27,46 +21,20 @@ import org.tron.protos.contract.AssetIssueContractOuterClass; @Slf4j -public class SetAccountIdActuatorTest { +public class SetAccountIdActuatorTest extends BaseTest { - private static final String dbPath = "output_setaccountid_test"; private static final String ACCOUNT_NAME = "ownertest"; private static final String ACCOUNT_NAME_1 = "ownertest1"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_1; private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_1 = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java index 9ba4809bede..b71ba432018 100755 --- a/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/ShieldedTransferActuatorTest.java @@ -1,16 +1,16 @@ package org.tron.core.actuator; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.core.Constant; @@ -22,16 +22,13 @@ import org.tron.core.capsule.PedersenHashCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.PermissionException; import org.tron.core.exception.ValidateSignatureException; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; -import org.tron.core.utils.TransactionUtil; import org.tron.core.zen.ZenTransactionBuilder; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; import org.tron.core.zen.address.FullViewingKey; @@ -41,20 +38,17 @@ import org.tron.core.zen.note.Note; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction.Contract; -import org.tron.protos.Protocol.TransactionSign; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; import org.tron.protos.contract.ShieldContract.PedersenHash; import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; @Slf4j -public class ShieldedTransferActuatorTest { +public class ShieldedTransferActuatorTest extends BaseTest { - private static final String dbPath = "output_shield_transfer_test"; private static final String PUBLIC_ADDRESS_ONE; private static final String ADDRESS_ONE_PRIVATE_KEY; private static final String PUBLIC_ADDRESS_TWO; private static final String ADDRESS_TWO_PRIVATE_KEY; - private static final String PUBLIC_ADDRESS_OFF_LINE; private static final long AMOUNT = 100000000L; private static final long OWNER_BALANCE = 9999999000000L; private static final long TO_BALANCE = 100001000000L; @@ -69,22 +63,19 @@ public class ShieldedTransferActuatorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static Wallet wallet; - private static Manager dbManager; - private static TronApplicationContext context; - private static TransactionUtil transactionUtil; + + @Resource + private Wallet wallet; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - PUBLIC_ADDRESS_ONE = - Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; - ADDRESS_ONE_PRIVATE_KEY = "7f7f701e94d4f1dd60ee5205e7ea8ee31121427210417b608a6b2e96433549a7"; + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + ADDRESS_ONE_PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); + PUBLIC_ADDRESS_ONE = PublicMethod.getHexAddressByPrivateKey(ADDRESS_ONE_PRIVATE_KEY); + + ADDRESS_TWO_PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); PUBLIC_ADDRESS_TWO = - Wallet.getAddressPreFixString() + "8ba2aaae540c642e44e3bed5522c63bbc21fff92"; - ADDRESS_TWO_PRIVATE_KEY = "e4e0edd6bff7b353dfc69a590721e902e6915c5e3e87d36dcb567a9716304720"; - PUBLIC_ADDRESS_OFF_LINE = - Wallet.getAddressPreFixString() + "7bcb781f4743afaacf9f9528f3ea903b3782339f"; + PublicMethod.getHexAddressByPrivateKey(ADDRESS_TWO_PRIVATE_KEY); + DEFAULT_OVK = ByteArray.fromHexString( "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); } @@ -95,28 +86,11 @@ public class ShieldedTransferActuatorTest { @BeforeClass public static void init() throws ZksnarkException { Args.setFullNodeAllowShieldedTransaction(true); - wallet = context.getBean(Wallet.class); - transactionUtil = context.getBean(TransactionUtil.class); - dbManager = context.getBean(Manager.class); librustzcashInitZksnarkParams(); } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - private static void librustzcashInitZksnarkParams() throws ZksnarkException { - FullNodeHttpApiService.librustzcashInitZksnarkParams(); + private static void librustzcashInitZksnarkParams() { + ZksnarkInitService.librustzcashInitZksnarkParams(); } /** @@ -192,8 +166,8 @@ private IncrementalMerkleVoucherContainer createSimpleMerkleVoucherContainer(byt private long getAssertBalance(AccountCapsule accountCapsule) { String token = String.valueOf(tokenId); - if (accountCapsule != null && accountCapsule.getAssetMapV2().containsKey(token)) { - return accountCapsule.getAssetMapV2().get(token); + if (accountCapsule != null && accountCapsule.getAssetV2MapForTest().containsKey(token)) { + return accountCapsule.getAssetV2MapForTest().get(token); } else { return 0; } @@ -232,11 +206,8 @@ public void publicAddressToShieldedAddressSuccess() { TransactionCapsule transactionCap = getPublicToShieldedTransaction(); //Add public address sign - TransactionSign.Builder transactionSignBuild = TransactionSign.newBuilder(); - transactionSignBuild.setTransaction(transactionCap.getInstance()); - transactionSignBuild.setPrivateKey(ByteString.copyFrom( - ByteArray.fromHexString(ADDRESS_ONE_PRIVATE_KEY))); - transactionCap = transactionUtil.addSign(transactionSignBuild.build()); + transactionCap = TransactionUtils.addTransactionSign(transactionCap.getInstance(), + ADDRESS_ONE_PRIVATE_KEY, dbManager.getAccountStore()); Assert.assertTrue(dbManager.pushTransaction(transactionCap)); } catch (Exception e) { @@ -263,11 +234,8 @@ public void publicAddressToPublicAddressAndZereValueOutputSuccess() { TransactionCapsule transactionCap = builder.build(); //Add public address sign - TransactionSign.Builder transactionSignBuild = TransactionSign.newBuilder(); - transactionSignBuild.setTransaction(transactionCap.getInstance()); - transactionSignBuild.setPrivateKey(ByteString.copyFrom( - ByteArray.fromHexString(ADDRESS_ONE_PRIVATE_KEY))); - transactionCap = transactionUtil.addSign(transactionSignBuild.build()); + transactionCap = TransactionUtils.addTransactionSign(transactionCap.getInstance(), + ADDRESS_ONE_PRIVATE_KEY, dbManager.getAccountStore()); Assert.assertTrue(dbManager.pushTransaction(transactionCap)); } catch (Exception e) { @@ -286,11 +254,8 @@ public void publicAddressToShieldedAddressInvalidSign() { TransactionCapsule transactionCap = getPublicToShieldedTransaction(); //Add public address sign - TransactionSign.Builder transactionSignBuild = TransactionSign.newBuilder(); - transactionSignBuild.setTransaction(transactionCap.getInstance()); - transactionSignBuild.setPrivateKey(ByteString.copyFrom( - ByteArray.fromHexString(ADDRESS_TWO_PRIVATE_KEY))); - transactionUtil.addSign(transactionSignBuild.build()); + TransactionUtils.addTransactionSign(transactionCap.getInstance(), ADDRESS_TWO_PRIVATE_KEY, + dbManager.getAccountStore()); Assert.assertTrue(false); } catch (PermissionException e) { Assert.assertTrue(e instanceof PermissionException); @@ -429,11 +394,8 @@ public void publicAddressToShieldedAddressNotConsumeBandwidth() { try { TransactionCapsule transactionCap = getPublicToShieldedTransaction(); //Add public address sign - TransactionSign.Builder transactionSignBuild = TransactionSign.newBuilder(); - transactionSignBuild.setTransaction(transactionCap.getInstance()); - transactionSignBuild.setPrivateKey(ByteString.copyFrom( - ByteArray.fromHexString(ADDRESS_ONE_PRIVATE_KEY))); - transactionCap = transactionUtil.addSign(transactionSignBuild.build()); + transactionCap = TransactionUtils.addTransactionSign(transactionCap.getInstance(), + ADDRESS_ONE_PRIVATE_KEY, dbManager.getAccountStore()); AccountCapsule accountCapsule = dbManager.getAccountStore().get(ByteArray.fromHexString(PUBLIC_ADDRESS_ONE)); @@ -1020,11 +982,8 @@ public void publicToShieldAddressAndShieldToPublicAddressWithZoreValueSuccess() TransactionCapsule transactionCapOne = builderOne.build(); //Add public address sign - TransactionSign.Builder transactionSignBuild = TransactionSign.newBuilder(); - transactionSignBuild.setTransaction(transactionCapOne.getInstance()); - transactionSignBuild.setPrivateKey(ByteString.copyFrom( - ByteArray.fromHexString(ADDRESS_ONE_PRIVATE_KEY))); - transactionCapOne = transactionUtil.addSign(transactionSignBuild.build()); + transactionCapOne = TransactionUtils.addTransactionSign(transactionCapOne.getInstance(), + ADDRESS_ONE_PRIVATE_KEY, dbManager.getAccountStore()); Assert.assertTrue(dbManager.pushTransaction(transactionCapOne)); AccountCapsule accountCapsuleOne = diff --git a/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java index 9a26a445e20..12df9031ca8 100644 --- a/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/TransferActuatorTest.java @@ -5,41 +5,35 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Date; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.AssetIssueContractOuterClass; import org.tron.protos.contract.BalanceContract.TransferContract; @Slf4j -public class TransferActuatorTest { +public class TransferActuatorTest extends BaseTest { - private static final String dbPath = "output_transfer_test"; private static final String OWNER_ADDRESS; private static final String TO_ADDRESS; private static final long AMOUNT = 100; @@ -50,12 +44,9 @@ public class TransferActuatorTest { private static final String OWNER_ACCOUNT_INVALID; private static final String OWNER_NO_BALANCE; private static final String To_ACCOUNT_INVALID; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ACCOUNT_INVALID = @@ -65,32 +56,6 @@ public class TransferActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3422"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -526,11 +491,11 @@ public void transferToSmartContractAddress() long value = 1; long feeLimit = 100000000; long consumeUserResourcePercent = 0; - DepositImpl deposit = DepositImpl.createRoot(dbManager); + RepositoryImpl repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); byte[] contractAddress = TvmTestUtils .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, codes, value, feeLimit, consumeUserResourcePercent, null, 0, 0, - deposit, null); + repository, null); TransferActuator actuator = new TransferActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) diff --git a/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java index d047ff4ce1c..8c936f16dc5 100755 --- a/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/TransferAssetActuatorTest.java @@ -20,34 +20,28 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.TvmTestUtils; -import org.tron.common.storage.DepositImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.ReceiptCheckErrException; import org.tron.core.exception.VMIllegalException; +import org.tron.core.store.StoreFactory; import org.tron.core.vm.config.VMConfig; +import org.tron.core.vm.repository.RepositoryImpl; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction.Result.code; import org.tron.protos.contract.AssetIssueContractOuterClass; @@ -55,9 +49,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; @Slf4j -public class TransferAssetActuatorTest { +public class TransferAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_transferasset_test"; private static final String ASSET_NAME = "trx"; private static final String OWNER_ADDRESS; private static final String TO_ADDRESS; @@ -77,42 +70,16 @@ public class TransferAssetActuatorTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static TronApplicationContext context; - private static Manager dbManager; - private static Any contract; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; TO_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a146a"; NOT_EXIT_ADDRESS = Wallet.getAddressPreFixString() + "B56446E617E924805E4D6CA021D341FEF6E2013B"; NOT_EXIT_ADDRESS_2 = Wallet.getAddressPreFixString() - + "B56446E617E924805E4D6CA021D341FEF6E21234"; + + "B56446E617E924805E4D6CA021D341FEF6E21234"; ownerAsset_ADDRESS = - Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049010"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049010"; } /** @@ -121,14 +88,12 @@ public static void destroy() { @Before public void createCapsule() { AccountCapsule toAccountCapsule = - new AccountCapsule( - ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS)), - ByteString.copyFromUtf8("toAccount"), - AccountType.Normal); + new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS)), + ByteString.copyFromUtf8("toAccount"), + AccountType.Normal); dbManager.getAccountStore().put(toAccountCapsule.getAddress().toByteArray(), toAccountCapsule); - dbManager.getAccountAssetStore().put(toAccountCapsule.getAddress().toByteArray(), - new AccountAssetCapsule(toAccountCapsule.getAddress())); } private boolean isNullOrZero(Long value) { @@ -140,29 +105,29 @@ private boolean isNullOrZero(Long value) { public void createAsset(String assetName) { AccountCapsule ownerCapsule = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); ownerCapsule.addAsset(assetName.getBytes(), OWNER_ASSET_BALANCE); long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; dbManager.getDynamicPropertiesStore().saveTokenIdNum(id); AssetIssueContract assetIssueContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(assetName))) - .setId(Long.toString(id)) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(assetName))) + .setId(Long.toString(id)) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); dbManager.getAssetIssueStore() - .put(assetIssueCapsule.createDbKey(), assetIssueCapsule); + .put(assetIssueCapsule.createDbKey(), assetIssueCapsule); } private Any getContract(long sendCoin) { @@ -173,32 +138,32 @@ private Any getContract(long sendCoin) { } return Any.pack( - TransferAssetContract.newBuilder() - .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName))) - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))) - .setAmount(sendCoin) - .build()); + TransferAssetContract.newBuilder() + .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName))) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))) + .setAmount(sendCoin) + .build()); } private Any getContract(long sendCoin, ByteString assetName) { return Any.pack( - TransferAssetContract.newBuilder() - .setAssetName(assetName) - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))) - .setAmount(sendCoin) - .build()); + TransferAssetContract.newBuilder() + .setAssetName(assetName) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))) + .setAmount(sendCoin) + .build()); } private Any getContract(long sendCoin, String assetName) { return Any.pack( - TransferAssetContract.newBuilder() - .setAssetName(ByteString.copyFrom(ByteArray.fromString(assetName))) - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))) - .setAmount(sendCoin) - .build()); + TransferAssetContract.newBuilder() + .setAssetName(ByteString.copyFrom(ByteArray.fromString(assetName))) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS))) + .setAmount(sendCoin) + .build()); } private Any getContract(long sendCoin, String owner, String to) { @@ -208,12 +173,12 @@ private Any getContract(long sendCoin, String owner, String to) { assertName = String.valueOf(tokenIdNum); } return Any.pack( - TransferAssetContract.newBuilder() - .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName))) - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(owner))) - .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(to))) - .setAmount(sendCoin) - .build()); + TransferAssetContract.newBuilder() + .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName))) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(owner))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(to))) + .setAmount(sendCoin) + .build()); } private Any getContract(long sendCoin, byte[] toAddress) { @@ -224,12 +189,12 @@ private Any getContract(long sendCoin, byte[] toAddress) { } return Any.pack( - TransferAssetContract.newBuilder() - .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName))) - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setToAddress(ByteString.copyFrom(toAddress)) - .setAmount(sendCoin) - .build()); + TransferAssetContract.newBuilder() + .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName))) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress(ByteString.copyFrom(toAddress)) + .setAmount(sendCoin) + .build()); } private void createAssertBeforSameTokenNameActive() { @@ -237,33 +202,28 @@ private void createAssertBeforSameTokenNameActive() { long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; dbManager.getDynamicPropertiesStore().saveTokenIdNum(id); AssetIssueContract assetIssueContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) - .setId(Long.toString(id)) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) + .setId(Long.toString(id)) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); dbManager.getAssetIssueStore().put(assetIssueCapsule.createDbKey(), assetIssueCapsule); dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - AccountAssetCapsule ownerAssetCapsule = new AccountAssetCapsule( - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); - dbManager.getAccountAssetStore().put(ownerAssetCapsule.getAddress().toByteArray(), - ownerAssetCapsule); - AccountCapsule ownerCapsule = - new AccountCapsule( - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), - ByteString.copyFromUtf8("owner"), - AccountType.AssetIssue); + new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + ByteString.copyFromUtf8("owner"), + AccountType.AssetIssue); ownerCapsule.addAsset(ASSET_NAME.getBytes(), OWNER_ASSET_BALANCE); ownerCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), OWNER_ASSET_BALANCE); @@ -275,32 +235,27 @@ private void createAssertSameTokenNameActive() { long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; dbManager.getDynamicPropertiesStore().saveTokenIdNum(id); AssetIssueContract assetIssueContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) - .setId(Long.toString(id)) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) + .setId(Long.toString(id)) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - AccountAssetCapsule ownerAccountAssetCapsule = new AccountAssetCapsule( - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); - - dbManager.getAccountAssetStore().put(ownerAccountAssetCapsule.getAddress().toByteArray(), - ownerAccountAssetCapsule); AccountCapsule ownerCapsule = - new AccountCapsule( - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), - ByteString.copyFromUtf8("owner"), - AccountType.AssetIssue); + new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + ByteString.copyFromUtf8("owner"), + AccountType.AssetIssue); ownerCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), OWNER_ASSET_BALANCE); dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); @@ -321,21 +276,21 @@ public void SameTokenNameCloseSuccessTransfer() { actuator.execute(ret); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); // check V1 - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), - OWNER_ASSET_BALANCE - 100); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), 100L); + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), + OWNER_ASSET_BALANCE - 100); + Assert.assertEquals(toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), 100L); // check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); Assert.assertEquals( - owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE - 100); + owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE - 100); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - 100L); + toAccount.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + 100L); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -359,20 +314,20 @@ public void SameTokenNameOpenSuccessTransfer() { actuator.execute(ret); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); // V1, data is not exist - Assert.assertNull(owner.getAssetMap().get(ASSET_NAME)); - Assert.assertNull(toAccount.getAssetMap().get(ASSET_NAME)); + Assert.assertNull(owner.getAssetMapForTest().get(ASSET_NAME)); + Assert.assertNull(toAccount.getAssetMapForTest().get(ASSET_NAME)); // check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); Assert.assertEquals( - owner.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE - 100); + owner.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE - 100); Assert.assertEquals( - toAccount.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), - 100L); + toAccount.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), + 100L); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); @@ -389,7 +344,7 @@ public void SameTokenNameCloseSuccessTransfer2() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE)); + .setAny(getContract(OWNER_ASSET_BALANCE)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -397,20 +352,20 @@ public void SameTokenNameCloseSuccessTransfer2() { actuator.execute(ret); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); //check V1 - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), 0L); + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), 0L); Assert.assertEquals( - toAccount.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + toAccount.getAssetMapForTest().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); //check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); Assert.assertEquals( - owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), 0L); + owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), 0L); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); + toAccount.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -428,7 +383,7 @@ public void OldNotUpdateSuccessTransfer2() { dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE)); + .setAny(getContract(OWNER_ASSET_BALANCE)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -436,20 +391,20 @@ public void OldNotUpdateSuccessTransfer2() { actuator.execute(ret); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); //check V1 - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertNull(toAccount.getAssetMap().get(ASSET_NAME)); + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertNull(toAccount.getAssetMapForTest().get(ASSET_NAME)); //check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); Assert.assertEquals( - owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), 0L); + owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), 0L); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); + toAccount.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -465,7 +420,7 @@ public void SameTokenNameOpenSuccessTransfer2() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE)); + .setAny(getContract(OWNER_ASSET_BALANCE)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -473,19 +428,19 @@ public void SameTokenNameOpenSuccessTransfer2() { actuator.execute(ret); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); // V1, data is not exist - Assert.assertNull(owner.getAssetMap().get(ASSET_NAME)); - Assert.assertNull(toAccount.getAssetMap().get(ASSET_NAME)); + Assert.assertNull(owner.getAssetMapForTest().get(ASSET_NAME)); + Assert.assertNull(toAccount.getAssetMapForTest().get(ASSET_NAME)); //check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); Assert.assertEquals( - owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), 0L); + owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), 0L); Assert.assertEquals( - toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); + toAccount.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -500,12 +455,11 @@ public void SameTokenNameOpenSuccessTransfer2() { public void SameTokenNameCloseOwnerNoAssetTest() { createAssertBeforSameTokenNameActive(); AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); - owner.importAsset(); owner.setInstance(owner.getInstance().toBuilder().clearAsset().build()); dbManager.getAccountStore().put(owner.createDbKey(), owner); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE)); + .setAny(getContract(OWNER_ASSET_BALANCE)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -514,11 +468,10 @@ public void SameTokenNameCloseOwnerNoAssetTest() { Assert.assertTrue(false); } catch (ContractValidateException e) { Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Owner has no asset!", e.getMessage()); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -535,7 +488,7 @@ public void SameTokenNameOpenOwnerNoAssetTest() { dbManager.getAccountStore().put(owner.createDbKey(), owner); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE)); + .setAny(getContract(OWNER_ASSET_BALANCE)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -544,12 +497,12 @@ public void SameTokenNameOpenOwnerNoAssetTest() { Assert.assertTrue(false); } catch (ContractValidateException e) { Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Owner has no asset!", e.getMessage()); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertTrue(isNullOrZero( + toAccount.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -563,7 +516,7 @@ public void SameTokenNameCloseNotEnoughAssetTest() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE + 1)); + .setAny(getContract(OWNER_ASSET_BALANCE + 1)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -575,11 +528,12 @@ public void SameTokenNameCloseNotEnoughAssetTest() { Assert.assertTrue("assetBalance is not sufficient.".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest().get(ASSET_NAME).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -593,7 +547,7 @@ public void SameTokenNameOpenNotEnoughAssetTest() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(OWNER_ASSET_BALANCE + 1)); + .setAny(getContract(OWNER_ASSET_BALANCE + 1)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -605,13 +559,14 @@ public void SameTokenNameOpenNotEnoughAssetTest() { Assert.assertTrue("assetBalance is not sufficient.".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetV2MapForTest() + .get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -635,11 +590,12 @@ public void SameTokenNameCloseZeroAmountTest() { Assert.assertTrue("Amount must be greater than 0.".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -665,13 +621,14 @@ public void SameTokenNameOpenZeroAmountTest() { Assert.assertTrue("Amount must be greater than 0.".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -696,11 +653,12 @@ public void SameTokenNameCloseNegativeAmountTest() { Assert.assertTrue("Amount must be greater than 0.".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -726,13 +684,14 @@ public void SameTokenNameOpenNegativeAmountTest() { Assert.assertTrue("Amount must be greater than 0.".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -746,7 +705,7 @@ public void SameTokenNameCloseNoneExistAssetTest() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(1, "TTTTTTTTTTTT")); + .setAny(getContract(1, "TTTTTTTTTTTT")); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -758,11 +717,12 @@ public void SameTokenNameCloseNoneExistAssetTest() { Assert.assertTrue("No asset!".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -776,7 +736,7 @@ public void SameTokenNameOpenNoneExistAssetTest() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(1, "TTTTTTTTTTTT")); + .setAny(getContract(1, "TTTTTTTTTTTT")); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -788,13 +748,14 @@ public void SameTokenNameOpenNoneExistAssetTest() { Assert.assertTrue("No asset!".equals(e.getMessage())); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest() + .get(String.valueOf(tokenIdNum)).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -809,30 +770,30 @@ public void SameTokenNameCloseNoExitToAccount() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS, NOT_EXIT_ADDRESS)); + .setAny(getContract(100L, OWNER_ADDRESS, NOT_EXIT_ADDRESS)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { AccountCapsule noExitAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS)); + .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS)); Assert.assertTrue(null == noExitAccount); actuator.validate(); actuator.execute(ret); noExitAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS)); + .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS)); Assert.assertFalse(null == noExitAccount); //Had created. Assert.assertEquals(noExitAccount.getBalance(), 0); actuator.execute(ret); } catch (ContractValidateException e) { Assert.assertTrue(e instanceof ContractValidateException); - Assert - .assertEquals("Validate TransferAssetActuator error, insufficient fee.", e.getMessage()); + Assert.assertEquals( + "Validate TransferAssetActuator error, insufficient fee.", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert - .assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); AccountCapsule noExitAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS)); + .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS)); Assert.assertTrue(noExitAccount == null); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -847,31 +808,31 @@ public void SameTokenNameOpenNoExitToAccount() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS, NOT_EXIT_ADDRESS_2)); + .setAny(getContract(100L, OWNER_ADDRESS, NOT_EXIT_ADDRESS_2)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { AccountCapsule noExitAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS_2)); + .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS_2)); Assert.assertTrue(null == noExitAccount); actuator.validate(); actuator.execute(ret); noExitAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS_2)); + .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS_2)); Assert.assertFalse(null == noExitAccount); //Had created. Assert.assertEquals(noExitAccount.getBalance(), 0); actuator.execute(ret); } catch (ContractValidateException e) { Assert.assertTrue(e instanceof ContractValidateException); - Assert - .assertEquals("Validate TransferAssetActuator error, insufficient fee.", e.getMessage()); + Assert.assertEquals( + "Validate TransferAssetActuator error, insufficient fee.", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); + Assert.assertEquals(owner.getAssetV2MapForTest() + .get(String.valueOf(tokenIdNum)).longValue(), OWNER_ASSET_BALANCE); AccountCapsule noExitAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS_2)); + .get(ByteArray.fromHexString(NOT_EXIT_ADDRESS_2)); Assert.assertTrue(noExitAccount == null); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); @@ -900,11 +861,13 @@ public void SameTokenNameCloseAddOverflowTest() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertTrue("long overflow".equals(e.getMessage())); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertEquals(toAccount.getAssetMap().get(ASSET_NAME).longValue(), Long.MAX_VALUE); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertEquals(toAccount.getAssetMapForTest() + .get(ASSET_NAME).longValue(), Long.MAX_VALUE); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -934,13 +897,13 @@ public void SameTokenNameOpenAddOverflowTest() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertTrue("long overflow".equals(e.getMessage())); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); toAccount = dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertEquals(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - Long.MAX_VALUE); + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertEquals(toAccount.getAssetV2MapForTest() + .get(String.valueOf(tokenIdNum)).longValue(), Long.MAX_VALUE); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -954,7 +917,7 @@ public void SameTokenNameCloseTransferToYourself() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS, OWNER_ADDRESS)); + .setAny(getContract(100L, OWNER_ADDRESS, OWNER_ADDRESS)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -966,11 +929,12 @@ public void SameTokenNameCloseTransferToYourself() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Cannot transfer asset to yourself.", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + .get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -985,7 +949,7 @@ public void SameTokenNameOpenTransferToYourself() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS, OWNER_ADDRESS)); + .setAny(getContract(100L, OWNER_ADDRESS, OWNER_ADDRESS)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -997,13 +961,14 @@ public void SameTokenNameOpenTransferToYourself() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Cannot transfer asset to yourself.", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(TO_ADDRESS)); + .get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1017,7 +982,7 @@ public void SameTokenNameCloseInvalidOwnerAddress() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS_INVALID, TO_ADDRESS)); + .setAny(getContract(100L, OWNER_ADDRESS_INVALID, TO_ADDRESS)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1028,11 +993,12 @@ public void SameTokenNameCloseInvalidOwnerAddress() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Invalid ownerAddress", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + .get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertTrue(e instanceof ContractExeException); } @@ -1046,7 +1012,7 @@ public void SameTokenNameOpenInvalidOwnerAddress() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS_INVALID, TO_ADDRESS)); + .setAny(getContract(100L, OWNER_ADDRESS_INVALID, TO_ADDRESS)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1057,13 +1023,14 @@ public void SameTokenNameOpenInvalidOwnerAddress() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Invalid ownerAddress", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(TO_ADDRESS)); + .get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertTrue(e instanceof ContractExeException); } @@ -1077,7 +1044,7 @@ public void SameTokenNameCloseInvalidToAddress() { createAssertBeforSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS, TO_ADDRESS_INVALID)); + .setAny(getContract(100L, OWNER_ADDRESS, TO_ADDRESS_INVALID)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1088,11 +1055,12 @@ public void SameTokenNameCloseInvalidToAddress() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Invalid toAddress", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + .get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1106,7 +1074,7 @@ public void SameTokenNameOpenInvalidToAddress() { createAssertSameTokenNameActive(); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, OWNER_ADDRESS, TO_ADDRESS_INVALID)); + .setAny(getContract(100L, OWNER_ADDRESS, TO_ADDRESS_INVALID)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1117,13 +1085,14 @@ public void SameTokenNameOpenInvalidToAddress() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Invalid toAddress", e.getMessage()); AccountCapsule owner = dbManager.getAccountStore() - .get(ByteArray.fromHexString(OWNER_ADDRESS)); + .get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = dbManager.getAccountStore() - .get(ByteArray.fromHexString(TO_ADDRESS)); + .get(ByteArray.fromHexString(TO_ADDRESS)); long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest() + .get(String.valueOf(tokenIdNum)).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1136,33 +1105,34 @@ public void SameTokenNameOpenInvalidToAddress() { public void SameTokenNameCloseOwnerNoThisAsset() { createAssertBeforSameTokenNameActive(); AccountCapsule ownerAssetCapsule = - new AccountCapsule( - ByteString.copyFrom(ByteArray.fromHexString(ownerAsset_ADDRESS)), - ByteString.copyFromUtf8("ownerAsset"), - AccountType.AssetIssue); + new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(ownerAsset_ADDRESS)), + ByteString.copyFromUtf8("ownerAsset"), + AccountType.AssetIssue); ownerAssetCapsule.addAsset(ownerASSET_NAME.getBytes(), OWNER_ASSET_Test_BALANCE); AssetIssueContract assetIssueTestContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAsset_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(ownerASSET_NAME))) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom( + ByteArray.fromHexString(ownerAsset_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(ownerASSET_NAME))) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueTestContract); dbManager.getAccountStore() - .put(ownerAssetCapsule.getAddress().toByteArray(), ownerAssetCapsule); + .put(ownerAssetCapsule.getAddress().toByteArray(), ownerAssetCapsule); dbManager - .getAssetIssueStore() - .put(assetIssueCapsule.createDbKey(), assetIssueCapsule); + .getAssetIssueStore() + .put(assetIssueCapsule.createDbKey(), assetIssueCapsule); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(1, ownerASSET_NAME)); + .setAny(getContract(1, ownerASSET_NAME)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1173,15 +1143,16 @@ public void SameTokenNameCloseOwnerNoThisAsset() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertTrue("assetBalance must be greater than 0.".equals(e.getMessage())); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMap().get(ASSET_NAME))); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest() + .get(ASSET_NAME).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount.getAssetMapForTest().get(ASSET_NAME))); AccountCapsule ownerAsset = - dbManager.getAccountStore().get(ByteArray.fromHexString(ownerAsset_ADDRESS)); - Assert.assertEquals(ownerAsset.getAssetMap().get(ownerASSET_NAME).longValue(), - OWNER_ASSET_Test_BALANCE); + dbManager.getAccountStore().get(ByteArray.fromHexString(ownerAsset_ADDRESS)); + Assert.assertEquals(ownerAsset.getAssetMapForTest() + .get(ownerASSET_NAME).longValue(), OWNER_ASSET_Test_BALANCE); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1195,36 +1166,37 @@ public void SameTokenNameOpenOwnerNoThisAsset() { createAssertSameTokenNameActive(); long tokenIdNum = 2000000; AccountCapsule ownerAssetCapsule = - new AccountCapsule( - ByteString.copyFrom(ByteArray.fromHexString(ownerAsset_ADDRESS)), - ByteString.copyFromUtf8("ownerAsset"), - AccountType.AssetIssue); + new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(ownerAsset_ADDRESS)), + ByteString.copyFromUtf8("ownerAsset"), + AccountType.AssetIssue); ownerAssetCapsule.addAssetV2(ByteArray.fromString(String.valueOf(tokenIdNum)), - OWNER_ASSET_Test_BALANCE); + OWNER_ASSET_Test_BALANCE); AssetIssueContract assetIssueTestContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAsset_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(ownerASSET_NAME))) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setId(String.valueOf(tokenIdNum)) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom( + ByteArray.fromHexString(ownerAsset_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(ownerASSET_NAME))) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setId(String.valueOf(tokenIdNum)) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueTestContract); dbManager.getAccountStore() - .put(ownerAssetCapsule.getAddress().toByteArray(), ownerAssetCapsule); + .put(ownerAssetCapsule.getAddress().toByteArray(), ownerAssetCapsule); dbManager.getAssetIssueV2Store() - .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(1, String.valueOf(tokenIdNum))); + .setAny(getContract(1, String.valueOf(tokenIdNum))); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1235,17 +1207,19 @@ public void SameTokenNameOpenOwnerNoThisAsset() { Assert.assertTrue(e instanceof ContractValidateException); Assert.assertTrue("assetBalance must be greater than 0.".equals(e.getMessage())); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); long secondTokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(secondTokenIdNum)).longValue(), - OWNER_ASSET_BALANCE); - Assert.assertTrue(isNullOrZero(toAccount.getAssetMapV2().get(String.valueOf(tokenIdNum)))); + Assert.assertEquals(owner.getAssetV2MapForTest() + .get(String.valueOf(secondTokenIdNum)).longValue(), OWNER_ASSET_BALANCE); + Assert.assertTrue(isNullOrZero(toAccount + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)))); AccountCapsule ownerAsset = - dbManager.getAccountStore().get(ByteArray.fromHexString(ownerAsset_ADDRESS)); - Assert.assertEquals(ownerAsset.getAssetMapV2().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_Test_BALANCE); + dbManager.getAccountStore().get(ByteArray.fromHexString(ownerAsset_ADDRESS)); + Assert.assertEquals(ownerAsset + .getAssetV2MapForTest().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_Test_BALANCE); } catch (ContractExeException e) { Assert.assertFalse(e instanceof ContractExeException); } @@ -1260,19 +1234,19 @@ public void sameTokenNameCloseNoOwnerAccount() { long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; dbManager.getDynamicPropertiesStore().saveTokenIdNum(id); AssetIssueContract assetIssueContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) - .setId(Long.toString(id)) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) + .setId(Long.toString(id)) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); dbManager.getAssetIssueStore().put(assetIssueCapsule.createDbKey(), assetIssueCapsule); @@ -1308,7 +1282,7 @@ public void SameTokenNameCloseAssetNameTest() { ByteString emptyName = ByteString.EMPTY; TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, emptyName)); + .setAny(getContract(100L, emptyName)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { @@ -1330,18 +1304,18 @@ public void SameTokenNameCloseAssetNameTest() { createAsset(assetName); actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, assetName)); + .setAny(getContract(100L, assetName)); try { actuator.validate(); actuator.execute(ret); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(assetName).longValue(), - OWNER_ASSET_BALANCE - 100); - Assert.assertEquals(toAccount.getAssetMap().get(assetName).longValue(), 100L); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest().get(assetName).longValue(), + OWNER_ASSET_BALANCE - 100); + Assert.assertEquals(toAccount.getAssetMapForTest().get(assetName).longValue(), 100L); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1353,18 +1327,18 @@ public void SameTokenNameCloseAssetNameTest() { createAsset(assetName); actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, assetName)); + .setAny(getContract(100L, assetName)); try { actuator.validate(); actuator.execute(ret); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); - Assert.assertEquals(owner.getAssetMap().get(assetName).longValue(), - OWNER_ASSET_BALANCE - 100); - Assert.assertEquals(toAccount.getAssetMap().get(assetName).longValue(), 100L); + dbManager.getAccountStore().get(ByteArray.fromHexString(TO_ADDRESS)); + Assert.assertEquals(owner.getAssetMapForTest().get(assetName).longValue(), + OWNER_ASSET_BALANCE - 100); + Assert.assertEquals(toAccount.getAssetMapForTest().get(assetName).longValue(), 100L); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -1380,10 +1354,10 @@ public void commonErrorCheck() { actuatorTest.noContract(); Any invalidContractTypes = Any.pack(AssetIssueContractOuterClass.AssetIssueContract.newBuilder() - .build()); + .build()); actuatorTest.setInvalidContract(invalidContractTypes); actuatorTest.setInvalidContractTypeMsg("contract type error", - "contract type error, expected type [TransferAssetContract], real type["); + "contract type error, expected type [TransferAssetContract], real type["); actuatorTest.invalidContractType(); actuatorTest.setContract(getContract(100L)); @@ -1398,8 +1372,8 @@ public void commonErrorCheck() { */ @Test public void transferToContractAddress() - throws ContractExeException, ReceiptCheckErrException, VMIllegalException, - ContractValidateException, BalanceInsufficientException { + throws ContractExeException, ReceiptCheckErrException, VMIllegalException, + ContractValidateException, BalanceInsufficientException { dbManager.getDynamicPropertiesStore().saveForbidTransferToContract(1); createAssertSameTokenNameActive(); VMConfig.initAllowMultiSign(1); @@ -1408,53 +1382,55 @@ public void transferToContractAddress() VMConfig.initAllowTvmSolidity059(1); String contractName = "testContract"; byte[] address = Hex.decode(OWNER_ADDRESS); - adjustBalance(dbManager.getChainBaseManager().getAccountStore(), address, 1000000000L); - - String ABI = - "[]"; - String codes = "608060405261019c806100136000396000f3fe608060405260043610610045577c0100000000000" - + "00000000000000000000000000000000000000000000060003504632a205edf811461004a5780634cd2270c" - + "146100c8575b600080fd5b34801561005657600080fd5b50d3801561006357600080fd5b50d2801561007057" - + "600080fd5b506100c6600480360360c081101561008757600080fd5b5073ffffffffffffffffffffffffffff" - + "ffffffffffff813581169160208101358216916040820135169060608101359060808101359060a001356100" - + "d0565b005b6100c661016e565b60405173ffffffffffffffffffffffffffffffffffffffff87169084156108" - + "fc029085906000818181858888f1505060405173ffffffffffffffffffffffffffffffffffffffff89169350" - + "85156108fc0292508591506000818181858888f1505060405173ffffffffffffffffffffffffffffffffffff" - + "ffff8816935084156108fc0292508491506000818181858888f15050505050505050505050565b56fea16562" - + "7a7a72305820cc2d598d1b3f968bbdc7825ce83d22dad48192f4bf95bda7f9e4ddf61669ba830029"; + adjustBalance(dbManager.getChainBaseManager() + .getAccountStore(), address, 1000000000L); + + String ABI = "[]"; + String codes = "608060405261019c806100136000396000f3fe6080604052600436106100455" + + "77c01000000000000000000000000000000000000000000000000000000006000350" + + "4632a205edf811461004a5780634cd2270c146100c8575b600080fd5b34801561005" + + "657600080fd5b50d3801561006357600080fd5b50d2801561007057600080fd5b506" + + "100c6600480360360c081101561008757600080fd5b5073fffffffffffffffffffff" + + "fffffffffffffffffff8135811691602081013582169160408201351690606081013" + + "59060808101359060a001356100d0565b005b6100c661016e565b60405173fffffff" + + "fffffffffffffffffffffffffffffffff87169084156108fc0290859060008181818" + + "58888f1505060405173ffffffffffffffffffffffffffffffffffffffff891693508" + + "5156108fc0292508591506000818181858888f1505060405173fffffffffffffffff" + + "fffffffffffffffffffffff8816935084156108fc029250849150600081818185888" + + "8f15050505050505050505050565b56fea165627a7a72305820cc2d598d1b3f968bb" + + "dc7825ce83d22dad48192f4bf95bda7f9e4ddf61669ba830029"; long value = 1; long feeLimit = 1000000000L; long consumeUserResourcePercent = 0; - DepositImpl deposit = DepositImpl.createRoot(dbManager); - byte[] contractAddress = TvmTestUtils - .deployContractWholeProcessReturnContractAddress(contractName, address, ABI, codes, value, - feeLimit, consumeUserResourcePercent, null, 0, 0, - deposit, null); + RepositoryImpl repository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + byte[] contractAddress = TvmTestUtils.deployContractWholeProcessReturnContractAddress( + contractName, address, ABI, codes, value, feeLimit, consumeUserResourcePercent, + null, 0, 0, repository, null); TransferAssetActuator actuator = new TransferAssetActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) - .setAny(getContract(100L, contractAddress)); + .setAny(getContract(100L, contractAddress)); TransactionResultCapsule ret = new TransactionResultCapsule(); try { actuator.validate(); actuator.execute(ret); Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); AccountCapsule owner = - dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); AccountCapsule toAccount = - dbManager.getAccountStore().get(contractAddress); + dbManager.getAccountStore().get(contractAddress); // V1, data is not exist - Assert.assertNull(owner.getAssetMap().get(ASSET_NAME)); - Assert.assertNull(toAccount.getAssetMap().get(ASSET_NAME)); + Assert.assertNull(owner.getAssetMapForTest().get(ASSET_NAME)); + Assert.assertNull(toAccount.getAssetMapForTest().get(ASSET_NAME)); // check V2 long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum(); Assert.assertEquals( - owner.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), - OWNER_ASSET_BALANCE - 100); + owner.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), + OWNER_ASSET_BALANCE - 100); Assert.assertEquals( - toAccount.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), - 100L); + toAccount.getInstance().getAssetV2Map().get(String.valueOf(tokenIdNum)).longValue(), + 100L); } catch (ContractValidateException e) { Assert.assertTrue(e.getMessage().contains("Cannot transfer")); } catch (ContractExeException e) { diff --git a/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java new file mode 100644 index 00000000000..eea1a0bf9b7 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/UnDelegateResourceActuatorTest.java @@ -0,0 +1,1026 @@ +package org.tron.core.actuator; + +import static junit.framework.TestCase.fail; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract.UnDelegateResourceContract; +import org.tron.protos.contract.Common.ResourceCode; + +@Slf4j +public class UnDelegateResourceActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "aaaa"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 10_000_000_000L; + private static final long delegateBalance = 1_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + /** + * create temp Capsule test need. + */ + @Before + public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + AccountCapsule receiverCapsule = new AccountCapsule(ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + + // clear delegate + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + dbManager.getDelegatedResourceStore().delete(DelegatedResourceCapsule.createDbKeyV2( + owner, receiver, false)); + dbManager.getDelegatedResourceStore().delete(DelegatedResourceCapsule.createDbKeyV2( + owner, receiver, true)); + dbManager.getDelegatedResourceAccountIndexStore().unDelegateV2(owner, receiver); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + } + + public void delegateBandwidthForOwner() { + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + dbManager.getAccountStore().put(owner, ownerCapsule); + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + dbManager.getAccountStore().put(receiver, receiverCapsule); + dbManager.getDynamicPropertiesStore().addTotalNetWeight(delegateBalance / TRX_PRECISION); + + DelegatedResourceCapsule delegatedResourceCapsule = new DelegatedResourceCapsule( + ByteString.copyFrom(owner), + ByteString.copyFrom(receiver)); + delegatedResourceCapsule.setFrozenBalanceForBandwidth(delegateBalance, 0); + dbManager.getDelegatedResourceStore().put( + DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false), delegatedResourceCapsule); + + dbManager.getDelegatedResourceAccountIndexStore().delegateV2(owner, receiver, 1); + } + + public void delegateLockedBandwidthForOwner(long period) { + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.addDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + dbManager.getAccountStore().put(owner, ownerCapsule); + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForBandwidth(delegateBalance); + dbManager.getAccountStore().put(receiver, receiverCapsule); + dbManager.getDynamicPropertiesStore().addTotalNetWeight(delegateBalance / TRX_PRECISION); + + DelegatedResourceCapsule delegatedResourceCapsule = new DelegatedResourceCapsule( + ByteString.copyFrom(owner), + ByteString.copyFrom(receiver)); + delegatedResourceCapsule.setFrozenBalanceForBandwidth(delegateBalance, period); + dbManager.getDelegatedResourceStore().put(DelegatedResourceCapsule + .createDbKeyV2(owner, receiver, true), delegatedResourceCapsule); + + dbManager.getDelegatedResourceAccountIndexStore().delegateV2(owner, receiver, 1); + } + + public void delegateCpuForOwner() { + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.addDelegatedFrozenV2BalanceForEnergy(delegateBalance); + dbManager.getAccountStore().put(owner, ownerCapsule); + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.addAcquiredDelegatedFrozenV2BalanceForEnergy(delegateBalance); + dbManager.getAccountStore().put(receiver, receiverCapsule); + dbManager.getDynamicPropertiesStore().addTotalEnergyWeight(delegateBalance / TRX_PRECISION); + + DelegatedResourceCapsule delegatedResourceCapsule = new DelegatedResourceCapsule( + ByteString.copyFrom(owner), + ByteString.copyFrom(receiver)); + delegatedResourceCapsule.setFrozenBalanceForEnergy(delegateBalance, 0); + dbManager.getDelegatedResourceStore().put( + DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false), delegatedResourceCapsule); + + dbManager.getDelegatedResourceAccountIndexStore().delegateV2(owner, receiver, 1); + } + + private Any getDelegatedContractForBandwidth(String ownerAddress, long balance) { + return Any.pack(UnDelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setBalance(balance).build()); + } + + private Any getDelegatedContractForCpu(long balance) { + return Any.pack(UnDelegateResourceContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .setResource(ResourceCode.ENERGY) + .setBalance(balance).build()); + } + + // test start + @Test + public void testUnDelegateForBandwidth() { + delegateBandwidthForOwner(); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + receiverCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setNetUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1000000000, ownerCapsule.getNetUsage()); + Assert.assertEquals(nowSlot, ownerCapsule.getLatestConsumeTime()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(0, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, receiverCapsule.getNetUsage()); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedCapsule = dbManager.getDelegatedResourceStore().get(key); + Assert.assertNull(delegatedCapsule); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(0, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(0, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testLockedUnDelegateForBandwidth() { + delegateLockedBandwidthForOwner(DELEGATE_PERIOD); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + receiverCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setNetUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + + Assert.assertNull(delegatedResourceCapsule); + Assert.assertNotNull(lockedResourceCapsule); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check + DelegatedResourceCapsule delegatedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNull(delegatedResourceCapsule1); + Assert.assertNull(lockedResourceCapsule1); + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1000000000, ownerCapsule.getNetUsage()); + Assert.assertEquals(nowSlot, ownerCapsule.getLatestConsumeTime()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(0, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, receiverCapsule.getNetUsage()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testLockedAndUnlockUnDelegateForBandwidth() { + delegateLockedBandwidthForOwner(Long.MAX_VALUE); + delegateBandwidthForOwner(); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + receiverCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setNetUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(2 * delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, + ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNotNull(delegatedResourceCapsule); + Assert.assertNotNull(lockedResourceCapsule); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check DelegatedResource + DelegatedResourceCapsule delegatedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNull(delegatedResourceCapsule1); + Assert.assertNotNull(lockedResourceCapsule1); + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(1000000000, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(750000000, ownerCapsule.getNetUsage()); + Assert.assertEquals(nowSlot, ownerCapsule.getLatestConsumeTime()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(1000000000, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(250000000, receiverCapsule.getNetUsage()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + + @Test + public void testLockedAndUnlockUnDelegateForBandwidthUsingWindowSizeV2() { + delegateLockedBandwidthForOwner(Long.MAX_VALUE); + delegateBandwidthForOwner(); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + receiverCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setNetUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(2 * delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, + ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNotNull(delegatedResourceCapsule); + Assert.assertNotNull(lockedResourceCapsule); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check DelegatedResource + DelegatedResourceCapsule delegatedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule1 = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNull(delegatedResourceCapsule1); + Assert.assertNotNull(lockedResourceCapsule1); + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(1000000000, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(2 * delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(750000000, ownerCapsule.getNetUsage()); + Assert.assertEquals(nowSlot, ownerCapsule.getLatestConsumeTime()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(1000000000, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(250000000, receiverCapsule.getNetUsage()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(0); + } + + @Test + public void testLockedUnDelegateBalanceForBandwidthInsufficient() { + delegateLockedBandwidthForOwner(Long.MAX_VALUE); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + receiverCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setNetUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTime(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + DelegatedResourceCapsule delegatedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false)); + DelegatedResourceCapsule lockedResourceCapsule = dbManager.getDelegatedResourceStore() + .get(DelegatedResourceCapsule.createDbKeyV2(owner, receiver, true)); + Assert.assertNull(delegatedResourceCapsule); + Assert.assertNotNull(lockedResourceCapsule); + + actuator.validate(); + Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("insufficient delegatedFrozenBalance(BANDWIDTH), " + + "request=1000000000, unlock_balance=0", e.getMessage()); + } + } + + @Test + public void testPartialUnDelegateForBandwidth() { + delegateBandwidthForOwner(); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setNetUsage(1_000_000_000); + receiverCapsule.setLatestConsumeTime(dbManager.getChainBaseManager().getHeadSlot()); + dbManager.getAccountStore().put(receiver, receiverCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance / 2)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(0, ownerCapsule.getNetUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getNetUsage()); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance / 2, + ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance / 2, + ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1000000000 / 2, ownerCapsule.getNetUsage()); + Assert.assertEquals(dbManager.getChainBaseManager().getHeadSlot(), + ownerCapsule.getLatestConsumeTime()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(delegateBalance / 2, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(1000000000 / 2, receiverCapsule.getNetUsage()); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedResourceCapsule = + dbManager.getDelegatedResourceStore().get(key); + Assert.assertEquals(delegateBalance / 2, + delegatedResourceCapsule.getFrozenBalanceForBandwidth()); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(1, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testUnDelegatedForBandwidthWithDeletedReceiver() { + delegateBandwidthForOwner(); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + dbManager.getAccountStore().delete(receiver); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(0, ownerCapsule.getNetUsage()); + + // check receiver + Assert.assertNull(dbManager.getAccountStore().get(receiver)); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedResourceCapsule = + dbManager.getDelegatedResourceStore().get(key); + Assert.assertNull(delegatedResourceCapsule); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(0, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(0, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + + } + + @Test + public void testUnDelegatedForBandwidthWithRecreatedReceiver() { + delegateBandwidthForOwner(); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + dbManager.getAccountStore().delete(receiver); + + AccountCapsule receiverCapsule = new AccountCapsule(ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), AccountType.Normal, + initBalance); + receiverCapsule.setAcquiredDelegatedFrozenV2BalanceForBandwidth(10L); + dbManager.getAccountStore().put(receiver, receiverCapsule); + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(10, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(0, ownerCapsule.getNetUsage()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(0, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForBandwidth()); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedCapsule = dbManager.getDelegatedResourceStore().get(key); + Assert.assertNull(delegatedCapsule); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(0, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(0, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + + } + + @Test + public void testUnDelegatedForCpu() { + delegateCpuForOwner(); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + long nowSlot = dbManager.getChainBaseManager().getHeadSlot(); + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setEnergyUsage(1_000_000_000); + receiverCapsule.setLatestConsumeTimeForEnergy(nowSlot - 14400); + dbManager.getAccountStore().put(receiver, receiverCapsule); + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + ownerCapsule.setEnergyUsage(1_000_000_000); + ownerCapsule.setLatestConsumeTimeForEnergy(nowSlot - 14400); + dbManager.getAccountStore().put(owner, ownerCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForCpu(delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getEnergyUsage()); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(nowSlot, ownerCapsule.getLatestConsumeTimeForEnergy()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(0, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(0, receiverCapsule.getEnergyUsage()); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedCapsule = dbManager.getDelegatedResourceStore().get(key); + Assert.assertNull(delegatedCapsule); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(0, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(0, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testPartialUnDelegatedForCpu() { + delegateCpuForOwner(); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule receiverCapsule = dbManager.getAccountStore().get(receiver); + receiverCapsule.setEnergyUsage(1_000_000_000); + receiverCapsule.setLatestConsumeTimeForEnergy(dbManager.getChainBaseManager().getHeadSlot()); + dbManager.getAccountStore().put(receiver, receiverCapsule); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForCpu(delegateBalance / 2)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(0, ownerCapsule.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(0, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(1_000_000_000, receiverCapsule.getEnergyUsage()); + + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(delegateBalance / 2, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance / 2, ownerCapsule.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(1_000_000_000 / 2, ownerCapsule.getEnergyUsage()); + Assert.assertEquals(dbManager.getChainBaseManager().getHeadSlot(), + ownerCapsule.getLatestConsumeTimeForEnergy()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(delegateBalance / 2, + receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(1_000_000_000 / 2, receiverCapsule.getEnergyUsage()); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedCapsule = dbManager.getDelegatedResourceStore().get(key); + Assert.assertEquals(delegateBalance / 2, + delegatedCapsule.getFrozenBalanceForEnergy()); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(1, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(1, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void testUnDelegatedForCpuWithDeletedReceiver() { + delegateCpuForOwner(); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + dbManager.getAccountStore().delete(receiver); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForCpu(delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(0, ownerCapsule.getEnergyUsage()); + + // check receiver + Assert.assertNull(dbManager.getAccountStore().get(receiver)); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedCapsule = dbManager.getDelegatedResourceStore().get(key); + Assert.assertNull(delegatedCapsule); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(0, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(0, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + + } + + @Test + public void testUnDelegatedForCpuWithRecreatedReceiver() { + delegateCpuForOwner(); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + byte[] receiver = ByteArray.fromHexString(RECEIVER_ADDRESS); + dbManager.getAccountStore().delete(receiver); + + AccountCapsule receiverCapsule = new AccountCapsule(ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), AccountType.Normal, + initBalance); + receiverCapsule.setAcquiredDelegatedFrozenV2BalanceForEnergy(10L); + dbManager.getAccountStore().put(receiver, receiverCapsule); + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(10, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForCpu(delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + + // check owner + AccountCapsule ownerCapsule = dbManager.getAccountStore().get(owner); + Assert.assertEquals(0, ownerCapsule.getDelegatedFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getFrozenV2BalanceForEnergy()); + Assert.assertEquals(delegateBalance, ownerCapsule.getTronPower()); + Assert.assertEquals(0, ownerCapsule.getEnergyUsage()); + + // check receiver + receiverCapsule = dbManager.getAccountStore().get(receiver); + Assert.assertEquals(0, receiverCapsule.getAcquiredDelegatedFrozenV2BalanceForEnergy()); + + //check DelegatedResource + byte[] key = DelegatedResourceCapsule.createDbKeyV2(owner, receiver, false); + DelegatedResourceCapsule delegatedResourceCapsule = + dbManager.getDelegatedResourceStore().get(key); + Assert.assertNull(delegatedResourceCapsule); + + //check DelegatedResourceAccountIndex + DelegatedResourceAccountIndexCapsule ownerIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(owner); + Assert.assertEquals(0, ownerIndexCapsule.getFromAccountsList().size()); + Assert.assertEquals(0, ownerIndexCapsule.getToAccountsList().size()); + + DelegatedResourceAccountIndexCapsule receiverIndexCapsule = dbManager + .getDelegatedResourceAccountIndexStore().getV2Index(receiver); + Assert.assertEquals(0, receiverIndexCapsule.getToAccountsList().size()); + Assert.assertEquals(0, receiverIndexCapsule.getFromAccountsList().size()); + + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(e.getMessage()); + } + + } + + @Test + public void invalidOwnerAddress() { + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForBandwidth(OWNER_ADDRESS_INVALID, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + Assert.assertEquals("Invalid address", e.getMessage()); + + } catch (ContractExeException e) { + Assert.fail(e.getMessage()); + } + + } + + @Test + public void invalidOwnerAccount() { + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()).setAny( + getDelegatedContractForBandwidth(OWNER_ACCOUNT_INVALID, delegateBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] does not exist", + e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void noDelegateBalance() { + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + + try { + actuator.validate(); + Assert.fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertEquals("delegated Resource does not exist", e.getMessage()); + } + + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForCpu(delegateBalance)); + + try { + actuator.validate(); + Assert.fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertEquals("delegated Resource does not exist", e.getMessage()); + } + } + + @Test + public void commonErrorCheck() { + delegateBandwidthForOwner(); + UnDelegateResourceActuator actuator = new UnDelegateResourceActuator(); + ActuatorTest actuatorTest = new ActuatorTest(actuator, dbManager); + actuatorTest.noContract(); + + Any invalidContractTypes = Any.pack(AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .build()); + actuatorTest.setInvalidContract(invalidContractTypes); + actuatorTest.setInvalidContractTypeMsg("contract type error", + "contract type error, expected type [UnDelegateResourceContract], real type["); + actuatorTest.invalidContractType(); + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + Assert.assertEquals(0, accountCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, accountCapsule.getDelegatedFrozenV2BalanceForBandwidth()); + Assert.assertEquals(delegateBalance, accountCapsule.getTronPower()); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + actuatorTest.setContract(getDelegatedContractForBandwidth(OWNER_ADDRESS, delegateBalance)); + actuatorTest.nullTransationResult(); + + actuatorTest.setNullDBManagerMsg("No account store or dynamic store!"); + actuatorTest.nullDBManger(); + } +} + diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java index f83260256a7..7471e9ba20f 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeAssetActuatorTest.java @@ -2,26 +2,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.Account; @@ -33,49 +26,22 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; @Slf4j -public class UnfreezeAssetActuatorTest { +public class UnfreezeAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_unfreeze_asset_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long frozenBalance = 1_000_000_000L; private static final String assetName = "testCoin"; - private static final String assetID = "123456"; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -106,11 +72,6 @@ private void createAssertBeforSameTokenNameActive() { dbManager.getAssetIssueStore().put(assetIssueCapsule.createDbKey(), assetIssueCapsule); dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - AccountAssetCapsule ownerAddressAsset = - new AccountAssetCapsule(StringUtil.hexString2ByteString(OWNER_ADDRESS)); - dbManager.getAccountAssetStore().put(ownerAddressAsset.getAddress().toByteArray(), - ownerAddressAsset); - AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFromUtf8("owner"), @@ -132,11 +93,6 @@ private void createAssertSameTokenNameActive() { AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(builder.build()); dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - AccountAssetCapsule ownerAddressAsset = - new AccountAssetCapsule(StringUtil.hexString2ByteString(OWNER_ADDRESS)); - dbManager.getAccountAssetStore().put(ownerAddressAsset.getAddress().toByteArray(), - ownerAddressAsset); - AccountCapsule ownerCapsule = new AccountCapsule( ByteString.copyFromUtf8("owner"), @@ -159,7 +115,6 @@ public void SameTokenNameCloseUnfreezeAsset() { dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); AccountCapsule ownerAccount = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - ownerAccount.importAsset(); Account account = ownerAccount .getInstance(); Frozen newFrozen0 = Frozen.newBuilder() @@ -185,9 +140,9 @@ public void SameTokenNameCloseUnfreezeAsset() { AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); //V1 - Assert.assertEquals(owner.getAssetMap().get(assetName).longValue(), frozenBalance); + Assert.assertEquals(owner.getAssetMapForTest().get(assetName).longValue(), frozenBalance); //V2 - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenId)).longValue(), frozenBalance); Assert.assertEquals(owner.getFrozenSupplyCount(), 1); } catch (ContractValidateException e) { @@ -209,7 +164,6 @@ public void SameTokenNameActiveUnfreezeAsset() { AccountCapsule ownerAccount = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - ownerAccount.importAsset(); Account account = ownerAccount.getInstance(); Frozen newFrozen0 = Frozen.newBuilder() .setFrozenBalance(frozenBalance) @@ -233,9 +187,9 @@ public void SameTokenNameActiveUnfreezeAsset() { AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); //V1 assert not exist - Assert.assertNull(owner.getAssetMap().get(assetName)); + Assert.assertNull(owner.getAssetMapForTest().get(assetName)); //V2 - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenId)).longValue(), frozenBalance); Assert.assertEquals(owner.getFrozenSupplyCount(), 1); } catch (ContractValidateException e) { @@ -259,7 +213,6 @@ public void SameTokenNameActiveInitAndAcitveUnfreezeAsset() { AccountCapsule ownerAccount = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - ownerAccount.importAsset(); Account account = ownerAccount .getInstance(); Frozen newFrozen0 = Frozen.newBuilder() @@ -285,9 +238,9 @@ public void SameTokenNameActiveInitAndAcitveUnfreezeAsset() { AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); //V1 assert not exist - Assert.assertNull(owner.getAssetMap().get(assetName)); + Assert.assertNull(owner.getAssetMapForTest().get(assetName)); //V2 - Assert.assertEquals(owner.getAssetMapV2().get(String.valueOf(tokenId)).longValue(), + Assert.assertEquals(owner.getAssetV2MapForTest().get(String.valueOf(tokenId)).longValue(), frozenBalance); Assert.assertEquals(owner.getFrozenSupplyCount(), 1); } catch (ContractValidateException e) { @@ -399,7 +352,6 @@ public void notTimeToUnfreeze() { AccountCapsule ownerAccount = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - ownerAccount.importAsset(); Account account = ownerAccount.getInstance(); Frozen newFrozen = Frozen.newBuilder() diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java index 9dd1b026d08..e9f1d934e5a 100644 --- a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceActuatorTest.java @@ -4,18 +4,14 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; @@ -23,9 +19,7 @@ import org.tron.core.capsule.DelegatedResourceCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -36,54 +30,23 @@ import org.tron.protos.contract.Common.ResourceCode; @Slf4j -public class UnfreezeBalanceActuatorTest { +public class UnfreezeBalanceActuatorTest extends BaseTest { - private static final String dbPath = "output_unfreeze_balance_test"; private static final String OWNER_ADDRESS; private static final String RECEIVER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long frozenBalance = 1_000_000_000L; - private static final long smallTatalResource = 100L; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -140,13 +103,14 @@ private Any getContract(String ownerAddress, ResourceCode resourceCode) { @Test public void testUnfreezeBalanceForBandwidth() { long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveAllowNewReward(0); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); AccountCapsule accountCapsule = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); accountCapsule.setFrozen(frozenBalance, now); - Assert.assertEquals(accountCapsule.getFrozenBalance(), frozenBalance); - Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getFrozenBalance()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -159,36 +123,120 @@ public void testUnfreezeBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(owner.getBalance(), initBalance + frozenBalance); - Assert.assertEquals(owner.getFrozenBalance(), 0); - Assert.assertEquals(owner.getTronPower(), 0L); + Assert.assertEquals(0, owner.getFrozenBalance()); + Assert.assertEquals(0L, owner.getTronPower()); long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); Assert.assertEquals(totalNetWeightBefore, totalNetWeightAfter + frozenBalance / 1000_000L); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void testUnfreezeSelfAndOthersForBandwidth() { + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + dbManager.getDynamicPropertiesStore().saveAllowNewReward(1); + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule owner = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + owner.setDelegatedFrozenBalanceForBandwidth(150_0000L); + owner.setFrozen(150_0000L, now); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(2L); + long beforeWeight = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + Assert.assertEquals(2, beforeWeight); + + AccountCapsule receiver = dbManager.getAccountStore() + .get(ByteArray.fromHexString(RECEIVER_ADDRESS)); + receiver.setAcquiredDelegatedFrozenBalanceForBandwidth(150_0000L); + + dbManager.getAccountStore().put(owner.createDbKey(), owner); + dbManager.getAccountStore().put(receiver.createDbKey(), receiver); + + //init DelegatedResourceCapsule + DelegatedResourceCapsule delegatedResourceCapsule = new DelegatedResourceCapsule( + owner.getAddress(), receiver.getAddress()); + delegatedResourceCapsule.setFrozenBalanceForBandwidth(150_0000L, now - 100L); + dbManager.getDelegatedResourceStore().put(DelegatedResourceCapsule + .createDbKey(ByteArray.fromHexString(OWNER_ADDRESS), + ByteArray.fromHexString(RECEIVER_ADDRESS)), delegatedResourceCapsule); + + //init DelegatedResourceAccountIndex + { + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndex = + new DelegatedResourceAccountIndexCapsule( + owner.getAddress()); + delegatedResourceAccountIndex + .addToAccount(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + dbManager.getDelegatedResourceAccountIndexStore() + .put(ByteArray.fromHexString(OWNER_ADDRESS), delegatedResourceAccountIndex); + } + + { + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndex = + new DelegatedResourceAccountIndexCapsule( + receiver.getAddress()); + delegatedResourceAccountIndex + .addFromAccount(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + dbManager.getDelegatedResourceAccountIndexStore() + .put(ByteArray.fromHexString(RECEIVER_ADDRESS), delegatedResourceAccountIndex); + } + + + + UnfreezeBalanceActuator actuator1 = new UnfreezeBalanceActuator(); + actuator1.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidth(OWNER_ADDRESS)); + TransactionResultCapsule ret1 = new TransactionResultCapsule(); + try { + actuator1.validate(); + actuator1.execute(ret1); + long afterWeight1 = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + Assert.assertEquals(1, afterWeight1); + Assert.assertEquals(code.SUCESS, ret1.getInstance().getRet()); } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); + logger.error("ContractValidateException", e); + Assert.fail(); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } - } + UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getDelegatedContractForBandwidth(OWNER_ADDRESS, RECEIVER_ADDRESS)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + long afterWeight = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + Assert.assertEquals(0, afterWeight); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); + } + dbManager.getDynamicPropertiesStore().saveAllowNewReward(0); + } @Test public void testUnfreezeBalanceForEnergy() { long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveAllowNewReward(0); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); AccountCapsule accountCapsule = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); accountCapsule.setFrozenForEnergy(frozenBalance, now); - Assert.assertEquals(accountCapsule.getAllFrozenBalanceForEnergy(), frozenBalance); - Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getAllFrozenBalanceForEnergy()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -200,20 +248,18 @@ public void testUnfreezeBalanceForEnergy() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(owner.getBalance(), initBalance + frozenBalance); - Assert.assertEquals(owner.getEnergyFrozenBalance(), 0); - Assert.assertEquals(owner.getTronPower(), 0L); + Assert.assertEquals(0, owner.getEnergyFrozenBalance()); + Assert.assertEquals(0L, owner.getTronPower()); long totalEnergyWeightAfter = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); Assert.assertEquals(totalEnergyWeightBefore, totalEnergyWeightAfter + frozenBalance / 1000_000L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -272,7 +318,7 @@ public void testUnfreezeDelegatedBalanceForBandwidth() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -299,11 +345,10 @@ public void testUnfreezeDelegatedBalanceForBandwidth() { Assert.assertEquals(0, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } + } @Test @@ -365,17 +410,18 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithDeletedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist"); + Assert.assertEquals( + "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -399,11 +445,8 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithDeletedReceiver() { Assert.assertEquals(0, delegatedResourceAccountIndexCapsuleReceiver.getFromAccountsList().size()); - } catch (ContractValidateException e) { - logger.error("", e); - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -478,10 +521,11 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithRecreatedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "AcquiredDelegatedFrozenBalanceForBandwidth[10] < delegatedBandwidth[1000000000]"); + Assert.assertEquals( + "AcquiredDelegatedFrozenBalanceForBandwidth[10] < delegatedBandwidth[1000000000]", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); @@ -489,7 +533,7 @@ public void testUnfreezeDelegatedBalanceForBandwidthWithRecreatedReceiver() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -584,10 +628,9 @@ public void testUnfreezeDelegatedBalanceForBandwidthSameTokenNameClose() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("no frozenBalance(BANDWIDTH)", e.getMessage()); } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -624,7 +667,7 @@ public void testUnfreezeDelegatedBalanceForCpu() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -635,11 +678,8 @@ public void testUnfreezeDelegatedBalanceForCpu() { Assert.assertEquals(0L, ownerResult.getTronPower()); Assert.assertEquals(0L, ownerResult.getDelegatedFrozenBalanceForEnergy()); Assert.assertEquals(0L, receiverResult.getAllFrozenBalanceForEnergy()); - } catch (ContractValidateException e) { - logger.error("", e); - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -680,10 +720,11 @@ public void testUnfreezeDelegatedBalanceForCpuWithDeletedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist"); + Assert.assertEquals( + "Receiver Account[a0abd4b9367799eaa3197fecb144eb71de1e049150] does not exist", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowTvmConstantinople(1); @@ -691,17 +732,15 @@ public void testUnfreezeDelegatedBalanceForCpuWithDeletedReceiver() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); Assert.assertEquals(initBalance + frozenBalance, ownerResult.getBalance()); Assert.assertEquals(0L, ownerResult.getTronPower()); Assert.assertEquals(0L, ownerResult.getDelegatedFrozenBalanceForEnergy()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -755,10 +794,11 @@ public void testUnfreezeDelegatedBalanceForCpuWithRecreatedReceiver() { actuator.execute(ret); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertEquals(e.getMessage(), - "AcquiredDelegatedFrozenBalanceForEnergy[10] < delegatedEnergy[1000000000]"); + Assert.assertEquals( + "AcquiredDelegatedFrozenBalanceForEnergy[10] < delegatedEnergy[1000000000]", + e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } dbManager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); @@ -767,7 +807,7 @@ public void testUnfreezeDelegatedBalanceForCpuWithRecreatedReceiver() { try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule ownerResult = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); @@ -776,9 +816,7 @@ public void testUnfreezeDelegatedBalanceForCpuWithRecreatedReceiver() { Assert.assertEquals(0L, ownerResult.getDelegatedFrozenBalanceForEnergy()); receiver = dbManager.getAccountStore().get(receiver.createDbKey()); Assert.assertEquals(0, receiver.getAcquiredDelegatedFrozenBalanceForEnergy()); - } catch (ContractValidateException e) { - Assert.fail(); - } catch (ContractExeException e) { + } catch (ContractValidateException | ContractExeException e) { Assert.fail(); } } @@ -802,12 +840,9 @@ public void invalidOwnerAddress() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); - Assert.assertEquals("Invalid address", e.getMessage()); - } catch (ContractExeException e) { - Assert.assertTrue(e instanceof ContractExeException); + Assert.fail(); } } @@ -830,11 +865,10 @@ public void invalidOwnerAccount() { actuator.execute(ret); fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] does not exist", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -850,10 +884,9 @@ public void noFrozenBalance() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("no frozenBalance(BANDWIDTH)", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @@ -876,17 +909,15 @@ public void notTimeToUnfreeze() { fail("cannot run here."); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("It's not time to unfreeze(BANDWIDTH).", e.getMessage()); } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + Assert.fail(); } } @Test public void testClearVotes() { byte[] ownerAddressBytes = ByteArray.fromHexString(OWNER_ADDRESS); - ByteString ownerAddress = ByteString.copyFrom(ownerAddressBytes); long now = System.currentTimeMillis(); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); @@ -906,14 +937,12 @@ public void testClearVotes() { VotesCapsule votesCapsule = dbManager.getVotesStore().get(ownerAddressBytes); Assert.assertNotNull(votesCapsule); Assert.assertEquals(0, votesCapsule.getNewVotes().size()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } // if had votes - List oldVotes = new ArrayList(); + List oldVotes = new ArrayList<>(); VotesCapsule votesCapsule = new VotesCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), oldVotes); votesCapsule.addNewVotes(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -927,10 +956,8 @@ public void testClearVotes() { votesCapsule = dbManager.getVotesStore().get(ownerAddressBytes); Assert.assertNotNull(votesCapsule); Assert.assertEquals(0, votesCapsule.getNewVotes().size()); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1009,8 +1036,8 @@ public void commonErrorCheck() { AccountCapsule accountCapsule = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); accountCapsule.setFrozen(frozenBalance, now); - Assert.assertEquals(accountCapsule.getFrozenBalance(), frozenBalance); - Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getFrozenBalance()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); @@ -1033,7 +1060,7 @@ public void testUnfreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() accountCapsule.setFrozenForEnergy(frozenBalance, now); accountCapsule.setOldTronPower(frozenBalance); accountCapsule.addVotes(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), 100L); - Assert.assertEquals(accountCapsule.getAllFrozenBalanceForEnergy(), frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getAllFrozenBalanceForEnergy()); dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); @@ -1044,16 +1071,14 @@ public void testUnfreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert.assertEquals(owner.getVotesList().size(), 0L); + Assert.assertEquals(0L, owner.getVotesList().size()); Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1079,16 +1104,14 @@ public void testUnfreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert.assertEquals(owner.getVotesList().size(), 1L); + Assert.assertEquals(1L, owner.getVotesList().size()); Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1114,16 +1137,14 @@ public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel try { actuator.validate(); actuator.execute(ret); - Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); AccountCapsule owner = dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)); - Assert.assertEquals(owner.getVotesList().size(), 0L); + Assert.assertEquals(0L, owner.getVotesList().size()); Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); - } catch (ContractValidateException e) { - Assert.assertFalse(e instanceof ContractValidateException); - } catch (ContractExeException e) { - Assert.assertFalse(e instanceof ContractExeException); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail(); } } @@ -1144,13 +1165,12 @@ public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel UnfreezeBalanceActuator actuator = new UnfreezeBalanceActuator(); actuator.setChainBaseManager(dbManager.getChainBaseManager()) .setAny(getContractForTronPower(OWNER_ADDRESS)); - TransactionResultCapsule ret = new TransactionResultCapsule(); try { actuator.validate(); Assert.fail(); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("It's not time to unfreeze(TronPower).", e.getMessage()); } } diff --git a/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java new file mode 100644 index 00000000000..749052736e5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/UnfreezeBalanceV2ActuatorTest.java @@ -0,0 +1,798 @@ +package org.tron.core.actuator; + +import static junit.framework.TestCase.fail; +import static org.tron.core.config.Parameter.ChainConstant.FROZEN_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.capsule.VotesCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.Protocol.Vote; +import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.Common.ResourceCode; + +@Slf4j +public class UnfreezeBalanceV2ActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String RECEIVER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "aaaa"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 10_000_000_000L; + private static final long frozenBalance = 1_000_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + RECEIVER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049150"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + /** + * create temp Capsule test need. + */ + @Before + public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + + AccountCapsule receiverCapsule = new AccountCapsule(ByteString.copyFromUtf8("receiver"), + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS)), AccountType.Normal, + initBalance); + dbManager.getAccountStore().put(receiverCapsule.getAddress().toByteArray(), receiverCapsule); + } + + private Any getContractForBandwidthV2(String ownerAddress, long unfreezeBalance) { + return Any.pack( + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(ownerAddress)) + ) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.BANDWIDTH) + .build() + ); + } + + private Any getContractForCpuV2(String ownerAddress, long unfreezeBalance) { + return Any.pack(BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.ENERGY).build()); + } + + private Any getContractForTronPowerV2(String ownerAddress, long unfreezeBalance) { + return Any.pack(BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.TRON_POWER).build()); + } + + private Any getDelegatedContractForBandwidth( + String ownerAddress, long unfreezeBalance + ) { + return Any.pack(BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.BANDWIDTH).build()); + } + + private Any getDelegatedContractForCpu( + String ownerAddress, String receiverAddress, long unfreezeBalance + ) { + return Any.pack(BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.ENERGY).build()); + } + + private Any getContract(String ownerAddress, ResourceCode resourceCode, long unfreezeBalance) { + return Any.pack(BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(resourceCode).build()); + } + + + private Any getContractForTronPowerV2_001(String ownerAddress, long unfreezeBalance) { + return Any.pack(BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))) + .setUnfreezeBalance(unfreezeBalance).build()); + } + + @Test + public void testUnfreezeBalanceForBandwidth() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(1000); + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + long unfreezeBalance = frozenBalance - 100; + + Assert.assertEquals(frozenBalance, accountCapsule.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + long totalNetWeightBefore = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + //Assert.assertEquals(owner.getBalance(), initBalance + frozenBalance); + Assert.assertEquals(100, owner.getFrozenV2BalanceForBandwidth()); + Assert.assertEquals(100L, owner.getTronPower()); + + long totalNetWeightAfter = dbManager.getDynamicPropertiesStore().getTotalNetWeight(); + Assert.assertEquals(totalNetWeightBefore - 1000, totalNetWeightAfter); + + } catch (Exception e) { + Assert.assertFalse(e instanceof ContractValidateException); + Assert.assertFalse(e instanceof ContractExeException); + } + } + + + @Test + public void testUnfreezeBalanceForEnergy() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveTotalNetWeight(1000); + long unfreezeBalance = frozenBalance - 100; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + Assert.assertEquals(frozenBalance, accountCapsule.getAllFrozenBalanceForEnergy()); + Assert.assertEquals(frozenBalance, accountCapsule.getTronPower()); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForCpuV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + long totalEnergyWeightBefore = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + //Assert.assertEquals(owner.getBalance(), initBalance + frozenBalance); + Assert.assertEquals(100, owner.getAllFrozenBalanceForEnergy()); + Assert.assertEquals(100, owner.getTronPower()); + long totalEnergyWeightAfter = dbManager.getDynamicPropertiesStore().getTotalEnergyWeight(); + Assert.assertEquals(totalEnergyWeightBefore - 1000, totalEnergyWeightAfter); + } catch (Exception e) { + Assert.assertFalse(e instanceof ContractValidateException); + Assert.assertFalse(e instanceof ContractExeException); + } + } + + + @Test + public void invalidOwnerAddress() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + long unfreezeBalance = frozenBalance; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.setFrozen(1_000_000_000L, now); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS_INVALID, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + Assert.assertTrue(e instanceof ContractValidateException); + + Assert.assertEquals("Invalid address", e.getMessage()); + + } catch (ContractExeException e) { + Assert.assertTrue(e instanceof ContractExeException); + } + + } + + @Test + public void invalidOwnerAccount() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + long unfreezeBalance = frozenBalance; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.setFrozen(1_000_000_000L, now); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ACCOUNT_INVALID, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] does not exist", + e.getMessage()); + } catch (ContractExeException e) { + Assert.assertFalse(e instanceof ContractExeException); + } + } + + @Test + public void noFrozenBalance() { + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + long unfreezeBalance = frozenBalance; + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + Assert.assertTrue(e instanceof ContractValidateException); + Assert.assertEquals("no frozenBalance(BANDWIDTH)", e.getMessage()); + } catch (ContractExeException e) { + Assert.assertFalse(e instanceof ContractExeException); + } + } + + @Test + public void testVotes() { + byte[] ownerAddressBytes = ByteArray.fromHexString(OWNER_ADDRESS); + long unfreezeBalance = frozenBalance / 2; + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(0); + AccountCapsule accountCapsule = dbManager.getAccountStore().get(ownerAddressBytes); + accountCapsule.addFrozenBalanceForBandwidthV2(1_000_000_000L); + accountCapsule.addVotes(ByteString.copyFrom(RECEIVER_ADDRESS.getBytes()), 500); + accountCapsule.addVotes(ByteString.copyFrom(OWNER_ACCOUNT_INVALID.getBytes()), 500); + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + VotesCapsule votesCapsule = dbManager.getVotesStore().get(ownerAddressBytes); + Assert.assertNotNull(votesCapsule); + for (Vote vote : votesCapsule.getOldVotes()) { + Assert.assertEquals(vote.getVoteCount(), 500); + } + for (Vote vote : votesCapsule.getNewVotes()) { + Assert.assertEquals(vote.getVoteCount(), 250); + } + accountCapsule = dbManager.getAccountStore().get(ownerAddressBytes); + for (Vote vote : accountCapsule.getVotesList()) { + Assert.assertEquals(vote.getVoteCount(), 250); + } + } catch (ContractValidateException | ContractExeException e) { + Assert.fail("cannot run here."); + } + + // clear for new resource model + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance / 2)); + try { + actuator.validate(); + actuator.execute(ret); + VotesCapsule votesCapsule = dbManager.getVotesStore().get(ownerAddressBytes); + Assert.assertNotNull(votesCapsule); + for (Vote vote : votesCapsule.getOldVotes()) { + Assert.assertEquals(vote.getVoteCount(), 500); + } + Assert.assertEquals(0, votesCapsule.getNewVotes().size()); + accountCapsule = dbManager.getAccountStore().get(ownerAddressBytes); + Assert.assertEquals(0, accountCapsule.getVotesList().size()); + } catch (ContractValidateException | ContractExeException e) { + Assert.fail("cannot run here."); + } + } + + @Test + public void commonErrorCheck() { + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + ActuatorTest actuatorTest = new ActuatorTest(actuator, dbManager); + actuatorTest.noContract(); + long unfreezeBalance = frozenBalance; + + Any invalidContractTypes = Any.pack( + AssetIssueContractOuterClass.AssetIssueContract.newBuilder().build() + ); + actuatorTest.setInvalidContract(invalidContractTypes); + actuatorTest.setInvalidContractTypeMsg("contract type error", + "contract type error, expected type [UnfreezeBalanceContract], real type["); + actuatorTest.invalidContractType(); + + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + Assert.assertEquals(accountCapsule.getAllFrozenBalanceForBandwidth(), frozenBalance); + Assert.assertEquals(accountCapsule.getTronPower(), frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + + actuatorTest.setContract(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + actuatorTest.nullTransationResult(); + + actuatorTest.setNullDBManagerMsg("No account store or dynamic store!"); + actuatorTest.nullDBManger(); + } + + + @Test + public void testUnfreezeBalanceForEnergyWithOldTronPowerAfterNewResourceModel() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + long unfreezeBalance = frozenBalance; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + accountCapsule.setOldTronPower(frozenBalance); + accountCapsule.addVotes( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), 100L); + Assert.assertEquals(accountCapsule.getAllFrozenBalanceForEnergy(), frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForCpuV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(owner.getVotesList().size(), 0L); + Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); + } catch (ContractValidateException e) { + Assert.assertFalse(e instanceof ContractValidateException); + } catch (ContractExeException e) { + Assert.assertFalse(e instanceof ContractExeException); + } + } + + + @Test + public void testUnfreezeBalanceForEnergyWithoutOldTronPowerAfterNewResourceModel() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + long unfreezeBalance = frozenBalance; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + accountCapsule.setOldTronPower(-1L); + accountCapsule.addVotes( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), 100L); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForCpuV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(owner.getVotesList().size(), 1L); + Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); + } catch (ContractValidateException e) { + Assert.assertFalse(e instanceof ContractValidateException); + } catch (ContractExeException e) { + Assert.assertFalse(e instanceof ContractExeException); + } + } + + + @Test + public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModel() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + long unfreezeBalance = frozenBalance - 100; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + accountCapsule.addFrozenForTronPowerV2(frozenBalance); + accountCapsule.addVotes( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), 100L); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForTronPowerV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + Assert.assertEquals(ret.getInstance().getRet(), code.SUCESS); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + Assert.assertEquals(owner.getVotesList().size(), 0L); + Assert.assertEquals(owner.getInstance().getOldTronPower(), -1L); + } catch (ContractValidateException e) { + Assert.assertFalse(e instanceof ContractValidateException); + } catch (ContractExeException e) { + Assert.assertFalse(e instanceof ContractExeException); + } + } + + + @Test + public void testUnfreezeBalanceForTronPowerWithOldTronPowerAfterNewResourceModelError() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + long unfreezeBalance = frozenBalance - 100; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + accountCapsule.addFrozenForTronPowerV2(frozenBalance); + accountCapsule.addVotes( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), 100L); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForTronPowerV2(OWNER_ADDRESS, unfreezeBalance)); + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + //Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + } + } + + + @Test + public void testUnfreezeBalanceCheckExistFreezedBalance() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + long unfreezeBalance = frozenBalance - 100; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + accountCapsule.addFrozenBalanceForEnergyV2(frozenBalance); + accountCapsule.addFrozenForTronPowerV2(frozenBalance); + //accountCapsule.addDelegatedFrozenBalanceForBandwidthV2(frozenBalance); + //accountCapsule.addDelegatedFrozenBalanceForEnergyV2(frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + boolean bret1 = actuator.checkExistFrozenBalance( + accountCapsule, ResourceCode.BANDWIDTH); + Assert.assertTrue(bret1); + boolean bret2 = actuator.checkExistFrozenBalance( + accountCapsule, ResourceCode.ENERGY); + Assert.assertTrue(bret2); + boolean bret3 = actuator.checkExistFrozenBalance( + accountCapsule, ResourceCode.TRON_POWER); + Assert.assertTrue(bret3); + + } + + + @Test + public void testUnfreezeBalanceCheckUnfreezeBalance() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + long unfreezeBalance = frozenBalance - 1; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + BalanceContract.UnfreezeBalanceV2Contract unfreezeBalanceV2Contract = + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.BANDWIDTH) + .build(); + boolean bret1 = actuator.checkUnfreezeBalance( + accountCapsule, unfreezeBalanceV2Contract, ResourceCode.BANDWIDTH + ); + Assert.assertTrue(bret1); + } + + + @Test + public void testUnfreezeBalanceGetFreezeType() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + long unfreezeBalance = frozenBalance - 1; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + BalanceContract.UnfreezeBalanceV2Contract unfreezeBalanceV2Contract = + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.TRON_POWER) + //.setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .build(); + + ResourceCode freezeType = unfreezeBalanceV2Contract.getResource(); + + Assert.assertEquals(ResourceCode.TRON_POWER, freezeType); + } + + @Test + public void testUnfreezeBalanceCalcUnfreezeExpireTime() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(30); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + long unfreezeBalance = frozenBalance - 1; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + BalanceContract.UnfreezeBalanceV2Contract unfreezeBalanceV2Contract = + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.TRON_POWER) + //.setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .build(); + + long ret = actuator.calcUnfreezeExpireTime(now); + Assert.assertTrue(ret > 0); + } + + @Test + public void testUnfreezeBalanceUpdateAccountFrozenInfo() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(30); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + long unfreezeBalance = frozenBalance - 1; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + accountCapsule.addFrozenBalanceForBandwidthV2(frozenBalance); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + BalanceContract.UnfreezeBalanceV2Contract unfreezeBalanceV2Contract = + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.TRON_POWER) + //.setReceiverAddress(ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))) + .build(); + + actuator.updateAccountFrozenInfo( + ResourceCode.BANDWIDTH, accountCapsule, unfreezeBalance + ); + + Assert.assertEquals(1, accountCapsule.getAllFrozenBalanceForBandwidth()); + } + + + @Test + public void testUnfreezeBalanceUnfreezeExpire() { + + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(30); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + + long unfreezeBalance = frozenBalance - 1; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + long balance = accountCapsule.getBalance(); + accountCapsule.addUnfrozenV2List( + ResourceCode.BANDWIDTH, + 1, + now + 19 * FROZEN_PERIOD + ); + accountCapsule.addUnfrozenV2List( + ResourceCode.BANDWIDTH, + 10, + now + 31 * FROZEN_PERIOD + ); + accountCapsule.addUnfrozenV2List( + ResourceCode.ENERGY, + 20, + now + 32 * FROZEN_PERIOD + ); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now + 31 * FROZEN_PERIOD); + actuator.unfreezeExpire(accountCapsule, + dbManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp()); + + Assert.assertEquals(accountCapsule.getBalance(), balance + 11); + Assert.assertEquals(accountCapsule.getUnfrozenV2List().size(), 1); + Assert.assertEquals(accountCapsule.getUnfrozenV2List().get(0).getUnfreezeAmount(), 20); + } + + + @Test + public void testAddTotalResourceWeight() { + + long now = System.currentTimeMillis(); + long total = frozenBalance; + dbManager.getDynamicPropertiesStore().saveTotalTronPowerWeight(total); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(30); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + + long unfreezeBalance = frozenBalance; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + long balance = accountCapsule.getBalance(); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + BalanceContract.UnfreezeBalanceV2Contract unfreezeBalanceV2Contract = + BalanceContract.UnfreezeBalanceV2Contract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setUnfreezeBalance(unfreezeBalance) + .setResource(ResourceCode.TRON_POWER) + .build(); + + actuator.updateTotalResourceWeight(accountCapsule, unfreezeBalanceV2Contract, unfreezeBalance); + + Assert.assertEquals(total - unfreezeBalance / TRX_PRECISION, + dbManager.getDynamicPropertiesStore().getTotalTronPowerWeight()); + + } + + @Test + public void testUnfreezeBalanceUnfreezeCount() { + + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(30); + dbManager.getDynamicPropertiesStore().saveAllowDelegateResource(1); + + long unfreezeBalance = frozenBalance - 1; + + AccountCapsule accountCapsule = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + + long balance = accountCapsule.getBalance(); + accountCapsule.addUnfrozenV2List( + ResourceCode.BANDWIDTH, + 1, + now + 19 * FROZEN_PERIOD + ); + accountCapsule.addUnfrozenV2List( + ResourceCode.BANDWIDTH, + 10, + now + 31 * FROZEN_PERIOD + ); + accountCapsule.addUnfrozenV2List( + ResourceCode.ENERGY, + 20, + now + 32 * FROZEN_PERIOD + ); + + int count = accountCapsule.getUnfreezingV2Count(now); + Assert.assertEquals(3, count); + + dbManager.getAccountStore().put(accountCapsule.createDbKey(), accountCapsule); + UnfreezeBalanceV2Actuator actuator = new UnfreezeBalanceV2Actuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContractForBandwidthV2(OWNER_ADDRESS, unfreezeBalance)); + + dbManager.getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(now + 32 * FROZEN_PERIOD); + actuator.unfreezeExpire(accountCapsule, + dbManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp()); + + + int after_count = accountCapsule.getUnfreezingV2Count(now); + Assert.assertEquals(0, after_count); + + } + + +} + diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java index 315a045128a..0e385347836 100755 --- a/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateAccountActuatorTest.java @@ -4,23 +4,17 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -29,46 +23,20 @@ import org.tron.protos.contract.AssetIssueContractOuterClass; @Slf4j -public class UpdateAccountActuatorTest { +public class UpdateAccountActuatorTest extends BaseTest { - private static final String dbPath = "output_updateaccount_test"; private static final String ACCOUNT_NAME = "ownerTest"; private static final String ACCOUNT_NAME_1 = "ownerTest1"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_1; private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ADDRESS_1 = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java index 6bd57c85361..3bdba2055af 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateAssetActuatorTest.java @@ -4,28 +4,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Date; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -34,9 +26,8 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; @Slf4j -public class UpdateAssetActuatorTest { +public class UpdateAssetActuatorTest extends BaseTest { - private static final String dbPath = "output_updateAsset_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String SECOND_ACCOUNT_ADDRESS; @@ -46,14 +37,9 @@ public class UpdateAssetActuatorTest { private static final long TOTAL_SUPPLY = 10000L; private static final String DESCRIPTION = "myCoin"; private static final String URL = "tron-my.com"; - private static TronApplicationContext context; - private static Application AppT; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -61,28 +47,6 @@ public class UpdateAssetActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java index e2ce611c56b..efd090b4b3a 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateBrokerageActuatorTest.java @@ -4,25 +4,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.DelegationStore; @@ -32,19 +26,15 @@ import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; @Slf4j(topic = "actuator") -public class UpdateBrokerageActuatorTest { +public class UpdateBrokerageActuatorTest extends BaseTest { - private static final String dbPath = "output_updatebrokerageactuator_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_NOTEXIST; private static final String OWNER_ADDRESS_INVALID; private static final int BROKEN_AGE = 10; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "1234b9367799eaa3197fecb144eb71de1e049123"; @@ -52,34 +42,10 @@ public class UpdateBrokerageActuatorTest { Wallet.getAddressPreFixString() + "354394500882809695a8a687866e7"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - @Before /** * set witness store, account store, dynamic store */ + @Before public void initDB() { // allow dynamic store dbManager.getDynamicPropertiesStore().saveChangeDelegation(1); diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java index 7dfcbee8824..60f52b541b9 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateEnergyLimitContractActuatorTest.java @@ -5,32 +5,26 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.io.File; import java.util.Arrays; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.Parameter.ForkBlockVersionConsts; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.core.exception.TronException; -import org.tron.core.vm.config.VMConfig; import org.tron.protos.Protocol; import org.tron.protos.contract.AssetIssueContractOuterClass; import org.tron.protos.contract.SmartContractOuterClass.SmartContract; @@ -38,10 +32,8 @@ @Slf4j -//@Ignore -public class UpdateEnergyLimitContractActuatorTest { +public class UpdateEnergyLimitContractActuatorTest extends BaseTest { - private static final String dbPath = "output_updateEnergyLimitContractActuator_test"; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String SMART_CONTRACT_NAME = "smart_contarct"; @@ -50,15 +42,12 @@ public class UpdateEnergyLimitContractActuatorTest { private static final long SOURCE_ENERGY_LIMIT = 10L; private static final long TARGET_ENERGY_LIMIT = 30L; private static final long INVALID_ENERGY_LIMIT = -200L; - private static TronApplicationContext context; - private static Manager dbManager; private static String OWNER_ADDRESS; private static String SECOND_ACCOUNT_ADDRESS; private static String OWNER_ADDRESS_NOTEXIST; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } /** @@ -66,34 +55,13 @@ public class UpdateEnergyLimitContractActuatorTest { */ @BeforeClass public static void init() { - dbManager = context.getBean(Manager.class); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; SECOND_ACCOUNT_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - - byte[] stats = new byte[27]; - Arrays.fill(stats, (byte) 1); - dbManager.getDynamicPropertiesStore() - .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); - VMConfig.initVmHardFork(true); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - CommonParameter.setENERGY_LIMIT_HARD_FORK(false); + CommonParameter.getInstance().setBlockNumForEnergyLimit(0); } /** @@ -101,6 +69,10 @@ public static void destroy() { */ @Before public void createCapsule() { + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + dbManager.getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionConsts.ENERGY_LIMIT, stats); // address in accountStore and the owner of contract AccountCapsule accountCapsule = new AccountCapsule( diff --git a/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java index 1113b4b1689..213bbd6cb85 100644 --- a/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/UpdateSettingContractActuatorTest.java @@ -4,25 +4,19 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -32,9 +26,8 @@ @Slf4j -public class UpdateSettingContractActuatorTest { +public class UpdateSettingContractActuatorTest extends BaseTest { - private static final String dbPath = "output_updatesettingcontract_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String SECOND_ACCOUNT_ADDRESS; @@ -46,12 +39,9 @@ public class UpdateSettingContractActuatorTest { private static final long SOURCE_PERCENT = 10L; private static final long TARGET_PERCENT = 30L; private static final long INVALID_PERCENT = 200L; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -59,28 +49,6 @@ public class UpdateSettingContractActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -140,8 +108,8 @@ public void successUpdateSettingContract() { Assert.assertEquals(ret.getInstance().getRet(), Protocol.Transaction.Result.code.SUCESS); Assert.assertEquals( dbManager.getContractStore().get(ByteArray.fromHexString(CONTRACT_ADDRESS)) - .getConsumeUserResourcePercent(), - TARGET_PERCENT); + .getConsumeUserResourcePercent( + dbManager.getDynamicPropertiesStore().disableJavaLangMath()), TARGET_PERCENT); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); } catch (ContractExeException e) { @@ -277,8 +245,8 @@ public void twiceUpdateSettingContract() { Assert.assertEquals(ret.getInstance().getRet(), Protocol.Transaction.Result.code.SUCESS); Assert.assertEquals( dbManager.getContractStore().get(ByteArray.fromHexString(CONTRACT_ADDRESS)) - .getConsumeUserResourcePercent(), - TARGET_PERCENT); + .getConsumeUserResourcePercent( + dbManager.getDynamicPropertiesStore().disableJavaLangMath()), TARGET_PERCENT); // second secondActuator.validate(); @@ -287,8 +255,8 @@ public void twiceUpdateSettingContract() { Assert.assertEquals(ret.getInstance().getRet(), Protocol.Transaction.Result.code.SUCESS); Assert.assertEquals( dbManager.getContractStore().get(ByteArray.fromHexString(CONTRACT_ADDRESS)) - .getConsumeUserResourcePercent(), - 90L); + .getConsumeUserResourcePercent( + dbManager.getDynamicPropertiesStore().disableJavaLangMath()), 90L); } catch (ContractValidateException e) { Assert.assertFalse(e instanceof ContractValidateException); diff --git a/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java index ef075f02168..d7fef2ab2f5 100644 --- a/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/VoteWitnessActuatorTest.java @@ -4,16 +4,13 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.Constant; @@ -22,10 +19,8 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -37,9 +32,8 @@ import org.tron.protos.contract.WitnessContract.VoteWitnessContract.Vote; @Slf4j -public class VoteWitnessActuatorTest { +public class VoteWitnessActuatorTest extends BaseTest { - private static final String dbPath = "output_VoteWitness_test"; private static final String ACCOUNT_NAME = "account"; private static final String OWNER_ADDRESS; private static final String WITNESS_NAME = "witness"; @@ -49,14 +43,16 @@ public class VoteWitnessActuatorTest { private static final String WITNESS_ADDRESS_NOACCOUNT; private static final String OWNER_ADDRESS_NOACCOUNT; private static final String OWNER_ADDRESS_BALANCENOTSUFFICIENT; - private static TronApplicationContext context; - private static Manager dbManager; - private static MaintenanceManager maintenanceManager; - private static ConsensusService consensusService; + @Resource + private MaintenanceManager maintenanceManager; + @Resource + private ConsensusService consensusService; + + private static boolean consensusStart; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + Args.getInstance().setConsensusLogicOptimization(1); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; WITNESS_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; WITNESS_ADDRESS_NOACCOUNT = @@ -67,31 +63,6 @@ public class VoteWitnessActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - maintenanceManager = context.getBean(MaintenanceManager.class); - consensusService = context.getBean(ConsensusService.class); - consensusService.start(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ @@ -120,6 +91,12 @@ public void createCapsule() { dbManager.getAccountStore() .put(ownerAccountFirstCapsule.getAddress().toByteArray(), ownerAccountFirstCapsule); dbManager.getWitnessStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + + if (consensusStart) { + return; + } + consensusService.start(); + consensusStart = true; } private Any getContract(String address, String voteaddress, Long value) { @@ -203,7 +180,6 @@ public void InvalidAddress() { actuator.execute(ret); fail("Invalid address"); } catch (ContractValidateException e) { - Assert.assertTrue(e instanceof ContractValidateException); Assert.assertEquals("Invalid address", e.getMessage()); maintenanceManager.doMaintenance(); WitnessCapsule witnessCapsule = dbManager.getWitnessStore() @@ -300,7 +276,7 @@ public void invalideVoteAddress() { try { actuator.validate(); actuator.execute(ret); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(0, dbManager.getAccountStore() .get(ByteArray.fromHexString(OWNER_ADDRESS)).getVotesList().size()); diff --git a/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java index ef979d8acb9..22a4acbb838 100644 --- a/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WithdrawBalanceActuatorTest.java @@ -4,26 +4,20 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.args.Witness; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; @@ -33,51 +27,21 @@ import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; @Slf4j -public class WithdrawBalanceActuatorTest { +public class WithdrawBalanceActuatorTest extends BaseTest { - private static final String dbPath = "output_withdraw_balance_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ACCOUNT_INVALID; private static final long initBalance = 10_000_000_000L; private static final long allowance = 32_000_000L; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; OWNER_ACCOUNT_INVALID = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java new file mode 100644 index 00000000000..34ac0d9bbeb --- /dev/null +++ b/framework/src/test/java/org/tron/core/actuator/WithdrawExpireUnfreezeActuatorTest.java @@ -0,0 +1,191 @@ +package org.tron.core.actuator; + +import static junit.framework.TestCase.fail; +import static org.junit.Assert.assertEquals; +import static org.tron.protos.contract.Common.ResourceCode.BANDWIDTH; +import static org.tron.protos.contract.Common.ResourceCode.ENERGY; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import java.util.List; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionResultCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.BalanceInsufficientException; +import org.tron.core.exception.ContractExeException; +import org.tron.core.exception.ContractValidateException; +import org.tron.protos.Protocol.Account.UnFreezeV2; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction.Result.code; +import org.tron.protos.contract.AssetIssueContractOuterClass; +import org.tron.protos.contract.BalanceContract.WithdrawExpireUnfreezeContract; + +@Slf4j +public class WithdrawExpireUnfreezeActuatorTest extends BaseTest { + + private static final String OWNER_ADDRESS; + private static final String OWNER_ADDRESS_INVALID = "abc"; + private static final String OWNER_ACCOUNT_INVALID; + private static final long initBalance = 10_000_000_000L; + private static final long allowance = 32_000_000L; + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + OWNER_ACCOUNT_INVALID = + Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + } + + /** + * create temp Capsule test need. + */ + @Before + public void createAccountCapsule() { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(1L); + dbManager.getDynamicPropertiesStore().saveAllowNewResourceModel(1L); + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), AccountType.Normal, + initBalance); + UnFreezeV2 unFreezeV2_1 = UnFreezeV2.newBuilder().setType(BANDWIDTH) + .setUnfreezeAmount(16_000_000L).setUnfreezeExpireTime(1).build(); + UnFreezeV2 unFreezeV2_2 = UnFreezeV2.newBuilder().setType(ENERGY) + .setUnfreezeAmount(16_000_000L).setUnfreezeExpireTime(1).build(); + UnFreezeV2 unFreezeV2_3 = UnFreezeV2.newBuilder().setType(ENERGY) + .setUnfreezeAmount(0).setUnfreezeExpireTime(Long.MAX_VALUE).build(); + ownerCapsule.addUnfrozenV2(unFreezeV2_1); + ownerCapsule.addUnfrozenV2(unFreezeV2_2); + ownerCapsule.addUnfrozenV2(unFreezeV2_3); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + } + + private Any getContract(String ownerAddress) { + return Any.pack(WithdrawExpireUnfreezeContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(ownerAddress))).build()); + } + + @Test + public void testWithdrawExpireUnfreeze() { + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + + AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); + assertEquals(0, accountCapsule.getLatestWithdrawTime()); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address), 100, + "http://baidu.com/"); + dbManager.getWitnessStore().put(address, witnessCapsule); + + WithdrawExpireUnfreezeActuator actuator = new WithdrawExpireUnfreezeActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContract(OWNER_ADDRESS)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + assertEquals(code.SUCESS, ret.getInstance().getRet()); + AccountCapsule owner = dbManager.getAccountStore() + .get(ByteArray.fromHexString(OWNER_ADDRESS)); + List unfrozenV2List = owner.getInstance().getUnfrozenV2List(); + assertEquals(1, unfrozenV2List.size()); + assertEquals(Long.MAX_VALUE, unfrozenV2List.get(0).getUnfreezeExpireTime()); + assertEquals(initBalance + 32_000_000L, owner.getBalance()); + assertEquals(32_000_000L, ret.getWithdrawExpireAmount()); + } catch (ContractValidateException | ContractExeException e) { + fail(); + } + } + + + @Test + public void invalidOwnerAddress() { + WithdrawExpireUnfreezeActuator actuator = new WithdrawExpireUnfreezeActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContract(OWNER_ADDRESS_INVALID)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + + } catch (ContractValidateException e) { + assertEquals("Invalid address", e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(e.getMessage()); + } + + } + + @Test + public void invalidOwnerAccount() { + WithdrawExpireUnfreezeActuator actuator = new WithdrawExpireUnfreezeActuator(); + actuator.setChainBaseManager(dbManager.getChainBaseManager()) + .setAny(getContract(OWNER_ACCOUNT_INVALID)); + + TransactionResultCapsule ret = new TransactionResultCapsule(); + + try { + actuator.validate(); + actuator.execute(ret); + fail("cannot run here."); + } catch (ContractValidateException e) { + assertEquals("Account[" + OWNER_ACCOUNT_INVALID + "] not exists", e.getMessage()); + } catch (ContractExeException e) { + Assert.fail(); + } + } + + @Test + public void commonErrorCheck() { + + WithdrawExpireUnfreezeActuator actuator = new WithdrawExpireUnfreezeActuator(); + ActuatorTest actuatorTest = new ActuatorTest(actuator, dbManager); + actuatorTest.noContract(); + + Any invalidContractTypes = Any.pack(AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .build()); + actuatorTest.setInvalidContract(invalidContractTypes); + actuatorTest.setInvalidContractTypeMsg("contract type error", + "contract type error, expected type [WithdrawExpireUnfreezeContract], real type["); + actuatorTest.invalidContractType(); + + long now = System.currentTimeMillis(); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(now); + byte[] address = ByteArray.fromHexString(OWNER_ADDRESS); + try { + dbManager.getMortgageService() + .adjustAllowance(dbManager.getAccountStore(), address, allowance); + } catch (BalanceInsufficientException e) { + fail("BalanceInsufficientException"); + } + AccountCapsule accountCapsule = dbManager.getAccountStore().get(address); + assertEquals(allowance, accountCapsule.getAllowance()); + assertEquals(0, accountCapsule.getLatestWithdrawTime()); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address), 100, + "http://google.com/"); + dbManager.getWitnessStore().put(address, witnessCapsule); + + actuatorTest.setContract(getContract(OWNER_ADDRESS)); + actuatorTest.nullTransationResult(); + + actuatorTest.setNullDBManagerMsg("No account store or dynamic store!"); + actuatorTest.nullDBManger(); + } + +} + diff --git a/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java index 2c85ae00deb..0809ed2993e 100644 --- a/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WitnessCreateActuatorTest.java @@ -4,24 +4,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol.AccountType; @@ -30,10 +24,8 @@ import org.tron.protos.contract.WitnessContract.WitnessCreateContract; @Slf4j +public class WitnessCreateActuatorTest extends BaseTest { -public class WitnessCreateActuatorTest { - - private static final String dbPath = "output_WitnessCreate_test"; private static final String ACCOUNT_NAME_FIRST = "ownerF"; private static final String OWNER_ADDRESS_FIRST; private static final String ACCOUNT_NAME_SECOND = "ownerS"; @@ -42,12 +34,9 @@ public class WitnessCreateActuatorTest { private static final String OWNER_ADDRESS_INVALID = "aaaa"; private static final String OWNER_ADDRESS_NOACCOUNT; private static final String OWNER_ADDRESS_BALANCENOTSUFFIENT; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS_FIRST = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_SECOND = @@ -58,29 +47,6 @@ public class WitnessCreateActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e06d4271a1ced"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java b/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java index bad820cc7bb..6ad6e381c5e 100644 --- a/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java +++ b/framework/src/test/java/org/tron/core/actuator/WitnessUpdateActuatorTest.java @@ -4,24 +4,18 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ContractExeException; import org.tron.core.exception.ContractValidateException; import org.tron.protos.Protocol; @@ -30,9 +24,8 @@ import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; @Slf4j -public class WitnessUpdateActuatorTest { +public class WitnessUpdateActuatorTest extends BaseTest { - private static final String dbPath = "output_WitnessUpdate_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "test_account"; private static final String OWNER_ADDRESS_NOT_WITNESS; @@ -41,12 +34,9 @@ public class WitnessUpdateActuatorTest { private static final String URL = "https://tron.network/"; private static final String NewURL = "https://tron.org/"; private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static TronApplicationContext context; - private static Manager dbManager; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; OWNER_ADDRESS_NOTEXIST = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; @@ -54,28 +44,6 @@ public class WitnessUpdateActuatorTest { Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d427122222"; } - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - /** * create temp Capsule test need. */ diff --git a/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java b/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java index 1ad57367fdd..e8a1e862f54 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/ProposalUtilTest.java @@ -1,81 +1,66 @@ package org.tron.core.actuator.utils; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.ForkController; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.ProposalCapsule; +import org.tron.core.config.Parameter; import org.tron.core.config.Parameter.ForkBlockVersionEnum; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; +import org.tron.core.consensus.ProposalService; import org.tron.core.exception.ContractValidateException; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.utils.ProposalUtil; import org.tron.core.utils.ProposalUtil.ProposalType; +import org.tron.protos.Protocol; @Slf4j(topic = "actuator") -public class ProposalUtilTest { +public class ProposalUtilTest extends BaseTest { - private static final String dbPath = "output_ProposalUtil_test"; private static final long LONG_VALUE = 100_000_000_000_000_000L; private static final String LONG_VALUE_ERROR = "Bad chain parameter value, valid range is [0," + LONG_VALUE + "]"; - public static Application AppT; - private static TronApplicationContext context; - private static Manager dbManager; + + @Resource + private DynamicPropertiesStore dynamicPropertiesStore; + + ForkController forkUtils = ForkController.instance(); /** * Init . */ @BeforeClass public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - AppT = ApplicationFactory.create(context); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } - + @Test public void validProposalTypeCheck() throws ContractValidateException { - Assert.assertEquals(false, ProposalType.contain(4000)); - Assert.assertEquals(false, ProposalType.contain(-1)); - Assert.assertEquals(true, ProposalType.contain(2)); + Assert.assertFalse(ProposalType.contain(4000)); + Assert.assertFalse(ProposalType.contain(-1)); + Assert.assertTrue(ProposalType.contain(2)); - Assert.assertEquals(null, ProposalType.getEnumOrNull(-2)); + Assert.assertNull(ProposalType.getEnumOrNull(-2)); Assert.assertEquals(ProposalType.ALLOW_TVM_SOLIDITY_059, ProposalType.getEnumOrNull(32)); long code = -1; try { ProposalType.getEnum(code); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals("Does not support code : " + code, e.getMessage()); } @@ -87,128 +72,124 @@ public void validProposalTypeCheck() throws ContractValidateException { @Test public void validateCheck() { - ProposalUtil actuatorUtil = new ProposalUtil(); - DynamicPropertiesStore dynamicPropertiesStore = null; - ForkController forkUtils = ForkController.instance(); long invalidValue = -1; try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ACCOUNT_UPGRADE_COST.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ACCOUNT_UPGRADE_COST.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_ACCOUNT_FEE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_ACCOUNT_FEE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ASSET_ISSUE_FEE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ASSET_ISSUE_FEE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_PAY_PER_BLOCK.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.WITNESS_STANDBY_ALLOWANCE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), invalidValue); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.CREATE_NEW_ACCOUNT_BANDWIDTH_RATE.getCode(), LONG_VALUE + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals(LONG_VALUE_ERROR, e.getMessage()); } - long value = 32; try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 3 * 27 * 1000 - 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", @@ -216,9 +197,9 @@ public void validateCheck() { } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAINTENANCE_TIME_INTERVAL.getCode(), 24 * 3600 * 1000 + 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [3 * 27 * 1000,24 * 3600 * 1000]", @@ -226,9 +207,9 @@ public void validateCheck() { } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_CREATION_OF_CONTRACTS.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[ALLOW_CREATION_OF_CONTRACTS] is only allowed to be 1", @@ -238,9 +219,9 @@ public void validateCheck() { dynamicPropertiesStore = dbManager.getDynamicPropertiesStore(); dynamicPropertiesStore.saveRemoveThePowerOfTheGr(1); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[REMOVE_THE_POWER_OF_THE_GR] is only allowed to be 1", @@ -249,9 +230,9 @@ public void validateCheck() { dynamicPropertiesStore.saveRemoveThePowerOfTheGr(-1); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.REMOVE_THE_POWER_OF_THE_GR.getCode(), 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This proposal has been executed before and is only allowed to be executed once", @@ -259,27 +240,27 @@ public void validateCheck() { } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 9); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [10,100]", e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.MAX_CPU_TIME_OF_ONE_TX.getCode(), 101); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "Bad chain parameter value, valid range is [10,100]", e.getMessage()); } try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_DELEGATE_RESOURCE.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[ALLOW_DELEGATE_RESOURCE] is only allowed to be 1", e.getMessage()); @@ -287,9 +268,9 @@ public void validateCheck() { dynamicPropertiesStore.saveAllowSameTokenName(1); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 2); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals( "This value[ALLOW_TVM_TRANSFER_TRC10] is only allowed to be 1", e.getMessage()); @@ -297,9 +278,9 @@ public void validateCheck() { dynamicPropertiesStore.saveAllowSameTokenName(0); try { - actuatorUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, ProposalType.ALLOW_TVM_TRANSFER_TRC10.getCode(), 1); - Assert.assertTrue(false); + Assert.fail(); } catch (ContractValidateException e) { Assert.assertEquals("[ALLOW_SAME_TOKEN_NAME] proposal must be approved " + "before [ALLOW_TVM_TRANSFER_TRC10] can be proposed", e.getMessage()); @@ -356,5 +337,334 @@ public void validateCheck() { Assert.assertEquals("Bad chain parameter value, valid range is [0, 1_000_000_000_000L]", e.getMessage()); } + + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "Bad chain parameter id [ALLOW_OLD_REWARD_OPT]", + e.getMessage()); + } + hardForkTime = + ((ForkBlockVersionEnum.VERSION_4_7_4.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + forkUtils.getManager().getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(hardForkTime + 1); + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_7_4.getValue(), stats); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "This value[ALLOW_OLD_REWARD_OPT] is only allowed to be 1", + e.getMessage()); + } + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[ALLOW_NEW_REWARD] or [ALLOW_TVM_VOTE] proposal must be approved " + + "before [ALLOW_OLD_REWARD_OPT] can be proposed", + e.getMessage()); + } + dynamicPropertiesStore.put("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes(), + new BytesCapsule(ByteArray.fromLong(4000))); + dynamicPropertiesStore.saveAllowOldRewardOpt(1); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_OLD_REWARD_OPT.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[ALLOW_OLD_REWARD_OPT] has been valid, no need to propose again", + e.getMessage()); + } + + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "Bad chain parameter id [ALLOW_STRICT_MATH]", + e.getMessage()); + } + hardForkTime = + ((ForkBlockVersionEnum.VERSION_4_7_7.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + forkUtils.getManager().getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(hardForkTime + 1); + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_7_7.getValue(), stats); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "This value[ALLOW_STRICT_MATH] is only allowed to be 1", + e.getMessage()); + } + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 1); + } catch (ContractValidateException e) { + Assert.fail(e.getMessage()); + } + Protocol.Proposal proposal = Protocol.Proposal.newBuilder().putParameters( + ProposalType.ALLOW_STRICT_MATH.getCode(), 1).build(); + ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); + ProposalService.process(dbManager, proposalCapsule); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_STRICT_MATH.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[ALLOW_STRICT_MATH] has been valid, no need to propose again", + e.getMessage()); + } + + testEnergyAdjustmentProposal(); + + testConsensusLogicOptimizationProposal(); + + testAllowTvmCancunProposal(); + + testAllowTvmBlobProposal(); + + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.ENERGY_LIMIT.getValue(), stats); + forkUtils.reset(); + } + + private void testEnergyAdjustmentProposal() { + // Should fail because cannot pass the fork controller check + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "Bad chain parameter id [ALLOW_ENERGY_ADJUSTMENT]", + e.getMessage()); + } + + long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() + .getMaintenanceTimeInterval(); + + long hardForkTime = + ((ForkBlockVersionEnum.VERSION_4_7_5.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + forkUtils.getManager().getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(hardForkTime + 1); + + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_7_5.getValue(), stats); + + // Should fail because the proposal value is invalid + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "This value[ALLOW_ENERGY_ADJUSTMENT] is only allowed to be 1", + e.getMessage()); + } + + // Should succeed + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1); + } catch (Throwable t) { + Assert.fail(); + } + + ProposalCapsule proposalCapsule = new ProposalCapsule(ByteString.empty(), 0); + Map parameter = new HashMap<>(); + parameter.put(81L, 1L); + proposalCapsule.setParameters(parameter); + ProposalService.process(dbManager, proposalCapsule); + + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_ENERGY_ADJUSTMENT.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[ALLOW_ENERGY_ADJUSTMENT] has been valid, no need to propose again", + e.getMessage()); + } + } + + private void testConsensusLogicOptimizationProposal() { + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "Bad chain parameter id [CONSENSUS_LOGIC_OPTIMIZATION]", + e.getMessage()); + } + + long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() + .getMaintenanceTimeInterval(); + + long hardForkTime = + ((ForkBlockVersionEnum.VERSION_4_8_0.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + forkUtils.getManager().getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(hardForkTime + 1); + + byte[] stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); + + // Should fail because the proposal value is invalid + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "This value[CONSENSUS_LOGIC_OPTIMIZATION] is only allowed to be 1", + e.getMessage()); + } + + dynamicPropertiesStore.saveConsensusLogicOptimization(1); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.CONSENSUS_LOGIC_OPTIMIZATION.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[CONSENSUS_LOGIC_OPTIMIZATION] has been valid, no need to propose again", + e.getMessage()); + } + + } + + private void testAllowTvmCancunProposal() { + byte[] stats = new byte[27]; + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_CANCUN.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "Bad chain parameter id [ALLOW_TVM_CANCUN]", + e.getMessage()); + } + + long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() + .getMaintenanceTimeInterval(); + + long hardForkTime = + ((ForkBlockVersionEnum.VERSION_4_8_0.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + forkUtils.getManager().getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(hardForkTime + 1); + + stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); + + // Should fail because the proposal value is invalid + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_CANCUN.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "This value[ALLOW_TVM_CANCUN] is only allowed to be 1", + e.getMessage()); + } + + dynamicPropertiesStore.saveAllowTvmCancun(1); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_CANCUN.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[ALLOW_TVM_CANCUN] has been valid, no need to propose again", + e.getMessage()); + } + + } + + private void testAllowTvmBlobProposal() { + byte[] stats = new byte[27]; + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_BLOB.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "Bad chain parameter id [ALLOW_TVM_BLOB]", + e.getMessage()); + } + + long maintenanceTimeInterval = forkUtils.getManager().getDynamicPropertiesStore() + .getMaintenanceTimeInterval(); + + long hardForkTime = + ((ForkBlockVersionEnum.VERSION_4_8_0.getHardForkTime() - 1) / maintenanceTimeInterval + 1) + * maintenanceTimeInterval; + forkUtils.getManager().getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(hardForkTime + 1); + + stats = new byte[27]; + Arrays.fill(stats, (byte) 1); + forkUtils.getManager().getDynamicPropertiesStore() + .statsByVersion(ForkBlockVersionEnum.VERSION_4_8_0.getValue(), stats); + + // Should fail because the proposal value is invalid + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_BLOB.getCode(), 2); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "This value[ALLOW_TVM_BLOB] is only allowed to be 1", + e.getMessage()); + } + + dynamicPropertiesStore.saveAllowTvmBlob(1); + try { + ProposalUtil.validator(dynamicPropertiesStore, forkUtils, + ProposalType.ALLOW_TVM_BLOB.getCode(), 1); + Assert.fail(); + } catch (ContractValidateException e) { + Assert.assertEquals( + "[ALLOW_TVM_BLOB] has been valid, no need to propose again", + e.getMessage()); + } + + } + + @Test + public void blockVersionCheck() { + for (ForkBlockVersionEnum forkVersion : ForkBlockVersionEnum.values()) { + if (forkVersion.getValue() > Parameter.ChainConstant.BLOCK_VERSION) { + Assert.fail("ForkBlockVersion must be less than BLOCK_VERSION"); + } + } } } diff --git a/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java b/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java index a46bf546821..0eb69f8fd66 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/TransactionUtilTest.java @@ -1,147 +1,454 @@ package org.tron.core.actuator.utils; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.tron.common.math.Maths.max; import static org.tron.core.capsule.utils.TransactionUtil.isNumber; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_COST_BASE_SIZE; +import static org.tron.core.config.Parameter.ChainConstant.DELEGATE_PERIOD; +import static org.tron.core.config.Parameter.ChainConstant.TRX_PRECISION; +import static org.tron.core.utils.TransactionUtil.validAccountId; +import static org.tron.core.utils.TransactionUtil.validAccountName; +import static org.tron.core.utils.TransactionUtil.validAssetName; +import static org.tron.core.utils.TransactionUtil.validTokenAbbrName; -import java.io.File; -import java.io.UnsupportedEncodingException; +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionCapsule; import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.utils.TransactionUtil; - +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; @Slf4j(topic = "capsule") -public class TransactionUtilTest { +public class TransactionUtilTest extends BaseTest { - private static final String dbPath = "output_transactionUtil_test"; - public static Application AppT; - private static TronApplicationContext context; + private static String OWNER_ADDRESS; /** * Init . */ @BeforeClass public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; } - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); + @Before + public void setUp() { + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(owner), + AccountType.Normal, + 10_000_000_000L); + ownerCapsule.setFrozenForBandwidth(1000000L, 1000000L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + } + + // only for testing + public static long consumeBandWidthSize( + final TransactionCapsule transactionCapsule, + ChainBaseManager chainBaseManager) { + long bs; + + boolean supportVM = chainBaseManager.getDynamicPropertiesStore().supportVM(); + if (supportVM) { + bs = transactionCapsule.getInstance().toBuilder().clearRet().build().getSerializedSize(); } else { - logger.info("Release resources failure."); + bs = transactionCapsule.getSerializedSize(); + } + + List contracts = transactionCapsule.getInstance().getRawData() + .getContractList(); + for (Transaction.Contract contract : contracts) { + if (contract.getType() == Transaction.Contract.ContractType.ShieldedTransferContract) { + continue; + } + if (supportVM) { + bs += Constant.MAX_RESULT_SIZE_IN_TX; + } } + + return bs; + } + + // only for testing + public static long estimateConsumeBandWidthSize(final AccountCapsule ownerCapsule, + ChainBaseManager chainBaseManager) { + DelegateResourceContract.Builder builder; + if (chainBaseManager.getDynamicPropertiesStore().supportMaxDelegateLockPeriod()) { + builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setLockPeriod(chainBaseManager.getDynamicPropertiesStore().getMaxDelegateLockPeriod()) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + } else { + builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + } + TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build(), + ContractType.DelegateResourceContract); + long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager); + + DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build(), + ContractType.DelegateResourceContract); + long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); + long addSize = max(size1 - size2, 0L, true); + + return DELEGATE_COST_BASE_SIZE + addSize; + } + + // only for testing + public static long estimateConsumeBandWidthSizeOld( + final AccountCapsule ownerCapsule, + ChainBaseManager chainBaseManager) { + DelegateResourceContract.Builder builder = DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(ownerCapsule.getFrozenV2BalanceForBandwidth()); + TransactionCapsule fakeTransactionCapsule = new TransactionCapsule(builder.build(), + ContractType.DelegateResourceContract); + long size1 = consumeBandWidthSize(fakeTransactionCapsule, chainBaseManager); + + DelegateResourceContract.Builder builder2 = DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + TransactionCapsule fakeTransactionCapsule2 = new TransactionCapsule(builder2.build(), + ContractType.DelegateResourceContract); + long size2 = consumeBandWidthSize(fakeTransactionCapsule2, chainBaseManager); + long addSize = max(size1 - size2, 0L, true); + + return DELEGATE_COST_BASE_SIZE + addSize; } @Test - public void validAccountNameCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); - String account = ""; - Assert.assertEquals(true, actuatorUtil.validAccountName(account.getBytes("utf-8"))); + public void validAccountNameCheck() { + StringBuilder account = new StringBuilder(); + assertTrue(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 200; i++) { - account += (char) ('a' + (i % 26)); + account.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validAccountName(account.getBytes("utf-8"))); - account += 'z'; - Assert.assertEquals(false, actuatorUtil.validAccountName(account.getBytes("utf-8"))); - + assertTrue(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); + account.append('z'); + assertFalse(validAccountName(account.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void validAccountIdCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); - String accountId = ""; - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); + public void validAccountIdCheck() { + StringBuilder accountId = new StringBuilder(); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 7; i++) { - accountId += (char) ('a' + (i % 26)); + accountId.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 26; i++) { - accountId += (char) ('a' + (i % 26)); + accountId.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); - accountId = "ab cdefghij"; - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); - accountId = Character.toString((char) 128) + "abcdefjijk" + Character.toString((char) 129); - Assert.assertEquals(false, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); - accountId = ""; + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); + accountId = new StringBuilder("ab cdefghij"); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); + accountId = new StringBuilder((char) 128 + "abcdefjijk" + (char) 129); + assertFalse(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); + accountId = new StringBuilder(); for (int i = 0; i < 30; i++) { - accountId += (char) ('a' + (i % 26)); + accountId.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validAccountId(accountId.getBytes("utf-8"))); + assertTrue(validAccountId(accountId.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void validAssetNameCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); - String assetName = ""; - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); + public void validAssetNameCheck() { + StringBuilder assetName = new StringBuilder(); + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 33; i++) { - assetName += (char) ('a' + (i % 26)); + assetName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); - assetName = "ab cdefghij"; - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); - assetName = Character.toString((char) 128) + "abcdefjijk" + Character.toString((char) 129); - Assert.assertEquals(false, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); - assetName = ""; + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); + assetName = new StringBuilder("ab cdefghij"); + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); + assetName = new StringBuilder((char) 128 + "abcdefjijk" + (char) 129); + assertFalse(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); + assetName = new StringBuilder(); for (int i = 0; i < 20; i++) { - assetName += (char) ('a' + (i % 26)); + assetName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validAssetName(assetName.getBytes("utf-8"))); + assertTrue(validAssetName(assetName.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void validTokenAbbrNameCheck() throws UnsupportedEncodingException { - - TransactionUtil actuatorUtil = new TransactionUtil(); - String abbrName = ""; - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); + public void validTokenAbbrNameCheck() { + StringBuilder abbrName = new StringBuilder(); + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); for (int i = 0; i < 6; i++) { - abbrName += (char) ('a' + (i % 26)); + abbrName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); - abbrName = "a bd"; - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); - abbrName = "a" + Character.toString((char) 129) + 'f'; - Assert.assertEquals(false, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); - abbrName = ""; + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); + abbrName = new StringBuilder("a bd"); + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); + abbrName = new StringBuilder("a" + (char) 129 + 'f'); + assertFalse(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); + abbrName = new StringBuilder(); for (int i = 0; i < 5; i++) { - abbrName += (char) ('a' + (i % 26)); + abbrName.append((char) ('a' + (i % 26))); } - Assert.assertEquals(true, actuatorUtil.validTokenAbbrName(abbrName.getBytes("utf-8"))); + assertTrue(validTokenAbbrName(abbrName.toString().getBytes(StandardCharsets.UTF_8))); } @Test - public void isNumberCheck() throws UnsupportedEncodingException { - TransactionUtil actuatorUtil = new TransactionUtil(); + public void isNumberCheck() { String number = ""; - Assert.assertEquals(false, isNumber(number.getBytes("utf-8"))); + assertFalse(isNumber(number.getBytes(StandardCharsets.UTF_8))); number = "123df34"; - Assert.assertEquals(false, isNumber(number.getBytes("utf-8"))); + assertFalse(isNumber(number.getBytes(StandardCharsets.UTF_8))); number = "013"; - Assert.assertEquals(false, isNumber(number.getBytes("utf-8"))); + assertFalse(isNumber(number.getBytes(StandardCharsets.UTF_8))); number = "24"; - Assert.assertEquals(true, isNumber(number.getBytes("utf-8"))); + assertTrue(isNumber(number.getBytes(StandardCharsets.UTF_8))); + } + + @Test + public void testEstimateConsumeBandWidthSize() { + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + long estimateConsumeBandWidthSize = estimateConsumeBandWidthSize(ownerCapsule, + dbManager.getChainBaseManager()); + assertEquals(275L, estimateConsumeBandWidthSize); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + @Test + public void testEstimateConsumeBandWidthSize2() { + chainBaseManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(864000L); + AccountCapsule ownerCapsule = + dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + long estimateConsumeBandWidthSize = estimateConsumeBandWidthSize(ownerCapsule, + dbManager.getChainBaseManager()); + assertEquals(277L, estimateConsumeBandWidthSize); + chainBaseManager.getDynamicPropertiesStore().saveMaxDelegateLockPeriod(DELEGATE_PERIOD / 3000); + } + + + @Test + public void testEstimateConsumeBandWidthSizeOld() { + dbManager.getDynamicPropertiesStore().saveAllowCreationOfContracts(1L); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + long balance = 1000_000L; + + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + ownerCapsule = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)); + long estimateConsumeBandWidthSize1 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(277, estimateConsumeBandWidthSize1); + + balance = 1000_000_000L; + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + long estimateConsumeBandWidthSize2 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(279, estimateConsumeBandWidthSize2); + + balance = 1000_000_000_000L; + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + long estimateConsumeBandWidthSize3 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(280, estimateConsumeBandWidthSize3); + + balance = 1000_000_000_000_000L; + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + long estimateConsumeBandWidthSize4 = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + Assert.assertEquals(282, estimateConsumeBandWidthSize4); + } + + + @Test + public void testEstimateConsumeBandWidthSizeNew() { + long balance = 1000_000L; + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long estimateConsumeBandWidthSize1 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(277, estimateConsumeBandWidthSize1); + + balance = 1000_000_000L; + long estimateConsumeBandWidthSize2 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(279, estimateConsumeBandWidthSize2); + + balance = 1000_000_000_000L; + long estimateConsumeBandWidthSize3 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(280, estimateConsumeBandWidthSize3); + + balance = 1000_000_000_000_000L; + long estimateConsumeBandWidthSize4 = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(282, estimateConsumeBandWidthSize4); } + + @Test + public void testEstimateConsumeBandWidthSize3() { + dbManager.getDynamicPropertiesStore().saveAllowCreationOfContracts(1L); + ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = 1000_000L; + + AccountCapsule ownerCapsule; + long estimateConsumeBandWidthSizeOld; + long estimateConsumeBandWidthSizeNew; + + for (int i = 0; i < 100; i++) { + // old value is + ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), Protocol.AccountType.Normal, + balance); + ownerCapsule.addFrozenBalanceForBandwidthV2(balance); + dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + estimateConsumeBandWidthSizeOld = estimateConsumeBandWidthSizeOld( + ownerCapsule, chainBaseManager); + + // new value is + estimateConsumeBandWidthSizeNew = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + + System.out.println("balance:" + + balance + + ", estimateConsumeBandWidthSizeOld:" + + estimateConsumeBandWidthSizeOld + + ", estimateConsumeBandWidthSizeNew:" + + estimateConsumeBandWidthSizeNew); + // new value assert equal to old value + Assert.assertEquals(estimateConsumeBandWidthSizeOld, estimateConsumeBandWidthSizeNew); + + // balance accumulated + balance = balance * 10; + if (balance < 0) { + break; + } + } + + } + + @Test + public void estimateConsumeBandWidthSizePositive() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = 100; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L, true); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeBoundary() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = TRX_PRECISION; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L, true); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeEdge() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = TRX_PRECISION + 1; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L, true); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void estimateConsumeBandWidthSizeCorner() { + DynamicPropertiesStore dps = chainBaseManager.getDynamicPropertiesStore(); + long balance = Long.MAX_VALUE; + DelegateResourceContract.Builder builder = + DelegateResourceContract.newBuilder() + .setLock(true) + .setBalance(balance); + DelegateResourceContract.Builder builder2 = + DelegateResourceContract.newBuilder() + .setBalance(TRX_PRECISION); + + long expected = DELEGATE_COST_BASE_SIZE + max( + builder.build().getSerializedSize() - builder2.build().getSerializedSize(), 0L, true); + long actual = TransactionUtil.estimateConsumeBandWidthSize(dps, balance); + Assert.assertEquals(expected, actual); + } + + @Test + public void testConcurrentToString() throws InterruptedException { + Transaction.Builder builder = Transaction.newBuilder(); + TransactionCapsule trx = new TransactionCapsule(builder.build()); + List threadList = new ArrayList<>(); + int n = 10; + for (int i = 0; i < n; i++) { + threadList.add(new Thread(() -> trx.toString())); + } + for (int i = 0; i < n; i++) { + threadList.get(i).start(); + } + for (int i = 0; i < n; i++) { + threadList.get(i).join(); + } + Assert.assertTrue(true); + } } diff --git a/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java b/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java index 3fd3a352a48..952aab1a91d 100644 --- a/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java +++ b/framework/src/test/java/org/tron/core/actuator/utils/ZenChainParamsTest.java @@ -1,74 +1,38 @@ package org.tron.core.actuator.utils; -import java.io.File; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; import org.tron.core.utils.ZenChainParams; @Slf4j(topic = "capsule") public class ZenChainParamsTest { - private static final String dbPath = "output_zenchainparams_test"; - public static Application AppT; - private static TronApplicationContext context; - - /** - * Init . - */ - @BeforeClass - public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void variableCheck() { - ZenChainParams actuatorUtils = new ZenChainParams(); - Assert.assertEquals(16, actuatorUtils.NOTEENCRYPTION_AUTH_BYTES); - Assert.assertEquals(1, actuatorUtils.ZC_NOTEPLAINTEXT_LEADING); - Assert.assertEquals(8, actuatorUtils.ZC_V_SIZE); - Assert.assertEquals(32, actuatorUtils.ZC_R_SIZE); - Assert.assertEquals(512, actuatorUtils.ZC_MEMO_SIZE); - Assert.assertEquals(11, actuatorUtils.ZC_DIVERSIFIER_SIZE); - Assert.assertEquals(32, actuatorUtils.ZC_JUBJUB_POINT_SIZE); - Assert.assertEquals(32, actuatorUtils.ZC_JUBJUB_SCALAR_SIZE); + ZenChainParams zenChainParams = new ZenChainParams(); + assertNotNull(zenChainParams); + assertEquals(16, ZenChainParams.NOTEENCRYPTION_AUTH_BYTES); + assertEquals(1, ZenChainParams.ZC_NOTEPLAINTEXT_LEADING); + assertEquals(8, ZenChainParams.ZC_V_SIZE); + assertEquals(32, ZenChainParams.ZC_R_SIZE); + assertEquals(512, ZenChainParams.ZC_MEMO_SIZE); + assertEquals(11, ZenChainParams.ZC_DIVERSIFIER_SIZE); + assertEquals(32, ZenChainParams.ZC_JUBJUB_POINT_SIZE); + assertEquals(32, ZenChainParams.ZC_JUBJUB_SCALAR_SIZE); int ZC_ENCPLAINTEXT_SIZE = - actuatorUtils.ZC_NOTEPLAINTEXT_LEADING + actuatorUtils.ZC_DIVERSIFIER_SIZE - + actuatorUtils.ZC_V_SIZE + actuatorUtils.ZC_R_SIZE + actuatorUtils.ZC_MEMO_SIZE; - Assert.assertEquals(ZC_ENCPLAINTEXT_SIZE, actuatorUtils.ZC_ENCPLAINTEXT_SIZE); - int ZC_ENCCIPHERTEXT_SIZE = (actuatorUtils.ZC_ENCPLAINTEXT_SIZE - + actuatorUtils.NOTEENCRYPTION_AUTH_BYTES); - Assert.assertEquals(ZC_ENCCIPHERTEXT_SIZE, actuatorUtils.ZC_ENCCIPHERTEXT_SIZE); - int ZC_OUTCIPHERTEXT_SIZE = (actuatorUtils.ZC_OUTPLAINTEXT_SIZE - + actuatorUtils.NOTEENCRYPTION_AUTH_BYTES); - Assert.assertEquals(ZC_OUTCIPHERTEXT_SIZE, actuatorUtils.ZC_OUTCIPHERTEXT_SIZE); - Assert.assertTrue(actuatorUtils instanceof ZenChainParams); + ZenChainParams.ZC_NOTEPLAINTEXT_LEADING + ZenChainParams.ZC_DIVERSIFIER_SIZE + + ZenChainParams.ZC_V_SIZE + ZenChainParams.ZC_R_SIZE + ZenChainParams.ZC_MEMO_SIZE; + assertEquals(ZenChainParams.ZC_ENCPLAINTEXT_SIZE, ZC_ENCPLAINTEXT_SIZE); + int ZC_ENCCIPHERTEXT_SIZE = (ZenChainParams.ZC_ENCPLAINTEXT_SIZE + + ZenChainParams.NOTEENCRYPTION_AUTH_BYTES); + assertEquals(ZenChainParams.ZC_ENCCIPHERTEXT_SIZE, ZC_ENCCIPHERTEXT_SIZE); + int ZC_OUTCIPHERTEXT_SIZE = (ZenChainParams.ZC_OUTPLAINTEXT_SIZE + + ZenChainParams.NOTEENCRYPTION_AUTH_BYTES); + assertEquals(ZenChainParams.ZC_OUTCIPHERTEXT_SIZE, ZC_OUTCIPHERTEXT_SIZE); } } diff --git a/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceListenerTest.java b/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceListenerTest.java index 7cd1b41f5a5..089711219f8 100644 --- a/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceListenerTest.java +++ b/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceListenerTest.java @@ -1,6 +1,6 @@ package org.tron.core.actuator.vm; -import java.io.File; +import java.io.IOException; import java.lang.reflect.Field; import java.util.List; import java.util.Map; @@ -8,9 +8,10 @@ import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.config.args.Args; import org.tron.core.db.TransactionStoreTest; @@ -20,7 +21,8 @@ @Slf4j(topic = "VM") public class ProgramTraceListenerTest { - private static final String dbPath = "output_programTraceListener_test"; + @ClassRule + public static TemporaryFolder temporaryFolder = new TemporaryFolder(); private static final int WORD_SIZE = 32; private ProgramTraceListener traceListener; @@ -30,15 +32,15 @@ public class ProgramTraceListenerTest { private DataWord storageWordValue = new DataWord(3); @BeforeClass - public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + public static void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); } @AfterClass public static void destroy() { Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); } private void invokeProgramTraceListener(ProgramTraceListener traceListener) { diff --git a/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceTest.java b/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceTest.java index c9c4966e208..46be28deed0 100644 --- a/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceTest.java +++ b/framework/src/test/java/org/tron/core/actuator/vm/ProgramTraceTest.java @@ -1,14 +1,15 @@ package org.tron.core.actuator.vm; -import java.io.File; +import java.io.IOException; import java.math.BigInteger; import java.util.List; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.config.args.Args; import org.tron.core.vm.trace.Op; @@ -16,17 +17,19 @@ import org.tron.core.vm.trace.ProgramTrace; public class ProgramTraceTest { - private static final String dbPath = "output_programTrace_test"; + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass - public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + public static void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); } @AfterClass public static void destroy() { Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java index e0a9e188b06..7a217dfd787 100644 --- a/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/AccountCapsuleTest.java @@ -1,39 +1,25 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; -import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Random; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.capsule.utils.AssetUtil; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.store.AccountAssetStore; -import org.tron.core.store.AccountStore; -import org.tron.protos.Protocol; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Key; import org.tron.protos.Protocol.Permission; import org.tron.protos.Protocol.Vote; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -public class AccountCapsuleTest { +public class AccountCapsuleTest extends BaseTest { - private static final String dbPath = "output_accountCapsule_test"; - private static final Manager dbManager; - private static final TronApplicationContext context; private static final String OWNER_ADDRESS; private static final String ASSET_NAME = "trx"; private static final long TOTAL_SUPPLY = 10000L; @@ -50,10 +36,7 @@ public class AccountCapsuleTest { static AccountCapsule accountCapsule; static { - Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "a06a17a49648a8ad32055c06f60fa14ae46df91234"; } @@ -69,13 +52,6 @@ public static void init() { accountCapsuleTest.setBalance(1111L); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - public static byte[] randomBytes(int length) { //generate the random number byte[] result = new byte[length]; @@ -114,11 +90,11 @@ public void AssetAmountTest() { String nameAdd = "TokenX"; long amountAdd = 222L; boolean addBoolean = accountCapsuleTest - .addAssetAmount(nameAdd.getBytes(), amountAdd); + .addAssetAmount(nameAdd.getBytes(), amountAdd, true); Assert.assertTrue(addBoolean); - Map assetMap = accountCapsuleTest.getAssetMap(); + Map assetMap = accountCapsuleTest.getAssetMapForTest(); for (Map.Entry entry : assetMap.entrySet()) { Assert.assertEquals(nameAdd, entry.getKey()); Assert.assertEquals(amountAdd, entry.getValue().longValue()); @@ -126,17 +102,16 @@ public void AssetAmountTest() { long amountReduce = 22L; boolean reduceBoolean = accountCapsuleTest - .reduceAssetAmount(ByteArray.fromString("TokenX"), amountReduce); + .reduceAssetAmount(ByteArray.fromString("TokenX"), amountReduce, false); Assert.assertTrue(reduceBoolean); - Map assetMapAfter = accountCapsuleTest.getAssetMap(); + Map assetMapAfter = accountCapsuleTest.getAssetMapForTest(); for (Map.Entry entry : assetMapAfter.entrySet()) { Assert.assertEquals(nameAdd, entry.getKey()); Assert.assertEquals(amountAdd - amountReduce, entry.getValue().longValue()); } - String key = nameAdd; long value = 11L; - boolean addAsssetBoolean = accountCapsuleTest.addAsset(key.getBytes(), value); + boolean addAsssetBoolean = accountCapsuleTest.addAsset(nameAdd.getBytes(), value); Assert.assertFalse(addAsssetBoolean); String keyName = "TokenTest"; @@ -198,9 +173,9 @@ public void sameTokenNameCloseAssertAmountV2test() { dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); accountCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), 1000L); - Assert.assertEquals(accountCapsule.getAssetMap().get(ASSET_NAME).longValue(), 1000L); - Assert.assertEquals(accountCapsule.getAssetMapV2().get(String.valueOf(id)).longValue(), - 1000L); + Assert.assertEquals(1000L, accountCapsule.getAssetMapForTest().get(ASSET_NAME).longValue()); + Assert.assertEquals(1000L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue()); //assetBalanceEnoughV2 Assert.assertTrue(accountCapsule.assetBalanceEnoughV2(ByteArray.fromString(ASSET_NAME), @@ -222,10 +197,11 @@ public void sameTokenNameCloseAssertAmountV2test() { Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString(ASSET_NAME), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); // 1000-999 +500 - Assert.assertEquals(accountCapsule.getAssetMap().get(ASSET_NAME).longValue(), 501L); + Assert.assertEquals(501L, accountCapsule.getAssetMapForTest().get(ASSET_NAME).longValue()); Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString("abc"), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); - Assert.assertEquals(accountCapsule.getAssetMap().get("abc").longValue(), 500L); + Assert.assertEquals(500L, + accountCapsule.getAssetMapForTest().get("abc").longValue()); } /** @@ -279,8 +255,8 @@ public void sameTokenNameOpenAssertAmountV2test() { 10000); accountCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), 1000L); dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); - Assert.assertEquals(accountCapsule.getAssetMapV2().get(String.valueOf(id)).longValue(), - 1000L); + Assert.assertEquals(1000L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue()); //assetBalanceEnoughV2 Assert.assertTrue(accountCapsule.assetBalanceEnoughV2(ByteArray.fromString(String.valueOf(id)), @@ -305,14 +281,14 @@ public void sameTokenNameOpenAssertAmountV2test() { Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString(String.valueOf(id)), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); // 1000-999 +500 - Assert.assertEquals(accountCapsule.getAssetMapV2().get(String.valueOf(id)).longValue(), - 501L); + Assert.assertEquals(501L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id)).longValue()); //abc Assert.assertTrue(accountCapsule.addAssetAmountV2(ByteArray.fromString(String.valueOf(id + 1)), 500, dbManager.getDynamicPropertiesStore(), dbManager.getAssetIssueStore())); Assert - .assertEquals(accountCapsule.getAssetMapV2().get(String.valueOf(id + 1)).longValue(), - 500L); + .assertEquals(500L, + accountCapsule.getAssetV2MapForTest().get(String.valueOf(id + 1)).longValue()); } @Test @@ -324,9 +300,8 @@ public void witnessPermissionTest() { AccountType.Normal, 10000); - Assert.assertTrue( - Arrays.equals(ByteArray.fromHexString(OWNER_ADDRESS), - accountCapsule.getWitnessPermissionAddress())); + Assert.assertArrayEquals(ByteArray.fromHexString(OWNER_ADDRESS), + accountCapsule.getWitnessPermissionAddress()); String witnessPermissionAddress = Wallet.getAddressPreFixString() + "cc6a17a49648a8ad32055c06f60fa14ae46df912cc"; @@ -335,78 +310,7 @@ public void witnessPermissionTest() { .setAddress(ByteString.copyFrom(ByteArray.fromHexString(witnessPermissionAddress))) .build()).build()).build()); - Assert.assertTrue( - Arrays.equals(ByteArray.fromHexString(witnessPermissionAddress), - accountCapsule.getWitnessPermissionAddress())); - } - - @Test - public void importAssetTest() { - AccountAssetStore accountAssetStore = dbManager.getAccountAssetStore(); - AccountStore accountStore = dbManager.getAccountStore(); - - dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); - long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; - dbManager.getDynamicPropertiesStore().saveTokenIdNum(id); - - AssetIssueContract assetIssueContract = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) - .setId(Long.toString(id)) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); - AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); - dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); - - AssetIssueContract assetIssueContract2 = - AssetIssueContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) - .setName(ByteString.copyFrom(ByteArray.fromString("abc"))) - .setId(Long.toString(id + 1)) - .setTotalSupply(TOTAL_SUPPLY) - .setTrxNum(TRX_NUM) - .setNum(NUM) - .setStartTime(START_TIME) - .setEndTime(END_TIME) - .setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) - .build(); - AssetIssueCapsule assetIssueCapsule2 = new AssetIssueCapsule(assetIssueContract2); - dbManager.getAssetIssueV2Store().put(assetIssueCapsule2.createDbV2Key(), assetIssueCapsule2); - - AccountCapsule accountCapsule = - new AccountCapsule( - ByteString.copyFromUtf8("owner"), - ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), - AccountType.Normal, - 10000); - accountCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), 1000L); - byte[] address = accountCapsule.getAddress().toByteArray(); - accountStore.put(address, accountCapsule); - - Protocol.Account account = accountCapsule.getInstance(); - Protocol.AccountAsset accountAsset = AssetUtil.getAsset(account); - if (null != accountAsset) { - accountAssetStore.put(accountCapsule.getAddress().toByteArray(), new AccountAssetCapsule( - accountAsset)); - account = AssetUtil.clearAsset(account); - accountCapsule.setIsAssetImport(false); - accountCapsule.setInstance(account); - } - - accountStore.put(address, accountCapsule); - Assert.assertEquals(accountCapsule.getAssetMapV2().size(), 0); - AccountAssetCapsule accountAssetCapsule = accountAssetStore.get(address); - Assert.assertNotNull(accountAssetCapsule); - Assert.assertEquals(accountAssetCapsule.getAssetMapV2().size(), 1); + Assert.assertArrayEquals(ByteArray.fromHexString(witnessPermissionAddress), + accountCapsule.getWitnessPermissionAddress()); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java index 60766a07863..3c86d893895 100644 --- a/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java @@ -1,14 +1,20 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -20,24 +26,27 @@ @Slf4j public class BlockCapsuleTest { + private final String privateKey = PublicMethod.getRandomPrivateKey(); + private LocalWitnesses localWitnesses; + private static BlockCapsule blockCapsule0 = new BlockCapsule(1, Sha256Hash.wrap(ByteString .copyFrom(ByteArray .fromHexString("9938a342238077182498b464ac0292229938a342238077182498b464ac029222"))), 1234, ByteString.copyFrom("1234567".getBytes())); - private static String dbPath = "output_bloackcapsule_test"; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); @BeforeClass - public static void init() { - Args.setParam(new String[]{"-d", dbPath}, + public static void init() throws IOException { + Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); } @AfterClass public static void removeDb() { Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); } @Test @@ -119,9 +128,15 @@ public void testGetInsHash() { Sha256Hash.wrap(blockCapsule0.getParentHashStr())); } + @Test public void testHasWitnessSignature() { + localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + Assert.assertFalse(blockCapsule0.hasWitnessSignature()); blockCapsule0 .sign(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); @@ -133,4 +148,20 @@ public void testGetTimeStamp() { Assert.assertEquals(1234L, blockCapsule0.getTimeStamp()); } -} \ No newline at end of file + @Test + public void testConcurrentToString() throws InterruptedException { + List threadList = new ArrayList<>(); + int n = 10; + for (int i = 0; i < n; i++) { + threadList.add(new Thread(() -> blockCapsule0.toString())); + } + for (int i = 0; i < n; i++) { + threadList.get(i).start(); + } + for (int i = 0; i < n; i++) { + threadList.get(i).join(); + } + Assert.assertTrue(true); + } + +} diff --git a/framework/src/test/java/org/tron/core/capsule/ContractStateCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/ContractStateCapsuleTest.java new file mode 100644 index 00000000000..c90ad89abb3 --- /dev/null +++ b/framework/src/test/java/org/tron/core/capsule/ContractStateCapsuleTest.java @@ -0,0 +1,180 @@ +package org.tron.core.capsule; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.vm.config.VMConfig; +import org.tron.protos.contract.SmartContractOuterClass; + +public class ContractStateCapsuleTest { + + @Test + public void testCatchUpCycle() { + ContractStateCapsule capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertFalse(capsule.catchUpToCycle(1000L, 2_000_000L, 2000L, 10_00L, false, false)); + Assert.assertEquals(1000L, capsule.getUpdateCycle()); + Assert.assertEquals(1_000_000L, capsule.getEnergyUsage()); + Assert.assertEquals(5000L, capsule.getEnergyFactor()); + + Assert.assertTrue(capsule.catchUpToCycle(1010L, 900_000L, 1000L, 10_000L, false, false)); + Assert.assertEquals(1010L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(3137L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1001L, 2_000_000L, 2000L, 10_000L, false, false)); + Assert.assertEquals(1001L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(4250L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1001L, 1_000_000L, 2000L, 10_000L, false, false)); + Assert.assertEquals(1001L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(4250L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1001L, 900_000L, 2000L, 10_000L, false, false)); + Assert.assertEquals(1001L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(8000L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1001L, 900_000L, 5000L, 10_000L, false, false)); + Assert.assertEquals(1001L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(10_000L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1002L, 900_000L, 5000L, 10_000L, false, false)); + Assert.assertEquals(1002L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(7500L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1003L, 900_000L, 5000L, 10_000L, false, false)); + Assert.assertEquals(1003L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(5312L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1004L, 900_000L, 5000L, 10_000L, false, false)); + Assert.assertEquals(1004L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(3398L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1005L, 900_000L, 5000L, 10_000L, true, true)); + Assert.assertEquals(1005L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(1723L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1005L, 900_000L, 5000L, 10_000L, true, true)); + Assert.assertEquals(1005L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(1723L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + + Assert.assertTrue(capsule.catchUpToCycle(1006L, 900_000L, 5000L, 10_000L, true, true)); + Assert.assertEquals(1006L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(258L, capsule.getEnergyFactor()); + + capsule = new ContractStateCapsule( + SmartContractOuterClass.ContractState.newBuilder() + .setEnergyUsage(1_000_000L) + .setEnergyFactor(5000L) + .setUpdateCycle(1000L) + .build()); + Args.getInstance().setAllowStrictMath(1); + VMConfig.initAllowStrictMath(Args.getInstance().getAllowStrictMath()); + DynamicPropertiesStore dps = Mockito.mock(DynamicPropertiesStore.class); + Mockito.when(dps.getCurrentCycleNumber()).thenReturn(1007L); + Mockito.when(dps.getDynamicEnergyThreshold()).thenReturn(900_000L); + Mockito.when(dps.getDynamicEnergyIncreaseFactor()).thenReturn(5000L); + Mockito.when(dps.getDynamicEnergyMaxFactor()).thenReturn(10_000L); + Mockito.when(dps.allowStrictMath()).thenReturn(VMConfig.allowStrictMath()); + Assert.assertTrue(capsule.catchUpToCycle(dps)); + Assert.assertEquals(1007L, capsule.getUpdateCycle()); + Assert.assertEquals(0L, capsule.getEnergyUsage()); + Assert.assertEquals(0L, capsule.getEnergyFactor()); + + } + + @After + public void reset() { + Args.clearParam(); + + } + +} diff --git a/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java index d1a86f273db..5fcd259d738 100644 --- a/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/ExchangeCapsuleTest.java @@ -1,69 +1,21 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.db.StorageMarket; import org.tron.core.exception.ItemNotFoundException; @Slf4j -public class ExchangeCapsuleTest { - - private static final String dbPath = "output_exchange_capsule_test_test"; - private static final String OWNER_ADDRESS; - private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static final String OWNER_ACCOUNT_INVALID; - private static final long initBalance = 10_000_000_000_000_000L; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static StorageMarket storageMarket; - private static TronApplicationContext context; +public class ExchangeCapsuleTest extends BaseTest { static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - OWNER_ACCOUNT_INVALID = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - storageMarket = new StorageMarket(chainBaseManager.getAccountStore(), - chainBaseManager.getDynamicPropertiesStore()); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } /** @@ -100,8 +52,8 @@ public void testExchange() { long sellQuant = 1_000_000L; byte[] sellID = "abc".getBytes(); - - long result = exchangeCapsule.transaction(sellID, sellQuant); + boolean useStrictMath = chainBaseManager.getDynamicPropertiesStore().allowStrictMath(); + long result = exchangeCapsule.transaction(sellID, sellQuant, useStrictMath); Assert.assertEquals(990_099L, result); sellBalance += sellQuant; Assert.assertEquals(sellBalance, exchangeCapsule.getFirstTokenBalance()); @@ -109,7 +61,7 @@ public void testExchange() { Assert.assertEquals(buyBalance, exchangeCapsule.getSecondTokenBalance()); sellQuant = 9_000_000L; - long result2 = exchangeCapsule.transaction(sellID, sellQuant); + long result2 = exchangeCapsule.transaction(sellID, sellQuant, useStrictMath); Assert.assertEquals(9090909L, result + result2); sellBalance += sellQuant; Assert.assertEquals(sellBalance, exchangeCapsule.getFirstTokenBalance()); diff --git a/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java index ed0a3bda670..7065608f188 100644 --- a/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/TransactionCapsuleTest.java @@ -1,91 +1,36 @@ package org.tron.core.capsule; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.BAD_JUMP_DESTINATION; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.PRECOMPILED_CONTRACT; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; + import com.google.protobuf.ByteString; -import java.io.File; -import java.util.Objects; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; +import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.Protocol.Transaction.Result; import org.tron.protos.Protocol.Transaction.Result.contractResult; +import org.tron.protos.Protocol.Transaction.raw; @Slf4j -public class TransactionCapsuleTest { +public class TransactionCapsuleTest extends BaseTest { - private static Manager dbManager; - private static TronApplicationContext context; - private static Application AppT; - private static String dbPath = "output_transactioncapsule_test"; private static String OWNER_ADDRESS; - private static String OWNER_KEY = - "bfa67cb3dc6609b3a0c98e717d66f38ed1a159b5b3421678dfab85961c40de2f"; - private static String TO_ADDRESS; - private static String OWNER_ACCOUNT_NOT_Exist; - private static String KEY_11 = "1111111111111111111111111111111111111111111111111111111111111111"; - private static String KEY_12 = "1212121212121212121212121212121212121212121212121212121212121212"; - private static String KEY_13 = "1313131313131313131313131313131313131313131313131313131313131313"; - private static String KEY_21 = "2121212121212121212121212121212121212121212121212121212121212121"; - private static String KEY_22 = "2222222222222222222222222222222222222222222222222222222222222222"; - private static String KEY_23 = "2323232323232323232323232323232323232323232323232323232323232323"; - private static String KEY_31 = "3131313131313131313131313131313131313131313131313131313131313131"; - private static String KEY_32 = "3232323232323232323232323232323232323232323232323232323232323232"; - private static String KEY_33 = "3333333333333333333333333333333333333333333333333333333333333333"; - - private static String KEY_ADDRESS_11; - private static String KEY_ADDRESS_12; - private static String KEY_ADDRESS_13; - private static String KEY_ADDRESS_21; - private static String KEY_ADDRESS_22; - private static String KEY_ADDRESS_23; - private static String KEY_ADDRESS_31; - private static String KEY_ADDRESS_32; - private static String KEY_ADDRESS_33; @BeforeClass public static void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "03702350064AD5C1A8AA6B4D74B051199CFF8EA7"; - TO_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - OWNER_ACCOUNT_NOT_Exist = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; - KEY_ADDRESS_11 = Wallet.getAddressPreFixString() + "19E7E376E7C213B7E7E7E46CC70A5DD086DAFF2A"; - KEY_ADDRESS_12 = Wallet.getAddressPreFixString() + "1C5A77D9FA7EF466951B2F01F724BCA3A5820B63"; - KEY_ADDRESS_13 = Wallet.getAddressPreFixString() + "03A1BBA60B5AA37094CF16123ADD674C01589488"; - - KEY_ADDRESS_21 = Wallet.getAddressPreFixString() + "2BD0C9FE079C8FCA0E3352EB3D02839C371E5C41"; - KEY_ADDRESS_22 = Wallet.getAddressPreFixString() + "1563915E194D8CFBA1943570603F7606A3115508"; - KEY_ADDRESS_23 = Wallet.getAddressPreFixString() + "D3E442496EB66A4748912EC4A3B7A111D0B855D6"; - - KEY_ADDRESS_31 = Wallet.getAddressPreFixString() + "77952CE83CA3CAD9F7ADCFABEDA85BD2F1F52008"; - KEY_ADDRESS_32 = Wallet.getAddressPreFixString() + "94622CC2A5B64A58C25A129D48A2BEEC4B65B779"; - KEY_ADDRESS_33 = Wallet.getAddressPreFixString() + "5CBDD86A2FA8DC4BDDD8A8F69DBA48572EEC07FB"; - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - AppT.shutdownServices(); - AppT.shutdown(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } /** @@ -98,984 +43,6 @@ public void createAccountCapsule() { dbManager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); } - /*@Test - public void getDefaultPermission() { - String[] names = {"active", "owner", "other"}; - ByteString address = ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)); - for (String name : names) { - Permission permission = TransactionCapsule - .getDefaultPermission(address, name); - Assert.assertEquals(permission.getName(), name); - Assert.assertEquals(permission.getThreshold(), 1); - if ("owner".equalsIgnoreCase(name)) { - Assert.assertEquals(permission.getParent(), ""); - } else { - Assert.assertEquals(permission.getParent(), "owner"); - } - Assert.assertEquals(permission.getKeysCount(), 1); - Key key = permission.getKeys(0); - Assert.assertEquals(key.getAddress(), address); - Assert.assertEquals(key.getWeight(), 1); - } - } - - public TransferContract createTransferContract(byte[] to, byte[] owner, long amount) { - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - return builder.build(); - } - - public PermissionAddKeyContract createPermissionAddKeyContract(byte[] owner, String name, - byte[] address, int weight) { - PermissionAddKeyContract.Builder contractBuilder = PermissionAddKeyContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setPermissionName(name); - Key.Builder keyBuilder = Key.newBuilder(); - keyBuilder.setAddress(ByteString.copyFrom(address)); - keyBuilder.setWeight(weight); - contractBuilder.setKey(keyBuilder.build()); - return contractBuilder.build(); - } - - public void updatePermission(List permissions, byte[] address) { - Account account = dbManager.getAccountStore().get(address).getInstance(); - Account.Builder builder = account.toBuilder(); - for (Permission permission : permissions) { - builder.addPermissions(permission); - } - dbManager.getAccountStore().put(address, new AccountCapsule(builder.build())); - } - - public List buildPermissions() { - Permission.Builder builder1 = Permission.newBuilder(); - Key.Builder key11 = Key.newBuilder(); - Key.Builder key12 = Key.newBuilder(); - Key.Builder key13 = Key.newBuilder(); - key11.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_11))).setWeight(1); - key12.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_12))).setWeight(1); - key13.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_13))).setWeight(1); - builder1.setName("owner").setThreshold(2).setParent("").addKeys(key11).addKeys(key12) - .addKeys(key13); - Permission.Builder builder2 = Permission.newBuilder(); - Key.Builder key21 = Key.newBuilder(); - Key.Builder key22 = Key.newBuilder(); - Key.Builder key23 = Key.newBuilder(); - key21.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_21))).setWeight(1); - key22.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_22))).setWeight(1); - key23.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_23))).setWeight(1); - builder2.setName("active").setThreshold(2).setParent("").addKeys(key21).addKeys(key22) - .addKeys(key23); - Permission.Builder builder3 = Permission.newBuilder(); - Key.Builder key31 = Key.newBuilder(); - Key.Builder key32 = Key.newBuilder(); - Key.Builder key33 = Key.newBuilder(); - key31.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_31))).setWeight(1); - key32.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_32))).setWeight(1); - key33.setAddress(ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_33))).setWeight(1); - builder3.setName("other").setThreshold(2).setParent("").addKeys(key31).addKeys(key32) - .addKeys(key33); - List list = new ArrayList<>(); - list.add(builder1.build()); - list.add(builder2.build()); - list.add(builder3.build()); - return list; - } - - @Test - public void getPermission() { - //Default "active" permission - byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); - Account account = dbManager.getAccountStore().get(owner).getInstance(); - try { - Permission permission = TransactionCapsule.getPermission(account, "active"); - Permission permission1 = TransactionCapsule - .getDefaultPermission(ByteString.copyFrom(owner), "active"); - Assert.assertEquals(permission, permission1); - } catch (PermissionException e) { - Assert.assertFalse(true); - } - //Default "owner" permission - try { - Permission permission = TransactionCapsule.getPermission(account, "owner"); - Permission permission1 = TransactionCapsule - .getDefaultPermission(ByteString.copyFrom(owner), "owner"); - Assert.assertEquals(permission, permission1); - } catch (PermissionException e) { - Assert.assertFalse(true); - } - //Add 3 permission : owner active other - List permissions = buildPermissions(); - updatePermission(permissions, owner); - Permission permission1 = permissions.get(0); - Permission permission2 = permissions.get(1); - account = dbManager.getAccountStore().get(owner).getInstance(); - try { - Permission permission = TransactionCapsule.getPermission(account, "owner"); - Assert.assertEquals(permission, permission1); - } catch (PermissionException e) { - Assert.assertFalse(true); - } - - try { - Permission permission = TransactionCapsule.getPermission(account, "active"); - Assert.assertEquals(permission, permission2); - } catch (PermissionException e) { - Assert.assertFalse(true); - } - } - - @Test - public void getWeight() { - List permissions = buildPermissions(); - Permission permission1 = permissions.get(0); - Permission permission2 = permissions.get(1); - Permission permission3 = permissions.get(2); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_11))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_12))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_13))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_21))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_22))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_23))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_31))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_32))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission1, ByteArray.fromHexString(KEY_ADDRESS_33))); - - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_11))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_12))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_13))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_21))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_22))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_23))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_31))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_32))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission2, ByteArray.fromHexString(KEY_ADDRESS_33))); - - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_11))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_12))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_13))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_21))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_22))); - Assert.assertEquals(0, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_23))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_31))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_32))); - Assert.assertEquals(1, - TransactionCapsule.getWeight(permission3, ByteArray.fromHexString(KEY_ADDRESS_33))); - } - - public ArrayList sign(List priKeys, byte[] hash) { - ArrayList list = new ArrayList<>(); - for (byte[] priKey : priKeys) { - ECKey ecKey = ECKey.fromPrivate(priKey); - ECDSASignature signature = ecKey.sign(hash); - ByteString result = ByteString.copyFrom(signature.toByteArray()); - list.add(result); - } - return list; - } - - @Test - public void checkWeight() { - List permissions = buildPermissions(); - Permission permission = permissions.get(0); - byte[] hash = Sha256Hash.hash("test".getBytes()); - - //SignatureFormatException - ArrayList list = new ArrayList<>(); - ByteString test = ByteString.copyFromUtf8("test"); - list.add(test); - try { - TransactionCapsule.checkWeight(permission, list, hash, null); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertEquals(e.getMessage(), "Signature size is " + test.size()); - } - //SignatureException: Header byte out of range: - //Ignore more exception case. - byte[] rand = new byte[65]; - new Random().nextBytes(rand); - rand[64] = 8; // v = 8 < 27 v += 35 > 35 - try { - ArrayList list1 = new ArrayList<>(); - list1.add(ByteString.copyFrom(rand)); - TransactionCapsule.checkWeight(permission, list1, hash, null); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertEquals(e.getMessage(), "Header byte out of range: 35"); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Permission does not contain KEY - List prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_11)); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign11_21 = sign(prikeys, hash); - try { - TransactionCapsule.checkWeight(permission, sign11_21, hash, null); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - ByteString sign21 = sign11_21.get(1); - Assert.assertEquals(e.getMessage(), - ByteArray.toHexString(sign21.toByteArray()) + " is signed by " + Wallet - .encode58Check(ByteArray.fromHexString(KEY_ADDRESS_21)) - + " but it is not contained of permission."); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Too many signature - prikeys.add(ByteArray.fromHexString(KEY_12)); - prikeys.add(ByteArray.fromHexString(KEY_13)); - ArrayList sign11_21_12_13 = sign(prikeys, hash); - try { - TransactionCapsule.checkWeight(permission, sign11_21_12_13, hash, null); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - "Signature count is " + prikeys.size() + " more than key counts of permission : " - + permission.getKeysCount()); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - //Sign twice by same key - prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_11)); - prikeys.add(ByteArray.fromHexString(KEY_12)); - prikeys.add(ByteArray.fromHexString(KEY_11)); - ArrayList sign11_12_11 = sign(prikeys, hash); - try { - TransactionCapsule.checkWeight(permission, sign11_12_11, hash, null); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - WalletUtil.encode58Check(ByteArray.fromHexString(KEY_ADDRESS_11)) + " has signed twice!"); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - // - prikeys = new ArrayList<>(); - List approveList = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_11)); - ArrayList sign11 = sign(prikeys, hash); - try { - long weight = TransactionCapsule.checkWeight(permission, sign11, hash, approveList); - Assert.assertEquals(weight, 1); - Assert.assertEquals(approveList.size(), 1); - Assert.assertEquals(approveList.get(0), - ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_11))); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - approveList = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_12)); - ArrayList sign11_12 = sign(prikeys, hash); - try { - long weight = TransactionCapsule.checkWeight(permission, sign11_12, hash, approveList); - Assert.assertEquals(weight, 2); - Assert.assertEquals(approveList.size(), 2); - Assert.assertEquals(approveList.get(0), - ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_11))); - Assert.assertEquals(approveList.get(1), - ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_12))); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - approveList = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_13)); - ArrayList sign11_12_13 = sign(prikeys, hash); - try { - long weight = TransactionCapsule.checkWeight(permission, sign11_12_13, hash, approveList); - Assert.assertEquals(weight, 3); - Assert.assertEquals(approveList.size(), 3); - Assert.assertEquals(approveList.get(0), - ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_11))); - Assert.assertEquals(approveList.get(1), - ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_12))); - Assert.assertEquals(approveList.get(2), - ByteString.copyFrom(ByteArray.fromHexString(KEY_ADDRESS_13))); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - } - - @Test - public void addSign() { - - byte[] to = ByteArray.fromHexString(TO_ADDRESS); - byte[] owner_not_exist = ByteArray.fromHexString(OWNER_ACCOUNT_NOT_Exist); - TransferContract transferContract = createTransferContract(to, owner_not_exist, 1); - Transaction.Builder trxBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = Transaction.raw.newBuilder(); - Contract.Builder contractBuilder = Contract.newBuilder(); - contractBuilder.setType(ContractType.TransferContract).setParameter(Any.pack(transferContract)) - .build(); - rawBuilder.addContract(contractBuilder); - trxBuilder.setRawData(rawBuilder); - AccountStore accountStore = dbManager.getAccountStore(); - TransactionCapsule transactionCapsule = new TransactionCapsule(trxBuilder.build()); - //Accout not exist - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_11), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), "Account is not exist!"); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); - transferContract = createTransferContract(to, owner, 1); - transactionCapsule = new TransactionCapsule(transferContract, accountStore); - //Defalut permission - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_11), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - KEY_11 + "'s address is " + WalletUtil - .encode58Check(ByteArray.fromHexString(KEY_ADDRESS_11)) - + " but it is not contained of permission."); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - try { - transactionCapsule.addSign(ByteArray.fromHexString(OWNER_KEY), accountStore); - Assert.assertEquals(transactionCapsule.getInstance().getSignatureCount(), 1); - ByteString signature = transactionCapsule.getInstance().getSignature(0); - Assert.assertEquals(signature.size(), 65); - byte[] sign = signature.toByteArray(); - byte[] r = ByteArray.subArray(sign, 0, 32); - byte[] s = ByteArray.subArray(sign, 32, 64); - byte v = sign[64]; - ECDSASignature ecdsaSignature = ECDSASignature.fromComponents(r, s, (byte) (v + 27)); - byte[] address = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature); - Assert.assertTrue(Arrays.equals(address, ByteArray.fromHexString(OWNER_ADDRESS))); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - // Sign twice - try { - transactionCapsule.addSign(ByteArray.fromHexString(OWNER_KEY), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - WalletUtil.encode58Check(ByteArray.fromHexString(OWNER_ADDRESS)) + " had signed!"); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Update permission, can signed by key21 key22 key23 - List permissions = buildPermissions(); - Account account = accountStore.get(ByteArray.fromHexString(OWNER_ADDRESS)).getInstance(); - Account.Builder builder = account.toBuilder(); - builder.addPermissions(permissions.get(0)); - builder.addPermissions(permissions.get(1)); - builder.addPermissions(permissions.get(2)); - accountStore.put(ByteArray.fromHexString(OWNER_ADDRESS), new AccountCapsule(builder.build())); - - transactionCapsule = new TransactionCapsule(transferContract, accountStore); - try { - transactionCapsule.addSign(ByteArray.fromHexString(OWNER_KEY), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - OWNER_KEY + "'s address is " + Wallet - .encode58Check(ByteArray.fromHexString(OWNER_ADDRESS)) - + " but it is not contained of permission."); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Sign KEY_21 - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_21), accountStore); - Assert.assertEquals(transactionCapsule.getInstance().getSignatureCount(), 1); - ByteString signature = transactionCapsule.getInstance().getSignature(0); - Assert.assertEquals(signature.size(), 65); - byte[] sign = signature.toByteArray(); - byte[] r = ByteArray.subArray(sign, 0, 32); - byte[] s = ByteArray.subArray(sign, 32, 64); - byte v = sign[64]; - ECDSASignature ecdsaSignature = ECDSASignature.fromComponents(r, s, (byte) (v + 27)); - byte[] address = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature); - Assert.assertTrue(Arrays.equals(address, ByteArray.fromHexString(KEY_ADDRESS_21))); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Sign KEY_12 - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_22), accountStore); - Assert.assertEquals(transactionCapsule.getInstance().getSignatureCount(), 2); - ByteString signature = transactionCapsule.getInstance().getSignature(0); - Assert.assertEquals(signature.size(), 65); - byte[] sign = signature.toByteArray(); - byte[] r21 = ByteArray.subArray(sign, 0, 32); - byte[] s21 = ByteArray.subArray(sign, 32, 64); - byte v21 = sign[64]; - ECDSASignature ecdsaSignature11 = ECDSASignature.fromComponents(r21, s21, (byte) (v21 + 27)); - byte[] address21 = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature11); - Assert.assertTrue(Arrays.equals(address21, ByteArray.fromHexString(KEY_ADDRESS_21))); - - ByteString signature1 = transactionCapsule.getInstance().getSignature(1); - - byte[] r22 = ByteArray.subArray(signature1.toByteArray(), 0, 32); - byte[] s22 = ByteArray.subArray(signature1.toByteArray(), 32, 64); - byte v22 = signature1.toByteArray()[64]; - ECDSASignature ecdsaSignature12 = ECDSASignature.fromComponents(r22, s22, (byte) (v22 + 27)); - byte[] address22 = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature12); - Assert.assertTrue(Arrays.equals(address22, ByteArray.fromHexString(KEY_ADDRESS_22))); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Sign KEY_23 - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_23), accountStore); - Assert.assertEquals(transactionCapsule.getInstance().getSignatureCount(), 3); - ByteString signature = transactionCapsule.getInstance().getSignature(0); - Assert.assertEquals(signature.size(), 65); - byte[] sign = signature.toByteArray(); - byte[] r21 = ByteArray.subArray(sign, 0, 32); - byte[] s21 = ByteArray.subArray(sign, 32, 64); - byte v21 = sign[64]; - ECDSASignature ecdsaSignature21 = ECDSASignature.fromComponents(r21, s21, (byte) (v21 + 27)); - byte[] address21 = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature21); - Assert.assertTrue(Arrays.equals(address21, ByteArray.fromHexString(KEY_ADDRESS_21))); - - ByteString signature1 = transactionCapsule.getInstance().getSignature(1); - Assert.assertEquals(signature1.size(), 65); - byte[] sign1 = signature1.toByteArray(); - byte[] r22 = ByteArray.subArray(sign1, 0, 32); - byte[] s22 = ByteArray.subArray(sign1, 32, 64); - byte v22 = sign1[64]; - ECDSASignature ecdsaSignature22 = ECDSASignature.fromComponents(r22, s22, (byte) (v22 + 27)); - byte[] address22 = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature22); - Assert.assertTrue(Arrays.equals(address22, ByteArray.fromHexString(KEY_ADDRESS_22))); - - ByteString signature2 = transactionCapsule.getInstance().getSignature(2); - Assert.assertEquals(signature2.size(), 65); - byte[] sign2 = signature2.toByteArray(); - byte[] r23 = ByteArray.subArray(sign2, 0, 32); - byte[] s23 = ByteArray.subArray(sign2, 32, 64); - byte v23 = sign2[64]; - ECDSASignature ecdsaSignature23 = ECDSASignature.fromComponents(r23, s23, (byte) (v23 + 27)); - byte[] address23 = ECKey - .signatureToAddress(transactionCapsule.getTransactionId().getBytes(), ecdsaSignature23); - Assert.assertTrue(Arrays.equals(address23, ByteArray.fromHexString(KEY_ADDRESS_23))); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Sign KEY_11, throw exception - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_11), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - KEY_11 + "'s address is " + Wallet - .encode58Check(ByteArray.fromHexString(KEY_ADDRESS_11)) - + " but it is not contained of permission."); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //invalidate signature - transactionCapsule = new TransactionCapsule(transferContract, accountStore); - Transaction.Builder builder1 = transactionCapsule.getInstance().toBuilder(); - builder1.addSignature(ByteString.copyFromUtf8("test")); - transactionCapsule = new TransactionCapsule(builder1.build()); - //Sign KEY_21, throw exception - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_11), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertEquals(e.getMessage(), "Signature size is " + "test".length()); - } - - //invalidate signature - transactionCapsule = new TransactionCapsule(transferContract, accountStore); - builder1 = transactionCapsule.getInstance().toBuilder(); - builder1.addSignature(ByteString.copyFromUtf8("test")); - transactionCapsule = new TransactionCapsule(builder1.build()); - //Sign KEY_21, throw exception - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_11), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertEquals(e.getMessage(), "Signature size is " + "test".length()); - } - //transaction already have a signature signed by a invalidate key - //that the key is not in the permission. - transactionCapsule = new TransactionCapsule(transferContract, accountStore); - List prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_11)); - ArrayList sign11 = sign(prikeys, transactionCapsule.getTransactionId().getBytes()); - builder1 = transactionCapsule.getInstance().toBuilder(); - builder1.addAllSignature(sign11); - transactionCapsule = new TransactionCapsule(builder1.build()); - - try { - transactionCapsule.addSign(ByteArray.fromHexString(KEY_21), accountStore); - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - ByteArray.toHexString(sign11.get(0).toByteArray()) + " is signed by " + Wallet - .encode58Check(ByteArray.fromHexString(KEY_ADDRESS_11)) - + " but it is not contained of permission."); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - } - - @Test - // test public static boolean validateSignature(Transaction.Contract contract, - ByteString sigs, byte[] hash, AccountStore accountStore) - public void validateSignature0() { - //Update permission, can signed by key21 key22 key23 - AccountStore accountStore = dbManager.getAccountStore(); - List permissions = buildPermissions(); - - byte[] to = ByteArray.fromHexString(TO_ADDRESS); - byte[] owner_not_exist = ByteArray.fromHexString(OWNER_ACCOUNT_NOT_Exist); - TransferContract transferContract = createTransferContract(to, owner_not_exist, 1); - Transaction.Builder trxBuilder = Transaction - .newBuilder(); - Transaction.raw.Builder rawBuilder = Transaction.raw.newBuilder(); - Contract.Builder contractBuilder = Contract.newBuilder(); - contractBuilder.setType(ContractType.TransferContract).setParameter(Any.pack(transferContract)); - rawBuilder.addContract(contractBuilder.build()); - trxBuilder.setRawData(rawBuilder.build()); - List prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign = sign(prikeys, Sha256Hash.hash(rawBuilder.build().toByteArray())); - trxBuilder.addAllSignature(sign); - - Account account = accountStore.get(ByteArray.fromHexString(OWNER_ADDRESS)).getInstance(); - Account.Builder builder = account.toBuilder(); - builder.clearPermissions(); - builder.addPermissions(permissions.get(0)); - builder.addPermissions(permissions.get(1)); - builder.addPermissions(permissions.get(2)); - accountStore.put(ByteArray.fromHexString(OWNER_ADDRESS), new AccountCapsule(builder.build())); - byte[] hash = Sha256Hash.hash("test".getBytes()); - - byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); - transferContract = createTransferContract(to, owner, 1); - contractBuilder = Contract.newBuilder(); - contractBuilder.setParameter(Any.pack(transferContract)).setType(ContractType.TransferContract); - rawBuilder.clearContract().addContract(contractBuilder.build()); - trxBuilder.setRawData(rawBuilder.build()); - - //SignatureFormatException - ByteString test = ByteString.copyFromUtf8("test"); - trxBuilder.clearSignature().addSignature(test); - try { - TransactionCapsule.validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertEquals(e.getMessage(), "Signature size is " + test.size()); - } - //SignatureException: Header byte out of range: - //Ignore more exception case. - byte[] rand = new byte[65]; - new Random().nextBytes(rand); - rand[64] = 8; // v = 8 < 27 v += 35 > 35 - trxBuilder.clearSignature().addSignature(ByteString.copyFrom(rand)); - try { - TransactionCapsule.validateSignature(trxBuilder.build(), hash, - accountStore); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertEquals(e.getMessage(), "Header byte out of range: 35"); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Permission is not contain KEY - prikeys = new ArrayList<>(); - prikeys.clear(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - prikeys.add(ByteArray.fromHexString(KEY_11)); - ArrayList sign21_11 = sign(prikeys, hash); - trxBuilder.clearSignature().addAllSignature(sign21_11); - try { - TransactionCapsule.validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - ByteString sign21 = sign21_11.get(1); - Assert.assertEquals(e.getMessage(), - ByteArray.toHexString(sign21.toByteArray()) + " is signed by " + Wallet - .encode58Check(ByteArray.fromHexString(KEY_ADDRESS_11)) - + " but it is not contained of permission."); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - //Too many signature - prikeys.add(ByteArray.fromHexString(KEY_22)); - prikeys.add(ByteArray.fromHexString(KEY_23)); - ArrayList sign21_11_22_23 = sign(prikeys, hash); - trxBuilder.clearSignature().addAllSignature(sign21_11_22_23); - try { - TransactionCapsule - .validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - "Signature count is " + prikeys.size() + " more than key counts of permission : " - + permissions.get(1).getKeysCount()); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - //Sign twices by same key - prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - prikeys.add(ByteArray.fromHexString(KEY_22)); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign21_22_21 = sign(prikeys, hash); - trxBuilder.clearSignature().addAllSignature(sign21_22_21); - try { - TransactionCapsule - .validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertFalse(true); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertEquals(e.getMessage(), - WalletUtil.encode58Check(ByteArray.fromHexString(KEY_ADDRESS_21)) + " has signed twice!"); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - // - prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign21 = sign(prikeys, hash); - trxBuilder.clearSignature().addAllSignature(sign21); - try { - boolean result = TransactionCapsule - .validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertFalse(result); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - prikeys.add(ByteArray.fromHexString(KEY_22)); - ArrayList sign21_22 = sign(prikeys, hash); - trxBuilder.clearSignature().addAllSignature(sign21_22); - try { - boolean result = TransactionCapsule - .validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertTrue(result); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - - prikeys.add(ByteArray.fromHexString(KEY_23)); - ArrayList sign21_22_23 = sign(prikeys, hash); - trxBuilder.clearSignature().addAllSignature(sign21_22_23); - try { - boolean result = TransactionCapsule - .validateSignature(trxBuilder.build(), hash, accountStore); - Assert.assertTrue(result); - } catch (SignatureException e) { - Assert.assertFalse(true); - } catch (PermissionException e) { - Assert.assertFalse(true); - } catch (SignatureFormatException e) { - Assert.assertFalse(true); - } - } - - @Test - // test public boolean validateSignature(AccountStore accountStore) - public void validateSignature1() { - //Update permission, can signed by key21 key22 key23 - List permissions = buildPermissions(); - Account account = dbManager.getAccountStore().get(ByteArray.fromHexString(OWNER_ADDRESS)) - .getInstance(); - Account.Builder builder = account.toBuilder(); - builder.clearPermissions(); - builder.addPermissions(permissions.get(0)); - builder.addPermissions(permissions.get(1)); - builder.addPermissions(permissions.get(2)); - dbManager.getAccountStore() - .put(ByteArray.fromHexString(OWNER_ADDRESS), new AccountCapsule(builder.build())); - - byte[] to = ByteArray.fromHexString(TO_ADDRESS); - byte[] owner_not_exist = ByteArray.fromHexString(OWNER_ACCOUNT_NOT_Exist); - TransferContract transferContract = createTransferContract(to, owner_not_exist, 1); - Transaction.Builder trxBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = Transaction.raw.newBuilder(); - Contract.Builder contractBuilder = Contract.newBuilder(); - contractBuilder.setType(ContractType.TransferContract).setParameter(Any.pack(transferContract)) - .build(); - rawBuilder.addContract(contractBuilder); - trxBuilder.setRawData(rawBuilder); - TransactionCapsule transactionCapsule = new TransactionCapsule(trxBuilder.build()); - List prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign = sign(prikeys, Sha256Hash.hash(rawBuilder.build().toByteArray())); - trxBuilder.addAllSignature(sign); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - - // no contract - prikeys.clear(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - trxBuilder = Transaction.newBuilder(); - rawBuilder = Transaction.raw.newBuilder(); - rawBuilder.setTimestamp(System.currentTimeMillis()); - trxBuilder.setRawData(rawBuilder); - sign = sign(prikeys, Sha256Hash.hash(rawBuilder.build().toByteArray())); - trxBuilder.addAllSignature(sign); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), "miss sig or contract"); - } - // no sign - byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); - transferContract = createTransferContract(to, owner, 1); - transactionCapsule = new TransactionCapsule(transferContract, dbManager.getAccountStore()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), "miss sig or contract"); - } - - transactionCapsule = new TransactionCapsule(transferContract, dbManager.getAccountStore()); - byte[] hash = transactionCapsule.getTransactionId().getBytes(); - trxBuilder = transactionCapsule.getInstance().toBuilder(); - //SignatureFormatException - ByteString test = ByteString.copyFromUtf8("test"); - trxBuilder.clearSignature(); - trxBuilder.addSignature(test); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), "Signature size is " + test.size()); - } - //SignatureException: Header byte out of range: - //Ignore more exception case. - byte[] rand = new byte[65]; - new Random().nextBytes(rand); - rand[64] = 8; // v = 8 < 27 v += 35 > 35 - trxBuilder.clearSignature(); - trxBuilder.addSignature(ByteString.copyFrom(rand)); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), "Header byte out of range: 35"); - } - //Permission is not contain KEY - prikeys.clear(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - prikeys.add(ByteArray.fromHexString(KEY_11)); - ArrayList sign21_11 = sign(prikeys, hash); - trxBuilder.clearSignature(); - trxBuilder.addAllSignature(sign21_11); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - ByteString sign21 = sign21_11.get(1); - Assert.assertEquals(e.getMessage(), - ByteArray.toHexString(sign21.toByteArray()) + " is signed by " + Wallet - .encode58Check(ByteArray.fromHexString(KEY_ADDRESS_11)) - + " but it is not contained of permission."); - } - //Too many signature - prikeys.add(ByteArray.fromHexString(KEY_22)); - prikeys.add(ByteArray.fromHexString(KEY_23)); - ArrayList sign21_11_22_23 = sign(prikeys, hash); - trxBuilder.clearSignature(); - trxBuilder.addAllSignature(sign21_11_22_23); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), - "Signature count is " + prikeys.size() + " more than key counts of permission : " - + permissions.get(1).getKeysCount()); - } - - //Sign twices by same key - prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - prikeys.add(ByteArray.fromHexString(KEY_22)); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign21_22_21 = sign(prikeys, hash); - trxBuilder.clearSignature(); - trxBuilder.addAllSignature(sign21_22_21); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), - WalletUtil.encode58Check(ByteArray.fromHexString(KEY_ADDRESS_21)) + " has signed twice!"); - } - - // - prikeys = new ArrayList<>(); - prikeys.add(ByteArray.fromHexString(KEY_21)); - ArrayList sign21 = sign(prikeys, hash); - trxBuilder.clearSignature(); - trxBuilder.addAllSignature(sign21); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - transactionCapsule.validateSignature(dbManager); - Assert.assertFalse(true); - } catch (ValidateSignatureException e) { - Assert.assertEquals(e.getMessage(), "sig error"); - } - - prikeys.add(ByteArray.fromHexString(KEY_22)); - ArrayList sign21_22 = sign(prikeys, hash); - trxBuilder.clearSignature(); - trxBuilder.addAllSignature(sign21_22); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - boolean result = transactionCapsule.validateSignature(dbManager); - Assert.assertTrue(result); - } catch (ValidateSignatureException e) { - Assert.assertFalse(true); - } - - prikeys.add(ByteArray.fromHexString(KEY_23)); - ArrayList sign21_22_23 = sign(prikeys, hash); - trxBuilder.clearSignature(); - trxBuilder.addAllSignature(sign21_22_23); - transactionCapsule = new TransactionCapsule(trxBuilder.build()); - try { - boolean result = transactionCapsule.validateSignature(dbManager); - Assert.assertTrue(result); - } catch (ValidateSignatureException e) { - Assert.assertFalse(true); - } - }*/ - @Test public void trxCapsuleClearTest() { Transaction tx = Transaction.newBuilder() @@ -1086,6 +53,20 @@ public void trxCapsuleClearTest() { Assert.assertEquals(trxCap.getInstance().getRetCount(), 0); trxCap.setResultCode(contractResult); Assert.assertEquals(trxCap.getInstance() - .getRet(0).getContractRet(), contractResult.OUT_OF_TIME); + .getRet(0).getContractRet(), Result.contractResult.OUT_OF_TIME); + } + + @Test + public void testRemoveRedundantRet() { + Transaction.Builder transaction = Transaction.newBuilder().setRawData(raw.newBuilder() + .addContract(Transaction.Contract.newBuilder().setType(ContractType.TriggerSmartContract)) + .setFeeLimit(1000000000)).build().toBuilder(); + transaction.addRet(Result.newBuilder().setContractRet(SUCCESS).build()); + transaction.addRet(Result.newBuilder().setContractRet(PRECOMPILED_CONTRACT).build()); + transaction.addRet(Result.newBuilder().setContractRet(BAD_JUMP_DESTINATION).build()); + TransactionCapsule transactionCapsule = new TransactionCapsule(transaction.build()); + transactionCapsule.removeRedundantRet(); + Assert.assertEquals(1, transactionCapsule.getInstance().getRetCount()); + Assert.assertEquals(SUCCESS, transactionCapsule.getInstance().getRet(0).getContractRet()); } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/capsule/VotesCapsuleTest.java b/framework/src/test/java/org/tron/core/capsule/VotesCapsuleTest.java index 467d801996e..64bb660ab9a 100644 --- a/framework/src/test/java/org/tron/core/capsule/VotesCapsuleTest.java +++ b/framework/src/test/java/org/tron/core/capsule/VotesCapsuleTest.java @@ -1,15 +1,16 @@ package org.tron.core.capsule; import com.google.protobuf.ByteString; -import java.io.File; +import java.io.IOException; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; +import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.utils.FileUtil; +import org.junit.rules.TemporaryFolder; import org.tron.common.utils.StringUtil; import org.tron.core.Constant; import org.tron.core.Wallet; @@ -21,7 +22,8 @@ @Slf4j public class VotesCapsuleTest { - private static String dbPath = "output_votesCapsule_test"; + @ClassRule + public static TemporaryFolder temporaryFolder = new TemporaryFolder(); private static final String OWNER_ADDRESS; private static List oldVotes; @@ -31,15 +33,15 @@ public class VotesCapsuleTest { } @BeforeClass - public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + public static void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); } @AfterClass public static void destroy() { Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); } @Test diff --git a/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java b/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java index 11e77097baa..b966b26a299 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/AssetUtilTest.java @@ -1,61 +1,30 @@ -/* - * 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.core.capsule.utils; import com.google.common.collect.Lists; import com.google.protobuf.ByteString; -import java.io.File; +import java.util.ArrayList; import java.util.List; import java.util.Random; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.api.GrpcAPI.AssetIssueList; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; -import org.tron.core.capsule.AccountAssetCapsule; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; +import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.store.AccountAssetStore; +import org.tron.core.db.BandwidthProcessor; import org.tron.protos.Protocol; - - - +import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @Slf4j -public class AssetUtilTest { +public class AssetUtilTest extends BaseTest { - private static String dbPath = "output_AssetUtil_test"; - private static Manager dbManager; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF); } public static byte[] randomBytes(int length) { @@ -65,61 +34,20 @@ public static byte[] randomBytes(int length) { return result; } - private static AccountCapsule createAccount() { + private AccountCapsule createAccount2() { com.google.protobuf.ByteString accountName = - com.google.protobuf.ByteString.copyFrom(randomBytes(16)); - com.google.protobuf.ByteString address = - ByteString.copyFrom(randomBytes(32)); - Protocol.AccountType accountType = Protocol.AccountType.forNumber(1); - AccountCapsule accountCapsule = new AccountCapsule(accountName, address, accountType); - accountCapsule.addAssetV2(ByteArray.fromString(String.valueOf(1)), 1000L); - Protocol.Account build = accountCapsule.getInstance().toBuilder() - .addAllFrozenSupply(getFrozenList()) - .build(); - accountCapsule.setInstance(build); - - return accountCapsule; - } - - private static AccountCapsule createAccount2() { - AccountAssetStore accountAssetStore = dbManager.getAccountAssetStore(); - com.google.protobuf.ByteString accountName = - com.google.protobuf.ByteString.copyFrom(randomBytes(16)); + com.google.protobuf.ByteString.copyFrom(randomBytes(16)); com.google.protobuf.ByteString address = ByteString.copyFrom(randomBytes(32)); Protocol.AccountType accountType = Protocol.AccountType.forNumber(1); - AccountCapsule accountCapsule = new AccountCapsule(accountName, address, accountType); - Protocol.AccountAsset accountAsset = - Protocol.AccountAsset.newBuilder() - .setAddress(accountCapsule.getInstance().getAddress()) - .setAssetIssuedID(accountCapsule.getAssetIssuedID()) - .setAssetIssuedName(accountCapsule.getAssetIssuedName()) - .build(); - accountAssetStore.put(accountCapsule.createDbKey(), - new AccountAssetCapsule( - accountAsset)); - return accountCapsule; - } - - @Test - public void testGetAsset() { - AccountCapsule account = createAccount(); - Protocol.AccountAsset asset = AssetUtil.getAsset(account.getInstance()); - Assert.assertNotNull(asset); - } - - @Test - public void testImport() { - AccountCapsule account = createAccount2(); - Protocol.Account asset = AssetUtil.importAsset(account.getInstance()); - Assert.assertNotNull(asset); + return new AccountCapsule(accountName, address, accountType); } @Test public void tetGetFrozen() { AccountCapsule account = createAccount2(); Protocol.Account build = account.getInstance().toBuilder() - .addAllFrozenSupply(getFrozenList()) - .build(); + .addAllFrozenSupply(getFrozenList()) + .build(); account.setInstance(build); Assert.assertNotNull(account.getFrozenSupplyList()); } @@ -128,12 +56,40 @@ private static List getFrozenList() { List frozenList = Lists.newArrayList(); for (int i = 0; i < 3; i++) { Protocol.Account.Frozen newFrozen = Protocol.Account.Frozen.newBuilder() - .setFrozenBalance(i * 1000 + 1) - .setExpireTime(1000) - .build(); + .setFrozenBalance(i * 1000 + 1) + .setExpireTime(1000) + .build(); frozenList.add(newFrozen); } return frozenList; } + + @Test + public void testUpdateUsage() { + List assetIssueCapsuleList = new ArrayList<>(); + + AssetIssueContract assetIssueContract = + AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString("111"))) + .setId(Long.toString(1)) + .build(); + AssetIssueCapsule capsule1 = new AssetIssueCapsule(assetIssueContract); + capsule1.setPublicFreeAssetNetUsage(60); + capsule1.setPublicLatestFreeNetTime(14400L); + + assetIssueCapsuleList.add(capsule1); + + BandwidthProcessor processor = new BandwidthProcessor(chainBaseManager); + AssetIssueList.Builder builder = AssetIssueList.newBuilder(); + assetIssueCapsuleList.forEach( + issueCapsule -> { + processor.updateUsage(issueCapsule, 28800); + builder.addAssetIssue(issueCapsule.getInstance()); + } + ); + + Assert.assertEquals(30L, + builder.build().getAssetIssue(0).getPublicFreeAssetNetUsage()); + } } diff --git a/framework/src/test/java/org/tron/core/capsule/utils/DecodeResultTest.java b/framework/src/test/java/org/tron/core/capsule/utils/DecodeResultTest.java new file mode 100644 index 00000000000..008224f98a1 --- /dev/null +++ b/framework/src/test/java/org/tron/core/capsule/utils/DecodeResultTest.java @@ -0,0 +1,28 @@ +package org.tron.core.capsule.utils; + +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.utils.ByteUtil; + +public class DecodeResultTest { + + @Test + public void testConstruct() { + DecodeResult decodeResult = new DecodeResult(0, "decoded"); + Assert.assertEquals(decodeResult.getPos(), 0); + Assert.assertEquals(decodeResult.getDecoded(), "decoded"); + Assert.assertEquals(decodeResult.toString(), "decoded"); + } + + @Test + public void testToString() { + DecodeResult decodeResult = new DecodeResult(0, "decoded"); + Assert.assertEquals(decodeResult.toString(), "decoded"); + decodeResult = new DecodeResult(0, ByteUtil.intToBytes(1000)); + Assert.assertEquals(Hex.toHexString(ByteUtil.intToBytes(1000)), decodeResult.toString()); + Object[] decodedData = {"aa","bb"}; + decodeResult = new DecodeResult(0, decodedData); + Assert.assertEquals("aabb", decodeResult.toString()); + } +} diff --git a/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java b/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java index 50d01e2b982..717c62b01a8 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/ExchangeProcessorTest.java @@ -1,36 +1,21 @@ package org.tron.core.capsule.utils; -import java.io.File; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; -import org.tron.core.Wallet; import org.tron.core.capsule.ExchangeProcessor; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @Slf4j -public class ExchangeProcessorTest { +public class ExchangeProcessorTest extends BaseTest { - private static final String dbPath = "output_buy_exchange_processor_test"; - private static final String OWNER_ADDRESS; - private static final String OWNER_ADDRESS_INVALID = "aaaa"; - private static final String OWNER_ACCOUNT_INVALID; - private static final long initBalance = 10_000_000_000_000_000L; private static ExchangeProcessor processor; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - OWNER_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - OWNER_ACCOUNT_INVALID = - Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a3456"; + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } /** @@ -39,25 +24,7 @@ public class ExchangeProcessorTest { @BeforeClass public static void init() { long supply = 1_000_000_000_000_000_000L; - processor = new ExchangeProcessor(supply); - // Args.setParam(new String[]{"--output-directory", dbPath}, - // "config-junit.conf"); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + processor = new ExchangeProcessor(supply, false); } @Test @@ -168,5 +135,15 @@ public void testWithdraw() { } + @Test + public void testStrictMath() { + long supply = 1_000_000_000_000_000_000L; + ExchangeProcessor processor = new ExchangeProcessor(supply, false); + long anotherTokenQuant = processor.exchange(4732214, 2202692725330L, 29218); + processor = new ExchangeProcessor(supply, true); + long result = processor.exchange(4732214, 2202692725330L, 29218); + Assert.assertNotEquals(anotherTokenQuant, result); + } + } diff --git a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java index 4e3273203c8..df84433726e 100644 --- a/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/capsule/utils/MerkleTreeTest.java @@ -1,18 +1,31 @@ package org.tron.core.capsule.utils; +import static org.tron.common.math.Maths.pow; + +import com.google.protobuf.ByteString; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.MerkleRoot; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.utils.MerkleTree.Leaf; @Slf4j public class MerkleTreeTest { + @Rule + public ExpectedException exception = ExpectedException.none(); + private static List getHash(int hashNum) { List hashList = new ArrayList(); for (int i = 0; i < hashNum; i++) { @@ -75,7 +88,7 @@ private static int getRank(int num) { num = num >> 1; rank++; } - if (temp == Math.pow(2, rank - 1)) { + if (temp == pow(2, rank - 1, true)) { rank -= 1; } return rank; @@ -173,4 +186,28 @@ public void testAnyHashNum() { pareTree(root, hashList, maxRank, 0, 0); } } -} \ No newline at end of file + + @Test + @Ignore + public void testConcurrent() { + Sha256Hash root1 = Sha256Hash.wrap( + ByteString.fromHex("6cb38b4f493db8bacf26123cd4253bbfc530c708b97b3747e782f64097c3c482")); + Sha256Hash root2 = Sha256Hash.wrap( + ByteString.fromHex("4bfc60ea3de4f5d1476f839874df0aba38eec4e524d6fa63f5b19c4bf527eaf3")); + List list1 = IntStream.range(0, 10000).mapToObj(i -> + Sha256Hash.of(true, ("byte1-" + i).getBytes(StandardCharsets.UTF_8))) + .collect(Collectors.toList()); + List list2 = IntStream.range(0, 10000).mapToObj(i -> + Sha256Hash.of(true, ("byte2-" + i).getBytes(StandardCharsets.UTF_8))) + .collect(Collectors.toList()); + Assert.assertEquals(root1, MerkleTree.getInstance().createTree(list1).getRoot().getHash()); + Assert.assertEquals(root2, MerkleTree.getInstance().createTree(list2).getRoot().getHash()); + Assert.assertEquals(root1, MerkleRoot.root(list1)); + Assert.assertEquals(root2, MerkleRoot.root(list2)); + exception.expect(ArrayIndexOutOfBoundsException.class); + IntStream.range(0, 1000).parallel().forEach(i -> Assert.assertEquals( + MerkleTree.getInstance().createTree(i % 2 == 0 ? list1 : list2).getRoot().getHash(), + MerkleRoot.root(i % 2 == 0 ? list1 : list2)) + ); + } +} diff --git a/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java b/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java new file mode 100644 index 00000000000..500e7454dbe --- /dev/null +++ b/framework/src/test/java/org/tron/core/capsule/utils/RLPListTest.java @@ -0,0 +1,85 @@ +package org.tron.core.capsule.utils; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.util.Random; +import org.bouncycastle.util.BigIntegers; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.utils.Value; + +public class RLPListTest { + + @Test + public void testRecursivePrint() { + RLPItem element = new RLPItem("rlpItem".getBytes()); + Assert.assertEquals("rlpItem", new String(element.getRLPData())); + RLPList.recursivePrint(element); + RLPList rlpList = new RLPList(); + rlpList.add(new RLPItem("rlpItem0".getBytes())); + RLPList.recursivePrint(rlpList); + Assert.assertThrows(RuntimeException.class, () -> RLPList.recursivePrint(null)); + + RLPItem rlpItem = new RLPItem(new byte[0]); + Assert.assertNull(rlpItem.getRLPData()); + + } + + @Test + public void testGetRLPData() { + RLPList rlpList = new RLPList(); + rlpList.setRLPData("rlpData".getBytes()); + Assert.assertEquals(new String(rlpList.getRLPData()), "rlpData"); + } + + @Test + public void testToBytes() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method method = RLP.class.getDeclaredMethod("toBytes", Object.class); + method.setAccessible(true); + + byte[] aBytes = new byte[10]; + byte[] bBytes = (byte[]) method.invoke(RLP.class, aBytes); + Assert.assertArrayEquals(aBytes, bBytes); + + int i = new Random().nextInt(); + byte[] cBytes = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(i)); + byte[] dBytes = (byte[]) method.invoke(RLP.class, i); + Assert.assertArrayEquals(cBytes, dBytes); + + long j = new Random().nextInt(); + byte[] eBytes = BigIntegers.asUnsignedByteArray(BigInteger.valueOf(j)); + byte[] fBytes = (byte[]) method.invoke(RLP.class, j); + Assert.assertArrayEquals(eBytes, fBytes); + + String test = "testA"; + byte[] gBytes = test.getBytes(); + byte[] hBytes = (byte[]) method.invoke(RLP.class, test); + Assert.assertArrayEquals(gBytes, hBytes); + + BigInteger bigInteger = BigInteger.valueOf(100); + byte[] iBytes = BigIntegers.asUnsignedByteArray(bigInteger); + byte[] jBytes = (byte[]) method.invoke(RLP.class, bigInteger); + Assert.assertArrayEquals(iBytes, jBytes); + + Value v = new Value(new byte[0]); + byte[] kBytes = v.asBytes(); + byte[] lBytes = (byte[]) method.invoke(RLP.class, v); + Assert.assertArrayEquals(kBytes, lBytes); + + char c = 'a'; + try { + method.invoke(RLP.class, c); + Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(true); + } + } + + @Test + public void testEncode() { + byte[] aBytes = RLP.encode(new byte[1]); + Assert.assertEquals(1, aBytes.length); + } +} 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 24a34dbcd0e..f3ca2da5312 100644 --- a/framework/src/test/java/org/tron/core/config/ConfigurationTest.java +++ b/framework/src/test/java/org/tron/core/config/ConfigurationTest.java @@ -17,7 +17,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.tron.common.utils.PublicMethod.getRandomPrivateKey; +import static org.tron.common.utils.client.utils.AbiUtil.generateOccupationConstantPrivateKey; +import static org.tron.core.Constant.ADD_PRE_FIX_STRING_MAINNET; import com.typesafe.config.Config; import java.lang.reflect.Field; @@ -46,13 +50,10 @@ public void resetSingleton() @Test public void testGetEcKey() { - ECKey key = ECKey.fromPrivate( - Hex.decode("1cd5a70741c6e583d2dd3c5f17231e608eb1e52437210d948c5085e141c2d830")); - - //log.debug("address = {}", ByteArray.toHexString(key.getOwnerAddress())); - - assertEquals(Wallet.getAddressPreFixString() + "125b6c87b3d67114b3873977888c34582f27bbb0", - ByteArray.toHexString(key.getAddress())); + ECKey key = ECKey.fromPrivate(Hex.decode(generateOccupationConstantPrivateKey())); + assertNotNull(key); + assertEquals("2e988a386a799f506693793c6a5af6b54dfaabfb", + ByteArray.toHexString(key.getAddress()).substring(2)); } @Test(expected = IllegalArgumentException.class) 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 ed79bd5c855..4bb8e7e4909 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 @@ -16,20 +16,40 @@ package org.tron.core.config.args; import com.google.common.collect.Lists; +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; import io.grpc.internal.GrpcUtil; import io.grpc.netty.NettyServerBuilder; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Assert; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.tron.common.args.GenesisBlock; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; +import org.tron.common.utils.DecodeUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; +import org.tron.core.config.Configuration; @Slf4j public class ArgsTest { + private final String privateKey = PublicMethod.getRandomPrivateKey(); + private String address; + private LocalWitnesses localWitnesses; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + @After public void destroy() { Args.clearParam(); @@ -37,12 +57,19 @@ public void destroy() { @Test public void get() { - Args.setParam(new String[]{"-w"}, Constant.TEST_CONF); + Args.setParam(new String[] {"-c", Constant.TEST_CONF}, Constant.TESTNET_CONF); CommonParameter parameter = Args.getInstance(); Args.logConfig(); + localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + address = ByteArray.toHexString(Args.getLocalWitnesses() + .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine())); + Assert.assertEquals(Constant.ADD_PRE_FIX_STRING_TESTNET, DecodeUtil.addressPreFixString); Assert.assertEquals(0, parameter.getBackupPriority()); Assert.assertEquals(3000, parameter.getKeepAliveInterval()); @@ -51,7 +78,7 @@ public void get() { Assert.assertEquals("database", parameter.getStorage().getDbDirectory()); - Assert.assertEquals(11, parameter.getSeedNode().getIpList().size()); + Assert.assertEquals(11, parameter.getSeedNode().getAddressList().size()); GenesisBlock genesisBlock = parameter.getGenesisBlock(); @@ -65,18 +92,20 @@ public void get() { genesisBlock.getParentHash()); Assert.assertEquals( - Lists.newArrayList("f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"), + Lists.newArrayList(privateKey), Args.getLocalWitnesses().getPrivateKeys()); Assert.assertTrue(parameter.isNodeDiscoveryEnable()); Assert.assertTrue(parameter.isNodeDiscoveryPersist()); - Assert.assertEquals("127.0.0.1", parameter.getNodeDiscoveryBindIp()); Assert.assertEquals("46.168.1.1", parameter.getNodeExternalIp()); Assert.assertEquals(18888, parameter.getNodeListenPort()); Assert.assertEquals(2000, parameter.getNodeConnectionTimeout()); Assert.assertEquals(0, parameter.getActiveNodes().size()); - Assert.assertEquals(30, parameter.getNodeMaxActiveNodes()); + Assert.assertEquals(30, parameter.getMaxConnections()); Assert.assertEquals(43, parameter.getNodeP2pVersion()); + Assert.assertEquals(54, parameter.getMaxUnsolidifiedBlocks()); + Assert.assertEquals(false, parameter.isUnsolidifiedBlockCheck()); + Assert.assertEquals(1000, parameter.getMaxCreateAccountTxSize()); //Assert.assertEquals(30, args.getSyncNodeCount()); // gRPC network configs checking @@ -90,11 +119,163 @@ public void get() { Assert.assertEquals(GrpcUtil.DEFAULT_MAX_MESSAGE_SIZE, parameter.getMaxMessageSize()); Assert.assertEquals(GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE, parameter.getMaxHeaderListSize()); Assert.assertEquals(1L, parameter.getAllowCreationOfContracts()); + Assert.assertEquals(0, parameter.getConsensusLogicOptimization()); - Assert.assertEquals("f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62", + Assert.assertEquals(privateKey, Args.getLocalWitnesses().getPrivateKey()); - Assert.assertEquals("a0299f3db80a24b20a254b89ce639d59132f157f13", + + Assert.assertEquals(address, ByteArray.toHexString(Args.getLocalWitnesses() .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine()))); } + + @Test + public void testIpFromLibP2p() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Args.setParam(new String[] {}, Constant.TEST_CONF); + CommonParameter parameter = Args.getInstance(); + + String configuredExternalIp = parameter.getNodeExternalIp(); + Assert.assertEquals("46.168.1.1", configuredExternalIp); + + Config config = Configuration.getByFileName(null, Constant.TEST_CONF); + Config config3 = config.withoutPath(Constant.NODE_DISCOVERY_EXTERNAL_IP); + + CommonParameter.getInstance().setNodeExternalIp(null); + + Method method2 = Args.class.getDeclaredMethod("externalIp", Config.class); + method2.setAccessible(true); + method2.invoke(Args.class, config3); + + Assert.assertNotEquals(configuredExternalIp, parameter.getNodeExternalIp()); + } + + @Test + public void testOldRewardOpt() { + thrown.expect(IllegalArgumentException.class); + Args.setParam(new String[] {"-c", "args-test.conf"}, Constant.TESTNET_CONF); + } + + @Test + public void testInitService() { + Map storage = new HashMap<>(); + // avoid the exception for the missing storage + storage.put("storage.db.directory", "database"); + Config config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage)); + // test default value + Args.setParam(config); + Assert.assertTrue(Args.getInstance().isRpcEnable()); + Assert.assertTrue(Args.getInstance().isRpcSolidityEnable()); + Assert.assertTrue(Args.getInstance().isRpcPBFTEnable()); + Assert.assertTrue(Args.getInstance().isFullNodeHttpEnable()); + Assert.assertTrue(Args.getInstance().isSolidityNodeHttpEnable()); + Assert.assertTrue(Args.getInstance().isPBFTHttpEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpFullNodeEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpSolidityNodeEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpPBFTNodeEnable()); + Assert.assertEquals(5000, Args.getInstance().getJsonRpcMaxBlockRange()); + Assert.assertEquals(1000, Args.getInstance().getJsonRpcMaxSubTopics()); + Args.clearParam(); + // test set all true value + storage.put("node.rpc.enable", "true"); + storage.put("node.rpc.solidityEnable", "true"); + storage.put("node.rpc.PBFTEnable", "true"); + storage.put("node.http.fullNodeEnable", "true"); + storage.put("node.http.solidityEnable", "true"); + storage.put("node.http.PBFTEnable", "true"); + storage.put("node.jsonrpc.httpFullNodeEnable", "true"); + storage.put("node.jsonrpc.httpSolidityEnable", "true"); + storage.put("node.jsonrpc.httpPBFTEnable", "true"); + storage.put("node.jsonrpc.maxBlockRange", "10"); + storage.put("node.jsonrpc.maxSubTopics", "20"); + config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage)); + // test value + Args.setParam(config); + Assert.assertTrue(Args.getInstance().isRpcEnable()); + Assert.assertTrue(Args.getInstance().isRpcSolidityEnable()); + Assert.assertTrue(Args.getInstance().isRpcPBFTEnable()); + Assert.assertTrue(Args.getInstance().isFullNodeHttpEnable()); + Assert.assertTrue(Args.getInstance().isSolidityNodeHttpEnable()); + Assert.assertTrue(Args.getInstance().isPBFTHttpEnable()); + Assert.assertTrue(Args.getInstance().isJsonRpcHttpFullNodeEnable()); + Assert.assertTrue(Args.getInstance().isJsonRpcHttpSolidityNodeEnable()); + Assert.assertTrue(Args.getInstance().isJsonRpcHttpPBFTNodeEnable()); + Assert.assertEquals(10, Args.getInstance().getJsonRpcMaxBlockRange()); + Assert.assertEquals(20, Args.getInstance().getJsonRpcMaxSubTopics()); + Args.clearParam(); + // test set all false value + storage.put("node.rpc.enable", "false"); + storage.put("node.rpc.solidityEnable", "false"); + storage.put("node.rpc.PBFTEnable", "false"); + storage.put("node.http.fullNodeEnable", "false"); + storage.put("node.http.solidityEnable", "false"); + storage.put("node.http.PBFTEnable", "false"); + storage.put("node.jsonrpc.httpFullNodeEnable", "false"); + storage.put("node.jsonrpc.httpSolidityEnable", "false"); + storage.put("node.jsonrpc.httpPBFTEnable", "false"); + storage.put("node.jsonrpc.maxBlockRange", "5000"); + storage.put("node.jsonrpc.maxSubTopics", "1000"); + config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage)); + // test value + Args.setParam(config); + Assert.assertFalse(Args.getInstance().isRpcEnable()); + Assert.assertFalse(Args.getInstance().isRpcSolidityEnable()); + Assert.assertFalse(Args.getInstance().isRpcPBFTEnable()); + Assert.assertFalse(Args.getInstance().isFullNodeHttpEnable()); + Assert.assertFalse(Args.getInstance().isSolidityNodeHttpEnable()); + Assert.assertFalse(Args.getInstance().isPBFTHttpEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpFullNodeEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpSolidityNodeEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpPBFTNodeEnable()); + Assert.assertEquals(5000, Args.getInstance().getJsonRpcMaxBlockRange()); + Assert.assertEquals(1000, Args.getInstance().getJsonRpcMaxSubTopics()); + Args.clearParam(); + // test set random value + storage.put("node.rpc.enable", "false"); + storage.put("node.rpc.solidityEnable", "false"); + storage.put("node.rpc.PBFTEnable", "true"); + storage.put("node.http.fullNodeEnable", "false"); + storage.put("node.http.solidityEnable", "true"); + storage.put("node.http.PBFTEnable", "false"); + storage.put("node.jsonrpc.httpFullNodeEnable", "true"); + storage.put("node.jsonrpc.httpSolidityEnable", "false"); + storage.put("node.jsonrpc.httpPBFTEnable", "true"); + storage.put("node.jsonrpc.maxBlockRange", "30"); + storage.put("node.jsonrpc.maxSubTopics", "40"); + config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage)); + // test value + Args.setParam(config); + Assert.assertFalse(Args.getInstance().isRpcEnable()); + Assert.assertFalse(Args.getInstance().isRpcSolidityEnable()); + Assert.assertTrue(Args.getInstance().isRpcPBFTEnable()); + Assert.assertFalse(Args.getInstance().isFullNodeHttpEnable()); + Assert.assertTrue(Args.getInstance().isSolidityNodeHttpEnable()); + Assert.assertFalse(Args.getInstance().isPBFTHttpEnable()); + Assert.assertTrue(Args.getInstance().isJsonRpcHttpFullNodeEnable()); + Assert.assertFalse(Args.getInstance().isJsonRpcHttpSolidityNodeEnable()); + Assert.assertTrue(Args.getInstance().isJsonRpcHttpPBFTNodeEnable()); + Assert.assertEquals(30, Args.getInstance().getJsonRpcMaxBlockRange()); + Assert.assertEquals(40, Args.getInstance().getJsonRpcMaxSubTopics()); + + // test set invalid value + storage.put("node.jsonrpc.maxBlockRange", "0"); + storage.put("node.jsonrpc.maxSubTopics", "0"); + config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage)); + // check value + Args.setParam(config); + Assert.assertEquals(0, Args.getInstance().getJsonRpcMaxBlockRange()); + Assert.assertEquals(0, Args.getInstance().getJsonRpcMaxSubTopics()); + + // test set invalid value + storage.put("node.jsonrpc.maxBlockRange", "-2"); + storage.put("node.jsonrpc.maxSubTopics", "-4"); + config = ConfigFactory.defaultOverrides().withFallback(ConfigFactory.parseMap(storage)); + // check value + Args.setParam(config); + Assert.assertEquals(-2, Args.getInstance().getJsonRpcMaxBlockRange()); + Assert.assertEquals(-4, Args.getInstance().getJsonRpcMaxSubTopics()); + + Args.clearParam(); + } } + diff --git a/framework/src/test/java/org/tron/core/config/args/DynamicArgsTest.java b/framework/src/test/java/org/tron/core/config/args/DynamicArgsTest.java new file mode 100644 index 00000000000..2a3af9c440e --- /dev/null +++ b/framework/src/test/java/org/tron/core/config/args/DynamicArgsTest.java @@ -0,0 +1,73 @@ +package org.tron.core.config.args; + +import java.io.File; +import java.io.IOException; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.net.TronNetService; +import org.tron.p2p.P2pConfig; + +public class DynamicArgsTest { + protected TronApplicationContext context; + private DynamicArgs dynamicArgs; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void init() throws IOException { + Args.setParam(new String[]{"--output-directory", temporaryFolder.newFolder().toString()}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + dynamicArgs = context.getBean(DynamicArgs.class); + + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + + @Test + public void start() { + CommonParameter parameter = Args.getInstance(); + Assert.assertTrue(parameter.isDynamicConfigEnable()); + Assert.assertEquals(600, parameter.getDynamicConfigCheckInterval()); + + dynamicArgs.init(); + Assert.assertEquals(0, (long) ReflectUtils.getFieldObject(dynamicArgs, "lastModified")); + + TronNetService tronNetService = context.getBean(TronNetService.class); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", new P2pConfig()); + File config = new File(Constant.TESTNET_CONF); + if (!config.exists()) { + try { + config.createNewFile(); + } catch (Exception e) { + return; + } + dynamicArgs.run(); + try { + config.delete(); + } catch (Exception e) { + return; + } + } + try { + dynamicArgs.reload(); + } catch (Exception e) { + // no need to deal with + } + + dynamicArgs.close(); + } +} diff --git a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java index 45466c547d1..27d5effd6b1 100644 --- a/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java +++ b/framework/src/test/java/org/tron/core/config/args/LocalWitnessTest.java @@ -20,27 +20,33 @@ import org.junit.Before; import org.junit.Test; import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; public class LocalWitnessTest { - private LocalWitnesses localWitness = new LocalWitnesses(); + private final LocalWitnesses localWitness = new LocalWitnesses(); + private static final String PRIVATE_KEY = PublicMethod.getRandomPrivateKey(); @Before public void setLocalWitness() { localWitness .setPrivateKeys( Lists.newArrayList( - "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62")); + PRIVATE_KEY)); } @Test public void whenSetNullPrivateKey() { localWitness.setPrivateKeys(null); + Assert.assertNotNull(localWitness.getPrivateKey()); + Assert.assertNotNull(localWitness.getPublicKey()); } @Test public void whenSetEmptyPrivateKey() { localWitness.setPrivateKeys(Lists.newArrayList("")); + Assert.assertNotNull(localWitness.getPrivateKey()); + Assert.assertNotNull(localWitness.getPublicKey()); } @Test(expected = IllegalArgumentException.class) @@ -52,16 +58,33 @@ public void whenSetBadFormatPrivateKey() { public void whenSetPrefixPrivateKey() { localWitness .setPrivateKeys(Lists - .newArrayList("0xf31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62")); + .newArrayList("0x" + PRIVATE_KEY)); localWitness .setPrivateKeys(Lists - .newArrayList("0Xf31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62")); + .newArrayList("0X" + PRIVATE_KEY)); + Assert.assertNotNull(localWitness.getPrivateKey()); } @Test public void getPrivateKey() { Assert.assertEquals(Lists - .newArrayList("f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"), + .newArrayList(PRIVATE_KEY), localWitness.getPrivateKeys()); } + + @Test + public void testConstructor() { + LocalWitnesses localWitnesses = new LocalWitnesses(PublicMethod.getRandomPrivateKey()); + LocalWitnesses localWitnesses1 = + new LocalWitnesses(Lists.newArrayList(PublicMethod.getRandomPrivateKey())); + localWitnesses.setWitnessAccountAddress(new byte[0]); + Assert.assertNotNull(localWitnesses1.getPublicKey()); + + LocalWitnesses localWitnesses2 = new LocalWitnesses(); + Assert.assertNull(localWitnesses2.getPrivateKey()); + Assert.assertNull(localWitnesses2.getPublicKey()); + localWitnesses2.initWitnessAccountAddress(true); + LocalWitnesses localWitnesses3 = new LocalWitnesses(); + Assert.assertNotNull(localWitnesses3.getWitnessAccountAddress(true)); + } } diff --git a/framework/src/test/java/org/tron/core/config/args/StorageTest.java b/framework/src/test/java/org/tron/core/config/args/StorageTest.java index a6d9d9e7f73..eb349a2d146 100644 --- a/framework/src/test/java/org/tron/core/config/args/StorageTest.java +++ b/framework/src/test/java/org/tron/core/config/args/StorageTest.java @@ -93,7 +93,7 @@ public void getOptions() { Assert.assertEquals(1000, options.maxOpenFiles()); options = StorageUtils.getOptionsByDbName("trans"); - Assert.assertEquals(256 * 1024 * 1024, options.writeBufferSize()); + Assert.assertEquals(16 * 1024 * 1024, options.writeBufferSize()); Assert.assertEquals(50, options.maxOpenFiles()); } diff --git a/framework/src/test/java/org/tron/core/consensus/DposServiceTest.java b/framework/src/test/java/org/tron/core/consensus/DposServiceTest.java new file mode 100644 index 00000000000..dc6802d71d5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/consensus/DposServiceTest.java @@ -0,0 +1,117 @@ +package org.tron.core.consensus; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.parameter.CommonParameter; +import org.tron.consensus.ConsensusDelegate; +import org.tron.consensus.dpos.DposService; +import org.tron.consensus.dpos.DposSlot; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.p2p.utils.NetUtil; +import org.tron.protos.Protocol; + +public class DposServiceTest { + DposService service = new DposService(); + + + @AfterClass + public static void destroy() { + Args.clearParam(); + } + + @Test + public void testValidBlockTime() throws Exception { + long headTime = 1724036757000L; + + ConsensusDelegate consensusDelegate = mock(ConsensusDelegate.class); + Field field = service.getClass().getDeclaredField("consensusDelegate"); + field.setAccessible(true); + field.set(service, consensusDelegate); + + DynamicPropertiesStore store = mock(DynamicPropertiesStore.class); + Mockito.when(consensusDelegate.getDynamicPropertiesStore()).thenReturn(store); + + Mockito.when(consensusDelegate.getLatestBlockHeaderNumber()).thenReturn(0L); + boolean f = service.validBlock(null); + Assert.assertTrue(f); + + Protocol.BlockHeader.raw raw = Protocol.BlockHeader.raw.newBuilder() + .setTimestamp(headTime + 3001).build(); + Protocol.BlockHeader header = Protocol.BlockHeader.newBuilder().setRawData(raw).build(); + Protocol.Block block = Protocol.Block.newBuilder().setBlockHeader(header).build(); + + Mockito.when(consensusDelegate.getLatestBlockHeaderNumber()).thenReturn(100L); + Mockito.when(store.allowConsensusLogicOptimization()).thenReturn(true); + + Mockito.when(consensusDelegate.getLatestBlockHeaderTimestamp()).thenReturn(headTime + 3000); + f = service.validBlock(new BlockCapsule(block)); + Assert.assertTrue(!f); + + } + + @Test + public void testValidSlot() throws Exception { + Args.setParam(new String[] {}, Constant.TEST_CONF); + long headTime = 1724036757000L; + ByteString witness = ByteString.copyFrom(NetUtil.getNodeId()); + ByteString witness2 = ByteString.copyFrom(NetUtil.getNodeId()); + + ConsensusDelegate consensusDelegate = mock(ConsensusDelegate.class); + Field field = service.getClass().getDeclaredField("consensusDelegate"); + field.setAccessible(true); + field.set(service, consensusDelegate); + + DposSlot dposSlot = mock(DposSlot.class); + field = service.getClass().getDeclaredField("dposSlot"); + field.setAccessible(true); + field.set(service, dposSlot); + + Mockito.when(dposSlot.getAbSlot(headTime)).thenReturn(headTime / 3000); + Mockito.when(dposSlot.getAbSlot(headTime + 3000)).thenReturn((headTime + 3000) / 3000); + + DynamicPropertiesStore store = mock(DynamicPropertiesStore.class); + Mockito.when(consensusDelegate.getDynamicPropertiesStore()).thenReturn(store); + + Mockito.when(consensusDelegate.getLatestBlockHeaderNumber()).thenReturn(0L); + boolean f = service.validBlock(null); + Assert.assertTrue(f); + + Mockito.when(consensusDelegate.getLatestBlockHeaderNumber()).thenReturn(100L); + + Protocol.BlockHeader.raw raw = Protocol.BlockHeader.raw.newBuilder() + .setTimestamp(headTime + 3000) + .setWitnessAddress(witness).build(); + Protocol.BlockHeader header = Protocol.BlockHeader.newBuilder().setRawData(raw).build(); + Protocol.Block block = Protocol.Block.newBuilder().setBlockHeader(header).build(); + + Mockito.when(consensusDelegate.getLatestBlockHeaderTimestamp()).thenReturn(headTime + 3000); + f = service.validBlock(new BlockCapsule(block)); + Assert.assertTrue(!f); + + Mockito.when(consensusDelegate.getLatestBlockHeaderTimestamp()).thenReturn(headTime); + + Mockito.when(dposSlot.getSlot(headTime + 3000)).thenReturn(0L); + + Mockito.when(dposSlot.getScheduledWitness(0L)).thenReturn(witness2); + f = service.validBlock(new BlockCapsule(block)); + Assert.assertTrue(!f); + + Mockito.when(dposSlot.getScheduledWitness(0L)).thenReturn(witness); + f = service.validBlock(new BlockCapsule(block)); + Assert.assertTrue(f); + + Mockito.when(store.allowConsensusLogicOptimization()).thenReturn(true); + f = service.validBlock(new BlockCapsule(block)); + Assert.assertTrue(!f); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/consensus/DposTaskTest.java b/framework/src/test/java/org/tron/core/consensus/DposTaskTest.java new file mode 100644 index 00000000000..89d887d5fe9 --- /dev/null +++ b/framework/src/test/java/org/tron/core/consensus/DposTaskTest.java @@ -0,0 +1,64 @@ +package org.tron.core.consensus; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.consensus.base.BlockHandle; +import org.tron.consensus.base.State; +import org.tron.consensus.dpos.DposService; +import org.tron.consensus.dpos.DposSlot; +import org.tron.consensus.dpos.DposTask; +import org.tron.consensus.dpos.StateManager; + +public class DposTaskTest { + private DposTask dposTask = new DposTask(); + + @Test + public void tet() throws Exception { + StateManager stateManager = mock(StateManager.class); + Mockito.when(stateManager.getState()).thenReturn(State.BACKUP_IS_NOT_MASTER); + + Field field = dposTask.getClass().getDeclaredField("stateManager"); + field.setAccessible(true); + field.set(dposTask, stateManager); + + Method method = dposTask.getClass().getDeclaredMethod("produceBlock"); + method.setAccessible(true); + State state = (State) method.invoke(dposTask); + + Assert.assertEquals(State.BACKUP_IS_NOT_MASTER, state); + + + Mockito.when(stateManager.getState()).thenReturn(State.OK); + + DposSlot dposSlot = mock(DposSlot.class); + Mockito.when(dposSlot.getTime(1)).thenReturn(Long.MAX_VALUE); + + field = dposTask.getClass().getDeclaredField("dposSlot"); + field.setAccessible(true); + field.set(dposTask, dposSlot); + + + Mockito.when(stateManager.getState()).thenReturn(State.OK); + + BlockHandle blockHandle = mock(BlockHandle.class); + Mockito.when(blockHandle.getLock()).thenReturn(new Object()); + + + DposService dposService = mock(DposService.class); + Mockito.when(dposService.getBlockHandle()).thenReturn(blockHandle); + + field = dposTask.getClass().getDeclaredField("dposService"); + field.setAccessible(true); + field.set(dposTask, dposService); + + state = (State) method.invoke(dposTask); + + Assert.assertEquals(State.NOT_TIME_YET, state); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/AbiStoreTest.java b/framework/src/test/java/org/tron/core/db/AbiStoreTest.java new file mode 100644 index 00000000000..0cb134c50ce --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/AbiStoreTest.java @@ -0,0 +1,61 @@ +package org.tron.core.db; + +import static org.tron.common.utils.PublicMethod.jsonStr2Abi; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.AbiCapsule; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.AbiStore; +import org.tron.core.store.AccountIndexStore; +import org.tron.protos.Protocol.AccountType; +import org.tron.protos.contract.SmartContractOuterClass; + +public class AbiStoreTest extends BaseTest { + + @Resource + private AbiStore abiStore; + + private static final byte[] contractAddr = Hex.decode( + "41000000000000000000000000000000000000dEaD"); + + private static final SmartContractOuterClass.SmartContract.ABI SOURCE_ABI = jsonStr2Abi( + "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\"" + + ":\"constructor\"}]"); + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testPut() { + abiStore.put(contractAddr, new AbiCapsule(SOURCE_ABI)); + Assert.assertEquals(abiStore.has(contractAddr), Boolean.TRUE); + } + + @Test + public void testGet() { + abiStore.put(contractAddr, new AbiCapsule(SOURCE_ABI)); + AbiCapsule abiCapsule = abiStore.get(contractAddr); + Assert.assertEquals(abiCapsule.getInstance(), SOURCE_ABI); + } + + @Test + public void testGetTotalAbi() { + abiStore.put(contractAddr, new AbiCapsule(SOURCE_ABI)); + Assert.assertEquals(abiStore.getTotalABIs(), 1); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java index 47c6723067d..48c24d98af1 100644 --- a/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountAssetStoreTest.java @@ -1,64 +1,138 @@ package org.tron.core.db; +import com.google.common.primitives.Longs; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; + +import java.util.Map; +import javax.annotation.Resource; + import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; -import org.tron.core.capsule.AccountAssetCapsule; -import org.tron.core.config.DefaultConfig; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.config.args.Args; import org.tron.core.store.AccountAssetStore; +import org.tron.core.store.AccountStore; +import org.tron.protos.Protocol; +import org.tron.protos.contract.AssetIssueContractOuterClass; + +public class AccountAssetStoreTest extends BaseTest { + private static final byte[] ASSET_KEY = "20000".getBytes(); + private static AccountCapsule ownerCapsule; -public class AccountAssetStoreTest { + private static String OWNER_ADDRESS = Wallet.getAddressPreFixString() + + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + private static final long TOTAL_SUPPLY = 1000_000_000L; + private static final int TRX_NUM = 10; + private static final int NUM = 1; + private static final long START_TIME = 1; + private static final long END_TIME = 2; + private static final int VOTE_SCORE = 2; + private static final String DESCRIPTION = "TRX"; + private static final String URL = "https://tron.network/"; - private static final byte[] data = TransactionStoreTest.randomBytes(32); - private static String dbPath = "output_AccountAssetStore_test"; - private static String dbDirectory = "db_AccountAssetStore_test"; - private static String indexDirectory = "index_AccountAssetStore_test"; - private static TronApplicationContext context; - private static AccountAssetStore accountAssetStore; - private static byte[] address = TransactionStoreTest.randomBytes(32); + @Resource + private AccountAssetStore accountAssetStore; + + @Resource + private AccountStore accountStore; static { Args.setParam( - new String[]{ - "--output-directory", dbPath, - "--storage-db-directory", dbDirectory, - "--storage-index-directory", indexDirectory - }, - Constant.TEST_CONF + new String[]{ + "--output-directory", dbPath(), + }, + Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); } - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + @Before + public void init() { + accountAssetStore.put(ASSET_KEY, Longs.toByteArray(200L)); + + ownerCapsule = + new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + ByteString.copyFromUtf8("owner"), + Protocol.AccountType.AssetIssue); + } + + + private long createAsset(String tokenName) { + long id = chainBaseManager.getDynamicPropertiesStore().getTokenIdNum() + 1; + chainBaseManager.getDynamicPropertiesStore().saveTokenIdNum(id); + AssetIssueContractOuterClass.AssetIssueContract assetIssueContract = + AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setName(ByteString.copyFrom(ByteArray.fromString(tokenName))) + .setId(Long.toString(id)) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM) + .setNum(NUM) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setVoteScore(VOTE_SCORE) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))) + .build(); + AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); + chainBaseManager.getAssetIssueV2Store() + .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + try { + ownerCapsule.addAssetV2(ByteArray.fromString(String.valueOf(id)), TOTAL_SUPPLY); + } catch (Exception e) { + e.printStackTrace(); + } + accountStore.put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + return id; } - @BeforeClass - public static void init() { - accountAssetStore = context.getBean(AccountAssetStore.class); - AccountAssetCapsule accountCapsule = new AccountAssetCapsule( - ByteString.copyFrom(address)); - accountAssetStore.put(data, accountCapsule); + @Test + public void testPut() { + byte[] key = "10000".getBytes(); + accountAssetStore.put(key, Longs.toByteArray(100L)); + byte[] bytes = accountAssetStore.get(key); + Assert.assertEquals(100L, Longs.fromByteArray(bytes)); } @Test - public void get() { - Assert.assertEquals(ByteArray.toHexString(address), - ByteArray.toHexString(accountAssetStore.get(data) - .getInstance().getAddress().toByteArray())); - Assert.assertTrue(accountAssetStore.has(data)); + public void testGet() { + byte[] bytes = accountAssetStore.get(ASSET_KEY); + Assert.assertEquals(200L, Longs.fromByteArray(bytes)); + } + + @Test + public void testGetAccountAssets() { + long assetKey = createAsset("testToken1"); + AccountCapsule accountCapsule = accountStore.get(ownerCapsule.getAddress().toByteArray()); + long assetValue = accountCapsule.getAssetV2(String.valueOf(assetKey)); + Assert.assertEquals(assetValue, TOTAL_SUPPLY); + } + + @Test + public void testGetAllAssets() { + long assetKey1 = createAsset("testToken1"); + long assetKey2 = createAsset("testToken2"); + AccountCapsule accountCapsule = accountStore.get(ownerCapsule.getAddress().toByteArray()); + + Map allAssets = accountAssetStore.getAllAssets(accountCapsule.getInstance()); + Long assetValue1 = allAssets.get(String.valueOf(assetKey1)); + Assert.assertNotNull(assetValue1); + + Long assetV1 = accountCapsule.getAssetV2(String.valueOf(assetKey1)); + Assert.assertEquals(assetValue1, assetV1); + + Long assetValue2 = allAssets.get(String.valueOf(assetKey2)); + Assert.assertNotNull(assetValue2); + + Long assetV2 = accountCapsule.getAssetV2(String.valueOf(assetKey2)); + Assert.assertEquals(assetValue1, assetV2); } } diff --git a/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java index 6e50f3dfca7..9033e90481c 100644 --- a/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountIdIndexStoreTest.java @@ -1,23 +1,21 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Random; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.AccountIdIndexStore; import org.tron.protos.Protocol.AccountType; -public class AccountIdIndexStoreTest { +public class AccountIdIndexStoreTest extends BaseTest { private static final byte[] ACCOUNT_ADDRESS_ONE = randomBytes(16); private static final byte[] ACCOUNT_ADDRESS_TWO = randomBytes(16); @@ -28,30 +26,20 @@ public class AccountIdIndexStoreTest { private static final byte[] ACCOUNT_NAME_THREE = randomBytes(6); private static final byte[] ACCOUNT_NAME_FOUR = randomBytes(6); private static final byte[] ACCOUNT_NAME_FIVE = randomBytes(6); - private static String dbPath = "output_AccountIndexStore_test"; - private static TronApplicationContext context; - private static AccountIdIndexStore accountIdIndexStore; + @Resource + private AccountIdIndexStore accountIdIndexStore; private static AccountCapsule accountCapsule1; private static AccountCapsule accountCapsule2; private static AccountCapsule accountCapsule3; private static AccountCapsule accountCapsule4; static { - Args.setParam(new String[]{"--output-directory", dbPath}, + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - accountIdIndexStore = context.getBean(AccountIdIndexStore.class); accountCapsule1 = new AccountCapsule(ByteString.copyFrom(ACCOUNT_ADDRESS_ONE), ByteString.copyFrom(ACCOUNT_NAME_ONE), AccountType.Normal); accountCapsule1.setAccountId(ByteString.copyFrom(ACCOUNT_NAME_ONE).toByteArray()); @@ -64,6 +52,11 @@ public static void init() { accountCapsule4 = new AccountCapsule(ByteString.copyFrom(ACCOUNT_ADDRESS_FOUR), ByteString.copyFrom(ACCOUNT_NAME_FOUR), AccountType.Normal); accountCapsule4.setAccountId(ByteString.copyFrom(ACCOUNT_NAME_FOUR).toByteArray()); + + } + + @Before + public void before() { accountIdIndexStore.put(accountCapsule1); accountIdIndexStore.put(accountCapsule2); accountIdIndexStore.put(accountCapsule3); diff --git a/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java index fd0474f4dee..a4dc848b749 100755 --- a/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountIndexStoreTest.java @@ -1,53 +1,40 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.AccountIndexStore; import org.tron.protos.Protocol.AccountType; -public class AccountIndexStoreTest { +public class AccountIndexStoreTest extends BaseTest { - private static String dbPath = "output_AccountIndexStore_test"; private static String dbDirectory = "db_AccountIndexStore_test"; private static String indexDirectory = "index_AccountIndexStore_test"; - private static TronApplicationContext context; - private static AccountIndexStore accountIndexStore; + @Resource + private AccountIndexStore accountIndexStore; private static byte[] address = TransactionStoreTest.randomBytes(32); private static byte[] accountName = TransactionStoreTest.randomBytes(32); static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory }, Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); } - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - - @BeforeClass - public static void init() { - accountIndexStore = context.getBean(AccountIndexStore.class); + @Before + public void init() { AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom(address), ByteString.copyFrom(accountName), AccountType.forNumber(1)); diff --git a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java index a64b71f411e..9249a3358dc 100755 --- a/framework/src/test/java/org/tron/core/db/AccountStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/AccountStoreTest.java @@ -1,58 +1,64 @@ package org.tron.core.db; +import static org.junit.Assert.assertEquals; + import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; +import org.tron.core.db2.ISession; import org.tron.core.store.AccountStore; +import org.tron.core.store.AssetIssueStore; +import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.AccountType; -public class AccountStoreTest { +public class AccountStoreTest extends BaseTest { private static final byte[] data = TransactionStoreTest.randomBytes(32); - private static String dbPath = "output_AccountStore_test"; private static String dbDirectory = "db_AccountStore_test"; private static String indexDirectory = "index_AccountStore_test"; - private static TronApplicationContext context; - private static AccountStore accountStore; + @Resource + private AccountStore accountStore; + @Resource + private DynamicPropertiesStore dynamicPropertiesStore; + @Resource + private AssetIssueStore assetIssueStore; private static byte[] address = TransactionStoreTest.randomBytes(32); private static byte[] accountName = TransactionStoreTest.randomBytes(32); + private static boolean init; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory }, Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } - @BeforeClass - public static void init() { - accountStore = context.getBean(AccountStore.class); + @Before + public void init() { + if (init) { + return; + } + assetIssueStore = chainBaseManager.getAssetIssueStore(); + dynamicPropertiesStore.saveAllowBlackHoleOptimization(1); AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom(address), ByteString.copyFrom(accountName), AccountType.forNumber(1)); + accountStore.put(data, accountCapsule); + init = true; } @Test @@ -76,4 +82,108 @@ public void put() { AccountType.forNumber(1)); accountStore.put(data, accountCapsule); } -} \ No newline at end of file + + @Test + public void assetTest() { + + dynamicPropertiesStore.setAllowAssetOptimization(1); + dynamicPropertiesStore.saveAllowSameTokenName(1); + AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom(address), + ByteString.copyFrom(accountName), + AccountType.forNumber(1)); + accountCapsule.addAsset("100".getBytes(), 1); + accountCapsule.addAssetAmountV2("100".getBytes(), 1, + dynamicPropertiesStore, assetIssueStore); + accountCapsule.addAssetAmountV2("200".getBytes(), 1, + dynamicPropertiesStore, assetIssueStore); + accountCapsule = saveAccount(accountCapsule); + assertEquals(0, accountCapsule.getAssetMap().size()); + assertEquals(1, accountCapsule.getAssetV2("100")); + assertEquals(1, accountCapsule.getAssetV2("200")); + assertEquals(2, accountCapsule.getAssetMapV2().size()); + assertEquals(0, accountCapsule.getAssetV2("300")); + + accountCapsule.clearAsset(); + accountCapsule.reduceAssetAmountV2("100".getBytes(), 1, + dynamicPropertiesStore, assetIssueStore); + accountCapsule = saveAccount(accountCapsule); + assertEquals(1, accountCapsule.getAssetMapV2().size()); + assertEquals(0, accountCapsule.getAssetV2("100")); + assertEquals(1, accountCapsule.getAssetV2("200")); + assertEquals(0, accountCapsule.getAssetV2("300")); + assertEquals(3, accountCapsule.getAssetMapV2().size()); + + accountCapsule.clearAsset(); + accountStore.delete(accountCapsule.createDbKey()); + accountCapsule = saveAccount(accountCapsule); + assertEquals(0, accountCapsule.getAssetMapV2().size()); + + Map map = new HashMap<>(); + map.put("100", 100L); + map.put("200", 100L); + accountCapsule.addAssetMapV2(map); + accountCapsule = saveAccount(accountCapsule); + assertEquals(100, accountCapsule.getAssetV2("100")); + assertEquals(100, accountCapsule.getAssetV2("200")); + + accountCapsule.clearAsset(); + Map assets = accountCapsule.getAssetV2MapForTest(); + assertEquals(2, assets.size()); + assertEquals(100, (long)assets.get("100")); + assertEquals(100, (long)assets.get("200")); + + accountCapsule.clearAsset(); + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { + accountCapsule.addAssetAmountV2("100".getBytes(), 1, + dynamicPropertiesStore, assetIssueStore); + accountCapsule.reduceAssetAmountV2("200".getBytes(), 1, + dynamicPropertiesStore, assetIssueStore); + accountCapsule = saveAccount(accountCapsule); + tmpSession.commit(); + } + assertEquals(101, accountCapsule.getAssetV2("100")); + assertEquals(99, accountCapsule.getAssetV2("200")); + + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { + tmpSession.commit(); + } + + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { + accountCapsule.reduceAssetAmountV2("200".getBytes(), 89, + dynamicPropertiesStore, assetIssueStore); + accountCapsule.addAssetAmountV2("300".getBytes(), 10, + dynamicPropertiesStore, assetIssueStore); + accountCapsule = saveAccount(accountCapsule); + tmpSession.commit(); + } + assets = accountCapsule.getAssetV2MapForTest(); + assertEquals(3, assets.size()); + assertEquals(101, (long)assets.get("100")); + assertEquals(10, (long)assets.get("200")); + assertEquals(10, (long)assets.get("300")); + + try (ISession tmpSession = dbManager.getRevokingStore().buildSession()) { + accountCapsule.reduceAssetAmountV2("100".getBytes(), 91, + dynamicPropertiesStore, assetIssueStore); + accountCapsule.addAssetAmountV2("200".getBytes(), 0, + dynamicPropertiesStore, assetIssueStore); + accountCapsule.addAssetAmountV2("400".getBytes(), 10, + dynamicPropertiesStore, assetIssueStore); + accountCapsule = saveAccount(accountCapsule); + tmpSession.commit(); + } + assets = accountCapsule.getAssetV2MapForTest(); + assertEquals(4, assets.size()); + assertEquals(10, (long)assets.get("100")); + assertEquals(10, (long)assets.get("200")); + assertEquals(10, (long)assets.get("300")); + assertEquals(10, (long)assets.get("400")); + } + + private AccountCapsule saveAccount(AccountCapsule accountCapsule) { + accountStore.put(accountCapsule.createDbKey(), accountCapsule); + accountCapsule = accountStore.get(accountCapsule.createDbKey()); + return accountCapsule; + } + +} diff --git a/framework/src/test/java/org/tron/core/db/AccountTraceStoreTest.java b/framework/src/test/java/org/tron/core/db/AccountTraceStoreTest.java new file mode 100644 index 00000000000..5a6d44a8c7c --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/AccountTraceStoreTest.java @@ -0,0 +1,70 @@ +package org.tron.core.db; + +import com.google.common.primitives.Bytes; +import com.google.common.primitives.Longs; +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.apache.commons.lang3.tuple.Pair; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.AccountTraceCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.AccountIndexStore; +import org.tron.core.store.AccountTraceStore; +import org.tron.protos.Protocol.AccountType; + +public class AccountTraceStoreTest extends BaseTest { + + @Resource + private AccountTraceStore accountTraceStore; + private static byte[] address = TransactionStoreTest.randomBytes(32); + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + + @Test + public void testRecordBalanceWithBlock() throws BadItemException, ItemNotFoundException { + accountTraceStore.recordBalanceWithBlock(address,1,9999); + Assert.assertNotNull(accountTraceStore.get(Bytes.concat(address, + Longs.toByteArray(1L ^ Long.MAX_VALUE)))); + } + + @Test + public void testGetPrevBalance() { + accountTraceStore.recordBalanceWithBlock(address,2,9999); + Pair pair = accountTraceStore.getPrevBalance(address,2); + Assert.assertEquals((long)pair.getKey(),2L); + Assert.assertEquals((long)pair.getValue(), 0L); + byte[] address2 = TransactionStoreTest.randomBytes(21); + accountTraceStore.recordBalanceWithBlock(address2,3,99); + Pair pair2 = accountTraceStore.getPrevBalance(address2, 3); + Assert.assertEquals((long)pair2.getKey(),3L); + Assert.assertEquals((long)pair2.getValue(), 99L); + } + + @Test + public void testPut() { + long number = 2 ^ Long.MAX_VALUE; + long balance = 9999; + byte[] key = Bytes.concat(address, Longs.toByteArray(number)); + accountTraceStore.put(key, new AccountTraceCapsule(balance)); + Pair pair = accountTraceStore.getPrevBalance(address,2); + Assert.assertEquals((long)pair.getKey(),2L); + Assert.assertEquals((long)pair.getValue(), 0L); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/AssetIssueStoreTest.java b/framework/src/test/java/org/tron/core/db/AssetIssueStoreTest.java new file mode 100644 index 00000000000..34a4a8507d6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/AssetIssueStoreTest.java @@ -0,0 +1,90 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.AssetIssueCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.AssetIssueStore; +import org.tron.protos.contract.AssetIssueContractOuterClass; + +public class AssetIssueStoreTest extends BaseTest { + + private static final String NAME = "test-asset"; + private static final long TOTAL_SUPPLY = 10000L; + private static final int TRX_NUM = 10000; + private static final int NUM = 100000; + private static final String DESCRIPTION = "myCoin"; + private static final String URL = "tron.network"; + + @Resource + private AssetIssueStore assetIssueStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, + Constant.TEST_CONF + ); + } + + @Before + public void init() { + long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; + AssetIssueCapsule assetIssueCapsule = createAssetIssue(id, NAME); + assetIssueStore.put(assetIssueCapsule.createDbKey(), assetIssueCapsule); + } + + private AssetIssueCapsule createAssetIssue(long id, String name) { + dbManager.getDynamicPropertiesStore().saveTokenIdNum(id); + AssetIssueContractOuterClass.AssetIssueContract assetIssueContract = + AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .setName(ByteString.copyFrom(ByteArray.fromString(name))).setId(Long.toString(id)) + .setTotalSupply(TOTAL_SUPPLY) + .setTrxNum(TRX_NUM).setNum(NUM).setStartTime(1).setEndTime(100).setVoteScore(2) + .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) + .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))).build(); + AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); + return assetIssueCapsule; + } + + @Test + public void testPut() { + long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; + String issueName = "test-asset2"; + AssetIssueCapsule assetIssueCapsule = createAssetIssue(id, issueName); + assetIssueStore.put(assetIssueCapsule.createDbKey(), assetIssueCapsule); + AssetIssueCapsule assetIssueCapsule1 = assetIssueStore.get(ByteArray.fromString(issueName)); + + Assert.assertNotNull(assetIssueCapsule1); + Assert.assertEquals(issueName, new String(assetIssueCapsule1.getName().toByteArray())); + } + + @Test + public void testGet() { + AssetIssueCapsule assetIssueCapsule = assetIssueStore.get(ByteArray.fromString(NAME)); + Assert.assertNotNull(assetIssueCapsule); + Assert.assertEquals(NAME, new String(assetIssueCapsule.getName().toByteArray())); + Assert.assertEquals(TOTAL_SUPPLY, assetIssueCapsule.getInstance().getTotalSupply()); + } + + @Test + public void testDelete() { + long id = dbManager.getDynamicPropertiesStore().getTokenIdNum() + 1; + String issueName = "test-asset-delete"; + AssetIssueCapsule assetIssueCapsule = createAssetIssue(id, issueName); + assetIssueStore.put(assetIssueCapsule.createDbKey(), assetIssueCapsule); + AssetIssueCapsule assetIssueCapsule1 = assetIssueStore.get(ByteArray.fromString(issueName)); + Assert.assertNotNull(assetIssueCapsule1); + assetIssueStore.delete(assetIssueCapsule1.createDbKey()); + AssetIssueCapsule assetIssueCapsule2 = assetIssueStore.get(ByteArray.fromString(issueName)); + Assert.assertNull(assetIssueCapsule2); + + } +} diff --git a/framework/src/test/java/org/tron/core/db/AssetIssueV2StoreTest.java b/framework/src/test/java/org/tron/core/db/AssetIssueV2StoreTest.java new file mode 100644 index 00000000000..e92027e3a28 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/AssetIssueV2StoreTest.java @@ -0,0 +1,91 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.AssetIssueCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.AssetIssueV2Store; +import org.tron.protos.contract.AssetIssueContractOuterClass; + + +public class AssetIssueV2StoreTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, + Constant.TEST_CONF + ); + } + + private AssetIssueCapsule assetIssueCapsule; + + @Resource + private AssetIssueV2Store assetIssueV2Store; + + @Before + public void init() { + String firstTokenId = "abc"; + assetIssueCapsule = + new AssetIssueCapsule( + AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .setName(ByteString.copyFrom(firstTokenId.getBytes())) + .build()); + assetIssueCapsule.setId(String.valueOf(1L)); + assetIssueV2Store + .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + } + + @Test + public void testPut() { + String firstTokenId = "efg"; + assetIssueCapsule = + new AssetIssueCapsule( + AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .setName(ByteString.copyFrom(firstTokenId.getBytes())) + .build()); + assetIssueCapsule.setId(String.valueOf(2L)); + assetIssueV2Store + .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + AssetIssueCapsule assetIssueCapsule = + assetIssueV2Store.get(this.assetIssueCapsule.createDbV2Key()); + Assert.assertNotNull(assetIssueCapsule); + String assetName = new String(assetIssueCapsule.getName().toByteArray()); + Assert.assertEquals(firstTokenId, assetName); + } + + @Test + public void testGet() { + AssetIssueCapsule assetIssueCapsule1 = assetIssueV2Store.get(assetIssueCapsule.createDbV2Key()); + Assert.assertNotNull(assetIssueCapsule1); + String assetName = new String(assetIssueCapsule1.getName().toByteArray()); + Assert.assertEquals("abc", assetName); + } + + @Test + public void testDelete() { + String firstTokenId = "hij"; + assetIssueCapsule = + new AssetIssueCapsule( + AssetIssueContractOuterClass.AssetIssueContract.newBuilder() + .setName(ByteString.copyFrom(firstTokenId.getBytes())) + .build()); + assetIssueCapsule.setId(String.valueOf(2L)); + assetIssueV2Store + .put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + AssetIssueCapsule assetIssueCapsule = + assetIssueV2Store.get(this.assetIssueCapsule.createDbV2Key()); + Assert.assertNotNull(assetIssueCapsule); + + assetIssueV2Store.delete(assetIssueCapsule.createDbV2Key()); + AssetIssueCapsule assetIssueCapsule1 = + assetIssueV2Store.get(this.assetIssueCapsule.createDbV2Key()); + Assert.assertNull(assetIssueCapsule1); + } +} diff --git a/framework/src/test/java/org/tron/core/db/BalanceTraceStoreTest.java b/framework/src/test/java/org/tron/core/db/BalanceTraceStoreTest.java new file mode 100644 index 00000000000..82547a997da --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/BalanceTraceStoreTest.java @@ -0,0 +1,131 @@ +package org.tron.core.db; + +import static org.junit.Assert.assertEquals; +import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferContract; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import javax.annotation.Resource; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockBalanceTraceCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.BalanceTraceStore; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + + +public class BalanceTraceStoreTest extends BaseTest { + + @Resource + private BalanceTraceStore balanceTraceStoreUnderTest; + + private static final byte[] contractAddr = Hex.decode( + "41000000000000000000000000000000000000dEaD"); + + BlockCapsule blockCapsule = new BlockCapsule(Protocol.Block.newBuilder().setBlockHeader( + Protocol.BlockHeader.newBuilder().setRawData(Protocol.BlockHeader.raw.newBuilder() + .setParentHash(ByteString.copyFrom(ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))))).build()); + final TransactionCapsule transactionCapsule = + new TransactionCapsule(Protocol.Transaction.newBuilder().build()); + BalanceContract.TransactionBalanceTrace transactionBalanceTrace = + BalanceContract.TransactionBalanceTrace.newBuilder() + .setTransactionIdentifier(transactionCapsule.getTransactionId().getByteString()) + .setType(TransferContract.name()) + .setStatus(SUCCESS.name()) + .build(); + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Before + public void clear() { + balanceTraceStoreUnderTest.resetCurrentTransactionTrace(); + balanceTraceStoreUnderTest.resetCurrentBlockTrace(); + } + + + @Test + public void testSetCurrentTransactionId() throws Exception { + balanceTraceStoreUnderTest.setCurrentBlockId(blockCapsule); + balanceTraceStoreUnderTest.setCurrentTransactionId(transactionCapsule); + Assert.assertEquals(balanceTraceStoreUnderTest.getCurrentTransactionId(), + transactionCapsule.getTransactionId()); + } + + @Test + public void testSetCurrentBlockId() { + balanceTraceStoreUnderTest.setCurrentBlockId(blockCapsule); + Assert.assertEquals(blockCapsule.getBlockId(), balanceTraceStoreUnderTest.getCurrentBlockId()); + } + + @Test + public void testResetCurrentTransactionTrace() { + balanceTraceStoreUnderTest.setCurrentBlockId(blockCapsule); + balanceTraceStoreUnderTest.setCurrentTransactionId(transactionCapsule); + balanceTraceStoreUnderTest.resetCurrentTransactionTrace(); + balanceTraceStoreUnderTest.resetCurrentBlockTrace(); + Assert.assertNotNull(balanceTraceStoreUnderTest.getCurrentTransactionId()); + Assert.assertNull(balanceTraceStoreUnderTest.getCurrentTransactionBalanceTrace()); + } + + @Test + public void testInitCurrentBlockBalanceTrace() { + balanceTraceStoreUnderTest.initCurrentBlockBalanceTrace(blockCapsule); + Assert.assertNull(balanceTraceStoreUnderTest.getCurrentBlockId()); + } + + @Test + public void testInitCurrentTransactionBalanceTrace() { + balanceTraceStoreUnderTest.setCurrentBlockId(blockCapsule); + balanceTraceStoreUnderTest.initCurrentTransactionBalanceTrace(transactionCapsule); + Assert.assertEquals(blockCapsule.getBlockId(), balanceTraceStoreUnderTest.getCurrentBlockId()); + Assert.assertNull(balanceTraceStoreUnderTest.getCurrentTransactionId()); + } + + @Test + public void testUpdateCurrentTransactionStatus() { + balanceTraceStoreUnderTest.setCurrentBlockId(blockCapsule); + balanceTraceStoreUnderTest.updateCurrentTransactionStatus(""); + Assert.assertNull(balanceTraceStoreUnderTest.getCurrentTransactionBalanceTrace()); + } + + @Test + public void testGetBlockBalanceTrace() throws Exception { + BlockBalanceTraceCapsule blockBalanceTraceCapsule = new BlockBalanceTraceCapsule(blockCapsule); + balanceTraceStoreUnderTest.put(ByteArray.fromLong(blockCapsule.getNum()), + blockBalanceTraceCapsule); + final BlockBalanceTraceCapsule result = + balanceTraceStoreUnderTest.getBlockBalanceTrace(blockCapsule.getBlockId()); + assertEquals(Arrays.toString(result.getData()), + Arrays.toString(blockBalanceTraceCapsule.getData())); + } + + @Test + public void testGetTransactionBalanceTrace() throws Exception { + BlockBalanceTraceCapsule blockBalanceTraceCapsule = new BlockBalanceTraceCapsule(blockCapsule); + blockBalanceTraceCapsule.addTransactionBalanceTrace(transactionBalanceTrace); + balanceTraceStoreUnderTest.put(ByteArray.fromLong(blockCapsule.getNum()), + blockBalanceTraceCapsule); + final BalanceContract.TransactionBalanceTrace result = + balanceTraceStoreUnderTest.getTransactionBalanceTrace(blockCapsule.getBlockId(), + transactionCapsule.getTransactionId()); + Assert.assertEquals(result.getStatus(),"SUCCESS"); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/BandwidthPriceHistoryLoaderTest.java b/framework/src/test/java/org/tron/core/db/BandwidthPriceHistoryLoaderTest.java new file mode 100644 index 00000000000..298b9f40235 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/BandwidthPriceHistoryLoaderTest.java @@ -0,0 +1,204 @@ +package org.tron.core.db; + +import static org.tron.core.store.DynamicPropertiesStore.DEFAULT_BANDWIDTH_PRICE_HISTORY; +import static org.tron.core.utils.ProposalUtil.ProposalType.ALLOW_CREATION_OF_CONTRACTS; +import static org.tron.core.utils.ProposalUtil.ProposalType.ALLOW_TVM_FREEZE; +import static org.tron.core.utils.ProposalUtil.ProposalType.ALLOW_TVM_LONDON; +import static org.tron.core.utils.ProposalUtil.ProposalType.ALLOW_TVM_VOTE; +import static org.tron.core.utils.ProposalUtil.ProposalType.ASSET_ISSUE_FEE; +import static org.tron.core.utils.ProposalUtil.ProposalType.CREATE_ACCOUNT_FEE; +import static org.tron.core.utils.ProposalUtil.ProposalType.CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT; +import static org.tron.core.utils.ProposalUtil.ProposalType.TRANSACTION_FEE; +import static org.tron.core.utils.ProposalUtil.ProposalType.WITNESS_127_PAY_PER_BLOCK; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.ProposalCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.api.BandwidthPriceHistoryLoader; +import org.tron.protos.Protocol.Proposal; +import org.tron.protos.Protocol.Proposal.State; + + +@Slf4j +public class BandwidthPriceHistoryLoaderTest { + + private static ChainBaseManager chainBaseManager; + private static TronApplicationContext context; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + private static long t1; + private static long price1; + private static long t2; + private static long price2; + private static long t5; + private static long price5; + + // Note, here use @Before and @After instead of @BeforeClass and @AfterClass, + // because it needs to initialize DB before the single test every time + @Before + public void init() throws IOException { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + chainBaseManager = context.getBean(ChainBaseManager.class); + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + + public void initDB() { + t1 = 1606240800000L; + price1 = 40; + initProposal(TRANSACTION_FEE.getCode(), t1, price1, State.APPROVED); + + t2 = 1613044800000L; + price2 = 140; + initProposal(TRANSACTION_FEE.getCode(), t2, price2, State.APPROVED); + + long t3 = 1626501600000L; + long price3 = 1000; + Map parameters = new HashMap<>(); + parameters.put(TRANSACTION_FEE.getCode(), price3); + parameters.put(CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), 1000000L); + initProposal(parameters, t3, State.CANCELED); + + long t4 = 1626501600000L; + long price4 = 1000; + parameters = new HashMap<>(); + parameters.put(TRANSACTION_FEE.getCode(), price4); + parameters.put(CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), 1000000L); + initProposal(parameters, t4, State.DISAPPROVED); + + t5 = 1627279200000L; + price5 = 1000L; + parameters = new HashMap<>(); + parameters.put(TRANSACTION_FEE.getCode(), price4); + parameters.put(CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT.getCode(), 1000000L); + initProposal(parameters, t5, State.APPROVED); + + long t6 = 1634299200000L; + parameters = new HashMap<>(); + parameters.put(ALLOW_TVM_FREEZE.getCode(), 1L); + parameters.put(ALLOW_TVM_VOTE.getCode(), 1L); + initProposal(parameters, t6, State.DISAPPROVED); + + initProposal(ALLOW_TVM_LONDON.getCode(), 1647604800000L, 1, State.APPROVED); + + initProposal(ALLOW_CREATION_OF_CONTRACTS.getCode(), 1539259200000L, 1, State.APPROVED); + initProposal(CREATE_ACCOUNT_FEE.getCode(), 1621468800000L, 1, State.DISAPPROVED); + + parameters = new HashMap<>(); + parameters.put(ASSET_ISSUE_FEE.getCode(), 48000000L); + parameters.put(WITNESS_127_PAY_PER_BLOCK.getCode(), 128000000L); + initProposal(parameters, 1572609600000L, State.CANCELED); + } + + private static void initProposal(long code, long timestamp, long price, State state) { + long id = chainBaseManager.getDynamicPropertiesStore().getLatestProposalNum() + 1; + + Proposal proposal = Proposal.newBuilder().putParameters(code, price) + .setExpirationTime(timestamp) + .setState(state) + .setProposalId(id) + .build(); + ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); + + chainBaseManager.getProposalStore().put(proposalCapsule.createDbKey(), proposalCapsule); + chainBaseManager.getDynamicPropertiesStore().saveLatestProposalNum(id); + } + + private static void initProposal(Map parameters, long timestamp, State state) { + long id = chainBaseManager.getDynamicPropertiesStore().getLatestProposalNum() + 1; + + Proposal proposal = Proposal.newBuilder().putAllParameters(parameters) + .setExpirationTime(timestamp) + .setState(state) + .setProposalId(id) + .build(); + ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); + + chainBaseManager.getProposalStore().put(proposalCapsule.createDbKey(), proposalCapsule); + chainBaseManager.getDynamicPropertiesStore().saveLatestProposalNum(id); + } + + @Test + public void testLoaderWork() { + + initDB(); + + String preBandwidthPriceHistory = + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + String expectedRes = preBandwidthPriceHistory + "," + t1 + ":" + price1 + + "," + t2 + ":" + price2 + + "," + t5 + ":" + price5; + + BandwidthPriceHistoryLoader loader = new BandwidthPriceHistoryLoader(chainBaseManager); + loader.getBandwidthProposals(); + String historyStr = loader.parseProposalsToStr(); + + Assert.assertEquals(expectedRes, historyStr); + } + + @Test + public void testProposalEmpty() { + String preBandwidthPriceHistory = + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + Assert.assertEquals(DEFAULT_BANDWIDTH_PRICE_HISTORY, preBandwidthPriceHistory); + + chainBaseManager.getDynamicPropertiesStore().saveBandwidthPriceHistoryDone(0); + + // loader work + BandwidthPriceHistoryLoader loader = new BandwidthPriceHistoryLoader(chainBaseManager); + loader.doWork(); + + // check result + String afterBandwidthPriceHistory = + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + Assert.assertEquals(DEFAULT_BANDWIDTH_PRICE_HISTORY, afterBandwidthPriceHistory); + Assert.assertEquals(1L, + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistoryDone()); + } + + @Test + public void testLoaderWithProposals() { + String preBandwidthPriceHistory = + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + Assert.assertEquals(DEFAULT_BANDWIDTH_PRICE_HISTORY, preBandwidthPriceHistory); + + chainBaseManager.getDynamicPropertiesStore().saveBandwidthPriceHistoryDone(0); + + // init proposals + initDB(); + + // loader work + BandwidthPriceHistoryLoader loader = new BandwidthPriceHistoryLoader(chainBaseManager); + loader.doWork(); + + // check result + String afterBandwidthPriceHistory = + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + String expectedRes = preBandwidthPriceHistory + "," + t1 + ":" + price1 + + "," + t2 + ":" + price2 + + "," + t5 + ":" + price5; + + Assert.assertEquals(expectedRes, afterBandwidthPriceHistory); + Assert.assertEquals(1L, + chainBaseManager.getDynamicPropertiesStore().getBandwidthPriceHistoryDone()); + } +} diff --git a/framework/src/test/java/org/tron/core/db/BlockGenerate.java b/framework/src/test/java/org/tron/core/db/BlockGenerate.java index d7a2d21e408..197dd562485 100644 --- a/framework/src/test/java/org/tron/core/db/BlockGenerate.java +++ b/framework/src/test/java/org/tron/core/db/BlockGenerate.java @@ -1,6 +1,7 @@ package org.tron.core.db; import com.google.protobuf.ByteString; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.crypto.ECKey.ECDSASignature; import org.tron.common.parameter.CommonParameter; diff --git a/framework/src/test/java/org/tron/core/db/BlockIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/BlockIndexStoreTest.java new file mode 100644 index 00000000000..a5600b34b26 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/BlockIndexStoreTest.java @@ -0,0 +1,64 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; + +public class BlockIndexStoreTest extends BaseTest { + + @Resource + private BlockIndexStore blockIndexStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + private BlockCapsule getBlockCapsule(long number) { + return new BlockCapsule(number, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + } + + @Test + public void testPut() { + BlockCapsule blockCapsule = getBlockCapsule(1); + blockIndexStore.put(blockCapsule.getBlockId()); + byte[] key = ByteArray.fromLong(blockCapsule.getBlockId().getNum()); + Assert.assertTrue(blockIndexStore.has(key)); + } + + @Test + public void testGet() throws ItemNotFoundException { + BlockCapsule blockCapsule = getBlockCapsule(1); + blockIndexStore.put(blockCapsule.getBlockId()); + byte[] key = ByteArray.fromLong(blockCapsule.getBlockId().getNum()); + BytesCapsule bytesCapsule = blockIndexStore.get(key); + Assert.assertNotNull(bytesCapsule); + } + + @Test + public void testDelete() throws ItemNotFoundException { + BlockCapsule blockCapsule = getBlockCapsule(1); + blockIndexStore.put(blockCapsule.getBlockId()); + byte[] key = ByteArray.fromLong(blockCapsule.getBlockId().getNum()); + BytesCapsule bytesCapsule = blockIndexStore.get(key); + Assert.assertNotNull(bytesCapsule); + + blockIndexStore.delete(key); + BytesCapsule capsule = blockIndexStore.getUnchecked(key); + Assert.assertNull(capsule.getData()); + } +} diff --git a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java index 0a5df8bf9bd..937a102193f 100644 --- a/framework/src/test/java/org/tron/core/db/BlockStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/BlockStoreTest.java @@ -1,43 +1,90 @@ package org.tron.core.db; -import java.io.File; +import com.google.protobuf.ByteString; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Before; +import org.junit.Assert; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; +import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; +import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.args.Args; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ItemNotFoundException; + @Slf4j -public class BlockStoreTest { +public class BlockStoreTest extends BaseTest { - private static final String dbPath = "output-blockStore-test"; - private static TronApplicationContext context; + @Resource + private BlockStore blockStore; static { - Args.setParam(new String[]{"--output-directory", dbPath}, + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); } - BlockStore blockStore; + private BlockCapsule getBlockCapsule(long number) { + return new BlockCapsule(number, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + } - @Before - public void init() { - blockStore = context.getBean(BlockStore.class); + @Test + public void testCreateBlockStore() { } - @After - public void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + @Test + public void testPut() { + long number = 1; + BlockCapsule blockCapsule = getBlockCapsule(number); + + byte[] blockId = blockCapsule.getBlockId().getBytes(); + blockStore.put(blockId, blockCapsule); + try { + BlockCapsule blockCapsule1 = blockStore.get(blockId); + Assert.assertNotNull(blockCapsule1); + Assert.assertEquals(number, blockCapsule1.getNum()); + } catch (ItemNotFoundException | BadItemException e) { + e.printStackTrace(); + } } @Test - public void testCreateBlockStore() { + public void testGet() { + long number = 2; + BlockCapsule blockCapsule = getBlockCapsule(number); + byte[] blockId = blockCapsule.getBlockId().getBytes(); + blockStore.put(blockId, blockCapsule); + try { + boolean has = blockStore.has(blockId); + Assert.assertTrue(has); + BlockCapsule blockCapsule1 = blockStore.get(blockId); + + Assert.assertEquals(number, blockCapsule1.getNum()); + } catch (ItemNotFoundException | BadItemException e) { + e.printStackTrace(); + } } + + @Test + public void testDelete() { + long number = 1; + BlockCapsule blockCapsule = getBlockCapsule(number); + + byte[] blockId = blockCapsule.getBlockId().getBytes(); + blockStore.put(blockId, blockCapsule); + try { + BlockCapsule blockCapsule1 = blockStore.get(blockId); + Assert.assertNotNull(blockCapsule1); + Assert.assertEquals(number, blockCapsule1.getNum()); + + blockStore.delete(blockId); + BlockCapsule blockCapsule2 = blockStore.getUnchecked(blockId); + Assert.assertNull(blockCapsule2); + } catch (ItemNotFoundException | BadItemException e) { + e.printStackTrace(); + } + } + } diff --git a/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java b/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java new file mode 100644 index 00000000000..fdf5877b87c --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ByteArrayWrapperTest.java @@ -0,0 +1,22 @@ +package org.tron.core.db; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.utils.ByteArray; + +@Slf4j +public class ByteArrayWrapperTest { + + @Test + public void createByteArray() { + ByteArrayWrapper byteArrayWrapper1 = new ByteArrayWrapper(ByteArray.fromHexString("1")); + ByteArrayWrapper byteArrayWrapper2 = new ByteArrayWrapper(ByteArray.fromHexString("2")); + Assert.assertEquals(byteArrayWrapper1.compareTo(byteArrayWrapper2), -1); + Assert.assertFalse(byteArrayWrapper1.equals(byteArrayWrapper2)); + Assert.assertFalse(byteArrayWrapper1.getData().equals(byteArrayWrapper2.getData())); + Assert.assertTrue(byteArrayWrapper1.hashCode() != byteArrayWrapper2.hashCode()); + Assert.assertEquals(byteArrayWrapper1.toString().equals(byteArrayWrapper2.toString()),false); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/CodeStoreTest.java b/framework/src/test/java/org/tron/core/db/CodeStoreTest.java new file mode 100644 index 00000000000..59bfba2236a --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/CodeStoreTest.java @@ -0,0 +1,74 @@ +package org.tron.core.db; + +import static org.junit.Assert.assertEquals; + +import java.util.Arrays; +import javax.annotation.Resource; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.CodeCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.CodeStore; + +public class CodeStoreTest extends BaseTest { + + private static final byte[] contractAddr1 = Hex.decode( + "41000000000000000000000000000000000000dEaD"); + private static final byte[] contractAddr2 = Hex.decode( + "41000000000000000000000000000000000000dEbD"); + private static final byte[] contractAddr3 = Hex.decode( + "41000000000000000000000000000000000000dEcD"); + + private static String codeString = + "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d28015" + + "61002a57600080fd5b50600436106100495760003560e01c806385bb7d69146100555761004a565b5b61" + + "0052610073565b50005b61005d610073565b60405161006a91906100b9565b60405180910390f35b6000" + + "80600090505b60028110156100a657808261009091906100d4565b915060018161009f91906100d4565b" + + "905061007b565b5090565b6100b38161012a565b82525050565b60006020820190506100ce6000830184" + + "6100aa565b92915050565b60006100df8261012a565b91506100ea8361012a565b9250827fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffff0382111561011f5761011e61013456" + + "5b5b828201905092915050565b6000819050919050565b7f4e487b710000000000000000000000000000" + + "0000000000000000000000000000600052601160045260246000fdfea26474726f6e58221220f3d01983" + + "23c67293b97323c101e294e6d2cac7fb29555292675277e11c275a4b64736f6c63430008060033"; + private static final CodeCapsule codeCapsule = new CodeCapsule(ByteArray + .fromHexString(codeString)); + + @Resource + private CodeStore codeStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testGet() { + codeStore.put(contractAddr1, codeCapsule); + final CodeCapsule result = codeStore.get(contractAddr1); + assertEquals(result.toString(), Arrays.toString(ByteArray.fromHexString(codeString))); + } + + @Test + public void testGetTotalCodes() throws Exception { + codeStore.put(contractAddr1, codeCapsule); + codeStore.put(codeCapsule.getCodeHash().getBytes(), codeCapsule); + final long result = codeStore.getTotalCodes(); + assertEquals(2L, result); + } + + @Test + public void testFindCodeByHash() { + codeStore.put(codeCapsule.getCodeHash().getBytes(), codeCapsule); + final byte[] result = codeStore.findCodeByHash(codeCapsule.getCodeHash().getBytes()); + assertEquals(Arrays.toString(result), Arrays.toString(ByteArray.fromHexString(codeString))); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/ContractStoreTest.java b/framework/src/test/java/org/tron/core/db/ContractStoreTest.java new file mode 100644 index 00000000000..391a2013636 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ContractStoreTest.java @@ -0,0 +1,101 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.ContractStore; +import org.tron.protos.contract.SmartContractOuterClass; + +public class ContractStoreTest extends BaseTest { + + private static final String SMART_CONTRACT_NAME = "smart_contract_test"; + private static final String CONTRACT_ADDRESS = "111111"; + private static final long SOURCE_ENERGY_LIMIT = 10L; + private static String OWNER_ADDRESS; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, + Constant.TEST_CONF + ); + } + + @Resource + private ContractStore contractStore; + + @Before + public void init() { + SmartContractOuterClass.SmartContract.Builder contract = + createContract(CONTRACT_ADDRESS, SMART_CONTRACT_NAME); + contractStore.put( + ByteArray.fromHexString(CONTRACT_ADDRESS), + new ContractCapsule(contract.build())); + } + + private SmartContractOuterClass.SmartContract.Builder createContract( + String contractAddress, String contractName) { + OWNER_ADDRESS = + Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + SmartContractOuterClass.SmartContract.Builder builder = + SmartContractOuterClass.SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + builder.setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(contractAddress))); + builder.setOriginEnergyLimit(SOURCE_ENERGY_LIMIT); + return builder; + } + + @Test + public void testGet() { + ContractCapsule contractCapsule = contractStore.get(ByteArray.fromHexString(CONTRACT_ADDRESS)); + byte[] originAddressByte = contractCapsule.getOriginAddress(); + String address = ByteArray.toHexString(originAddressByte); + Assert.assertEquals(OWNER_ADDRESS, address); + } + + @Test + public void testPut() { + String contractAddress = "22222222"; + String contractName = "test_contract_name"; + SmartContractOuterClass.SmartContract.Builder contract = + createContract(contractAddress, contractName); + + contractStore.put( + ByteArray.fromHexString(contractAddress), + new ContractCapsule(contract.build())); + + ContractCapsule contractCapsule = contractStore.get(ByteArray.fromHexString(contractAddress)); + Assert.assertNotNull(contractCapsule); + String name = contractCapsule.getInstance().getName(); + Assert.assertEquals(contractName, name); + } + + @Test + public void testDelete() { + String contractAddress = "3333333"; + String contractName = "test_contract_name3333"; + SmartContractOuterClass.SmartContract.Builder contract = + createContract(contractAddress, contractName); + contractStore.put( + ByteArray.fromHexString(contractAddress), + new ContractCapsule(contract.build())); + ContractCapsule contractCapsule = contractStore.get(ByteArray.fromHexString(contractAddress)); + Assert.assertNotNull(contractCapsule); + String name = contractCapsule.getInstance().getName(); + Assert.assertEquals(contractName, name); + + contractStore.delete(ByteArray.fromHexString(contractAddress)); + ContractCapsule contractCapsule2 = contractStore.get(ByteArray.fromHexString(contractAddress)); + Assert.assertNull(contractCapsule2); + } +} diff --git a/framework/src/test/java/org/tron/core/db/DBIteratorTest.java b/framework/src/test/java/org/tron/core/db/DBIteratorTest.java new file mode 100644 index 00000000000..b4f7ca424c0 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/DBIteratorTest.java @@ -0,0 +1,126 @@ +package org.tron.core.db; + +import static org.fusesource.leveldbjni.JniDBFactory.factory; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.NoSuchElementException; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.Options; +import org.junit.Assert; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.rocksdb.RocksDB; +import org.rocksdb.RocksDBException; +import org.tron.core.db.common.iterator.RockStoreIterator; +import org.tron.core.db.common.iterator.StoreIterator; + +public class DBIteratorTest { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Rule + public final ExpectedException thrown = ExpectedException.none(); + + + @Test + public void testLevelDb() throws IOException { + File file = temporaryFolder.newFolder(); + try (DB db = factory.open(file, new Options().createIfMissing(true))) { + db.put("1".getBytes(StandardCharsets.UTF_8), "1".getBytes(StandardCharsets.UTF_8)); + db.put("2".getBytes(StandardCharsets.UTF_8), "2".getBytes(StandardCharsets.UTF_8)); + StoreIterator iterator = new StoreIterator(db.iterator()); + iterator.seekToFirst(); + Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.getKey()); + Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.next().getValue()); + Assert.assertTrue(iterator.hasNext()); + + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.next().getKey()); + Assert.assertFalse(iterator.hasNext()); + + try { + iterator.seekToLast(); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalStateException); + } + + iterator = new StoreIterator(db.iterator()); + iterator.seekToLast(); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getKey()); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); + iterator.seekToFirst(); + while (iterator.hasNext()) { + iterator.next(); + } + Assert.assertFalse(iterator.hasNext()); + try { + iterator.getKey(); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalStateException); + } + try { + iterator.getValue(); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalStateException); + } + thrown.expect(NoSuchElementException.class); + iterator.next(); + } + + + } + + @Test + public void testRocksDb() throws RocksDBException, IOException { + File file = temporaryFolder.newFolder(); + try (org.rocksdb.Options options = new org.rocksdb.Options().setCreateIfMissing(true); + RocksDB db = RocksDB.open(options, file.toString())) { + db.put("1".getBytes(StandardCharsets.UTF_8), "1".getBytes(StandardCharsets.UTF_8)); + db.put("2".getBytes(StandardCharsets.UTF_8), "2".getBytes(StandardCharsets.UTF_8)); + RockStoreIterator iterator = new RockStoreIterator(db.newIterator()); + iterator.seekToFirst(); + Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.getKey()); + Assert.assertArrayEquals("1".getBytes(StandardCharsets.UTF_8), iterator.next().getValue()); + Assert.assertTrue(iterator.hasNext()); + + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.next().getKey()); + Assert.assertFalse(iterator.hasNext()); + + try { + iterator.seekToLast(); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalStateException); + } + + iterator = new RockStoreIterator(db.newIterator()); + iterator.seekToLast(); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getKey()); + Assert.assertArrayEquals("2".getBytes(StandardCharsets.UTF_8), iterator.getValue()); + iterator.seekToFirst(); + while (iterator.hasNext()) { + iterator.next(); + } + Assert.assertFalse(iterator.hasNext()); + try { + iterator.getKey(); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalStateException); + } + try { + iterator.getValue(); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalStateException); + } + thrown.expect(NoSuchElementException.class); + iterator.next(); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/db/DelegatedResourceAccountIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/DelegatedResourceAccountIndexStoreTest.java new file mode 100644 index 00000000000..fd5932603e3 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/DelegatedResourceAccountIndexStoreTest.java @@ -0,0 +1,150 @@ +package org.tron.core.db; + +import com.google.common.primitives.Bytes; +import com.google.protobuf.ByteString; +import java.util.Collections; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.DecodeUtil; +import org.tron.core.Constant; +import org.tron.core.capsule.DelegatedResourceAccountIndexCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.DelegatedResourceAccountIndexStore; + + +public class DelegatedResourceAccountIndexStoreTest extends BaseTest { + + @Resource + private DelegatedResourceAccountIndexStore delegatedResourceAccountIndexStore; + + String owner1 = DecodeUtil.addressPreFixString + "548794500882809695a8a687866e76d4271a1abc"; + private static final byte[] FROM_PREFIX = {0x01}; + private static final byte[] TO_PREFIX = {0x02}; + private static final byte[] V2_FROM_PREFIX = {0x03}; + private static final byte[] V2_TO_PREFIX = {0x04}; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testGet() { + delegatedResourceAccountIndexStore.put(ByteArray.fromHexString(owner1), + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom("testGet".getBytes()))); + final DelegatedResourceAccountIndexCapsule result = + delegatedResourceAccountIndexStore.get(ByteArray.fromHexString(owner1)); + Assert.assertNotNull(result); + Assert.assertEquals(result.getAccount(), ByteString.copyFrom("testGet".getBytes())); + } + + @Test + public void testConvert() { + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = + new DelegatedResourceAccountIndexCapsule(ByteString.copyFrom("testConvert".getBytes())); + delegatedResourceAccountIndexCapsule.setAllFromAccounts( + Collections.singletonList(ByteString.copyFrom("testConvertFrom".getBytes()))); + delegatedResourceAccountIndexCapsule.setAllToAccounts( + Collections.singletonList(ByteString.copyFrom("testConvertTo".getBytes()))); + delegatedResourceAccountIndexStore.put(ByteArray.fromHexString(owner1), + delegatedResourceAccountIndexCapsule); + delegatedResourceAccountIndexStore.convert(ByteArray.fromHexString(owner1)); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule1 = + delegatedResourceAccountIndexStore.get(Bytes.concat(FROM_PREFIX, + ByteArray.fromHexString(owner1), "testConvertTo".getBytes())); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule2 = + delegatedResourceAccountIndexStore.get(Bytes.concat(TO_PREFIX, + "testConvertTo".getBytes(), ByteArray.fromHexString(owner1))); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule1); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule2); + } + + @Test + public void testDelegate() throws Exception { + delegatedResourceAccountIndexStore.delegate("testDelegateFrom".getBytes(), + "testDelegateTo".getBytes(),1L); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule1 = + delegatedResourceAccountIndexStore.get(Bytes.concat(FROM_PREFIX, + "testDelegateFrom".getBytes(), "testDelegateTo".getBytes())); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule2 = + delegatedResourceAccountIndexStore.get(Bytes.concat(TO_PREFIX, "testDelegateTo".getBytes(), + "testDelegateFrom".getBytes())); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule1); + Assert.assertEquals(delegatedResourceAccountIndexCapsule1.getTimestamp(),1); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule2); + Assert.assertEquals(delegatedResourceAccountIndexCapsule2.getTimestamp(),1); + } + + @Test + public void testDelegateV2() { + delegatedResourceAccountIndexStore.delegateV2("testDelegatev2From".getBytes(), + "testDelegatev2To".getBytes(),2L); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule1 = + delegatedResourceAccountIndexStore.get(Bytes.concat(V2_FROM_PREFIX, + "testDelegatev2From".getBytes(), "testDelegatev2To".getBytes())); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule2 = + delegatedResourceAccountIndexStore.get(Bytes.concat(V2_TO_PREFIX, + "testDelegatev2To".getBytes(), "testDelegatev2From".getBytes())); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule1); + Assert.assertEquals(delegatedResourceAccountIndexCapsule1.getTimestamp(),2); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule2); + Assert.assertEquals(delegatedResourceAccountIndexCapsule2.getTimestamp(),2); + } + + @Test + public void testUnDelegate() throws Exception { + delegatedResourceAccountIndexStore.delegate("testDelegateFrom".getBytes(), + "testDelegateTo".getBytes(),1L); + delegatedResourceAccountIndexStore.unDelegate("testDelegateFrom".getBytes(), + "testDelegateTo".getBytes()); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule1 = + delegatedResourceAccountIndexStore.get(Bytes.concat(FROM_PREFIX, + "testDelegateFrom".getBytes(), "testDelegateTo".getBytes())); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule2 = + delegatedResourceAccountIndexStore.get(Bytes.concat(TO_PREFIX, + "testDelegateTo".getBytes(), "testDelegateFrom".getBytes())); + Assert.assertNull(delegatedResourceAccountIndexCapsule1); + Assert.assertNull(delegatedResourceAccountIndexCapsule2); + } + + @Test + public void testUnDelegateV2() { + delegatedResourceAccountIndexStore.delegateV2("testDelegateFrom".getBytes(), + "testDelegateTo".getBytes(),1L); + delegatedResourceAccountIndexStore.unDelegateV2("testDelegateFrom".getBytes(), + "testDelegateTo".getBytes()); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule1 = + delegatedResourceAccountIndexStore.get(Bytes.concat(V2_FROM_PREFIX, + "testDelegateFrom".getBytes(), "testDelegateTo".getBytes())); + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule2 = + delegatedResourceAccountIndexStore.get(Bytes.concat(V2_TO_PREFIX, + "testDelegateTo".getBytes(), "testDelegateFrom".getBytes())); + Assert.assertNull(delegatedResourceAccountIndexCapsule1); + Assert.assertNull(delegatedResourceAccountIndexCapsule2); + } + + @Test + public void testGetIndex() throws Exception { + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = + delegatedResourceAccountIndexStore.getIndex("testGetIndex".getBytes()); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule.getFromAccountsList()); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule.getToAccountsList()); + } + + @Test + public void testGetV2Index() { + DelegatedResourceAccountIndexCapsule delegatedResourceAccountIndexCapsule = + delegatedResourceAccountIndexStore.getV2Index("testGetV2Index".getBytes()); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule.getFromAccountsList()); + Assert.assertNotNull(delegatedResourceAccountIndexCapsule.getToAccountsList()); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/DelegatedResourceStoreTest.java b/framework/src/test/java/org/tron/core/db/DelegatedResourceStoreTest.java new file mode 100644 index 00000000000..905ef0384f1 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/DelegatedResourceStoreTest.java @@ -0,0 +1,86 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.DelegatedResourceCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.DelegatedResourceStore; + +public class DelegatedResourceStoreTest extends BaseTest { + private static final long BALANCE = 1_000_000; + private static final long EXPIRE_TIME = 1000L; + private static final String OWNER_ADDRESS = "111111111111"; + private static final String RECEIVER_ADDRESS = "222222222222"; + private static DelegatedResourceCapsule delegatedResourceCapsule; + + @Resource + private DelegatedResourceStore delegatedResourceStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, + Constant.TEST_CONF + ); + } + + @Before + public void init() { + delegatedResourceCapsule = create(OWNER_ADDRESS); + delegatedResourceStore.put(delegatedResourceCapsule.createDbKey(), + delegatedResourceCapsule); + } + + @Test + public void testGet() { + DelegatedResourceCapsule delegatedResource = delegatedResourceStore + .get(delegatedResourceCapsule.createDbKey()); + Assert.assertNotNull(delegatedResource); + Assert.assertEquals(delegatedResourceCapsule.getFrom(), delegatedResource.getFrom()); + } + + @Test + public void testPut() { + DelegatedResourceCapsule delegatedResourceCapsule = create("333333333333"); + byte[] key = delegatedResourceCapsule.createDbKey(); + delegatedResourceStore.put(key, delegatedResourceCapsule); + + DelegatedResourceCapsule delegatedResourceCapsule1 = delegatedResourceStore.get(key); + Assert.assertNotNull(delegatedResourceCapsule1); + Assert.assertEquals(BALANCE, delegatedResourceCapsule1.getFrozenBalanceForEnergy()); + } + + @Test + public void testDelete() { + DelegatedResourceCapsule delegatedResourceCapsule = create("444444444"); + byte[] key = delegatedResourceCapsule.createDbKey(); + delegatedResourceStore.put(key, delegatedResourceCapsule); + DelegatedResourceCapsule delegatedResourceCapsule1 = delegatedResourceStore.get(key); + Assert.assertNotNull(delegatedResourceCapsule1); + Assert.assertEquals(BALANCE, delegatedResourceCapsule1.getFrozenBalanceForEnergy()); + + delegatedResourceStore.delete(key); + DelegatedResourceCapsule delegatedResourceCapsule2 = delegatedResourceStore.get(key); + Assert.assertNull(delegatedResourceCapsule2); + + } + + public DelegatedResourceCapsule create(String address) { + byte[] ownerAddress = ByteArray.fromHexString(address); + byte[] receiverAddress = ByteArray.fromHexString(RECEIVER_ADDRESS); + DelegatedResourceCapsule delegatedResourceCapsule = new DelegatedResourceCapsule( + ByteString.copyFrom(ownerAddress), + ByteString.copyFrom(receiverAddress)); + + delegatedResourceCapsule.setFrozenBalanceForEnergy(BALANCE, EXPIRE_TIME); + return delegatedResourceCapsule; + } + +} diff --git a/framework/src/test/java/org/tron/core/db/DelegationStoreTest.java b/framework/src/test/java/org/tron/core/db/DelegationStoreTest.java new file mode 100644 index 00000000000..10e70a0a83b --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/DelegationStoreTest.java @@ -0,0 +1,88 @@ +package org.tron.core.db; + +import javax.annotation.Resource; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.DelegationStore; + + +public class DelegationStoreTest extends BaseTest { + + private static final String OWNER_ADDRESS = "11111111111"; + private static final long CYCLE = 100; + private static final long VALUE = 10_000_000; + + @Resource + private DelegationStore delegationStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, + Constant.TEST_CONF + ); + } + + @Before + public void init() { + create(); + } + + public void create() { + byte[] key = buildRewardKey(CYCLE, ByteArray.fromHexString(OWNER_ADDRESS)); + delegationStore.put(key, new BytesCapsule(ByteArray + .fromLong(VALUE))); + } + + private byte[] buildRewardKey(long cycle, byte[] address) { + return (cycle + "-" + Hex.toHexString(address) + "-reward").getBytes(); + } + + @Test + public void testGet() { + byte[] key = buildRewardKey(CYCLE, ByteArray.fromHexString(OWNER_ADDRESS)); + BytesCapsule bytesCapsule = delegationStore.get(key); + Assert.assertNotNull(bytesCapsule); + long actualValue = ByteArray.toLong(bytesCapsule.getData()); + Assert.assertEquals(VALUE, actualValue); + } + + @Test + public void testPut() { + long value = 20_000_000; + byte[] key = buildRewardKey(CYCLE, ByteArray.fromHexString("2222222222222")); + delegationStore.put(key, new BytesCapsule(ByteArray + .fromLong(20_000_000))); + + BytesCapsule bytesCapsule = delegationStore.get(key); + Assert.assertNotNull(bytesCapsule); + long actualValue = ByteArray.toLong(bytesCapsule.getData()); + Assert.assertEquals(value, actualValue); + } + + @Test + public void testDelete() { + long value = 20_000_000; + byte[] key = buildRewardKey(CYCLE, ByteArray.fromHexString("33333333")); + delegationStore.put(key, new BytesCapsule(ByteArray + .fromLong(20_000_000))); + + BytesCapsule bytesCapsule = delegationStore.get(key); + Assert.assertNotNull(bytesCapsule); + long actualValue = ByteArray.toLong(bytesCapsule.getData()); + Assert.assertEquals(value, actualValue); + + delegationStore.delete(key); + BytesCapsule bytesCapsule1 = delegationStore.getUnchecked(key); + Assert.assertNull(bytesCapsule1.getData()); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java b/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java index 7700dbdead2..995d9e01ecb 100644 --- a/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java +++ b/framework/src/test/java/org/tron/core/db/EnergyPriceHistoryLoaderTest.java @@ -8,21 +8,14 @@ import static org.tron.core.utils.ProposalUtil.ProposalType.TRANSACTION_FEE; import static org.tron.core.utils.ProposalUtil.ProposalType.WITNESS_127_PAY_PER_BLOCK; -import java.io.File; import java.util.HashMap; import java.util.Map; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Ignore; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.ChainBaseManager; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db.api.EnergyPriceHistoryLoader; import org.tron.core.store.ProposalStore; @@ -31,11 +24,8 @@ @Slf4j -public class EnergyPriceHistoryLoaderTest { +public class EnergyPriceHistoryLoaderTest extends BaseTest { - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static String dbPath = "output-EnergyPriceHistoryLoaderTest-test"; private static long t1 = 1542607200000L; private static long price1 = 20; private static long t3 = 1544724000000L; @@ -46,24 +36,7 @@ public class EnergyPriceHistoryLoaderTest { private static long price5 = 140L; static { - Args.setParam(new String[] {"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - chainBaseManager = context.getBean(ChainBaseManager.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[] {"--output-directory", dbPath()}, Constant.TEST_CONF); } public void initDB() { @@ -103,7 +76,7 @@ public void initDB() { initProposal(parameters, 1572609600000L, State.CANCELED); } - private static void initProposal(long code, long timestamp, long price, State state) { + private void initProposal(long code, long timestamp, long price, State state) { long id = chainBaseManager.getDynamicPropertiesStore().getLatestProposalNum() + 1; Proposal proposal = Proposal.newBuilder().putParameters(code, price) @@ -117,7 +90,7 @@ private static void initProposal(long code, long timestamp, long price, State st chainBaseManager.getDynamicPropertiesStore().saveLatestProposalNum(id); } - private static void initProposal(Map parameters, long timestamp, State state) { + private void initProposal(Map parameters, long timestamp, State state) { long id = chainBaseManager.getDynamicPropertiesStore().getLatestProposalNum() + 1; Proposal proposal = Proposal.newBuilder().putAllParameters(parameters) @@ -133,9 +106,6 @@ private static void initProposal(Map parameters, long timestamp, Sta @Test public void testLoader() { - if (chainBaseManager == null) { - init(); - } EnergyPriceHistoryLoader loader = new EnergyPriceHistoryLoader(chainBaseManager); initDB(); @@ -155,10 +125,6 @@ public void testLoader() { @Test public void testProposalEmpty() { - if (chainBaseManager == null) { - init(); - } - // clean DB firstly ProposalStore proposalStore = chainBaseManager.getProposalStore(); proposalStore.forEach( diff --git a/framework/src/test/java/org/tron/core/db/ExchangeStoreTest.java b/framework/src/test/java/org/tron/core/db/ExchangeStoreTest.java new file mode 100644 index 00000000000..685c137422c --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ExchangeStoreTest.java @@ -0,0 +1,87 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import java.util.List; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.ExchangeCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.ExchangeStore; +import org.tron.protos.Protocol; + +public class ExchangeStoreTest extends BaseTest { + + @Resource + private ExchangeStore exchangeStore; + private byte[] exchangeKey1; + private byte[] exchangeKey2; + + static { + Args.setParam( + new String[] { + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Before + public void init() { + Protocol.Exchange.Builder builder = Protocol.Exchange.newBuilder(); + builder.setExchangeId(1L).setCreatorAddress(ByteString.copyFromUtf8("Address1")); + ExchangeCapsule exchangeCapsule = new ExchangeCapsule(builder.build()); + exchangeKey1 = exchangeCapsule.createDbKey(); + chainBaseManager.getExchangeStore().put(exchangeKey1, exchangeCapsule); + builder.setExchangeId(2L).setCreatorAddress(ByteString.copyFromUtf8("Address2")); + exchangeCapsule = new ExchangeCapsule(builder.build()); + exchangeKey2 = exchangeCapsule.createDbKey(); + chainBaseManager.getExchangeStore().put(exchangeKey2, exchangeCapsule); + } + + + @Test + public void testGet() throws Exception { + final ExchangeCapsule result = exchangeStore.get(exchangeKey1); + Assert.assertNotNull(result); + Assert.assertEquals(result.getID(), 1); + } + + @Test + public void testPut() throws ItemNotFoundException { + Protocol.Exchange.Builder builder = Protocol.Exchange.newBuilder(); + builder.setExchangeId(1L).setCreatorAddress(ByteString.copyFromUtf8("Address1")); + ExchangeCapsule exchangeCapsule = new ExchangeCapsule(builder.build()); + exchangeKey1 = exchangeCapsule.createDbKey(); + chainBaseManager.getExchangeStore().put(exchangeKey1, exchangeCapsule); + + final ExchangeCapsule result = exchangeStore.get(exchangeKey1); + Assert.assertNotNull(result); + Assert.assertEquals(result.getID(), 1); + } + + @Test + public void testDelete() throws Exception { + final ExchangeCapsule result = exchangeStore.get(exchangeKey1); + Assert.assertNotNull(result); + Assert.assertEquals(result.getID(), 1); + + exchangeStore.delete(exchangeKey1); + ExchangeCapsule exchangeCapsule = exchangeStore.getUnchecked(exchangeKey1); + Assert.assertNull(exchangeCapsule); + } + + @Test + public void testGetAllExchanges() { + List exchangeCapsuleList = exchangeStore.getAllExchanges(); + ExchangeCapsule exchangeCapsule1 = exchangeCapsuleList.get(0); + ExchangeCapsule exchangeCapsule2 = exchangeCapsuleList.get(1); + Assert.assertEquals(exchangeCapsuleList.size(), 2); + Assert.assertEquals(exchangeCapsule1.getCreatorAddress(), ByteString.copyFromUtf8("Address1")); + Assert.assertEquals(exchangeCapsule2.getCreatorAddress(), ByteString.copyFromUtf8("Address2")); + } +} diff --git a/framework/src/test/java/org/tron/core/db/ExchangeV2StoreTest.java b/framework/src/test/java/org/tron/core/db/ExchangeV2StoreTest.java new file mode 100644 index 00000000000..97c5f599b6e --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ExchangeV2StoreTest.java @@ -0,0 +1,70 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.ExchangeCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.ExchangeV2Store; +import org.tron.protos.Protocol; + +public class ExchangeV2StoreTest extends BaseTest { + + @Resource + private ExchangeV2Store exchangeV2Store; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testGet() throws Exception { + byte[] key = putToExchangeV2(); + final ExchangeCapsule result = exchangeV2Store.get(key); + Assert.assertNotNull(result); + Assert.assertEquals(result.getID(), 1); + } + + @Test + public void testPut() throws ItemNotFoundException { + Protocol.Exchange.Builder builder = Protocol.Exchange.newBuilder().setExchangeId(1L) + .setCreatorAddress(ByteString.copyFromUtf8("Address2")); + ExchangeCapsule exchangeCapsule = new ExchangeCapsule(builder.build()); + byte[] exchangeKey1 = exchangeCapsule.createDbKey(); + exchangeV2Store.put(exchangeKey1, exchangeCapsule); + + final ExchangeCapsule result = exchangeV2Store.get(exchangeKey1); + Assert.assertNotNull(result); + Assert.assertEquals(result.getID(), 1); + } + + @Test + public void testDelete() throws ItemNotFoundException { + Protocol.Exchange.Builder builder = Protocol.Exchange.newBuilder().setExchangeId(1L) + .setCreatorAddress(ByteString.copyFromUtf8("Address3")); + ExchangeCapsule exchangeCapsule = new ExchangeCapsule(builder.build()); + byte[] exchangeKey1 = exchangeCapsule.createDbKey(); + exchangeV2Store.put(exchangeKey1, exchangeCapsule); + exchangeV2Store.delete(exchangeKey1); + ExchangeCapsule result = exchangeV2Store.getUnchecked(exchangeKey1); + Assert.assertNull(result); + } + + private byte[] putToExchangeV2() { + Protocol.Exchange.Builder builder = Protocol.Exchange.newBuilder().setExchangeId(1L) + .setCreatorAddress(ByteString.copyFromUtf8("Address1")); + ExchangeCapsule exchangeCapsule = new ExchangeCapsule(builder.build()); + byte[] exchangeKey1 = exchangeCapsule.createDbKey(); + exchangeV2Store.put(exchangeKey1, exchangeCapsule); + return exchangeKey1; + } +} diff --git a/framework/src/test/java/org/tron/core/db/IncrementalMerkleTreeStoreTest.java b/framework/src/test/java/org/tron/core/db/IncrementalMerkleTreeStoreTest.java new file mode 100644 index 00000000000..643f86d3fe5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/IncrementalMerkleTreeStoreTest.java @@ -0,0 +1,51 @@ +package org.tron.core.db; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.IncrementalMerkleTreeCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.IncrementalMerkleTreeStore; + +public class IncrementalMerkleTreeStoreTest extends BaseTest { + + private static final byte[] incrementalMerkleTreeData = {10, 0}; + + @Resource + private IncrementalMerkleTreeStore incrementalMerkleTreeStore; + + static { + Args.setParam( + new String[] { + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Before + public void init() { + incrementalMerkleTreeStore.put("Address1".getBytes(), new IncrementalMerkleTreeCapsule( + incrementalMerkleTreeData)); + } + + @Test + public void testGet() throws Exception { + final IncrementalMerkleTreeCapsule result = + incrementalMerkleTreeStore.get("Address1".getBytes()); + Assert.assertNotNull(result); + Assert.assertEquals(result.getInstance(), new IncrementalMerkleTreeCapsule( + incrementalMerkleTreeData).getInstance()); + } + + @Test + public void testContain() throws Exception { + final boolean result1 = incrementalMerkleTreeStore.contain("Address1".getBytes()); + final boolean result2 = incrementalMerkleTreeStore.contain("Address2".getBytes()); + Assert.assertTrue(result1); + Assert.assertFalse(result2); + } +} diff --git a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java index 031bb47eba2..72214c6743e 100644 --- a/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java +++ b/framework/src/test/java/org/tron/core/db/KhaosDatabaseTest.java @@ -1,25 +1,21 @@ package org.tron.core.db; +import com.google.common.collect.Lists; import com.google.protobuf.ByteString; -import java.io.File; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Pair; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadNumberBlockException; import org.tron.core.exception.NonCommonBlockException; @@ -29,29 +25,15 @@ import org.tron.protos.Protocol.BlockHeader.raw; @Slf4j -public class KhaosDatabaseTest { +public class KhaosDatabaseTest extends BaseTest { - private static final String dbPath = "output-khaosDatabase-test"; - private static KhaosDatabase khaosDatabase; - private static TronApplicationContext context; + @Resource + private KhaosDatabase khaosDatabase; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } - @BeforeClass - public static void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - khaosDatabase = context.getBean(KhaosDatabase.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } @Test public void testStartBlock() { diff --git a/framework/src/test/java/org/tron/core/db/ManagerMockTest.java b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java new file mode 100644 index 00000000000..364b86c82b4 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ManagerMockTest.java @@ -0,0 +1,441 @@ +package org.tron.core.db; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; + +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +import org.tron.common.cron.CronExpression; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.runtime.ProgramResult; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.capsule.TransactionInfoCapsule; +import org.tron.core.capsule.utils.TransactionUtil; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ContractSizeNotEqualToOneException; +import org.tron.core.exception.DupTransactionException; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.ReceiptCheckErrException; +import org.tron.core.exception.TaposException; +import org.tron.core.exception.TooBigTransactionException; +import org.tron.core.exception.TooBigTransactionResultException; +import org.tron.core.exception.TransactionExpirationException; +import org.tron.core.exception.ValidateSignatureException; +import org.tron.core.store.AccountStore; +import org.tron.core.store.BalanceTraceStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +@Slf4j +public class ManagerMockTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + @Test + public void processTransactionCostTimeMoreThan100() throws Exception { + TransactionTrace traceMock = mock(TransactionTrace.class); + BandwidthProcessor bandwidthProcessorMock = mock(BandwidthProcessor.class); + try (MockedConstruction mockedConstruction2 + = mockConstruction(TransactionTrace.class,(mock, context) -> { + when(mock).thenReturn(traceMock); }); + MockedConstruction mockedConstruction3 + = mockConstruction(BandwidthProcessor.class,(mock, context) -> { + when(mock).thenReturn(bandwidthProcessorMock); + }); + MockedStatic mockedStatic = mockStatic(TransactionUtil.class)) { + Manager dbManager = mock(Manager.class); + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6666; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract( + Protocol.Transaction.Contract.newBuilder() + .setParameter(Any.pack(transferContract)) + .setType(Protocol.Transaction.Contract.ContractType.TransferContract))) + .build(); + TransactionCapsule trxCap = new TransactionCapsule(transaction); + ProgramResult result = new ProgramResult(); + result.setResultCode(Protocol.Transaction.Result.contractResult.SUCCESS); + + Sha256Hash transactionId = trxCap.getTransactionId(); + TransactionCapsule trxCapMock = mock(TransactionCapsule.class); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + BalanceTraceStore balanceTraceStoreMock = mock(BalanceTraceStore.class); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + TransactionInfoCapsule transactionInfoCapsuleMock = mock(TransactionInfoCapsule.class); + Protocol.TransactionInfo transactionInfo = Protocol.TransactionInfo.newBuilder().build(); + + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + + BlockCapsule blockCapMock = Mockito.mock(BlockCapsule.class); + + when(TransactionUtil + .buildTransactionInfoInstance(trxCapMock, blockCapMock, traceMock)) + .thenReturn(transactionInfoCapsuleMock); + + // this make cost > 100 cond is true + when(blockCapMock.isMerkleRootEmpty()).thenAnswer(new Answer() { + @Override + public Boolean answer(InvocationOnMock invocation) throws Throwable { + Thread.sleep(100); + return true; + } + }); + + when(chainBaseManagerMock.getBalanceTraceStore()).thenReturn(balanceTraceStoreMock); + when(chainBaseManagerMock.getAccountStore()).thenReturn(mock(AccountStore.class)); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(mock(DynamicPropertiesStore.class)); + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + when(trxCapMock.getTransactionId()).thenReturn(transactionId); + when(traceMock.getRuntimeResult()).thenReturn(result); + when(transactionInfoCapsuleMock.getId()).thenReturn(transactionId.getBytes()); + when(transactionInfoCapsuleMock.getInstance()).thenReturn(transactionInfo); + when(trxCapMock.getInstance()).thenReturn(trxCap.getInstance()); + when(trxCapMock.validatePubSignature( + Mockito.any(AccountStore.class), + Mockito.any(DynamicPropertiesStore.class))).thenReturn(true); + when(trxCapMock.validateSignature( + Mockito.any(AccountStore.class), + Mockito.any(DynamicPropertiesStore.class))).thenReturn(true); + + doNothing().when(dbManager).validateTapos(trxCapMock); + doNothing().when(dbManager).validateCommon(trxCapMock); + doNothing().when(dbManager).validateDup(trxCapMock); + + + doNothing().when(transactionStoreMock).put(transactionId.getBytes(), trxCapMock); + doNothing().when(bandwidthProcessorMock).consume(trxCapMock, traceMock); + doNothing().when(dbManager).consumeBandwidth(trxCapMock, traceMock); + doNothing().when(balanceTraceStoreMock).initCurrentTransactionBalanceTrace(trxCapMock); + doNothing().when(balanceTraceStoreMock).updateCurrentTransactionStatus(anyString()); + doNothing().when(balanceTraceStoreMock).resetCurrentTransactionTrace(); + + + assertNotNull( + when(dbManager.processTransaction(trxCapMock, blockCapMock)).thenCallRealMethod() + ); + } + } + + private void initMockEnv(Manager dbManager, long headNum, long headTime, + long exitHeight, long exitCount, String blockTime) + throws Exception { + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Args argsMock = mock(Args.class); + + when(Args.getInstance()).thenReturn(argsMock); + + when(chainBaseManagerMock.getHeadBlockNum()).thenReturn(headNum); + when(chainBaseManagerMock.getHeadBlockTimeStamp()).thenReturn(headTime); + + when(argsMock.getShutdownBlockHeight()).thenReturn(exitHeight); + when(argsMock.getShutdownBlockCount()).thenReturn(exitCount); + when(argsMock.isP2pDisable()).thenReturn(false); + when(argsMock.getShutdownBlockTime()) + .thenReturn(new CronExpression(blockTime)); //"0 0 12 * * ?" + + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + } + + @Test + public void testInitAutoStop() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager, 100L, 12345L, + 10L, 0L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockHeight 10 is less than headNum 100", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop1() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 12345L, + 100L, 0L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockCount 0 is less than 1", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + } + + @Test + public void testInitAutoStop2() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 99726143865000L, + 100L, 1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockTime 0 0 12 * * ? is illegal", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop3() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 12345L, + 100L, 1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockHeight 100 and shutDownBlockCount 1 set both", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop4() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager, 10L, 12345L, + 100L, -1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockHeight 100 and shutDownBlockTime 0 0 12 * * ? set both", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testInitAutoStop5() throws Exception { + Manager dbManager = spy(new Manager()); + try (MockedStatic methodTestMockedStatic + = mockStatic(CommonParameter.class)) { + initMockEnv(dbManager,10L, 12345L, + 0L, 1L, "0 0 12 * * ?"); + + assertThrows( + "shutDownBlockCount 1 and shutDownBlockTime 0 0 12 * * ? set both", + Exception.class, + () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "initAutoStop"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + ); + } + + } + + @Test + public void testProcessTransaction() throws Exception { + Manager dbManager = spy(new Manager()); + TransactionCapsule transactionCapsuleMock = null; + BlockCapsule blockCapsuleMock = mock(BlockCapsule.class); + + Method privateMethod = Manager.class.getDeclaredMethod( + "processTransaction", + TransactionCapsule.class, BlockCapsule.class); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager, transactionCapsuleMock, blockCapsuleMock); + } + + @Test + public void testProcessTransaction1() { + Manager dbManager = spy(new Manager()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder() + .setData(ByteString.copyFrom("sb.toString()".getBytes(StandardCharsets.UTF_8)))) + .build(); + TransactionCapsule trxCap = new TransactionCapsule(transaction); + + BlockCapsule blockCapsuleMock = mock(BlockCapsule.class); + + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + Method privateMethod = Manager.class.getDeclaredMethod( + "processTransaction", + TransactionCapsule.class, BlockCapsule.class); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager, trxCap, blockCapsuleMock); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof ContractSizeNotEqualToOneException); + } + + @SneakyThrows + @Test + public void testRePush() { + Manager dbManager = spy(new Manager()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + when(transactionStoreMock.has(any())).thenReturn(true); + + dbManager.rePush(trx); + } + + @SneakyThrows + @Test + public void testRePush1() { + Manager dbManager = spy(new Manager()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + TransactionStore transactionStoreMock = mock(TransactionStore.class); + + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + + when(chainBaseManagerMock.getTransactionStore()).thenReturn(transactionStoreMock); + when(transactionStoreMock.has(any())).thenReturn(false); + + doThrow(new ValidateSignatureException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new DupTransactionException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TaposException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TooBigTransactionException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TransactionExpirationException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new ReceiptCheckErrException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + + doThrow(new TooBigTransactionResultException()).when(dbManager).pushTransaction(any()); + dbManager.rePush(trx); + } + + @Test + public void testPostSolidityFilter() throws Exception { + Manager dbManager = spy(new Manager()); + + Method privateMethod = Manager.class.getDeclaredMethod( + "postSolidityFilter", long.class, long.class); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager, 100L, 10L); + } + + @Test + public void testReOrgLogsFilter() throws Exception { + Manager dbManager = spy(new Manager()); + CommonParameter commonParameterMock = mock(Args.class); + mockStatic(CommonParameter.class); + ChainBaseManager chainBaseManagerMock = mock(ChainBaseManager.class); + + when(CommonParameter.getInstance()).thenReturn(commonParameterMock); + when(commonParameterMock.isJsonRpcHttpFullNodeEnable()).thenReturn(true); + when(chainBaseManagerMock.getDynamicPropertiesStore()) + .thenReturn(mock(DynamicPropertiesStore.class)); + Field field = dbManager.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(dbManager, chainBaseManagerMock); + doThrow(new ItemNotFoundException()).when(chainBaseManagerMock).getBlockById(any()); + + Method privateMethod = Manager.class.getDeclaredMethod("reOrgLogsFilter"); + privateMethod.setAccessible(true); + privateMethod.invoke(dbManager); + } + +} \ No newline at end of file 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 47e506a808f..db219377b74 100755 --- a/framework/src/test/java/org/tron/core/db/ManagerTest.java +++ b/framework/src/test/java/org/tron/core/db/ManagerTest.java @@ -1,16 +1,28 @@ package org.tron.core.db; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.spy; import static org.tron.common.utils.Commons.adjustAssetBalanceV2; -import static org.tron.common.utils.Commons.adjustBalance; import static org.tron.common.utils.Commons.adjustTotalShieldedPoolValue; import static org.tron.common.utils.Commons.getExchangeStoreFinal; +import static org.tron.common.utils.StringUtil.encode58Check; +import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED; +import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS; +import com.beust.jcommander.internal.Lists; import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; import java.util.stream.IntStream; @@ -18,11 +30,18 @@ import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.TronApplicationContext; import org.tron.common.crypto.ECKey; +import org.tron.common.runtime.RuntimeImpl; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.Commons; +import org.tron.common.utils.JsonUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.StringUtil; import org.tron.common.utils.Utils; @@ -36,8 +55,12 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.WitnessCapsule; import org.tron.core.config.DefaultConfig; +import org.tron.core.config.Parameter; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; +import org.tron.core.db.accountstate.AccountStateEntity; +import org.tron.core.db.accountstate.TrieService; +import org.tron.core.db.accountstate.storetrie.AccountStateStoreTrie; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadBlockException; import org.tron.core.exception.BadItemException; @@ -55,16 +78,20 @@ import org.tron.core.exception.TooBigTransactionException; import org.tron.core.exception.TooBigTransactionResultException; import org.tron.core.exception.TransactionExpirationException; +import org.tron.core.exception.TronError; import org.tron.core.exception.UnLinkedBlockException; import org.tron.core.exception.VMIllegalException; import org.tron.core.exception.ValidateScheduleException; import org.tron.core.exception.ValidateSignatureException; import org.tron.core.exception.ZksnarkException; +import org.tron.core.store.AccountStore; import org.tron.core.store.CodeStore; import org.tron.core.store.DynamicPropertiesStore; import org.tron.core.store.ExchangeStore; import org.tron.core.store.ExchangeV2Store; import org.tron.core.store.IncrementalMerkleTreeStore; +import org.tron.core.store.StoreFactory; +import org.tron.protos.Protocol; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.Transaction; @@ -85,14 +112,18 @@ public class ManagerTest extends BlockGenerate { private static DposSlot dposSlot; private static TronApplicationContext context; private static BlockCapsule blockCapsule2; - private static String dbPath = "output_manager_test"; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); private static AtomicInteger port = new AtomicInteger(0); private static String accountAddress = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; + private final String privateKey = PublicMethod.getRandomPrivateKey(); + private LocalWitnesses localWitnesses; @Before - public void init() { - Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); + public void init() throws IOException { + Args.setParam(new String[]{"-d", + temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); context = new TronApplicationContext(DefaultConfig.class); @@ -102,6 +133,12 @@ public void init() { consensusService = context.getBean(ConsensusService.class); consensusService.start(); chainManager = dbManager.getChainBaseManager(); + + localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(privateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + blockCapsule2 = new BlockCapsule( 1, @@ -117,13 +154,56 @@ public void init() { blockCapsule2.setMerkleRoot(); blockCapsule2.sign( ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); + Assert.assertTrue(dbManager.getMaxFlushCount() == 200); + + byte[] address = PublicMethod.getAddressByteByPrivateKey(privateKey); + ByteString addressByte = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressByte); + chainManager.getWitnessStore().put(addressByte.toByteArray(), witnessCapsule); + chainManager.addWitness(addressByte); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + chainManager.getAccountStore().put(addressByte.toByteArray(), accountCapsule); } @After public void removeDb() { Args.clearParam(); context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + } + + @Test + public void updateRecentTransaction() throws Exception { + TransferContract tc = + TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + TransactionCapsule trx = new TransactionCapsule(tc, ContractType.TransferContract); + BlockCapsule b = new BlockCapsule(1, chainManager.getGenesisBlockId(), + 0, ByteString.copyFrom(new byte[64])); + b.addTransaction(trx); + dbManager.updateRecentTransaction(b); + try { + dbManager.consumeBandwidth(trx, new TransactionTrace(trx, StoreFactory.getInstance(), + new RuntimeImpl())); + } catch (Exception e) { + Assert.assertTrue(e instanceof ContractValidateException); + } + dbManager.consumeMemoFee(trx, new TransactionTrace(trx, StoreFactory.getInstance(), + new RuntimeImpl())); + Assert.assertTrue(dbManager.getTxListFromPending().isEmpty()); + Assert.assertNull(dbManager.getTxFromPending(trx.getTransactionId().toString())); + Assert.assertEquals(0, dbManager.getPendingSize()); + Assert.assertEquals(1, chainManager.getRecentTransactionStore().size()); + byte[] key = ByteArray.subArray(ByteArray.fromLong(1), 6, 8); + byte[] value = chainManager.getRecentTransactionStore().get(key).getData(); + RecentTransactionItem item = JsonUtil.json2Obj(new String(value), RecentTransactionItem.class); + Assert.assertEquals(1, item.getNum()); + Assert.assertEquals(1, item.getTransactionIds().size()); + Assert.assertEquals(trx.getTransactionId().toString(), item.getTransactionIds().get(0)); } @Test @@ -156,6 +236,7 @@ public void setBlockReference() .setToAddress(ByteString.copyFromUtf8("bbb")) .build(); TransactionCapsule trx = new TransactionCapsule(tc, ContractType.TransferContract); + if (chainManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 0) { dbManager.pushBlock(blockCapsule); Assert.assertEquals(1, @@ -187,6 +268,9 @@ public void pushBlock() { } catch (Exception e) { Assert.assertTrue("pushBlock is error", false); } + TrieService trieService = context.getBean(TrieService.class); + Assert.assertTrue(trieService.getFullAccountStateRootHash().length > 0); + Assert.assertTrue(trieService.getSolidityAccountStateRootHash().length > 0); if (isUnlinked) { Assert.assertEquals("getBlockIdByNum is error", @@ -202,9 +286,56 @@ public void pushBlock() { } } + try { + chainManager.getBlockIdByNum(-1); + Assert.fail(); + } catch (ItemNotFoundException e) { + Assert.assertTrue(true); + } + try { + dbManager.getBlockChainHashesOnFork(blockCapsule2.getBlockId()); + } catch (Exception e) { + Assert.assertTrue(e instanceof NonCommonBlockException); + } Assert.assertTrue("hasBlocks is error", chainManager.hasBlocks()); } + @Test + public void transactionTest() { + TransactionCapsule trans0 = new TransactionCapsule(Transaction.newBuilder() + .setRawData(Transaction.raw.newBuilder().setData(ByteString.copyFrom( + new byte[Parameter.ChainConstant.BLOCK_SIZE + Constant.ONE_THOUSAND]))).build(), + ContractType.ShieldedTransferContract); + ShieldContract.ShieldedTransferContract trx1 = ShieldContract.ShieldedTransferContract + .newBuilder() + .setFromAmount(10) + .setToAmount(10) + .build(); + TransactionCapsule trans = new TransactionCapsule(trx1, ContractType.ShieldedTransferContract); + try { + dbManager.pushTransaction(trans0); + dbManager.pushTransaction(trans); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + dbManager.rePush(trans0); + ReflectUtils.invokeMethod(dbManager,"filterOwnerAddress", + new Class[]{trans.getClass(), Set.class},trans, Sets.newHashSet()); + Assert.assertNotNull(dbManager.getTxListFromPending()); + + try { + dbManager.validateTapos(trans); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + try { + dbManager.pushVerifiedBlock(chainManager.getHead()); + dbManager.getBlockChainHashesOnFork(chainManager.getHeadBlockId()); + } catch (Exception e) { + Assert.assertTrue(e instanceof TaposException); + } + } + @Test public void GetterInstanceTest() { @@ -228,6 +359,24 @@ public void GetterInstanceTest() { } + @Test + public void entityTest() { + AccountStateStoreTrie trie = context.getBean(AccountStateStoreTrie.class); + Assert.assertNull(trie.getAccount("".getBytes())); + Assert.assertNull(trie.getAccount("".getBytes(), "".getBytes())); + Assert.assertNull(trie.getSolidityAccount("".getBytes())); + Assert.assertTrue(trie.isEmpty()); + AccountStateEntity entity = new AccountStateEntity(); + AccountStateEntity parsedEntity = AccountStateEntity.parse("".getBytes()); + Assert.assertNotNull(parsedEntity); + Assert.assertNotNull(parsedEntity.getAccount()); + Assert.assertNotNull(org.tron.core.db.api.pojo.Account.of()); + Assert.assertNotNull(org.tron.core.db.api.pojo.AssetIssue.of()); + Assert.assertNotNull(org.tron.core.db.api.pojo.Block.of()); + Assert.assertNotNull(org.tron.core.db.api.pojo.Transaction.of()); + + } + @Test public void getHeadTest() { try { @@ -275,7 +424,8 @@ public void adjustBalanceTest() { Assert.assertTrue(false); } catch (BalanceInsufficientException e) { Assert.assertEquals( - StringUtil.createReadableString(account.createDbKey()) + " insufficient balance", + StringUtil.createReadableString(account.createDbKey()) + " insufficient balance" + + ", balance: " + account.getBalance() + ", amount: " + 40, e.getMessage()); } @@ -331,7 +481,8 @@ public void adjustAssetBalanceV2Test() { } catch (BalanceInsufficientException e) { Assert.assertTrue(e instanceof BalanceInsufficientException); Assert.assertEquals( - "reduceAssetAmount failed !", e.getMessage()); + "reduceAssetAmount failed! account: " + encode58Check(account.createDbKey()), + e.getMessage()); } account.setBalance(30); @@ -342,8 +493,8 @@ public void adjustAssetBalanceV2Test() { chainManager.getAccountStore(), chainManager.getAssetIssueStore(), chainManager.getDynamicPropertiesStore()); AccountCapsule copyAccount = chainManager.getAccountStore().get(ownerAddress); - Assert.assertEquals(copyAccount.getAssetMap().size(), 1); - copyAccount.getAssetMap().forEach((k, v) -> { + Assert.assertEquals(copyAccount.getAssetMapForTest().size(), 1); + copyAccount.getAssetMapForTest().forEach((k, v) -> { Assert.assertEquals(k, assetID); Assert.assertEquals(v.compareTo(10L), 0); }); @@ -366,7 +517,9 @@ public void pushBlockInvalidMerkelRoot() { Assert.assertTrue(false); } catch (BadBlockException e) { Assert.assertTrue(e instanceof BadBlockException); - Assert.assertEquals("The merkle hash is not validated", e.getMessage()); + Assert.assertTrue(e.getType().equals(CALC_MERKLE_ROOT_FAILED)); + Assert.assertEquals("The merkle hash is not validated for " + + blockCapsule2.getNum(), e.getMessage()); } catch (Exception e) { Assert.assertFalse(e instanceof Exception); } @@ -380,7 +533,7 @@ public void adjustTotalShieldPoolValueTest() { Assert.assertTrue(false); } catch (BalanceInsufficientException e) { Assert.assertTrue(e instanceof BalanceInsufficientException); - Assert.assertEquals("Total shielded pool value can not below 0", e.getMessage()); + Assert.assertEquals("total shielded pool value can not below 0, actual: -1", e.getMessage()); } long beforeTotalShieldValue = chainManager.getDynamicPropertiesStore() @@ -421,7 +574,8 @@ public void pushBlockTooMuchShieldedTransactions() { Assert.assertTrue(false); } catch (BadBlockException e) { Assert.assertTrue(e instanceof BadBlockException); - Assert.assertEquals("shielded transaction count > " + SHIELDED_TRANS_IN_BLOCK_COUNTS, + Assert.assertEquals("num: " + blockCapsule2.getNum() + + ", shielded transaction count > " + SHIELDED_TRANS_IN_BLOCK_COUNTS, e.getMessage()); } catch (Exception e) { Assert.assertFalse(e instanceof Exception); @@ -437,15 +591,36 @@ public void pushSwitchFork() TaposException, ReceiptCheckErrException, TooBigTransactionException, AccountResourceInsufficientException, EventBloomException { - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey(); + String key2 = PublicMethod.getRandomPrivateKey(); byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); + + WitnessCapsule sr1 = new WitnessCapsule( + ByteString.copyFrom(address), "www.tron.net/first"); + sr1.setVoteCount(1000000000L); + + + byte[] privateKey2 = ByteArray.fromHexString(key2); + final ECKey ecKey2 = ECKey.fromPrivate(privateKey2); + byte[] address2 = ecKey2.getAddress(); + WitnessCapsule sr2 = new WitnessCapsule( + ByteString.copyFrom(address2), "www.tron.net/second"); + sr2.setVoteCount(100000L); + chainManager.getWitnessStore().put(address, sr1); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); - + List witnessStandby1 = chainManager.getWitnessStore().getWitnessStandby( + chainManager.getDynamicPropertiesStore().allowWitnessSortOptimization()); Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); dbManager.pushBlock(new BlockCapsule(block)); @@ -482,6 +657,10 @@ public void pushSwitchFork() } catch (Exception e) { Assert.assertTrue(e instanceof Exception); } + chainManager.getWitnessStore().put(address, sr2); + List witnessStandby2 = chainManager.getWitnessStore().getWitnessStandby( + chainManager.getDynamicPropertiesStore().allowWitnessSortOptimization()); + Assert.assertNotEquals(witnessStandby1, witnessStandby2); } @@ -544,18 +723,28 @@ public void fork() BadBlockException, TaposException, BadNumberBlockException, NonCommonBlockException, ReceiptCheckErrException, VMIllegalException, TooBigTransactionResultException, ZksnarkException, EventBloomException { - Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); + Args.setParam(new String[]{}, Constant.TEST_CONF); long size = chainManager.getBlockStore().size(); // System.out.print("block store size:" + size + "\n"); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey(); byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); + + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); + chainManager.getWitnessStore().put(address, witnessCapsule); - Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); + Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947000L, privateKey); dbManager.pushBlock(new BlockCapsule(block)); @@ -565,7 +754,7 @@ public void fork() long num = chainManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber(); BlockCapsule blockCapsule0 = createTestBlockCapsule( - 1533529947843L + 3000, + 1533529947000L + 3000, num + 1, chainManager.getDynamicPropertiesStore().getLatestBlockHeaderHash() .getByteString(), @@ -573,7 +762,7 @@ public void fork() BlockCapsule blockCapsule1 = createTestBlockCapsule( - 1533529947843L + 3000, + 1533529947000L + 3000, num + 1, chainManager.getDynamicPropertiesStore().getLatestBlockHeaderHash() .getByteString(), @@ -584,7 +773,7 @@ public void fork() BlockCapsule blockCapsule2 = createTestBlockCapsule( - 1533529947843L + 6000, + 1533529947000L + 6000, num + 2, blockCapsule1.getBlockId().getByteString(), addressToProvateKeys); dbManager.pushBlock(blockCapsule2); @@ -611,6 +800,24 @@ public void fork() Assert.assertEquals( chainManager.getHead().getBlockId(), chainManager.getDynamicPropertiesStore().getLatestBlockHeaderHash()); + + dbManager.getDynamicPropertiesStore().saveConsensusLogicOptimization(1); + BlockCapsule blockCapsule3 = + createTestBlockCapsule2(1533529947000L + 9000, + num + 3, blockCapsule2.getBlockId().getByteString(), addressToProvateKeys); + + assertThrows(BadBlockException.class, () -> dbManager.pushBlock(blockCapsule3)); + } + + private Transaction buildTransaction(com.google.protobuf.Message message, + ContractType contractType) { + Transaction.raw.Builder rawBuilder = Transaction.raw.newBuilder().addContract( + Transaction.Contract.newBuilder().setType(contractType).setParameter( + (message instanceof Any ? (Any) message : Any.pack(message))).build()); + Transaction.Builder transactionBuilder = Transaction.newBuilder().setRawData(rawBuilder) + .addRet(Transaction.Result.newBuilder().setContractRet(SUCCESS).build()) + .addRet(Transaction.Result.newBuilder().setContractRet(SUCCESS).build()); + return transactionBuilder.build(); } @Test @@ -663,17 +870,23 @@ public void doNotSwitch() TaposException, BadNumberBlockException, NonCommonBlockException, ReceiptCheckErrException, VMIllegalException, TooBigTransactionResultException, ZksnarkException, EventBloomException { - Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); + Args.setParam(new String[]{}, Constant.TEST_CONF); long size = chainManager.getBlockStore().size(); System.out.print("block store size:" + size + "\n"); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey(); byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); - + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); + chainManager.getWitnessStore().put(address, witnessCapsule); Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); dbManager.pushBlock(new BlockCapsule(block)); @@ -769,17 +982,25 @@ public void switchBack() BadBlockException, TaposException, BadNumberBlockException, NonCommonBlockException, ReceiptCheckErrException, VMIllegalException, TooBigTransactionResultException, ZksnarkException, EventBloomException { - Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); + Args.setParam(new String[]{}, Constant.TEST_CONF); long size = chainManager.getBlockStore().size(); System.out.print("block store size:" + size + "\n"); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey();; byte[] privateKey = ByteArray.fromHexString(key); final ECKey ecKey = ECKey.fromPrivate(privateKey); byte[] address = ecKey.getAddress(); + + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressByte).build()); + chainManager.getAccountStore() + .put(addressByte.toByteArray(), accountCapsule); + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); chainManager.addWitness(ByteString.copyFrom(address)); - + chainManager.getWitnessStore().put(address, witnessCapsule); Block block = getSignedBlock(witnessCapsule.getAddress(), 1533529947843L, privateKey); dbManager.pushBlock(new BlockCapsule(block)); @@ -892,6 +1113,36 @@ private BlockCapsule createTestBlockCapsule(long time, return blockCapsule; } + private BlockCapsule createTestBlockCapsule2(long time, long number, ByteString hash, + Map addressToProvateKeys) { + TransferContract c1 = TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom("f1".getBytes())) + .setAmount(1).build(); + ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); + Protocol.BlockHeader.raw.Builder blockHeaderRawBuild = Protocol.BlockHeader.raw.newBuilder(); + Protocol.BlockHeader.raw blockHeaderRaw = blockHeaderRawBuild + .setTimestamp(time) + .setParentHash(hash) + .setWitnessAddress(witnessAddress) + .setNumber(number) + .build(); + + // block header + Protocol.BlockHeader.Builder blockHeaderBuild = Protocol.BlockHeader.newBuilder(); + Protocol.BlockHeader blockHeader = blockHeaderBuild.setRawData(blockHeaderRaw).build(); + + // block + Block.Builder blockBuild = Block.newBuilder(); + List transactions = Lists.newArrayList(buildTransaction(c1, + ContractType.TransferContract)); + transactions.forEach(blockBuild::addTransactions); + BlockCapsule blockCapsule = new BlockCapsule(blockBuild.setBlockHeader(blockHeader).build()); + blockCapsule.generatedByMyself = true; + blockCapsule.setMerkleRoot(); + blockCapsule.sign(ByteArray.fromHexString(addressToProvateKeys.get(witnessAddress))); + return blockCapsule; + } + private BlockCapsule createTestBlockCapsuleError(long time, long number, ByteString hash, Map addressToProvateKeys) { @@ -903,4 +1154,97 @@ private BlockCapsule createTestBlockCapsuleError(long time, blockCapsule.sign(ByteArray.fromHexString(addressToProvateKeys.get(witnessAddress))); return blockCapsule; } + + @Test + public void testExpireTransaction() { + TransferContract tc = + TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + TransactionCapsule trx = new TransactionCapsule(tc, ContractType.TransferContract); + long latestBlockTime = dbManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp(); + trx.setExpiration(latestBlockTime - 100); + try { + dbManager.validateCommon(trx); + Assert.fail(); + } catch (TransactionExpirationException e) { + Assert.assertTrue(true); + } catch (TooBigTransactionException e) { + Assert.fail(); + } + } + + @Test + public void testTooBigTransaction() { + TransferContract transferContract = + TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 6666; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + Transaction transaction = Transaction.newBuilder().setRawData(Transaction.raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract(Transaction.Contract.newBuilder().setParameter(Any.pack(transferContract)) + .setType(ContractType.TransferContract))).build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + trx.setInBlock(false); + assertThrows( + "Too big transaction with result, " + + "TxId 1c05e9fca6a2d0c366ed4430456527eb40198e70c8b20f5ceca4739c68a79af8, " + + "the size is 533483 bytes, maxTxSize 512000", + TooBigTransactionException.class, () -> dbManager.validateCommon(trx)); + + trx.setInBlock(true); + assertThrows( + "Too big transaction, " + + "TxId 1c05e9fca6a2d0c366ed4430456527eb40198e70c8b20f5ceca4739c68a79af8, " + + "the size is 1066643 bytes, maxTxSize 512000", + TooBigTransactionException.class, () -> dbManager.validateCommon(trx)); + + } + + @Test + public void testExpiration() { + dbManager.getDynamicPropertiesStore().saveConsensusLogicOptimization(1); + TransferContract transferContract = + TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 100; i++) { + sb.append("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); + } + Transaction transaction = Transaction.newBuilder().setRawData(Transaction.raw.newBuilder() + .setData(ByteString.copyFrom(sb.toString().getBytes(StandardCharsets.UTF_8))) + .addContract(Transaction.Contract.newBuilder().setParameter(Any.pack(transferContract)) + .setType(ContractType.TransferContract))).build(); + TransactionCapsule trx = new TransactionCapsule(transaction); + trx.setInBlock(true); + + assertThrows(TransactionExpirationException.class, () -> dbManager.validateCommon(trx)); + + } + + @Test + public void blockTrigger() { + Manager manager = spy(new Manager()); + doThrow(new RuntimeException("postBlockTrigger mock")).when(manager).postBlockTrigger(any()); + TronError thrown = Assert.assertThrows(TronError.class, () -> + manager.blockTrigger(new BlockCapsule(Block.newBuilder().build()), 1, 1)); + Assert.assertEquals(TronError.ErrCode.EVENT_SUBSCRIBE_ERROR, thrown.getErrCode()); + } + + public void adjustBalance(AccountStore accountStore, byte[] accountAddress, long amount) + throws BalanceInsufficientException { + Commons.adjustBalance(accountStore, accountAddress, amount, + chainManager.getDynamicPropertiesStore().disableJavaLangMath()); + } } diff --git a/framework/src/test/java/org/tron/core/db/MarketAccountStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketAccountStoreTest.java new file mode 100644 index 00000000000..ed94a64175d --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/MarketAccountStoreTest.java @@ -0,0 +1,53 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.MarketAccountOrderCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.MarketAccountStore; + +public class MarketAccountStoreTest extends BaseTest { + + @Resource + private MarketAccountStore marketAccountStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testGet() throws Exception { + String address = "Address1"; + + MarketAccountOrderCapsule marketAccountOrderCapsule = + marketAccountStore.getUnchecked(address.getBytes()); + Assert.assertNull(marketAccountOrderCapsule); + + marketAccountStore.put(address.getBytes(), + new MarketAccountOrderCapsule(ByteString.copyFrom(address.getBytes()))); + final MarketAccountOrderCapsule result = marketAccountStore.get(address.getBytes()); + Assert.assertNotNull(result); + Assert.assertEquals(result.getOwnerAddress(), ByteString.copyFrom(address.getBytes())); + } + + @Test + public void testPut() throws ItemNotFoundException { + String address = "Address1"; + marketAccountStore.put(address.getBytes(), + new MarketAccountOrderCapsule(ByteString.copyFrom(address.getBytes()))); + final MarketAccountOrderCapsule result = marketAccountStore.get(address.getBytes()); + Assert.assertNotNull(result); + Assert.assertEquals(result.getOwnerAddress(), ByteString.copyFrom(address.getBytes())); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/MarketOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketOrderStoreTest.java new file mode 100644 index 00000000000..1cfdb20da97 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/MarketOrderStoreTest.java @@ -0,0 +1,64 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.MarketOrderCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.MarketOrderStore; +import org.tron.protos.Protocol; + +public class MarketOrderStoreTest extends BaseTest { + + @Resource + private MarketOrderStore marketOrderStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testGet() throws Exception { + byte[] orderId = "testGet".getBytes(); + marketOrderStore.put(orderId, + new MarketOrderCapsule(Protocol.MarketOrder.newBuilder() + .setOrderId(ByteString.copyFrom(orderId)) + .setSellTokenId(ByteString.copyFrom("addr1".getBytes())) + .setSellTokenQuantity(200L) + .setBuyTokenId(ByteString.copyFrom("addr2".getBytes())) + .setBuyTokenQuantity(100L) + .build())); + final MarketOrderCapsule result = marketOrderStore.get(orderId); + Assert.assertNotNull(result); + Assert.assertEquals(new String(result.getSellTokenId()), "addr1"); + Assert.assertEquals(result.getSellTokenQuantity(), 200L); + Assert.assertEquals(new String(result.getBuyTokenId()), "addr2"); + Assert.assertEquals(result.getBuyTokenQuantity(), 100L); + } + + @Test + public void testDelete() throws ItemNotFoundException { + byte[] orderId = "testDelete".getBytes(); + marketOrderStore.put(orderId, + new MarketOrderCapsule(Protocol.MarketOrder.newBuilder() + .setOrderId(ByteString.copyFrom(orderId)) + .setSellTokenId(ByteString.copyFrom("addr1".getBytes())) + .setSellTokenQuantity(200L) + .setBuyTokenId(ByteString.copyFrom("addr2".getBytes())) + .setBuyTokenQuantity(100L) + .build())); + marketOrderStore.delete(orderId); + final MarketOrderCapsule result = marketOrderStore.getUnchecked(orderId); + Assert.assertNull(result); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java index a264b33ee98..d74229fb216 100755 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreTest.java @@ -1,22 +1,20 @@ package org.tron.core.db; -import java.io.File; +import static org.tron.common.math.Maths.random; +import static org.tron.common.math.Maths.round; + import java.util.List; import lombok.extern.slf4j.Slf4j; import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.MarketOrderIdListCapsule; import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.ItemNotFoundException; import org.tron.core.store.MarketPairPriceToOrderStore; @@ -25,34 +23,10 @@ import org.tron.protos.Protocol.MarketPrice; @Slf4j -public class MarketPairPriceToOrderStoreTest { - - private static final String dbPath = "output-MarketPairPriceToOrderStore-test"; - private static TronApplicationContext context; - private static Manager dbManager; +public class MarketPairPriceToOrderStoreTest extends BaseTest { static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - /** - * Init data. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } @After @@ -72,7 +46,7 @@ public void cleanDb() { } private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random(true) * (maxInt - minInt) + minInt, true); } @Test diff --git a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreWithCacheOldValueTest.java b/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreWithCacheOldValueTest.java deleted file mode 100644 index 4e8f5ffe866..00000000000 --- a/framework/src/test/java/org/tron/core/db/MarketPairPriceToOrderStoreWithCacheOldValueTest.java +++ /dev/null @@ -1,188 +0,0 @@ -package org.tron.core.db; - -import java.io.File; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.iq80.leveldb.Options; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; -import org.tron.common.utils.MarketOrderPriceComparatorForLevelDB; -import org.tron.common.utils.StorageUtils; -import org.tron.core.Constant; -import org.tron.core.capsule.MarketOrderIdListCapsule; -import org.tron.core.capsule.utils.MarketUtils; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; -import org.tron.core.exception.BadItemException; -import org.tron.core.exception.ItemNotFoundException; - -@Slf4j -public class MarketPairPriceToOrderStoreWithCacheOldValueTest { - - private AbstractRevokingStore revokingDatabase; - private TronApplicationContext context; - - @Before - public void init() { - Args.setParam(new String[]{"-d", "output_market_revokingStore_test"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - ApplicationFactory.create(context); - revokingDatabase = new TestRevokingTronDatabase(); - revokingDatabase.enable(); - } - - @After - public void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File("output_market_revokingStore_test")); - } - - /** - * Almost the same as testPriceSeqWithSamePair, except using the RevokingDBWithCachingOldValue. - * We add this test in order to test db.version=1. - * */ - @Test - public synchronized void testGetKeysNext() { - revokingDatabase.getStack().clear(); - String dbName = "testrevokingtronstore-testGetKeysNext"; - Options options = StorageUtils.getOptionsByDbName(dbName); - options.comparator(new MarketOrderPriceComparatorForLevelDB()); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore(dbName, options, - revokingDatabase); - - // put order: 2 1 3 0 - // lexicographical order: 0 < 3 < 1 = 2 - // key order: 0 < 1 = 2 < 3 - byte[] sellTokenID1 = ByteArray.fromString("100"); - byte[] buyTokenID1 = ByteArray.fromString("200"); - byte[] pairPriceKey0 = MarketUtils.createPairPriceKey( - sellTokenID1, - buyTokenID1, - 0L, - 0L - ); - byte[] pairPriceKey1 = MarketUtils.createPairPriceKey( - sellTokenID1, - buyTokenID1, - 10L, - 21L - ); - byte[] pairPriceKey2 = MarketUtils.createPairPriceKey( - sellTokenID1, - buyTokenID1, - 30L, - 63L - ); - byte[] pairPriceKey3 = MarketUtils.createPairPriceKey( - sellTokenID1, - buyTokenID1, - 1L, - 4L - ); - - // lexicographical order: 0 < 3 < 1 = 2 - Assert.assertTrue(ByteUtil.compare(pairPriceKey0, pairPriceKey3) < 0); - Assert.assertTrue(ByteUtil.compare(pairPriceKey3, pairPriceKey1) < 0); - Assert.assertEquals(0, ByteUtil.compare(pairPriceKey1, pairPriceKey2)); - - MarketOrderIdListCapsule capsule0 = new MarketOrderIdListCapsule(ByteArray.fromLong(0), - ByteArray.fromLong(0)); - MarketOrderIdListCapsule capsule1 = new MarketOrderIdListCapsule(ByteArray.fromLong(1), - ByteArray.fromLong(1)); - MarketOrderIdListCapsule capsule2 = new MarketOrderIdListCapsule(ByteArray.fromLong(2), - ByteArray.fromLong(2)); - MarketOrderIdListCapsule capsule3 = new MarketOrderIdListCapsule(ByteArray.fromLong(3), - ByteArray.fromLong(3)); - - // put: 2 1 0 3 - Assert.assertFalse(tronDatabase.has(pairPriceKey2)); - tronDatabase.put(pairPriceKey2, capsule2); - - try { - Assert - .assertArrayEquals(capsule2.getData(), - tronDatabase.get(pairPriceKey2).getData()); - } catch (ItemNotFoundException | BadItemException e) { - Assert.fail(); - } - - // pairPriceKey1 and pairPriceKey2 has the same value, - // After put pairPriceKey2, pairPriceKey2 will be replaced by pairPriceKey1, both key and value. - // But you can still get(pairPriceKey2) return pairPriceKey1's value - Assert.assertTrue(tronDatabase.has(pairPriceKey1)); - tronDatabase.put(pairPriceKey1, capsule1); - Assert.assertEquals(1, tronDatabase.size()); - - try { - Assert - .assertArrayEquals(capsule1.getData(), - tronDatabase.get(pairPriceKey1).getData()); - Assert - .assertArrayEquals(capsule1.getData(), - tronDatabase.get(pairPriceKey2).getData()); - } catch (ItemNotFoundException | BadItemException e) { - Assert.fail(); - } - - Assert.assertFalse(tronDatabase.has(pairPriceKey0)); - if (!tronDatabase.has(pairPriceKey0)) { - tronDatabase.put(pairPriceKey0, capsule0); - } - - Assert.assertEquals(2, tronDatabase.size()); - - Assert.assertFalse(tronDatabase.has(pairPriceKey3)); - if (!tronDatabase.has(pairPriceKey3)) { - tronDatabase.put(pairPriceKey3, capsule3); - } - - Assert.assertEquals(3, tronDatabase.size()); - - // get pairPriceKey1, will get pairPriceKey2's value capsule2 - try { - Assert - .assertArrayEquals(capsule0.getData(), - tronDatabase.get(pairPriceKey0).getData()); - Assert - .assertArrayEquals(capsule1.getData(), - tronDatabase.get(pairPriceKey1).getData()); - Assert - .assertArrayEquals(capsule1.getData(), - tronDatabase.get(pairPriceKey2).getData()); - Assert - .assertArrayEquals(capsule3.getData(), - tronDatabase.get(pairPriceKey3).getData()); - } catch (ItemNotFoundException | BadItemException e) { - Assert.fail(); - } - - List keyList = tronDatabase.getRevokingDB().getKeysNext(pairPriceKey0, 2 + 1); - Assert.assertArrayEquals(pairPriceKey0, keyList.get(0)); - Assert.assertArrayEquals(pairPriceKey1, keyList.get(1)); - Assert.assertArrayEquals(pairPriceKey3, keyList.get(2)); - - - tronDatabase.close(); - } - - private static class TestRevokingTronStore extends - TronStoreWithRevoking { - - private TestRevokingTronStore(String dbName, Options options, - RevokingDatabase revokingDatabase) { - super(dbName, options, revokingDatabase); - } - } - - private static class TestRevokingTronDatabase extends AbstractRevokingStore { - - } -} diff --git a/framework/src/test/java/org/tron/core/db/MarketPairToPriceStoreTest.java b/framework/src/test/java/org/tron/core/db/MarketPairToPriceStoreTest.java new file mode 100644 index 00000000000..adf315bb92e --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/MarketPairToPriceStoreTest.java @@ -0,0 +1,83 @@ +package org.tron.core.db; + +import static org.junit.Assert.assertEquals; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.MarketPairPriceToOrderStore; +import org.tron.core.store.MarketPairToPriceStore; + +public class MarketPairToPriceStoreTest extends BaseTest { + + @Resource + private MarketPairToPriceStore marketPairToPriceStore; + + @Resource + private MarketPairPriceToOrderStore marketPairPriceToOrderStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testGet() throws Exception { + marketPairToPriceStore.put("testGet".getBytes(), new BytesCapsule( + ByteArray.fromString("11.0"))); + final BytesCapsule result = marketPairToPriceStore.get("testGet".getBytes()); + Assert.assertNotNull(result); + Assert.assertEquals(new String(result.getData()), "11.0"); + } + + @Test + public void testGetPriceNum() { + marketPairToPriceStore.put("testGetPriceNum".getBytes(), new BytesCapsule( + ByteArray.fromLong(100))); + final long result = marketPairToPriceStore.getPriceNum("testGetPriceNum".getBytes()); + assertEquals(100L, result); + assertEquals(0L, marketPairToPriceStore.getPriceNum("testGetPriceNum1".getBytes())); + } + + @Test + public void testGetPriceNumByTokenId() { + marketPairToPriceStore.setPriceNum("tokenId1".getBytes(), "tokenId2".getBytes(),99); + final long result = + marketPairToPriceStore.getPriceNum("tokenId1".getBytes(), "tokenId2".getBytes()); + assertEquals(99L, result); + assertEquals(0L, marketPairToPriceStore.getPriceNum("tokenId2".getBytes(), + "tokenId1".getBytes())); + } + + @Test + public void testSetPriceNum() { + marketPairToPriceStore.setPriceNum("testSetPriceNum1".getBytes(), 98L); + long result = marketPairToPriceStore.getPriceNum("testSetPriceNum1".getBytes()); + assertEquals(result, 98); + } + + @Test + public void testSetPriceNumByToken() { + marketPairToPriceStore.setPriceNum("token3".getBytes(), "token4".getBytes(), 97L); + long result = marketPairToPriceStore.getPriceNum("token3".getBytes(), "token4".getBytes()); + assertEquals(result, 97); + } + + @Test + public void testAddNewPriceKey() { + marketPairToPriceStore + .addNewPriceKey("token5".getBytes(), "token6".getBytes(), marketPairPriceToOrderStore); + long result = marketPairToPriceStore.getPriceNum("token5".getBytes(), "token6".getBytes()); + assertEquals(1, result); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java b/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java index 58de5f0747f..6070182a5c1 100644 --- a/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/NullifierStoreTest.java @@ -1,57 +1,44 @@ package org.tron.core.db; -import java.io.File; import java.util.Random; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.BytesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.NullifierStore; -public class NullifierStoreTest { +public class NullifierStoreTest extends BaseTest { private static final byte[] NULLIFIER_ONE = randomBytes(32); private static final byte[] NULLIFIER_TWO = randomBytes(32); private static final byte[] TRX_TWO = randomBytes(32); private static final byte[] TRX_TWO_NEW = randomBytes(32); - public static Application AppT; - private static NullifierStore nullifierStore; - private static String dbPath = "output_NullifierStore_test"; - private static TronApplicationContext context; + @Resource + private NullifierStore nullifierStore; private static BytesCapsule nullifier1; private static BytesCapsule nullifier2; private static BytesCapsule nullifier2New; static { - Args.setParam(new String[]{"--output-directory", dbPath}, + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - nullifierStore = context.getBean(NullifierStore.class); nullifier1 = new BytesCapsule(NULLIFIER_ONE); nullifier2 = new BytesCapsule(TRX_TWO); nullifier2New = new BytesCapsule(TRX_TWO_NEW); + } + @Before + public void before() { nullifierStore.put(nullifier1); nullifierStore.put(NULLIFIER_TWO, nullifier2); } diff --git a/framework/src/test/java/org/tron/core/db/ProposalStoreTest.java b/framework/src/test/java/org/tron/core/db/ProposalStoreTest.java new file mode 100644 index 00000000000..b08402d33a0 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ProposalStoreTest.java @@ -0,0 +1,72 @@ +package org.tron.core.db; + +import static org.junit.Assert.assertThrows; + +import com.google.protobuf.ByteString; +import java.util.List; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.ProposalCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.ProposalStore; +import org.tron.protos.Protocol; + +public class ProposalStoreTest extends BaseTest { + + @Resource + private ProposalStore proposalStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Before + public void init() { + Protocol.Proposal.Builder builder = Protocol.Proposal.newBuilder() + .setProposalId(1L).putParameters(1,99).setState(Protocol.Proposal.State.PENDING) + .setProposerAddress(ByteString.copyFromUtf8("Address1")); + proposalStore.put("1".getBytes(), new ProposalCapsule(builder.build())); + builder.setProposalId(2L).setState(Protocol.Proposal.State.APPROVED).setProposerAddress( + ByteString.copyFromUtf8("Address2")); + proposalStore.put("2".getBytes(), new ProposalCapsule(builder.build())); + } + + @Test + public void testGet() throws Exception { + final ProposalCapsule result = proposalStore.get("1".getBytes()); + Assert.assertNotNull(result); + Assert.assertEquals(result.getID(),1); + Assert.assertEquals(result.getProposalAddress(), ByteString.copyFromUtf8("Address1")); + assertThrows(ItemNotFoundException.class, + () -> proposalStore.get("testGet1".getBytes())); + } + + @Test + public void testGetAllProposals() { + final List result = proposalStore.getAllProposals(); + Assert.assertEquals(result.size(), 2); + Assert.assertEquals(result.get(0).getID(), 1); + Assert.assertEquals(result.get(0).getProposalAddress(), ByteString.copyFromUtf8("Address1")); + } + + @Test + public void testGetSpecifiedProposals() { + final List result = + proposalStore.getSpecifiedProposals(Protocol.Proposal.State.PENDING, 1); + Assert.assertEquals(result.size(), 1); + Assert.assertEquals(result.get(0).getID(), 1); + Assert.assertEquals(result.get(0).getProposalAddress(), ByteString.copyFromUtf8("Address1")); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/RecentBlockStoreTest.java b/framework/src/test/java/org/tron/core/db/RecentBlockStoreTest.java new file mode 100644 index 00000000000..7856fe337a5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/RecentBlockStoreTest.java @@ -0,0 +1,81 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; + +public class RecentBlockStoreTest extends BaseTest { + + @Resource + private RecentBlockStore recentBlockStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + private BlockCapsule getBlockCapsule() { + long number = 1; + return new BlockCapsule(number, + Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), + ByteString.EMPTY); + } + + @Test + public void testPut() { + BlockCapsule blockCapsule = getBlockCapsule(); + byte[] key = ByteArray.subArray( + ByteArray.fromLong(blockCapsule.getNum()), 6, 8); + recentBlockStore.put(key, + new BytesCapsule(ByteArray.subArray(blockCapsule + .getBlockId().getBytes(), + 8, + 16))); + + Assert.assertTrue(recentBlockStore.has(key)); + } + + @Test + public void testGet() throws ItemNotFoundException { + BlockCapsule blockCapsule = getBlockCapsule(); + byte[] key = ByteArray.subArray( + ByteArray.fromLong(blockCapsule.getNum()), 6, 8); + BytesCapsule value = new BytesCapsule(ByteArray + .subArray(blockCapsule.getBlockId().getBytes(), + 8, + 16)); + recentBlockStore.put(key, value); + + BytesCapsule bytesCapsule = recentBlockStore.get(key); + Assert.assertNotNull(bytesCapsule); + Assert.assertArrayEquals(value.getData(), bytesCapsule.getData()); + } + + @Test + public void testDelete() { + BlockCapsule blockCapsule = getBlockCapsule(); + byte[] key = ByteArray.subArray( + ByteArray.fromLong(blockCapsule.getNum()), 6, 8); + recentBlockStore.put(key, + new BytesCapsule(ByteArray.subArray(blockCapsule + .getBlockId().getBytes(), + 8, + 16))); + recentBlockStore.delete(key); + Assert.assertFalse(recentBlockStore.has(key)); + } +} diff --git a/framework/src/test/java/org/tron/core/db/RecentTransactionStoreTest.java b/framework/src/test/java/org/tron/core/db/RecentTransactionStoreTest.java new file mode 100644 index 00000000000..20447dfc6a1 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/RecentTransactionStoreTest.java @@ -0,0 +1,72 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +public class RecentTransactionStoreTest extends BaseTest { + + @Resource + private RecentTransactionStore recentTransactionStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + private TransactionCapsule createTransaction() { + BalanceContract.TransferContract tc = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + return new TransactionCapsule(tc, + Protocol.Transaction.Contract.ContractType.TransferContract); + } + + + @Test + public void testPut() { + TransactionCapsule transaction = createTransaction(); + byte[] key = transaction.getTransactionId().getBytes(); + BytesCapsule value = new BytesCapsule(ByteArray.subArray(transaction + .getTransactionId().getBytes(), + 8, + 16)); + recentTransactionStore.put(key, value); + Assert.assertTrue(recentTransactionStore.has(key)); + } + + @Test + public void testGet() throws ItemNotFoundException { + TransactionCapsule transaction = createTransaction(); + byte[] key = transaction.getTransactionId().getBytes(); + BytesCapsule value = new BytesCapsule( + ByteArray.subArray(transaction + .getTransactionId().getBytes(), + 8, + 16)); + recentTransactionStore.put(key, value); + + BytesCapsule bytesCapsule = recentTransactionStore.get(key); + Assert.assertNotNull(bytesCapsule); + Assert.assertArrayEquals(value.getData(), bytesCapsule.getData()); + + } +} diff --git a/framework/src/test/java/org/tron/core/db/SerializedTest.java b/framework/src/test/java/org/tron/core/db/SerializedTest.java new file mode 100644 index 00000000000..221ca5e1139 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/SerializedTest.java @@ -0,0 +1,129 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; +import com.google.protobuf.InvalidProtocolBufferException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.utils.ByteArray; +import org.tron.protos.Protocol; + +public class SerializedTest { + + + @Test + public void SerializedSize() throws InvalidProtocolBufferException { + // block header raw + Protocol.BlockHeader.raw.Builder blockHeaderRawBuild = Protocol.BlockHeader.raw.newBuilder(); + Protocol.BlockHeader.raw blockHeaderRaw = blockHeaderRawBuild + .setNumber(47377682) + .setParentHash(ByteString.copyFrom(ByteArray.fromHexString( + "0000000002d2ed11cac713f84349dde3c1a4af38b8480fdb72c6c41a315abf25"))) + .setTimestamp(1672734363000L) + .setVersion(26) + .setWitnessAddress(ByteString.copyFrom(ByteArray.fromHexString( + "41af619f8ce75a9e95a19e851bebe63e89fcb1826e"))) + .setTxTrieRoot(ByteString.copyFrom(ByteArray.fromHexString( + "8b006c280022d325a1eb6a64f0b9ca6ce9e23bcc380fb07d58be397219f935b3"))) + .build(); + + // block header + Protocol.BlockHeader.Builder blockHeaderBuild = Protocol.BlockHeader.newBuilder(); + Protocol.BlockHeader blockHeader = blockHeaderBuild.setRawData(blockHeaderRaw) + .setWitnessSignature(ByteString.copyFrom(ByteArray.fromHexString( + "aae20ba4216a2797fd4ece92e9b0748a30bf547a58c03ba8e1b9c818ea8f24b12afd4da" + + "d6f6d246428d641d695d204d5749af93340da90d0f52b0436dd1853ae00"))) + .build(); + + // block + Protocol.Block.Builder blockBuild = Protocol.Block.newBuilder(); + + blockBuild.setBlockHeader(blockHeader).build(); + long current = blockBuild.build().getSerializedSize(); + + byte[] data = new byte[512 * 1_0240]; + + for (int i = 0; i < 512 * 1_0240; i++) { + data[i] = (byte) i; + } + Protocol.Transaction large = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder().setData( + ByteString.copyFrom(data)).build()).build(); + Protocol.Transaction t = Protocol.Transaction.parseFrom(ByteString.copyFrom( + ByteArray.fromHexString( + "0aab010a080000018576b86dec220d3136373237333430373633393640ecdbe1b5d7305222544e66" + + "584555517359584355507641474e7448476b716d636e797050783947566e6a5a65080112610a" + + "2d747970652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572" + + "436f6e747261637412300a1541f08012b4881c320eb40b80f1228731898824e09d121541878e" + + "5427dec577ec5cb0bbcc6056837cb1926f2d1801124135eda8606f37f9d80625533832830853" + + "8b413ba3594a53d810deb3c657aa567e6e3fc52854737dc68f40d69e0e78e67df8edc508de43" + + "38c56d5acafb2797eec6002a021801"))); + Protocol.Transaction small = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder().setData( + ByteString.copyFrom("1".getBytes(StandardCharsets.UTF_8))).build()).build(); + + + Protocol.Transaction min = Protocol.Transaction.getDefaultInstance(); + int c = 300; + List l = new ArrayList<>(); + l.add(large); + l.add(t); + l.add(small); + l.add(min); + Random r = new Random(); + for (int i = 0; i < c; i++) { + Protocol.Transaction transaction = l.get(r.nextInt(l.size())); + current += CodedOutputStream.computeMessageSize(1, transaction); + blockBuild.addTransactions(transaction); + } + long aft = blockBuild.build().getSerializedSize(); + Assert.assertEquals(aft, current); + + Protocol.Account.Builder account = Protocol.Account.newBuilder(); + long base = account.build().getSerializedSize(); + Protocol.Vote vote = Protocol.Vote.newBuilder().setVoteAddress(ByteString.copyFrom("1".getBytes( + StandardCharsets.UTF_8))).build(); + account.addVotes(vote); + long v1 = vote.getSerializedSize(); + long a1 = account.build().getSerializedSize(); + Assert.assertEquals(a1 - base, + CodedOutputStream.computeTagSize(5) + + CodedOutputStream.computeInt64SizeNoTag(v1) + v1); + Protocol.Vote vote2 = Protocol.Vote.newBuilder().setVoteAddress( + ByteString.copyFrom("2".getBytes(StandardCharsets.UTF_8))).build(); + account.addVotes(vote2); + long v2 = vote2.getSerializedSize(); + long a2 = account.build().getSerializedSize(); + Assert.assertEquals(a2 - a1, + CodedOutputStream.computeTagSize(5) + + CodedOutputStream.computeInt64SizeNoTag(v2) + v2); + Protocol.Account.Frozen frozen = Protocol.Account.Frozen.newBuilder() + .setFrozenBalance(1).build(); + long currentSize = a2; + long cc = 0; + for (int i = 0; i < 1000; i++) { + if ((currentSize += CodedOutputStream.computeMessageSize(7, frozen)) > 1600) { + break; + } + account.addFrozen(frozen); + cc = i + 1; + } + + long a3 = account.build().getSerializedSize(); + Assert.assertEquals((a3 - a2) / cc, + CodedOutputStream.computeTagSize(7) + + CodedOutputStream.computeInt64SizeNoTag(frozen.getSerializedSize()) + + frozen.getSerializedSize()); + + Protocol.Permission p = Protocol.Permission.newBuilder().build(); + long p1 = p.getSerializedSize(); + account.addActivePermission(p); + long a4 = account.build().getSerializedSize(); + Assert.assertEquals(a4 - a3, CodedOutputStream.computeTagSize(33) + + CodedOutputStream.computeInt64SizeNoTag(p1) + p1); + } +} diff --git a/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java new file mode 100644 index 00000000000..420b54525e4 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/TransactionExpireTest.java @@ -0,0 +1,201 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.util.Arrays; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.api.GrpcAPI; +import org.tron.api.GrpcAPI.Return.response_code; +import org.tron.api.GrpcAPI.TransactionApprovedList; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.BalanceContract.TransferContract; + +@Slf4j +public class TransactionExpireTest { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + private TronApplicationContext context; + private Wallet wallet; + private Manager dbManager; + private BlockCapsule blockCapsule; + + @Before + public void init() throws IOException { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + CommonParameter.PARAMETER.setMinEffectiveConnection(0); + CommonParameter.getInstance().setP2pDisable(true); + + context = new TronApplicationContext(DefaultConfig.class); + wallet = context.getBean(Wallet.class); + dbManager = context.getBean(Manager.class); + } + + private void initLocalWitness() { + String randomPrivateKey = PublicMethod.getRandomPrivateKey(); + LocalWitnesses localWitnesses = new LocalWitnesses(); + localWitnesses.setPrivateKeys(Arrays.asList(randomPrivateKey)); + localWitnesses.initWitnessAccountAddress(true); + Args.setLocalWitnesses(localWitnesses); + } + + @After + public void removeDb() { + Args.clearParam(); + context.destroy(); + } + + @Test + public void testExpireTransaction() { + blockCapsule = new BlockCapsule( + 1, + Sha256Hash.wrap(ByteString.copyFrom( + ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))), + 1, + ByteString.copyFromUtf8("testAddress")); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(blockCapsule.getNum()); + dbManager.getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(blockCapsule.getTimeStamp()); + dbManager.updateRecentBlock(blockCapsule); + initLocalWitness(); + + TransferContract transferContract = TransferContract.newBuilder() + .setAmount(1L) + .setOwnerAddress(ByteString.copyFrom(Args.getLocalWitnesses() + .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine()))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086")))) + .build(); + TransactionCapsule transactionCapsule = + new TransactionCapsule(transferContract, ContractType.TransferContract); + transactionCapsule.setReference(blockCapsule.getNum(), blockCapsule.getBlockId().getBytes()); + Assert.assertEquals(1, blockCapsule.getTimeStamp()); + + long blockTimeStamp = blockCapsule.getTimeStamp(); + transactionCapsule.setExpiration(blockTimeStamp - 1); + transactionCapsule.sign(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); + + GrpcAPI.Return result = wallet.broadcastTransaction(transactionCapsule.getInstance()); + Assert.assertEquals(response_code.TRANSACTION_EXPIRATION_ERROR, result.getCode()); + } + + @Test + public void testExpireTransactionNew() { + blockCapsule = new BlockCapsule( + 1, + Sha256Hash.wrap(ByteString.copyFrom( + ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))), + System.currentTimeMillis(), + ByteString.copyFromUtf8("testAddress")); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(blockCapsule.getNum()); + dbManager.getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(blockCapsule.getTimeStamp()); + dbManager.updateRecentBlock(blockCapsule); + initLocalWitness(); + byte[] address = Args.getLocalWitnesses() + .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine()); + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + accountCapsule.setBalance(1000_000_000L); + dbManager.getChainBaseManager().getAccountStore() + .put(accountCapsule.createDbKey(), accountCapsule); + + TransferContract transferContract = TransferContract.newBuilder() + .setAmount(1L) + .setOwnerAddress(addressByte) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086")))) + .build(); + TransactionCapsule transactionCapsule = + new TransactionCapsule(transferContract, ContractType.TransferContract); + transactionCapsule.setReference(blockCapsule.getNum(), blockCapsule.getBlockId().getBytes()); + + transactionCapsule.setExpiration(System.currentTimeMillis()); + transactionCapsule.sign(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); + + GrpcAPI.Return result = wallet.broadcastTransaction(transactionCapsule.getInstance()); + Assert.assertEquals(response_code.TRANSACTION_EXPIRATION_ERROR, result.getCode()); + } + + @Test + public void testTransactionApprovedList() { + blockCapsule = new BlockCapsule( + 1, + Sha256Hash.wrap(ByteString.copyFrom( + ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))), + 1, + ByteString.copyFromUtf8("testAddress")); + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(blockCapsule.getNum()); + dbManager.getDynamicPropertiesStore() + .saveLatestBlockHeaderTimestamp(blockCapsule.getTimeStamp()); + dbManager.updateRecentBlock(blockCapsule); + initLocalWitness(); + + byte[] address = Args.getLocalWitnesses() + .getWitnessAccountAddress(CommonParameter.getInstance().isECKeyCryptoEngine()); + TransferContract transferContract = TransferContract.newBuilder() + .setAmount(1L) + .setOwnerAddress(ByteString.copyFrom(address)) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086")))) + .build(); + TransactionCapsule transactionCapsule = + new TransactionCapsule(transferContract, ContractType.TransferContract); + transactionCapsule.setReference(blockCapsule.getNum(), blockCapsule.getBlockId().getBytes()); + transactionCapsule.sign(ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey())); + + TransactionApprovedList transactionApprovedList = wallet.getTransactionApprovedList( + transactionCapsule.getInstance()); + Assert.assertTrue( + transactionApprovedList.getResult().getMessage().contains("Account does not exist!")); + + ByteString addressByte = ByteString.copyFrom(address); + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + accountCapsule.setBalance(1000_000_000L); + dbManager.getChainBaseManager().getAccountStore() + .put(accountCapsule.createDbKey(), accountCapsule); + transactionApprovedList = wallet.getTransactionApprovedList(transactionCapsule.getInstance()); + Assert.assertEquals("", transactionApprovedList.getResult().getMessage()); + + byte[] randomSig = org.tron.keystore.Wallet.generateRandomBytes(64); + Transaction transaction = transactionCapsule.getInstance().toBuilder().clearSignature() + .addSignature(ByteString.copyFrom(randomSig)).build(); + transactionApprovedList = wallet.getTransactionApprovedList(transaction); + Assert.assertEquals(TransactionApprovedList.Result.response_code.SIGNATURE_FORMAT_ERROR, + transactionApprovedList.getResult().getCode()); + + randomSig = org.tron.keystore.Wallet.generateRandomBytes(65); + transaction = transactionCapsule.getInstance().toBuilder().clearSignature() + .addSignature(ByteString.copyFrom(randomSig)).build(); + transactionApprovedList = wallet.getTransactionApprovedList(transaction); + Assert.assertEquals(TransactionApprovedList.Result.response_code.COMPUTE_ADDRESS_ERROR, + transactionApprovedList.getResult().getCode()); + } +} diff --git a/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java b/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java index c7439d84d82..c5c249b6f70 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionHistoryTest.java @@ -1,57 +1,51 @@ package org.tron.core.db; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.TransactionInfoCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.store.TransactionHistoryStore; -public class TransactionHistoryTest { +public class TransactionHistoryTest extends BaseTest { private static final byte[] transactionId = TransactionStoreTest.randomBytes(32); - private static String dbPath = "output_TransactionHistoryStore_test"; private static String dbDirectory = "db_TransactionHistoryStore_test"; private static String indexDirectory = "index_TransactionHistoryStore_test"; - private static TronApplicationContext context; - private static TransactionHistoryStore transactionHistoryStore; + @Resource + private TransactionHistoryStore transactionHistoryStore; + + private static TransactionInfoCapsule transactionInfoCapsule; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory }, Constant.TEST_CONF ); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - transactionHistoryStore = context.getBean(TransactionHistoryStore.class); - TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); - + transactionInfoCapsule = new TransactionInfoCapsule(); transactionInfoCapsule.setId(transactionId); transactionInfoCapsule.setFee(1000L); transactionInfoCapsule.setBlockNumber(100L); transactionInfoCapsule.setBlockTimeStamp(200L); + + } + + @Before + public void before() { transactionHistoryStore.put(transactionId, transactionInfoCapsule); } @@ -65,4 +59,11 @@ public void get() throws BadItemException { Assert.assertEquals(ByteArray.toHexString(transactionId), ByteArray.toHexString(resultCapsule.getId())); } + + @Test + public void testDelete() throws BadItemException { + transactionHistoryStore.delete(transactionId); + TransactionInfoCapsule transactionInfoCapsule = transactionHistoryStore.get(transactionId); + Assert.assertNull(transactionInfoCapsule); + } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java b/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java index c4a629b12bc..b8aebe00aac 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionRetStoreTest.java @@ -1,52 +1,44 @@ package org.tron.core.db; -import java.io.File; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionInfoCapsule; import org.tron.core.capsule.TransactionRetCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.store.TransactionRetStore; import org.tron.protos.Protocol.Transaction; -public class TransactionRetStoreTest { +public class TransactionRetStoreTest extends BaseTest { private static final byte[] transactionId = TransactionStoreTest.randomBytes(32); private static final byte[] blockNum = ByteArray.fromLong(1); - private static String dbPath = "output_TransactionRetStore_test"; private static String dbDirectory = "db_TransactionRetStore_test"; private static String indexDirectory = "index_TransactionRetStore_test"; - private static TronApplicationContext context; - private static TransactionRetStore transactionRetStore; + @Resource + private TransactionRetStore transactionRetStore; private static Transaction transaction; - private static TransactionStore transactionStore; + @Resource + private TransactionStore transactionStore; + + private static TransactionCapsule transactionCapsule; + private static TransactionRetCapsule transactionRetCapsule; static { - Args.setParam(new String[]{"--output-directory", dbPath, "--storage-db-directory", dbDirectory, + Args.setParam(new String[]{"--output-directory", dbPath(), + "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } @BeforeClass public static void init() { - transactionRetStore = context.getBean(TransactionRetStore.class); - transactionStore = context.getBean(TransactionStore.class); TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); transactionInfoCapsule.setId(transactionId); @@ -54,12 +46,18 @@ public static void init() { transactionInfoCapsule.setBlockNumber(100L); transactionInfoCapsule.setBlockTimeStamp(200L); - TransactionRetCapsule transactionRetCapsule = new TransactionRetCapsule(); + transactionRetCapsule = new TransactionRetCapsule(); transactionRetCapsule.addTransactionInfo(transactionInfoCapsule.getInstance()); - transactionRetStore.put(blockNum, transactionRetCapsule); + transaction = Transaction.newBuilder().build(); - TransactionCapsule transactionCapsule = new TransactionCapsule(transaction); + transactionCapsule = new TransactionCapsule(transaction); transactionCapsule.setBlockNum(1); + + } + + @Before + public void before() { + transactionRetStore.put(blockNum, transactionRetCapsule); transactionStore.put(transactionId, transactionCapsule); } diff --git a/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java b/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java index 7993ee5b19c..21d34fb7a69 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionStoreTest.java @@ -1,26 +1,21 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Random; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ItemNotFoundException; @@ -32,7 +27,7 @@ import org.tron.protos.contract.WitnessContract.VoteWitnessContract.Vote; import org.tron.protos.contract.WitnessContract.WitnessCreateContract; -public class TransactionStoreTest { +public class TransactionStoreTest extends BaseTest { private static final byte[] key1 = TransactionStoreTest.randomBytes(21); private static final byte[] key2 = TransactionStoreTest.randomBytes(21); @@ -45,35 +40,17 @@ public class TransactionStoreTest { private static final long AMOUNT = 100; private static final String WITNESS_ADDRESS = Wallet.getAddressPreFixString() + "548794500882809695a8a687866e76d4271a1abc"; - private static String dbPath = "output_TransactionStore_test"; private static String dbDirectory = "db_TransactionStore_test"; private static String indexDirectory = "index_TransactionStore_test"; - private static TransactionStore transactionStore; - private static TronApplicationContext context; - private static Application AppT; - private static ChainBaseManager chainBaseManager; + @Resource + private TransactionStore transactionStore; /** * Init data. */ @BeforeClass public static void init() { - Args.setParam(new String[]{"--output-directory", dbPath, "--storage-db-directory", - dbDirectory, "--storage-index-directory", indexDirectory, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - chainBaseManager = context.getBean(ChainBaseManager.class); - transactionStore = chainBaseManager.getTransactionStore(); - } - - /** - * release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); } /** @@ -135,7 +112,7 @@ private VoteWitnessContract getVoteWitnessContract(String address, String votead public void getTransactionTest() throws BadItemException, ItemNotFoundException { final BlockStore blockStore = chainBaseManager.getBlockStore(); final TransactionStore trxStore = chainBaseManager.getTransactionStore(); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; + String key = PublicMethod.getRandomPrivateKey();; BlockCapsule blockCapsule = new BlockCapsule( @@ -204,8 +181,7 @@ public void createAccountTransactionStoreTest() throws BadItemException { public void getUncheckedTransactionTest() { final BlockStore blockStore = chainBaseManager.getBlockStore(); final TransactionStore trxStore = chainBaseManager.getTransactionStore(); - String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62"; - + String key = PublicMethod.getRandomPrivateKey(); BlockCapsule blockCapsule = new BlockCapsule( 1, diff --git a/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java b/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java index cb47bce4df6..08848fc9da1 100644 --- a/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java +++ b/framework/src/test/java/org/tron/core/db/TransactionTraceTest.java @@ -18,22 +18,17 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.io.File; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.RuntimeImpl; import org.tron.common.runtime.TvmTestUtils; import org.tron.common.utils.ByteArray; import org.tron.common.utils.Commons; -import org.tron.common.utils.FileUtil; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BalanceInsufficientException; import org.tron.core.exception.ContractExeException; @@ -53,93 +48,43 @@ import org.tron.protos.contract.SmartContractOuterClass.SmartContract; import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -public class TransactionTraceTest { +public class TransactionTraceTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_TransactionTrace_test"; private static String dbDirectory = "db_TransactionTrace_test"; private static String indexDirectory = "index_TransactionTrace_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; private static ByteString ownerAddress = ByteString.copyFrom(ByteArray.fromInt(1)); private static ByteString contractAddress = ByteString.copyFrom(ByteArray.fromInt(2)); - - /* - * DeployContract tracetestContract [{"constant":false,"inputs":[{"name":"accountId","type": - * "uint256"}],"name":"getVoters","outputs":[{"name":"","type":"uint256"}],"payable":false," - * stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type" - * :"uint256"}],"name":"voters","outputs":[{"name":"","type":"uint256"}],"payable":false, - * "stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"vote","type" - * :"uint256"}],"name":"addVoters","outputs":[],"payable":false,"stateMutability":"nonpayable", - * "type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type": - * "constructor"}] 608060405234801561001057600080fd5b5060015b620186a081101561003857600081815260 - * 2081905260409020819055600a01610014565b5061010b806100486000396000f300608060405260043610605257 - * 63ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166386b646f281 - * 146057578063da58c7d914607e578063eb91a5ff146093575b600080fd5b348015606257600080fd5b50606c6004 - * 3560aa565b60408051918252519081900360200190f35b348015608957600080fd5b50606c60043560bc565b3480 - * 15609e57600080fd5b5060a860043560ce565b005b60009081526020819052604090205490565b60006020819052 - * 908152604090205481565b6000818152602081905260409020555600a165627a7a72305820f9935f89890e51bcf3 - * ea98fa4841c91ac5957a197d99eeb7879a775b30ee9a2d0029 1000000000 100 - * */ - /* - * DeployContract tracetestContract [{"constant":false,"inputs":[{"name":"accountId","type": - * "uint256"}],"name":"getVoters","outputs":[{"name":"","type":"uint256"}],"payable":false, - * "stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"", - * "type":"uint256"}],"name":"voters","outputs":[{"name":"","type":"uint256"}],"payable":false, - * "stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"vote","type" - * :"uint256"}],"name":"addVoters","outputs":[],"payable":false,"stateMutability":"nonpayable", - * "type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type": - * "constructor"}] 608060405234801561001057600080fd5b5060015b620186a08110156100385760008181526020 - * 81905260409020819055600a01610014565b5061010b806100486000396000f30060806040526004361060525763ff - * ffffff7c010000000000000000000000000000000000000000000000000000000060003504166386b646f281146057 - * 578063da58c7d914607e578063eb91a5ff146093575b600080fd5b348015606257600080fd5b50606c60043560aa56 - * 5b60408051918252519081900360200190f35b348015608957600080fd5b50606c60043560bc565b348015609e576 - * 00080fd5b5060a860043560ce565b005b60009081526020819052604090205490565b6000602081905290815260409 - * 0205481565b6000818152602081905260409020555600a165627a7a72305820f9935f89890e51bcf3ea98fa4841c91 - * ac5957a197d99eeb7879a775b30ee9a2d0029 1000000000 40 - * */ private static String OwnerAddress = "TCWHANtDDdkZCTo2T2peyEq3Eg9c2XB7ut"; private static String TriggerOwnerAddress = "TCSgeWapPJhCqgWRxXCKb6jJ5AgNWSGjPA"; - /* - * triggercontract TPMBUANrTwwQAPwShn7ZZjTJz1f3F8jknj addVoters(uint256) 113 false 1000000000 0 - * */ + private static boolean init; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w", "--debug" }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(100_000L); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); VMConfig.initVmHardFork(false); - - } - - /** - * destroy clear data of testing. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -436,4 +381,69 @@ public void testPay() throws BalanceInsufficientException { transactionTrace.pay(); AccountCapsule accountCapsule1 = dbManager.getAccountStore().get(ownerAddress.toByteArray()); } + + + @Test + public void testTriggerUseUsageInWindowSizeV2() throws VMIllegalException, ContractExeException, + ContractValidateException, BalanceInsufficientException { + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(14); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(1); + + String contractName = "tracetestContract"; + String code = "608060405234801561001057600080fd5b5060005b6103e88110156100375760008181526020819" + + "05260409020819055600a01610014565b5061010f806100476000396000f300608060405260043610605257" + + "63ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634903b" + + "0d181146057578063da31158814607e578063fe4ba936146093575b600080fd5b348015606257600080fd5b" + + "50606c60043560ad565b60408051918252519081900360200190f35b348015608957600080fd5b50606c600" + + "43560bf565b348015609e57600080fd5b5060ab60043560243560d1565b005b600060208190529081526040" + + "90205481565b60009081526020819052604090205490565b600091825260208290526040909120555600a16" + + "5627a7a723058200596e6c0a5371c2c533eb97ba4c1c19b0521750a5624cb5d2e93249c8b7219d20029"; + String abi = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":" + + "\"balances\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"st" + + "ateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name" + + "\":\"account\",\"type\":\"uint256\"}],\"name\":\"getCoin\",\"outputs\":[{\"name\":\"\"" + + ",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"func" + + "tion\"},{\"constant\":false,\"inputs\":[{\"name\":\"receiver\",\"type\":\"uint256\"},{" + + "\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"setCoin\",\"outputs\":[],\"payab" + + "le\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"" + + "payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]"; + CreateSmartContract smartContract = TvmTestUtils.createSmartContract( + Commons.decodeFromBase58Check(OwnerAddress), contractName, abi, code, 0, + 100); + Transaction transaction = Transaction.newBuilder().setRawData(raw.newBuilder().addContract( + Contract.newBuilder().setParameter(Any.pack(smartContract)) + .setType(ContractType.CreateSmartContract)).setFeeLimit(1000000000) + .setTimestamp(System.currentTimeMillis())) + .build(); + + byte[] contractAddress = deployInit(transaction); + AccountCapsule accountCapsule = new AccountCapsule(ByteString.copyFrom("owner".getBytes()), + ByteString.copyFrom(Commons.decodeFromBase58Check(TriggerOwnerAddress)), + AccountType.Normal, + totalBalance); + + accountCapsule.setFrozenForEnergy(10_000_000L, 0L); + dbManager.getAccountStore() + .put(Commons.decodeFromBase58Check(TriggerOwnerAddress), accountCapsule); + TriggerSmartContract triggerContract = TvmTestUtils.createTriggerContract(contractAddress, + "setCoin(uint256,uint256)", "133,133", false, + 0, Commons.decodeFromBase58Check(TriggerOwnerAddress)); + Transaction transaction2 = Transaction.newBuilder().setRawData(raw.newBuilder().addContract( + Contract.newBuilder().setParameter(Any.pack(triggerContract)) + .setType(ContractType.TriggerSmartContract)).setFeeLimit(1000000000L)).build(); + TransactionCapsule transactionCapsule = new TransactionCapsule(transaction2); + TransactionTrace trace = new TransactionTrace(transactionCapsule, StoreFactory + .getInstance(), new RuntimeImpl()); + trace.init(null); + trace.exec(); + trace.pay(); + Assert.assertEquals(0, trace.getReceipt().getEnergyUsage()); + Assert.assertEquals(2025200, trace.getReceipt().getEnergyFee()); + accountCapsule = dbManager.getAccountStore().get(accountCapsule.getAddress().toByteArray()); + Assert.assertEquals(totalBalance, + accountCapsule.getBalance() + trace.getReceipt().getEnergyFee()); + + dbManager.getDynamicPropertiesStore().saveUnfreezeDelayDays(0); + dbManager.getDynamicPropertiesStore().saveAllowCancelAllUnfreezeV2(0); + } } diff --git a/framework/src/test/java/org/tron/core/db/TreeBlockIndexStoreTest.java b/framework/src/test/java/org/tron/core/db/TreeBlockIndexStoreTest.java new file mode 100644 index 00000000000..19d1329e580 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/TreeBlockIndexStoreTest.java @@ -0,0 +1,52 @@ +package org.tron.core.db; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.store.TreeBlockIndexStore; + +public class TreeBlockIndexStoreTest extends BaseTest { + + @Resource + private TreeBlockIndexStore treeBlockIndexStore; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath() + }, + Constant.TEST_CONF + ); + } + + @Test + public void testPut() throws ItemNotFoundException { + treeBlockIndexStore.put(1L, "testPut".getBytes()); + byte[] result = treeBlockIndexStore.get(1L); + Assert.assertEquals(new String(result),"testPut"); + } + + @Test + public void testGetByNum() throws Exception { + treeBlockIndexStore.put(2L, "testGetByNum".getBytes()); + byte[] result = treeBlockIndexStore.get(2L); + Assert.assertEquals(new String(result),"testGetByNum"); + Assert.assertThrows(ItemNotFoundException.class, () -> treeBlockIndexStore.get(0L)); + } + + @Test + public void testGet() throws Exception { + treeBlockIndexStore.put(3L, "testGet".getBytes()); + final BytesCapsule result = treeBlockIndexStore.get(ByteArray.fromLong(3L)); + Assert.assertEquals(new String(result.getData()),"testGet"); + Assert.assertThrows(ItemNotFoundException.class, () -> treeBlockIndexStore + .get(ByteArray.fromLong(0L))); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/TronDatabaseTest.java b/framework/src/test/java/org/tron/core/db/TronDatabaseTest.java new file mode 100644 index 00000000000..f38f55df64d --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/TronDatabaseTest.java @@ -0,0 +1,101 @@ +package org.tron.core.db; + +import com.google.protobuf.InvalidProtocolBufferException; +import java.io.IOException; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.rules.TemporaryFolder; +import org.rocksdb.RocksDB; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.exception.BadItemException; +import org.tron.core.exception.ItemNotFoundException; + +public class TronDatabaseTest extends TronDatabase { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + static { + RocksDB.loadLibrary(); + } + + @BeforeClass + public static void initArgs() throws IOException { + Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + } + + @Override + public void put(byte[] key, String item) { + + } + + @Override + public void delete(byte[] key) { + + } + + @Override + public String get(byte[] key) { + return "test"; + } + + @Override + public boolean has(byte[] key) { + return false; + } + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @Test + public void TestInit() { + TronDatabaseTest db = new TronDatabaseTest(); + Assert.assertNull(db.getDbSource()); + Assert.assertNull(db.getDbName()); + } + + @Test + public void TestIterator() { + TronDatabaseTest db = new TronDatabaseTest(); + thrown.expect(UnsupportedOperationException.class); + db.iterator(); + } + + @Test + public void TestIsNotEmpty() { + TronDatabaseTest db = new TronDatabaseTest(); + thrown.expect(UnsupportedOperationException.class); + db.isNotEmpty(); + } + + @Test + public void TestGetUnchecked() { + TronDatabaseTest db = new TronDatabaseTest(); + Assert.assertNull(db.getUnchecked("test".getBytes())); + } + + @Test + public void TestClose() { + TronDatabaseTest db = new TronDatabaseTest(); + db.close(); + } + + @Test + public void TestGetFromRoot() throws + InvalidProtocolBufferException, BadItemException, ItemNotFoundException { + TronDatabaseTest db = new TronDatabaseTest(); + Assert.assertEquals(db.getFromRoot("test".getBytes()), + "test"); + } +} diff --git a/framework/src/test/java/org/tron/core/db/TxCacheDBInitTest.java b/framework/src/test/java/org/tron/core/db/TxCacheDBInitTest.java new file mode 100644 index 00000000000..b976cf5f2da --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/TxCacheDBInitTest.java @@ -0,0 +1,103 @@ +package org.tron.core.db; + +import java.io.IOException; +import lombok.extern.slf4j.Slf4j; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.keystore.Wallet; + +@Slf4j +public class TxCacheDBInitTest { + + private static TronApplicationContext context; + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private final byte[][] hash = new byte[140000][64]; + + @AfterClass + public static void destroy() { + context.destroy(); + Args.clearParam(); + } + + /** + * Init data. + */ + @BeforeClass + public static void init() throws IOException { + Args.setParam(new String[]{"--output-directory", temporaryFolder.newFolder().toString(), + "--p2p-disable", "true"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + } + + @Test + public void reload() { + TransactionCache db = context.getBean(TransactionCache.class); + db.initCache(); + putTransaction(); + DefaultListableBeanFactory defaultListableBeanFactory = + (DefaultListableBeanFactory) context.getAutowireCapableBeanFactory(); + queryTransaction(); + db.close(); + defaultListableBeanFactory.destroySingleton("transactionCache"); + db = new TransactionCache("transactionCache", + context.getBean(RecentTransactionStore.class), + context.getBean(DynamicPropertiesStore.class)); + db.initCache(); + defaultListableBeanFactory.registerSingleton("transactionCache",db); + queryTransaction(); + db.close(); + defaultListableBeanFactory.destroySingleton("transactionCache"); + db = new TransactionCache("transactionCache", + context.getBean(RecentTransactionStore.class), + context.getBean(DynamicPropertiesStore.class)); + DynamicPropertiesStore dynamicPropertiesStore = context.getBean(DynamicPropertiesStore.class); + dynamicPropertiesStore.saveLatestBlockHeaderNumber(1); + defaultListableBeanFactory.registerSingleton("transactionCache",db); + db.initCache(); + Assert.assertFalse(db.has(hash[65538])); + } + + private void putTransaction() { + TransactionCache db = context.getBean(TransactionCache.class); + for (int i = 1; i < 140000; i++) { + hash[i] = Wallet.generateRandomBytes(64); + db.put(hash[i], new BytesCapsule(ByteArray.fromLong(i))); + } + } + + private void queryTransaction() { + TransactionCache db = context.getBean(TransactionCache.class); + // [1,65537] are expired + for (int i = 1; i < 65538; i++) { + try { + Assert.assertFalse("index = " + i, db.has(hash[i])); + } catch (Exception e) { + Assert.fail("transaction should be expired index = " + i); + } + } + // [65538,140000] are in cache + for (int i = 65538; i < 140000; i++) { + try { + Assert.assertTrue("index = " + i, db.has(hash[i])); + } catch (Exception e) { + Assert.fail("transaction should not be expired index = " + i); + } + } + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java b/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java new file mode 100644 index 00000000000..4d223e726ca --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/TxCacheDBTest.java @@ -0,0 +1,51 @@ +package org.tron.core.db; + +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.config.args.Args; +import org.tron.keystore.Wallet; + +public class TxCacheDBTest extends BaseTest { + + /** + * Init data. + */ + @BeforeClass + public static void init() { + String dbDirectory = "db_TransactionCache_test"; + String indexDirectory = "index_TransactionCache_test"; + Args.setParam(new String[]{"--output-directory", dbPath(), "--storage-db-directory", + dbDirectory, "--storage-index-directory", indexDirectory}, Constant.TEST_CONF); + } + + @Test + public void putTransactionTest() { + TransactionCache db = dbManager.getTransactionCache(); + byte[][] hash = new byte[140000][64]; + for (int i = 1; i < 140000; i++) { + hash[i] = Wallet.generateRandomBytes(64); + db.put(hash[i], new BytesCapsule(ByteArray.fromLong(i))); + } + // [1,65537] are expired + for (int i = 1; i < 65538; i++) { + try { + Assert.assertFalse("index = " + i, db.has(hash[i])); + } catch (Exception e) { + Assert.fail("transaction should be expired index = " + i); + } + } + // [65538,140000] are in cache + for (int i = 65538; i < 140000; i++) { + try { + Assert.assertTrue("index = " + i, db.has(hash[i])); + } catch (Exception e) { + Assert.fail("transaction should not be expired index = " + i); + } + } + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/VotesStoreTest.java b/framework/src/test/java/org/tron/core/db/VotesStoreTest.java index 55b0a4882e3..48d4d1324db 100755 --- a/framework/src/test/java/org/tron/core/db/VotesStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/VotesStoreTest.java @@ -1,47 +1,29 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.VotesCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.VotesStore; import org.tron.protos.Protocol.Vote; @Slf4j -public class VotesStoreTest { +public class VotesStoreTest extends BaseTest { - private static final String dbPath = "output-votesStore-test"; - private static TronApplicationContext context; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } - VotesStore votesStore; - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - - @Before - public void initDb() { - this.votesStore = context.getBean(VotesStore.class); - } + @Resource + private VotesStore votesStore; @Test public void putAndGetVotes() { diff --git a/framework/src/test/java/org/tron/core/db/WitnessScheduleStoreTest.java b/framework/src/test/java/org/tron/core/db/WitnessScheduleStoreTest.java new file mode 100644 index 00000000000..7588b1c7add --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/WitnessScheduleStoreTest.java @@ -0,0 +1,105 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import java.util.Arrays; +import java.util.List; +import javax.annotation.Resource; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.store.WitnessScheduleStore; + +public class WitnessScheduleStoreTest extends BaseTest { + + @Resource + private WitnessScheduleStore witnessScheduleStore; + private static final String KEY1 = "41f08012b4881c320eb40b80f1228731898824e09d"; + private static final String KEY2 = "41df309fef25b311e7895562bd9e11aab2a58816d2"; + private static final String KEY3 = "41F8C7ACC4C08CF36CA08FC2A61B1F5A7C8DEA7BEC"; + + private static final String CURRENT_KEY1 = "411D7ABA13EA199A63D1647E58E39C16A9BB9DA689"; + private static final String CURRENT_KEY2 = "410694981B116304ED21E05896FB16A6BC2E91C92C"; + private static final String CURRENT_KEY3 = "411155D10415FAC16A8F4CB2F382CE0E0F0A7E64CC"; + + private static List witnessAddresses; + private static List currentShuffledWitnesses; + + + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Before + public void init() { + witnessAddresses = Arrays.asList( + getByteString(KEY1), + getByteString(KEY2), + getByteString(KEY3) + ); + + currentShuffledWitnesses = Arrays.asList( + getByteString(CURRENT_KEY1), + getByteString(CURRENT_KEY2), + getByteString(CURRENT_KEY3) + ); + } + + private ByteString getByteString(String address) { + return ByteString.copyFrom( + ByteArray.fromHexString(address)); + } + + @Test + public void tetSaveActiveWitnesses() { + witnessScheduleStore.saveActiveWitnesses(witnessAddresses); + List activeWitnesses = witnessScheduleStore.getActiveWitnesses(); + Assert.assertNotNull(activeWitnesses); + Assert.assertEquals(3, activeWitnesses.size()); + ByteString firstWitness = activeWitnesses.get(0); + Assert.assertEquals(getByteString(KEY1), firstWitness); + } + + @Test + public void testGetActiveWitnesses() { + witnessScheduleStore.saveActiveWitnesses(witnessAddresses); + List activeWitnesses = witnessScheduleStore.getActiveWitnesses(); + Assert.assertNotNull(activeWitnesses); + Assert.assertEquals(3, activeWitnesses.size()); + ByteString firstWitness = activeWitnesses.get(0); + ByteString secondWitness = activeWitnesses.get(1); + ByteString thirdWitness = activeWitnesses.get(2); + Assert.assertEquals(getByteString(KEY1), firstWitness); + Assert.assertEquals(getByteString(KEY2), secondWitness); + Assert.assertEquals(getByteString(KEY3), thirdWitness); + } + + @Test + public void testSaveCurrentShuffledWitnesses() { + witnessScheduleStore.saveCurrentShuffledWitnesses(currentShuffledWitnesses); + List currentWitnesses = witnessScheduleStore.getCurrentShuffledWitnesses(); + Assert.assertNotNull(currentWitnesses); + Assert.assertEquals(3, currentWitnesses.size()); + ByteString firstWitness = currentWitnesses.get(0); + Assert.assertEquals(getByteString(CURRENT_KEY1), firstWitness); + } + + @Test + public void GetCurrentShuffledWitnesses() { + witnessScheduleStore.saveCurrentShuffledWitnesses(currentShuffledWitnesses); + List currentWitnesses = witnessScheduleStore.getCurrentShuffledWitnesses(); + Assert.assertNotNull(currentWitnesses); + Assert.assertEquals(3, currentWitnesses.size()); + ByteString firstWitness = currentWitnesses.get(0); + ByteString secondWitness = currentWitnesses.get(1); + ByteString thirdWitness = currentWitnesses.get(2); + Assert.assertEquals(getByteString(CURRENT_KEY1), firstWitness); + Assert.assertEquals(getByteString(CURRENT_KEY2), secondWitness); + Assert.assertEquals(getByteString(CURRENT_KEY3), thirdWitness); + } + +} diff --git a/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java b/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java index 5ae37650b6a..d141a5fd790 100755 --- a/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java +++ b/framework/src/test/java/org/tron/core/db/WitnessStoreTest.java @@ -1,44 +1,28 @@ package org.tron.core.db; import com.google.protobuf.ByteString; -import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.store.WitnessStore; @Slf4j -public class WitnessStoreTest { - - private static final String dbPath = "output-witnessStore-test"; - private static TronApplicationContext context; +public class WitnessStoreTest extends BaseTest { static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - WitnessStore witnessStore; - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } - @Before - public void initDb() { - this.witnessStore = context.getBean(WitnessStore.class); - } + @Resource + private WitnessStore witnessStore; @Test public void putAndGetWitness() { @@ -65,5 +49,27 @@ public void putAndGetWitness() { Assert.assertEquals(100L, witnessSource.getVoteCount()); } - + @Test + public void testSortWitness() { + this.witnessStore.reset(); + WitnessCapsule s1 = new WitnessCapsule( + ByteString.copyFrom(new byte[]{1, 2, 3}), 100L, "URL-1"); + this.witnessStore.put(s1.getAddress().toByteArray(), s1); + WitnessCapsule s2 = new WitnessCapsule( + ByteString.copyFrom(new byte[]{1, 1, 34}), 100L, "URL-2"); + this.witnessStore.put(s2.getAddress().toByteArray(), s2); + List allWitnesses = this.witnessStore.getAllWitnesses(); + List witnessAddress = allWitnesses.stream().map(WitnessCapsule::getAddress) + .collect(Collectors.toList()); + this.witnessStore.sortWitness(witnessAddress, false); + this.witnessStore.sortWitnesses(allWitnesses, false); + Assert.assertEquals(witnessAddress, allWitnesses.stream().map(WitnessCapsule::getAddress) + .collect(Collectors.toList())); + List pre = new ArrayList<>(witnessAddress); + this.witnessStore.sortWitness(witnessAddress, true); + this.witnessStore.sortWitnesses(allWitnesses, true); + Assert.assertEquals(witnessAddress, allWitnesses.stream().map(WitnessCapsule::getAddress) + .collect(Collectors.toList())); + Assert.assertNotEquals(pre, witnessAddress); + } } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db/ZKProofStoreTest.java b/framework/src/test/java/org/tron/core/db/ZKProofStoreTest.java new file mode 100644 index 00000000000..a8aa07c4342 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/ZKProofStoreTest.java @@ -0,0 +1,58 @@ +package org.tron.core.db; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.ZKProofStore; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +public class ZKProofStoreTest extends BaseTest { + + static { + Args.setParam(new String[]{"--output-directory", dbPath()}, + Constant.TEST_CONF); + } + + @Autowired + private ZKProofStore proofStore; + + private TransactionCapsule getTransactionCapsule() { + BalanceContract.TransferContract transferContract = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + return new TransactionCapsule(transferContract, + Protocol.Transaction.Contract.ContractType.TransferContract); + } + + @Test + public void testPut() { + TransactionCapsule trx = getTransactionCapsule(); + proofStore.put(trx.getTransactionId().getBytes(), + true); + boolean has = proofStore.has(trx.getTransactionId().getBytes()); + Assert.assertTrue(has); + } + + @Test + public void testGet() { + TransactionCapsule trx = getTransactionCapsule(); + proofStore.put(trx.getTransactionId().getBytes(), + true); + Boolean result = proofStore.get(trx.getTransactionId().getBytes()); + Assert.assertEquals(true, result); + + proofStore.put(trx.getTransactionId().getBytes(), + false); + result = proofStore.get(trx.getTransactionId().getBytes()); + Assert.assertEquals(false, result); + } +} diff --git a/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java b/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java index dcb899dde19..d1edd92c109 100644 --- a/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java +++ b/framework/src/test/java/org/tron/core/db/api/AssetUpdateHelperTest.java @@ -3,51 +3,39 @@ import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; import com.google.protobuf.ByteString; -import java.io.File; -import org.junit.AfterClass; +import java.util.Objects; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; -import org.tron.core.ChainBaseManager; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.AssetIssueCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.ExchangeCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.protos.Protocol.Account; import org.tron.protos.Protocol.Exchange; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -public class AssetUpdateHelperTest { +public class AssetUpdateHelperTest extends BaseTest { - private static ChainBaseManager chainBaseManager; - private static TronApplicationContext context; - private static String dbPath = "output_AssetUpdateHelperTest_test"; - private static Application AppT; - - private static ByteString assetName = ByteString.copyFrom("assetIssueName".getBytes()); + private static final ByteString assetName = ByteString.copyFrom("assetIssueName".getBytes()); + private static boolean init; static { - Args.setParam(new String[]{"-d", dbPath, "-w"}, "config-test-index.conf"); + Args.setParam(new String[]{"-d", dbPath()}, "config-test-index.conf"); Args.getInstance().setSolidityNode(true); - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); } - @BeforeClass - public static void init() { - - chainBaseManager = context.getBean(ChainBaseManager.class); - + @Before + public void init() { + if (init) { + return; + } AssetIssueContract contract = AssetIssueContract.newBuilder().setName(assetName).setNum(12581).setPrecision(5).build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(contract); @@ -84,13 +72,7 @@ public static void init() { .build()); chainBaseManager.getAccountStore().put(ByteArray.fromHexString("121212abc"), accountCapsule); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } @Test @@ -112,7 +94,7 @@ public void test() { Assert.assertEquals(5L, assetIssueCapsule.getPrecision()); AssetIssueCapsule assetIssueCapsule2 = - chainBaseManager.getAssetIssueV2Store().get(ByteArray.fromString(String.valueOf(idNum))); + chainBaseManager.getAssetIssueV2Store().get(ByteArray.fromString(idNum)); Assert.assertEquals(idNum, assetIssueCapsule2.getId()); Assert.assertEquals(assetName, assetIssueCapsule2.getName()); @@ -139,11 +121,12 @@ public void test() { chainBaseManager.getAccountStore().get(ByteArray.fromHexString("121212abc")); Assert.assertEquals( - ByteString.copyFrom(ByteArray.fromString("1000001")), accountCapsule.getAssetIssuedID()); + ByteString.copyFrom(Objects.requireNonNull(ByteArray.fromString("1000001"))), + accountCapsule.getAssetIssuedID()); - Assert.assertEquals(1, accountCapsule.getAssetMapV2().size()); + Assert.assertEquals(1, accountCapsule.getAssetV2MapForTest().size()); - Assert.assertEquals(100L, accountCapsule.getAssetMapV2().get("1000001").longValue()); + Assert.assertEquals(100L, accountCapsule.getAssetV2MapForTest().get("1000001").longValue()); Assert.assertEquals(1, accountCapsule.getAllFreeAssetNetUsageV2().size()); diff --git a/framework/src/test/java/org/tron/core/db/api/pojo/PojoTest.java b/framework/src/test/java/org/tron/core/db/api/pojo/PojoTest.java new file mode 100644 index 00000000000..f4661725a02 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db/api/pojo/PojoTest.java @@ -0,0 +1,80 @@ +package org.tron.core.db.api.pojo; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.common.collect.Lists; +import org.junit.Test; + +public class PojoTest { + + @Test + public void testAccountCreation() { + Account account = Account.of(); + account.setName("testName"); + account.setAddress("testAddress"); + account.setBalance(1622548800000L); + + assertNotNull(account); + assertEquals("testName", account.getName()); + assertEquals("testAddress", account.getAddress()); + assertEquals(1622548800000L, account.getBalance()); + } + + @Test + public void testAssetIssueCreation() { + AssetIssue assetIssue = AssetIssue.of(); + assetIssue.setName("testName"); + assetIssue.setAddress("testAddress"); + assetIssue.setStart(1622548800000L); + assetIssue.setEnd(1654084800000L); + + assertNotNull(assetIssue); + assertEquals("testName", assetIssue.getName()); + assertEquals("testAddress", assetIssue.getAddress()); + assertEquals(1622548800000L, assetIssue.getStart()); + assertEquals(1654084800000L, assetIssue.getEnd()); + } + + @Test + public void testBlockCreation() { + Block block = Block.of(); + block.setId("7654321"); + block.setNumber(1000L); + block.setTransactionIds(Lists.newArrayList("1234567")); + + assertNotNull(block); + assertEquals("7654321", block.getId()); + assertEquals(1000L, block.getNumber()); + assertEquals("1234567", block.getTransactionIds().get(0)); + } + + @Test + public void testTransactionCreation() { + Transaction transaction = Transaction.of(); + transaction.setId("7654321"); + transaction.setFrom("from"); + transaction.setTo("to"); + + assertNotNull(transaction); + assertEquals("7654321", transaction.getId()); + assertEquals("from", transaction.getFrom()); + assertEquals("to", transaction.getTo()); + } + + @Test + public void testWitnessCreation() { + Witness witness = Witness.of(); + witness.setAddress("testAddress"); + witness.setJobs(true); + witness.setUrl("https://cryptoai.com/"); + witness.setPublicKey("wergfsioejgbrotjsdfdoqwj"); + + assertNotNull(witness); + assertEquals("testAddress", witness.getAddress()); + assertTrue(witness.isJobs()); + assertEquals("https://cryptoai.com/", witness.getUrl()); + assertEquals("wergfsioejgbrotjsdfdoqwj", witness.getPublicKey()); + } +} diff --git a/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java b/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java index f63fafe060e..0153faeab71 100644 --- a/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java +++ b/framework/src/test/java/org/tron/core/db/backup/BackupDbUtilTest.java @@ -1,51 +1,43 @@ package org.tron.core.db.backup; import java.io.File; -import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.rocksdb.RocksDB; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.FileUtil; import org.tron.common.utils.PropUtil; import org.tron.consensus.dpos.DposSlot; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.Manager; import org.tron.core.db.ManagerForTest; -import org.tron.core.db2.core.Chainbase; -import org.tron.core.db2.core.SnapshotManager; @Slf4j -public class BackupDbUtilTest { +public class BackupDbUtilTest extends BaseTest { static { RocksDB.loadLibrary(); } - public TronApplicationContext context; - public Application AppT = null; - public BackupDbUtil dbBackupUtil; - public Manager dbManager; + @Resource public ConsensusService consensusService; + @Resource public DposSlot dposSlot; public ManagerForTest mngForTest; - public String dbPath = "output-BackupDbUtilTest"; String propPath; String bak1Path; String bak2Path; int frequency; - @Before - public void before() { + private static final String dbPath; + + static { + dbPath = dbPath(); Args.setParam( new String[]{ "--output-directory", dbPath, @@ -54,16 +46,12 @@ public void before() { }, "config-test-dbbackup.conf" ); + } - context = new TronApplicationContext(DefaultConfig.class); - AppT = ApplicationFactory.create(context); - dbManager = context.getBean(Manager.class); - dposSlot = context.getBean(DposSlot.class); - consensusService = context.getBean(ConsensusService.class); - dbBackupUtil = context.getBean(BackupDbUtil.class); + @Before + public void before() { consensusService.start(); mngForTest = new ManagerForTest(dbManager, dposSlot); - //prepare prop.properties propPath = dbPath + File.separator + "test_prop.properties"; bak1Path = dbPath + File.separator + "bak1/database"; @@ -75,49 +63,30 @@ public void before() { FileUtil.createFileIfNotExists(propPath); } - @After - public void after() { - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testDoBackup() { - PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), - String.valueOf("11")); + PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), "11"); mngForTest.pushNTestBlock(50); - List alist = ((SnapshotManager) dbBackupUtil.getDb()).getDbs(); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 50); - Assert.assertTrue("22".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(50, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("22", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 100); - Assert.assertTrue("11".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(100, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("11", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 150); - Assert.assertTrue("22".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(150, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("22", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); - PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), - String.valueOf("1")); + PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), "1"); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 200); - Assert.assertTrue("11".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(200, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("11", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); - PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), - String.valueOf("2")); + PropUtil.writeProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE(), "2"); mngForTest.pushNTestBlock(50); - Assert.assertTrue(dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() == 250); - Assert.assertTrue("22".equals( - PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE()))); + Assert.assertEquals(250, dbManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber()); + Assert.assertEquals("22", PropUtil.readProperty(propPath, BackupDbUtil.getDB_BACKUP_STATE())); } } diff --git a/framework/src/test/java/org/tron/core/db2/ChainbaseTest.java b/framework/src/test/java/org/tron/core/db2/ChainbaseTest.java new file mode 100644 index 00000000000..ee9813be633 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db2/ChainbaseTest.java @@ -0,0 +1,169 @@ +package org.tron.core.db2; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.rocksdb.RocksDB; +import org.tron.common.storage.leveldb.LevelDbDataSourceImpl; +import org.tron.common.storage.rocksdb.RocksDbDataSourceImpl; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.db.common.DbSourceInter; +import org.tron.core.db2.common.LevelDB; +import org.tron.core.db2.core.Chainbase; +import org.tron.core.db2.core.Snapshot; +import org.tron.core.db2.core.SnapshotRoot; + +@Slf4j +public class ChainbaseTest { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + private Chainbase chainbase = null; + + private final byte[] value0 = "00000".getBytes(); + private final byte[] value1 = "10000".getBytes(); + private final byte[] value2 = "20000".getBytes(); + private final byte[] value3 = "30000".getBytes(); + private final byte[] value4 = "40000".getBytes(); + private final byte[] value5 = "50000".getBytes(); + private final byte[] value6 = "60000".getBytes(); + private final byte[] value7 = "70000".getBytes(); + private final byte[] value8 = "80000".getBytes(); + private final byte[] valueRoot7 = "root70000".getBytes(); + private final byte[] valueRoot8 = "root80000".getBytes(); + private final byte[] value9 = "90000".getBytes(); + + private final byte[] key0 = "0aa".getBytes(); + private final byte[] key1 = "10000001aa".getBytes(); + private final byte[] key2 = "10000002aa".getBytes(); + private final byte[] key3 = "10000003aa".getBytes(); + private final byte[] key4 = "10000004aa".getBytes(); + private final byte[] key5 = "10000005aa".getBytes(); + private final byte[] key6 = "10000006aa".getBytes(); + private final byte[] key7 = "10000006ac".getBytes(); + private final byte[] key8 = "10000006ab".getBytes(); + private final byte[] key9 = "10000006dd".getBytes(); + + private final byte[] prefix = "1000000".getBytes(); + private final byte[] prefix2 = "2000000".getBytes(); + private final byte[] prefix3 = "0000000".getBytes(); + + /** + * Release resources. + */ + @AfterClass + public static void destroy() { + Args.clearParam(); + } + + @Before + public void initDb() throws IOException { + RocksDB.loadLibrary(); + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + } + + @Test + public void testPrefixQueryForLeveldb() { + LevelDbDataSourceImpl dataSource = new LevelDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "testPrefixQueryForLeveldb"); + dataSource.initDB(); + this.chainbase = new Chainbase(new SnapshotRoot( + new LevelDB(dataSource))); + testDb(chainbase); + testRoot(dataSource); + chainbase.reset(); + chainbase.close(); + } + + @Test + public void testPrefixQueryForRocksdb() { + RocksDbDataSourceImpl dataSource = new RocksDbDataSourceImpl( + Args.getInstance().getOutputDirectory(), "testPrefixQueryForRocksdb"); + dataSource.initDB(); + this.chainbase = new Chainbase(new SnapshotRoot( + new org.tron.core.db2.common.RocksDB(dataSource))); + testDb(chainbase); + testRoot(dataSource); + chainbase.reset(); + chainbase.close(); + } + + + private void testRoot(DbSourceInter dbSource) { + Map result = new HashMap<>(); + dbSource.prefixQuery(prefix).forEach((k, v) -> + result.put(ByteArray.toStr(k.getBytes()), ByteArray.toStr(v))); + + Map expect = new HashMap<>(); + expect.put(ByteArray.toStr(key2),ByteArray.toStr(value2)); + expect.put(ByteArray.toStr(key6),ByteArray.toStr(value6)); + expect.put(ByteArray.toStr(key7),ByteArray.toStr(valueRoot7)); + expect.put(ByteArray.toStr(key8),ByteArray.toStr(valueRoot8)); + Assert.assertEquals(expect, result); + Assert.assertTrue(dbSource.prefixQuery(prefix2).isEmpty()); + Assert.assertTrue(dbSource.prefixQuery(prefix3).isEmpty()); + } + + private void testDb(Chainbase chainbase) { + byte[] keyNotQuery1 = "123".getBytes(); + byte[] keyNotQuery2 = "0000001".getBytes(); + byte[] valueNotQuery1 = "v123".getBytes(); + byte[] valueNotQuery2 = "v0000001".getBytes(); + + chainbase.setHead(chainbase.getHead().advance()); + Snapshot head = chainbase.getHead(); + Snapshot root = head.getRoot(); + // put some data in head + head.put(key0, value0); + head.put(key1, value1); + head.put(key7, value7); + head.put(key3, value3); + head.put(key8, value8); + head.remove(key7); + // put some data in root + root.put(key2, value2); + root.put(key6, value6); + root.put(key3, value3); + root.put(key7, valueRoot7); + root.put(key8, valueRoot8); + root.put(keyNotQuery1, valueNotQuery1); + // advance head and put some data again + head = head.advance(); + head.put(key4, value4); + head.put(key5, value5); + head.put(key9,value9); + head.remove(key8); + head.put(keyNotQuery2, valueNotQuery2); + + head = head.advance(); + head.remove(key9); + root.remove(key3); + + // test for all, both in snapshotImpl and leveldb + Map result = new HashMap<>(); + chainbase.prefixQuery(prefix).forEach((k, v) -> + result.put(ByteArray.toStr(k.getBytes()), ByteArray.toStr(v))); + + Map expect = new HashMap<>(); + expect.put(ByteArray.toStr(key1),ByteArray.toStr(value1)); + expect.put(ByteArray.toStr(key2),ByteArray.toStr(value2)); + expect.put(ByteArray.toStr(key3),ByteArray.toStr(value3)); + expect.put(ByteArray.toStr(key4),ByteArray.toStr(value4)); + expect.put(ByteArray.toStr(key5),ByteArray.toStr(value5)); + expect.put(ByteArray.toStr(key6),ByteArray.toStr(value6)); + Assert.assertEquals(expect, result); + Assert.assertTrue(chainbase.prefixQuery(prefix2).isEmpty()); + Assert.assertTrue(chainbase.prefixQuery(prefix3).isEmpty()); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java new file mode 100644 index 00000000000..dff2d376fd5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/db2/CheckpointV2Test.java @@ -0,0 +1,106 @@ +package org.tron.core.db2; + +import com.google.common.collect.Maps; +import com.google.common.primitives.Bytes; +import com.google.common.primitives.Longs; +import com.google.protobuf.ByteString; +import java.io.File; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db2.RevokingDbWithCacheNewValueTest.TestRevokingTronStore; +import org.tron.core.db2.core.Chainbase; +import org.tron.core.db2.core.SnapshotManager; + +@Slf4j +public class CheckpointV2Test { + + private SnapshotManager revokingDatabase; + private TronApplicationContext context; + private Application appT; + private TestRevokingTronStore tronDatabase; + + @Before + public void init() { + Args.setParam(new String[]{"-d", "output_SnapshotManager_test"}, + Constant.TEST_CONF); + Args.getInstance().getStorage().setCheckpointVersion(2); + Args.getInstance().getStorage().setCheckpointSync(true); + context = new TronApplicationContext(DefaultConfig.class); + appT = ApplicationFactory.create(context); + revokingDatabase = context.getBean(SnapshotManager.class); + revokingDatabase.enable(); + tronDatabase = new TestRevokingTronStore("testSnapshotManager-test"); + revokingDatabase.add(tronDatabase.getRevokingDB()); + } + + @After + public void removeDb() { + Args.clearParam(); + context.destroy(); + tronDatabase.close(); + FileUtil.deleteDir(new File("output_SnapshotManager_test")); + revokingDatabase.getCheckTmpStore().close(); + tronDatabase.close(); + } + + @Test + public void testCheckpointV2() { + while (revokingDatabase.size() != 0) { + revokingDatabase.pop(); + } + + revokingDatabase.setMaxFlushCount(0); + revokingDatabase.setUnChecked(false); + revokingDatabase.setMaxSize(0); + List dbList = revokingDatabase.getDbs(); + Map dbMap = dbList.stream() + .map(db -> Maps.immutableEntry(db.getDbName(), db)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + for (int i = 1; i <= 5; i++) { + BlockCapsule blockCapsule = new BlockCapsule(i, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + try (ISession tmpSession = revokingDatabase.buildSession()) { + dbMap.get("block").put(Longs.toByteArray(i), blockCapsule.getData()); + tmpSession.commit(); + } + } + revokingDatabase.buildSession(); + + Iterator> iterator = dbMap.get("block").iterator(); + Sha256Hash preDbHash = Sha256Hash.ZERO_HASH; + while (iterator.hasNext()) { + Map.Entry entry = iterator.next(); + byte[] hashBytes = Bytes.concat(entry.getKey(), entry.getValue()); + preDbHash = Sha256Hash.of(true, Bytes.concat(preDbHash.getBytes(), hashBytes)); + } + + revokingDatabase.check(); + revokingDatabase.buildSession(); + + Iterator> iterator2 = dbMap.get("block").iterator(); + Sha256Hash afterDbHash = Sha256Hash.ZERO_HASH; + while (iterator2.hasNext()) { + Map.Entry entry = iterator2.next(); + byte[] hashBytes = Bytes.concat(entry.getKey(), entry.getValue()); + afterDbHash = Sha256Hash.of(true, Bytes.concat(afterDbHash.getBytes(), hashBytes)); + } + + Assert.assertEquals(0, preDbHash.compareTo(afterDbHash)); + } +} diff --git a/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java b/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java index 28a45be7868..2290df86978 100644 --- a/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java +++ b/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheNewValueTest.java @@ -7,6 +7,7 @@ import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.RandomStringUtils; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -34,9 +35,12 @@ public class RevokingDbWithCacheNewValueTest { private Application appT; private TestRevokingTronStore tronDatabase; + private String databasePath = ""; + @Before public void init() { - Args.setParam(new String[]{"-d", "output_revokingStore_test"}, + databasePath = "output_revokingStore_test_" + RandomStringUtils.randomAlphanumeric(10); + Args.setParam(new String[]{"-d", databasePath}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); appT = ApplicationFactory.create(context); @@ -47,7 +51,7 @@ public void removeDb() { Args.clearParam(); context.destroy(); tronDatabase.close(); - FileUtil.deleteDir(new File("output_revokingStore_test")); + FileUtil.deleteDir(new File(databasePath)); } @Test @@ -384,7 +388,8 @@ public synchronized void testGetKeysNextWithSameKey() { public synchronized void testGetKeysNextWithSameKeyOrderCheck() { revokingDatabase = context.getBean(SnapshotManager.class); revokingDatabase.enable(); - tronDatabase = new TestRevokingTronStore("testSnapshotManager-testGetKeysNextWithSameKey"); + tronDatabase = new TestRevokingTronStore( + "testSnapshotManager-testGetKeysNextWithSameKeyOrderCheck"); revokingDatabase.add(tronDatabase.getRevokingDB()); while (revokingDatabase.size() != 0) { revokingDatabase.pop(); diff --git a/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheOldValueTest.java b/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheOldValueTest.java deleted file mode 100644 index f7a4d58fd97..00000000000 --- a/framework/src/test/java/org/tron/core/db2/RevokingDbWithCacheOldValueTest.java +++ /dev/null @@ -1,279 +0,0 @@ -package org.tron.core.db2; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.ArrayUtils; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; -import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; -import org.tron.core.db.AbstractRevokingStore; -import org.tron.core.db.RevokingDatabase; -import org.tron.core.db.TronStoreWithRevoking; -import org.tron.core.db2.SnapshotRootTest.ProtoCapsuleTest; -import org.tron.core.exception.RevokingStoreIllegalStateException; - -@Slf4j -public class RevokingDbWithCacheOldValueTest { - - private AbstractRevokingStore revokingDatabase; - private TronApplicationContext context; - private Application appT; - - @Before - public void init() { - Args.setParam(new String[]{"-d", "output_revokingStore_test"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); - revokingDatabase = new TestRevokingTronDatabase(); - revokingDatabase.enable(); - } - - @After - public void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File("output_revokingStore_test")); - } - - @Test - public synchronized void testReset() { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-testReset", revokingDatabase); - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("reset").getBytes()); - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - tmpSession.commit(); - } - Assert.assertTrue(tronDatabase.has(testProtoCapsule.getData())); - tronDatabase.reset(); - Assert.assertFalse(tronDatabase.has(testProtoCapsule.getData())); - tronDatabase.reset(); - } - - @Test - public synchronized void testPop() throws RevokingStoreIllegalStateException { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-testPop", revokingDatabase); - - for (int i = 1; i < 11; i++) { - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("pop" + i).getBytes()); - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - Assert.assertEquals(1, revokingDatabase.getActiveDialog()); - tmpSession.commit(); - Assert.assertEquals(i, revokingDatabase.getStack().size()); - Assert.assertEquals(0, revokingDatabase.getActiveDialog()); - } - } - - for (int i = 1; i < 11; i++) { - revokingDatabase.pop(); - Assert.assertEquals(10 - i, revokingDatabase.getStack().size()); - } - - tronDatabase.close(); - - Assert.assertEquals(0, revokingDatabase.getStack().size()); - } - - @Test - public synchronized void testUndo() throws RevokingStoreIllegalStateException { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-testUndo", revokingDatabase); - - ISession dialog = revokingDatabase.buildSession(); - for (int i = 0; i < 10; i++) { - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("undo" + i).getBytes()); - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - Assert.assertEquals(2, revokingDatabase.getStack().size()); - tmpSession.merge(); - Assert.assertEquals(1, revokingDatabase.getStack().size()); - } - } - - Assert.assertEquals(1, revokingDatabase.getStack().size()); - - dialog.destroy(); - Assert.assertTrue(revokingDatabase.getStack().isEmpty()); - Assert.assertEquals(0, revokingDatabase.getActiveDialog()); - - dialog = revokingDatabase.buildSession(); - revokingDatabase.disable(); - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest("del".getBytes()); - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - revokingDatabase.enable(); - - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), new ProtoCapsuleTest("del2".getBytes())); - tmpSession.merge(); - } - - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), new ProtoCapsuleTest("del22".getBytes())); - tmpSession.merge(); - } - - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), new ProtoCapsuleTest("del222".getBytes())); - tmpSession.merge(); - } - - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.delete(testProtoCapsule.getData()); - tmpSession.merge(); - } - - dialog.destroy(); - - logger.info( - "**********testProtoCapsule:" + tronDatabase.getUnchecked(testProtoCapsule.getData()) - .toString()); - Assert.assertArrayEquals("del".getBytes(), - tronDatabase.getUnchecked(testProtoCapsule.getData()).getData()); - Assert.assertEquals(testProtoCapsule, tronDatabase.getUnchecked(testProtoCapsule.getData())); - - tronDatabase.close(); - } - - @Test - public synchronized void testGetlatestValues() { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-testGetlatestValues", revokingDatabase); - - for (int i = 0; i < 10; i++) { - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("getLastestValues" + i).getBytes()); - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - tmpSession.commit(); - } - } - Set result = tronDatabase.getRevokingDB().getlatestValues(5).stream() - .map(ProtoCapsuleTest::new) - .collect(Collectors.toSet()); - - for (int i = 9; i >= 5; i--) { - Assert.assertTrue(result.contains(new ProtoCapsuleTest(("getLastestValues" + i).getBytes()))); - } - tronDatabase.close(); - } - - @Test - public synchronized void testGetValuesNext() { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-testGetValuesNext", revokingDatabase); - - for (int i = 0; i < 10; i++) { - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("getValuesNext" + i).getBytes()); - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - tmpSession.commit(); - } - } - Set result = - tronDatabase.getRevokingDB().getValuesNext( - new ProtoCapsuleTest("getValuesNext2".getBytes()).getData(), 3) - .stream() - .map(ProtoCapsuleTest::new) - .collect(Collectors.toSet()); - - for (int i = 2; i < 5; i++) { - Assert.assertTrue(result.contains(new ProtoCapsuleTest(("getValuesNext" + i).getBytes()))); - } - tronDatabase.close(); - } - - @Test - public synchronized void testGetKeysNext() { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-testGetKeysNext", revokingDatabase); - - String protoCapsuleStr = "getKeysNext"; - for (int i = 0; i < 10; i++) { - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest((protoCapsuleStr + i).getBytes()); - try (ISession tmpSession = revokingDatabase.buildSession()) { - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - tmpSession.commit(); - } - } - - int start = 2; - List result = - tronDatabase.getRevokingDB().getKeysNext( - new ProtoCapsuleTest((protoCapsuleStr + start).getBytes()).getData(), 3); - - for (int i = start; i < 5; i++) { - Assert.assertArrayEquals(new ProtoCapsuleTest((protoCapsuleStr + i).getBytes()).getData(), - result.get(i - 2)); - } - tronDatabase.close(); - } - - @Test - public void shutdown() throws RevokingStoreIllegalStateException { - revokingDatabase.getStack().clear(); - TestRevokingTronStore tronDatabase = new TestRevokingTronStore( - "testrevokingtronstore-shutdown", revokingDatabase); - - List capsules = new ArrayList<>(); - for (int i = 1; i < 11; i++) { - revokingDatabase.buildSession(); - ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("test" + i).getBytes()); - capsules.add(testProtoCapsule); - tronDatabase.put(testProtoCapsule.getData(), testProtoCapsule); - Assert.assertEquals(revokingDatabase.getActiveDialog(), i); - Assert.assertEquals(revokingDatabase.getStack().size(), i); - } - - for (ProtoCapsuleTest capsule : capsules) { - logger.info(new String(capsule.getData())); - Assert.assertEquals(capsule, tronDatabase.getUnchecked(capsule.getData())); - } - - revokingDatabase.shutdown(); - - for (ProtoCapsuleTest capsule : capsules) { - logger.info(tronDatabase.getUnchecked(capsule.getData()).toString()); - Assert.assertEquals(null, tronDatabase.getUnchecked(capsule.getData()).getData()); - } - - Assert.assertEquals(0, revokingDatabase.getStack().size()); - tronDatabase.close(); - - } - - private static class TestRevokingTronStore extends TronStoreWithRevoking { - - protected TestRevokingTronStore(String dbName, RevokingDatabase revokingDatabase) { - super(dbName, revokingDatabase); - } - - @Override - public ProtoCapsuleTest get(byte[] key) { - byte[] value = this.revokingDB.getUnchecked(key); - return ArrayUtils.isEmpty(value) ? null : new ProtoCapsuleTest(value); - } - } - - private static class TestRevokingTronDatabase extends AbstractRevokingStore { - - } -} diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java new file mode 100644 index 00000000000..aab6f656b1f --- /dev/null +++ b/framework/src/test/java/org/tron/core/db2/SnapshotImplTest.java @@ -0,0 +1,201 @@ +package org.tron.core.db2; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.io.File; +import java.lang.reflect.Constructor; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.FileUtil; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db2.core.Snapshot; +import org.tron.core.db2.core.SnapshotImpl; +import org.tron.core.db2.core.SnapshotManager; +import org.tron.core.db2.core.SnapshotRoot; + +public class SnapshotImplTest { + private RevokingDbWithCacheNewValueTest.TestRevokingTronStore tronDatabase; + private TronApplicationContext context; + private Application appT; + private SnapshotManager revokingDatabase; + + @Before + public void init() { + Args.setParam(new String[]{"-d", "output_revokingStore_test"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + appT = ApplicationFactory.create(context); + + tronDatabase = new RevokingDbWithCacheNewValueTest.TestRevokingTronStore( + "testSnapshotRoot-testMerge"); + revokingDatabase = context.getBean(SnapshotManager.class); + revokingDatabase.enable(); + revokingDatabase.add(tronDatabase.getRevokingDB()); + } + + @After + public void removeDb() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File("output_revokingStore_test")); + + tronDatabase.close(); + revokingDatabase.shutdown(); + } + + /** + * linklist is: from -> root + * root:key1=>value1, key2=>value2 + * from:key3=>value3, key4=>value4 + * after construct, getSnapshotImplIns(root); + * from: key1=>value1, key2=>value2, key3=>value3, key4=>value4 + * from: get key1 or key2, traverse 0 times + */ + @Test + public void testMergeRoot() { + // linklist is: from -> root + SnapshotRoot root = new SnapshotRoot(tronDatabase.getDb()); + //root.setOptimized(true); + + root.put("key1".getBytes(), "value1".getBytes()); + root.put("key2".getBytes(), "value2".getBytes()); + SnapshotImpl from = getSnapshotImplIns(root); + from.put("key3".getBytes(), "value3".getBytes()); + from.put("key4".getBytes(), "value4".getBytes()); + + byte[] s1 = from.get("key1".getBytes()); + assertEquals(new String("value1".getBytes()), new String(s1)); + byte[] s2 = from.get("key2".getBytes()); + assertEquals(new String("value2".getBytes()), new String(s2)); + } + + /** + * linklist is: from2 -> from -> root + * root: + * from:key1=>value1, key2=>value2 + * from2:key3=>value3,key4=>value4 + * before merge: from2.mergeAhead(from); + * from2: get key1 or key2, traverse 1 times + * after merge + * from2:key1=>value1, key2=>value2, value3=>value3,key4=>value4 + * from2: get key1 or key2, traverse 0 times + * + */ + @Test + public void testMergeAhead() { + + // linklist is: from2 -> from -> root + SnapshotRoot root = new SnapshotRoot(tronDatabase.getDb()); + SnapshotImpl from = getSnapshotImplIns(root); + from.put("key1".getBytes(), "value1".getBytes()); + from.put("key2".getBytes(), "value2".getBytes()); + + SnapshotImpl from2 = getSnapshotImplIns(from); + from2.put("key3".getBytes(), "value3".getBytes()); + from2.put("key4".getBytes(), "value4".getBytes()); + + /* + // before merge get data in from is success,traverse 0 times + byte[] s1 = from.get("key1".getBytes()); + assertEquals(new String("value1".getBytes()), new String(s1)); + byte[] s2 = from.get("key2".getBytes()); + assertEquals(new String("value2".getBytes()), new String(s2)); + // before merge get data in from2 is success, traverse 0 times + byte[] s3 = from2.get("key3".getBytes()); + assertEquals(new String("value3".getBytes()), new String(s3)); + byte[] s4 = from2.get("key4".getBytes()); + assertEquals(new String("value4".getBytes()), new String(s4)); + */ + + // before merge from2 get data is success, traverse 1 times + byte[] s11 = from2.get("key1".getBytes()); + assertEquals(new String("value1".getBytes()), new String(s11)); + byte[] s12 = from2.get("key2".getBytes()); + assertEquals(new String("value2".getBytes()), new String(s12)); + // this can not get key3 and key4 + assertNull(from.get("key3".getBytes())); + assertNull(from.get("key4".getBytes())); + + // do mergeAhead + from2.mergeAhead(from); + /* + // after merge get data in from is success, traverse 0 times + s1 = from.get("key1".getBytes()); + assertEquals(new String("value1".getBytes()), new String(s1)); + s2 = from.get("key2".getBytes()); + assertEquals(new String("value2".getBytes()), new String(s2)); + + // after merge get data in from2 is success, traverse 0 times + s3 = from2.get("key3".getBytes()); + assertEquals(new String("value3".getBytes()), new String(s3)); + s4 = from2.get("key4".getBytes()); + assertEquals(new String("value4".getBytes()), new String(s4)); + */ + + // after merge from2 get data is success, traverse 0 times + byte[] s1 = from2.get("key1".getBytes()); + assertEquals(new String("value1".getBytes()), new String(s1)); + byte[] s2 = from2.get("key2".getBytes()); + assertEquals(new String("value2".getBytes()), new String(s2)); + + // this can not get key3 and key4 + assertNull(from.get("key3".getBytes())); + assertNull(from.get("key4".getBytes())); + } + + /** + * from: key1=>value1, key2=>value2, key3=>value31 + * from2: key3=>value32,key4=>value4 + * after merge: from2.mergeAhead(from); + * from2: key1=>value1, key2=>value2, key3=>value32, key4=>value4 + */ + @Test + public void testMergeOverride() { + // linklist is: from2 -> from -> root + SnapshotRoot root = new SnapshotRoot(tronDatabase.getDb()); + SnapshotImpl from = getSnapshotImplIns(root); + from.put("key1".getBytes(), "value1".getBytes()); + from.put("key2".getBytes(), "value2".getBytes()); + from.put("key3".getBytes(), "value31".getBytes()); + + SnapshotImpl from2 = getSnapshotImplIns(from); + from2.put("key3".getBytes(), "value32".getBytes()); + from2.put("key4".getBytes(), "value4".getBytes()); + // do mergeAhead + from2.mergeAhead(from); + + // after merge from2 get data is success, traverse 0 times + byte[] s1 = from2.get("key1".getBytes()); + assertEquals(new String("value1".getBytes()), new String(s1)); + byte[] s2 = from2.get("key2".getBytes()); + assertEquals(new String("value2".getBytes()), new String(s2)); + byte[] s3 = from2.get("key3".getBytes()); + assertEquals(new String("value32".getBytes()), new String(s3)); + byte[] s4 = from2.get("key4".getBytes()); + assertEquals(new String("value4".getBytes()), new String(s4)); + } + + /** + * The constructor of SnapshotImpl is not public + * so reflection is used to construct the object here. + */ + private SnapshotImpl getSnapshotImplIns(Snapshot snapshot) { + Class clazz = SnapshotImpl.class; + try { + Constructor constructor = clazz.getDeclaredConstructor(Snapshot.class); + constructor.setAccessible(true); + return (SnapshotImpl) constructor.newInstance(snapshot); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java index 81681346799..134dc99e51c 100644 --- a/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java +++ b/framework/src/test/java/org/tron/core/db2/SnapshotManagerTest.java @@ -1,6 +1,16 @@ package org.tron.core.db2; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.common.collect.Maps; +import com.google.common.primitives.Longs; +import com.google.protobuf.ByteString; import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Assert; @@ -10,14 +20,18 @@ import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.db2.RevokingDbWithCacheNewValueTest.TestRevokingTronStore; import org.tron.core.db2.SnapshotRootTest.ProtoCapsuleTest; +import org.tron.core.db2.core.Chainbase; import org.tron.core.db2.core.SnapshotManager; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ItemNotFoundException; +import org.tron.core.exception.TronError; @Slf4j public class SnapshotManagerTest { @@ -27,6 +41,7 @@ public class SnapshotManagerTest { private Application appT; private TestRevokingTronStore tronDatabase; + @Before public void init() { Args.setParam(new String[]{"-d", "output_SnapshotManager_test"}, @@ -59,11 +74,18 @@ public synchronized void testRefresh() revokingDatabase.setMaxFlushCount(0); revokingDatabase.setUnChecked(false); revokingDatabase.setMaxSize(5); + List dbList = revokingDatabase.getDbs(); + Map dbMap = dbList.stream() + .map(db -> Maps.immutableEntry(db.getDbName(), db)) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); ProtoCapsuleTest protoCapsule = new ProtoCapsuleTest("refresh".getBytes()); for (int i = 1; i < 11; i++) { ProtoCapsuleTest testProtoCapsule = new ProtoCapsuleTest(("refresh" + i).getBytes()); try (ISession tmpSession = revokingDatabase.buildSession()) { tronDatabase.put(protoCapsule.getData(), testProtoCapsule); + BlockCapsule blockCapsule = new BlockCapsule(i, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + dbMap.get("block").put(Longs.toByteArray(i), blockCapsule.getData()); tmpSession.commit(); } } @@ -93,4 +115,22 @@ public synchronized void testClose() { tronDatabase.get(protoCapsule.getData())); } + + @Test + public void testCheckError() { + SnapshotManager manager = spy(new SnapshotManager("")); + when(manager.getCheckpointList()).thenReturn(Arrays.asList("check1", "check2")); + TronError thrown = Assert.assertThrows(TronError.class, manager::check); + Assert.assertEquals(TronError.ErrCode.CHECKPOINT_VERSION, thrown.getErrCode()); + } + + @Test + public void testFlushError() { + SnapshotManager manager = spy(new SnapshotManager("")); + manager.setUnChecked(false); + when(manager.getCheckpointList()).thenReturn(Arrays.asList("check1", "check2")); + when(manager.shouldBeRefreshed()).thenReturn(true); + TronError thrown = Assert.assertThrows(TronError.class, manager::flush); + Assert.assertEquals(TronError.ErrCode.DB_FLUSH, thrown.getErrCode()); + } } diff --git a/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java b/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java index f7985017285..70b4d9eff30 100644 --- a/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java +++ b/framework/src/test/java/org/tron/core/db2/SnapshotRootTest.java @@ -1,9 +1,12 @@ package org.tron.core.db2; +import com.google.common.collect.Sets; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @@ -11,9 +14,11 @@ import org.junit.Assert; import org.junit.Before; import org.junit.Test; +import org.springframework.util.CollectionUtils; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; +import org.tron.common.cache.CacheStrategies; import org.tron.common.utils.FileUtil; import org.tron.common.utils.SessionOptional; import org.tron.core.Constant; @@ -24,6 +29,7 @@ import org.tron.core.db2.core.Snapshot; import org.tron.core.db2.core.SnapshotManager; import org.tron.core.db2.core.SnapshotRoot; +import org.tron.core.exception.ItemNotFoundException; public class SnapshotRootTest { @@ -31,6 +37,15 @@ public class SnapshotRootTest { private TronApplicationContext context; private Application appT; private SnapshotManager revokingDatabase; + private final Set noSecondCacheDBs = Sets.newHashSet(Arrays.asList("trans-cache", + "exchange-v2","nullifier","accountTrie","transactionRetStore","accountid-index", + "market_account","market_pair_to_price","recent-transaction","block-index","block", + "market_pair_price_to_order","proposal","tree-block-index","IncrementalMerkleTree", + "asset-issue","balance-trace","transactionHistoryStore","account-index","section-bloom", + "exchange","market_order","account-trace","contract-state","trans")); + private Set allDBNames; + private Set allRevokingDBNames; + @Before public void init() { @@ -113,6 +128,52 @@ public synchronized void testMergeList() { tronDatabase.close(); } + @Test + public void testSecondCacheCheck() + throws ItemNotFoundException { + revokingDatabase = context.getBean(SnapshotManager.class); + allRevokingDBNames = parseRevokingDBNames(context); + allDBNames = Arrays.stream(new File("output_revokingStore_test/database").list()) + .collect(Collectors.toSet()); + if (CollectionUtils.isEmpty(allDBNames)) { + throw new ItemNotFoundException("No DBs found"); + } + allDBNames.removeAll(noSecondCacheDBs); + allDBNames.removeAll(CacheStrategies.CACHE_DBS); + allDBNames.retainAll(allRevokingDBNames); + org.junit.Assert.assertEquals(String.format("New added dbs %s " + + "shall consider to add second cache or add to noNeedCheckDBs!", + allDBNames.stream().collect(Collectors.joining(","))), allDBNames.size(), 0); + } + + @Test + public void testSecondCacheCheckAddDb() + throws ItemNotFoundException { + revokingDatabase = context.getBean(SnapshotManager.class); + allRevokingDBNames = parseRevokingDBNames(context); + allRevokingDBNames.add("secondCheckTestDB"); + FileUtil.createDirIfNotExists("output_revokingStore_test/database/secondCheckTestDB"); + allDBNames = Arrays.stream(new File("output_revokingStore_test/database").list()) + .collect(Collectors.toSet()); + FileUtil.deleteDir(new File("output_revokingStore_test/database/secondCheckTestDB")); + if (CollectionUtils.isEmpty(allDBNames)) { + throw new ItemNotFoundException("No DBs found"); + } + allDBNames.removeAll(noSecondCacheDBs); + allDBNames.removeAll(CacheStrategies.CACHE_DBS); + allDBNames.retainAll(allRevokingDBNames); + org.junit.Assert.assertTrue(String.format("New added dbs %s " + + "check second cache failed!", + allDBNames.stream().collect(Collectors.joining(","))), allDBNames.size() == 1); + } + + private Set parseRevokingDBNames(TronApplicationContext context) { + SnapshotManager snapshotManager = context.getBean(SnapshotManager.class); + return snapshotManager.getDbs().stream().map(chainbase -> + chainbase.getDbName()).collect(Collectors.toSet()); + } + + @NoArgsConstructor @AllArgsConstructor @EqualsAndHashCode diff --git a/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java b/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java new file mode 100644 index 00000000000..e99433db3c6 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/BlockEventCacheTest.java @@ -0,0 +1,91 @@ +package org.tron.core.event; + +import java.util.List; +import java.util.Random; +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.services.event.BlockEventCache; +import org.tron.core.services.event.bo.BlockEvent; +import org.tron.core.services.event.exception.EventException; + +public class BlockEventCacheTest { + + @Test + public void test() throws Exception { + BlockEvent be1 = new BlockEvent(); + BlockCapsule.BlockId b1 = new BlockCapsule.BlockId(getBlockId(), 1); + be1.setBlockId(b1); + be1.setParentId(b1); + be1.setSolidId(b1); + try { + BlockEventCache.add(be1); + Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(e instanceof EventException); + } + + BlockEventCache.init(new BlockCapsule.BlockId(getBlockId(), 100)); + + try { + BlockEventCache.add(be1); + Assert.fail(); + } catch (Exception e) { + Assert.assertTrue(e instanceof EventException); + } + + BlockEventCache.init(b1); + + BlockEvent be2 = new BlockEvent(); + BlockCapsule.BlockId b2 = new BlockCapsule.BlockId(getBlockId(), 2); + be2.setBlockId(b2); + be2.setParentId(b1); + be2.setSolidId(b1); + BlockEventCache.add(be2); + Assert.assertEquals(be2, BlockEventCache.getHead()); + Assert.assertEquals(be2, BlockEventCache.getBlockEvent(b2)); + + BlockEvent be22 = new BlockEvent(); + BlockCapsule.BlockId b22 = new BlockCapsule.BlockId(getBlockId(), 2); + be22.setBlockId(b22); + be22.setParentId(b1); + be22.setSolidId(b22); + BlockEventCache.add(be22); + Assert.assertEquals(be2, BlockEventCache.getHead()); + Assert.assertEquals(be22, BlockEventCache.getBlockEvent(b22)); + Assert.assertEquals(b22, BlockEventCache.getSolidId()); + + BlockEvent be3 = new BlockEvent(); + BlockCapsule.BlockId b3 = new BlockCapsule.BlockId(getBlockId(), 3); + be3.setBlockId(b3); + be3.setParentId(b22); + be3.setSolidId(b22); + BlockEventCache.add(be3); + Assert.assertEquals(be3, BlockEventCache.getHead()); + + List list = BlockEventCache.getSolidBlockEvents(b2); + Assert.assertEquals(1, list.size()); + list = BlockEventCache.getSolidBlockEvents(b22); + Assert.assertEquals(1, list.size()); + + list = BlockEventCache.getSolidBlockEvents(b3); + Assert.assertEquals(2, list.size()); + + BlockEventCache.remove(b22); + Assert.assertEquals(2, BlockEventCache.getSolidNum()); + + list = BlockEventCache.getSolidBlockEvents(b2); + Assert.assertEquals(0, list.size()); + list = BlockEventCache.getSolidBlockEvents(b22); + Assert.assertEquals(0, list.size()); + + list = BlockEventCache.getSolidBlockEvents(b3); + Assert.assertEquals(1, list.size()); + } + + public static byte[] getBlockId() { + byte[] id = new byte[32]; + new Random().nextBytes(id); + return id; + } +} diff --git a/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java new file mode 100644 index 00000000000..b6835cfcf82 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/BlockEventGetTest.java @@ -0,0 +1,291 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.logsfilter.EventPluginConfig; +import org.tron.common.logsfilter.EventPluginLoader; +import org.tron.common.logsfilter.TriggerConfig; +import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionRetCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.consensus.ConsensusService; +import org.tron.core.db.BlockGenerate; +import org.tron.core.db.Manager; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.services.event.BlockEventGet; +import org.tron.core.services.event.bo.BlockEvent; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.TransactionRetStore; +import org.tron.protos.Protocol; + +@Slf4j +public class BlockEventGetTest extends BlockGenerate { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + static ChainBaseManager chainManager; + + private final String key = PublicMethod.getRandomPrivateKey(); + private final byte[] privateKey = ByteArray.fromHexString(key); + private final byte[] address = PublicMethod.getAddressByteByPrivateKey(key); + + private final AtomicInteger port = new AtomicInteger(0); + protected String dbPath; + protected Manager dbManager; + long currentHeader = -1; + private TronNetDelegate tronNetDelegate; + private TronApplicationContext context; + + + static LocalDateTime localDateTime = LocalDateTime.now(); + private long time = ZonedDateTime.of(localDateTime, + ZoneId.systemDefault()).toInstant().toEpochMilli(); + + protected void initDbPath() throws IOException { + dbPath = temporaryFolder.newFolder().toString(); + } + + @Before + public void before() throws IOException { + initDbPath(); + logger.info("Full node running."); + Args.setParam(new String[] {"-d", dbPath}, Constant.TEST_CONF); + Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); + + context = new TronApplicationContext(DefaultConfig.class); + + dbManager = context.getBean(Manager.class); + setManager(dbManager); + + context.getBean(ConsensusService.class).start(); + chainManager = dbManager.getChainBaseManager(); + tronNetDelegate = context.getBean(TronNetDelegate.class); + tronNetDelegate.setExit(false); + currentHeader = dbManager.getDynamicPropertiesStore() + .getLatestBlockHeaderNumberFromDB(); + + ByteString addressBS = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressBS); + chainManager.getWitnessStore().put(address, witnessCapsule); + chainManager.addWitness(addressBS); + + AccountCapsule accountCapsule = new AccountCapsule(Protocol.Account.newBuilder() + .setAddress(addressBS).setBalance((long) 1e10).build()); + chainManager.getAccountStore().put(address, accountCapsule); + + DynamicPropertiesStore dps = dbManager.getDynamicPropertiesStore(); + dps.saveAllowTvmTransferTrc10(1); + dps.saveAllowTvmConstantinople(1); + dps.saveAllowTvmShangHai(1); + } + + @After + public void after() throws IOException { + } + + @Test + public void test() throws Exception { + BlockEventGet blockEventGet = context.getBean(BlockEventGet.class); + Manager manager = context.getBean(Manager.class); + + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); + ChainBaseManager.getChainBaseManager() + .getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); + ChainBaseManager.getChainBaseManager().addWitness(ByteString.copyFrom(address)); + + String code = "608060405234801561000f575f80fd5b50d3801561001b575f80fd5b50d28015610027575f" + + "80fd5b503373ffffffffffffffffffffffffffffffffffffffff165f73ffffffffffffffffffffffff" + + "ffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3" + + "ef6402540be40060405161008a91906100e2565b60405180910390a36100fb565b5f81905091905056" + + "5b5f819050919050565b5f819050919050565b5f6100cc6100c76100c284610097565b6100a9565b61" + + "00a0565b9050919050565b6100dc816100b2565b82525050565b5f6020820190506100f55f83018461" + + "00d3565b92915050565b603e806101075f395ff3fe60806040525f80fdfea26474726f6e582212200c" + + "57c973388f044038eff0e6474425b38037e75e66d6b3047647290605449c7764736f6c63430008140033"; + Protocol.Transaction trx = TvmTestUtils.generateDeploySmartContractAndGetTransaction( + "TestTRC20", address, "[{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\"" + + ":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"}" + + ",{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\"," + + "\"type\":\"event\"}]", code, 0, (long) 1e9, 100, null, 1); + trx = trx.toBuilder().addRet( + Protocol.Transaction.Result.newBuilder() + .setContractRetValue(Protocol.Transaction.Result.contractResult.SUCCESS_VALUE) + .build()).build(); + + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); + BlockCapsule blockCapsule = new BlockCapsule(block.toBuilder().addTransactions(trx).build()); + blockCapsule.generatedByMyself = true; + blockCapsule.getTransactions().forEach(txCap -> { + txCap.setVerified(true); + chainManager.setBlockReference(txCap); + txCap.setExpiration(3000); + }); + manager.pushBlock(blockCapsule); + + // Set energy price history to test boundary cases + manager.getDynamicPropertiesStore().saveEnergyPriceHistory( + manager.getDynamicPropertiesStore().getEnergyPriceHistory() + + "," + time + ":210"); + + EventPluginConfig config = new EventPluginConfig(); + config.setSendQueueLength(1000); + config.setBindPort(5555); + config.setUseNativeQueue(true); + config.setTriggerConfigList(new ArrayList<>()); + + TriggerConfig blockTriggerConfig = new TriggerConfig(); + blockTriggerConfig.setTriggerName("block"); + blockTriggerConfig.setEnabled(true); + config.getTriggerConfigList().add(blockTriggerConfig); + + TriggerConfig txTriggerConfig = new TriggerConfig(); + txTriggerConfig.setTriggerName("transaction"); + txTriggerConfig.setEnabled(true); + txTriggerConfig.setEthCompatible(true); + config.getTriggerConfigList().add(txTriggerConfig); + + TriggerConfig solidityTriggerConfig = new TriggerConfig(); + solidityTriggerConfig.setTriggerName("solidity"); + solidityTriggerConfig.setEnabled(true); + config.getTriggerConfigList().add(solidityTriggerConfig); + + TriggerConfig contracteventTriggerConfig = new TriggerConfig(); + contracteventTriggerConfig.setTriggerName("contractevent"); + contracteventTriggerConfig.setEnabled(true); + config.getTriggerConfigList().add(contracteventTriggerConfig); + + TriggerConfig contractlogTriggerConfig = new TriggerConfig(); + contractlogTriggerConfig.setTriggerName("contractlog"); + contractlogTriggerConfig.setEnabled(true); + contractlogTriggerConfig.setRedundancy(true); + config.getTriggerConfigList().add(contractlogTriggerConfig); + + EventPluginLoader.getInstance().start(config); + try { + BlockEvent blockEvent = blockEventGet.getBlockEvent(1); + Assert.assertNotNull(blockEvent); + Assert.assertEquals(1, blockEvent.getTransactionLogTriggerCapsules().size()); + + // Here energy unit price should be 100 not 210, + // cause block time is equal to 210`s effective time + Assert.assertEquals(100, blockEvent.getTransactionLogTriggerCapsules() + .get(0).getTransactionLogTrigger().getEnergyUnitPrice()); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void getTransactionTriggers() throws Exception { + BlockEventGet blockEventGet = new BlockEventGet(); + BlockCapsule bc = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + 100, Sha256Hash.ZERO_HASH.getByteString()); + + List list = blockEventGet.getTransactionTriggers(bc, 1); + Assert.assertEquals(0, list.size()); + + List transactionList = new ArrayList<>(); + + Protocol.Transaction.raw rw = Protocol.Transaction.raw.newBuilder() + .addContract(Protocol.Transaction.Contract.newBuilder().build()).build(); + + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData(rw).build(); + + transactionList.add(transaction); + + bc = new BlockCapsule(100, ByteString.empty(), 1, transactionList); + + list = blockEventGet.getTransactionTriggers(bc, 1); + Assert.assertEquals(1, list.size()); + Assert.assertEquals(100, list.get(0).getTransactionLogTrigger().getTimeStamp()); + + Protocol.TransactionInfo.Builder infoBuild = Protocol.TransactionInfo.newBuilder(); + + Protocol.ResourceReceipt.Builder resourceBuild = Protocol.ResourceReceipt.newBuilder(); + resourceBuild.setEnergyFee(1); + resourceBuild.setEnergyUsageTotal(2); + resourceBuild.setEnergyUsage(3); + resourceBuild.setOriginEnergyUsage(4); + resourceBuild.setNetFee(5); + resourceBuild.setNetUsage(6); + + String address = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; + infoBuild + .setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(address))) + .addContractResult(ByteString.copyFrom(ByteArray.fromHexString("112233"))) + .setReceipt(resourceBuild.build()); + + Manager manager = mock(Manager.class); + ReflectUtils.setFieldValue(blockEventGet, "manager", manager); + + ChainBaseManager chainBaseManager = mock(ChainBaseManager.class); + Mockito.when(manager.getChainBaseManager()).thenReturn(chainBaseManager); + + TransactionRetStore transactionRetStore = mock(TransactionRetStore.class); + Mockito.when(chainBaseManager.getTransactionRetStore()).thenReturn(transactionRetStore); + + Protocol.TransactionRet transactionRet = Protocol.TransactionRet.newBuilder() + .addTransactioninfo(infoBuild.build()).build(); + + TransactionRetCapsule result = new TransactionRetCapsule(transactionRet.toByteArray()); + + Mockito.when(transactionRetStore.getTransactionInfoByBlockNum(ByteArray.fromLong(0))) + .thenReturn(result); + + Protocol.Block block = Protocol.Block.newBuilder() + .addTransactions(transaction).build(); + + BlockCapsule blockCapsule = new BlockCapsule(block); + blockCapsule.getTransactions().forEach(t -> t.setBlockNum(blockCapsule.getNum())); + + list = blockEventGet.getTransactionTriggers(blockCapsule, 1); + + Assert.assertEquals(1, list.size()); + Assert.assertEquals(1, + list.get(0).getTransactionLogTrigger().getLatestSolidifiedBlockNumber()); + Assert.assertEquals(0, + list.get(0).getTransactionLogTrigger().getBlockNumber()); + Assert.assertEquals(2, + list.get(0).getTransactionLogTrigger().getEnergyUsageTotal()); + + Mockito.when(transactionRetStore.getTransactionInfoByBlockNum(ByteArray.fromLong(0))) + .thenReturn(null); + list = blockEventGet.getTransactionTriggers(blockCapsule, 1); + Assert.assertEquals(1, list.size()); + Assert.assertEquals(1, + list.get(0).getTransactionLogTrigger().getLatestSolidifiedBlockNumber()); + Assert.assertEquals(0, + list.get(0).getTransactionLogTrigger().getBlockNumber()); + Assert.assertEquals(0, + list.get(0).getTransactionLogTrigger().getEnergyUsageTotal()); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/event/BlockEventLoadTest.java b/framework/src/test/java/org/tron/core/event/BlockEventLoadTest.java new file mode 100644 index 00000000000..991133fee78 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/BlockEventLoadTest.java @@ -0,0 +1,124 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.concurrent.BlockingQueue; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.db.Manager; +import org.tron.core.services.event.BlockEventCache; +import org.tron.core.services.event.BlockEventGet; +import org.tron.core.services.event.BlockEventLoad; +import org.tron.core.services.event.RealtimeEventService; +import org.tron.core.services.event.bo.BlockEvent; +import org.tron.core.services.event.bo.Event; +import org.tron.core.store.DynamicPropertiesStore; + +public class BlockEventLoadTest { + BlockEventLoad blockEventLoad = new BlockEventLoad(); + + @Test + public void test() throws Exception { + Method method = blockEventLoad.getClass().getDeclaredMethod("load"); + method.setAccessible(true); + + RealtimeEventService realtimeEventService = new RealtimeEventService(); + Field field = realtimeEventService.getClass().getDeclaredField("queue"); + field.setAccessible(true); + BlockingQueue queue = (BlockingQueue)field.get(BlockingQueue.class); + + BlockEventGet blockEventGet = mock(BlockEventGet.class); + Manager manager = mock(Manager.class); + ReflectUtils.setFieldValue(blockEventLoad, "realtimeEventService", realtimeEventService); + ReflectUtils.setFieldValue(blockEventLoad, "blockEventGet", blockEventGet); + ReflectUtils.setFieldValue(blockEventLoad, "manager", manager); + + DynamicPropertiesStore dynamicPropertiesStore = mock(DynamicPropertiesStore.class); + ChainBaseManager chainBaseManager = mock(ChainBaseManager.class); + Mockito.when(manager.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStore); + Mockito.when(manager.getChainBaseManager()).thenReturn(chainBaseManager); + + BlockCapsule.BlockId b0 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 0); + BlockEventCache.init(b0); + + /********** 1 ***********/ + Mockito.when(dynamicPropertiesStore.getLatestBlockHeaderNumber()).thenReturn(0L); + method.invoke(blockEventLoad); + Assert.assertEquals(0, queue.size()); + + /********** 2 ***********/ + BlockEvent be1 = new BlockEvent(); + BlockCapsule.BlockId b1 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 1); + be1.setBlockId(b1); + be1.setParentId(b0); + be1.setSolidId(b0); + + Mockito.when(dynamicPropertiesStore.getLatestBlockHeaderNumber()).thenReturn(1L); + Mockito.when(blockEventGet.getBlockEvent(1L)).thenReturn(be1); + method.invoke(blockEventLoad); + Assert.assertEquals(1, queue.size()); + Assert.assertEquals(b1, BlockEventCache.getHead().getBlockId()); + + /********** 3 ***********/ + BlockEventCache.init(b0); + queue.clear(); + + BlockEvent be2 = new BlockEvent(); + BlockCapsule.BlockId b2 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 2L); + be2.setBlockId(b2); + be2.setParentId(b1); + be2.setSolidId(b0); + + Mockito.when(dynamicPropertiesStore.getLatestBlockHeaderNumber()).thenReturn(2L); + Mockito.when(blockEventGet.getBlockEvent(2L)).thenReturn(be2); + method.invoke(blockEventLoad); + Assert.assertEquals(2, queue.size()); + Assert.assertEquals(b2, BlockEventCache.getHead().getBlockId()); + + /********** 4 ***********/ + BlockEventCache.init(b0); + queue.clear(); + + Mockito.when(dynamicPropertiesStore.getLatestBlockHeaderNumber()).thenReturn(1L); + method.invoke(blockEventLoad); + Assert.assertEquals(1, queue.size()); + queue.clear(); + + BlockEvent be21 = new BlockEvent(); + BlockCapsule.BlockId b21 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 1L); + be21.setBlockId(b21); + be21.setParentId(b0); + be21.setSolidId(b0); + + BlockEvent be22 = new BlockEvent(); + BlockCapsule.BlockId b22 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 2L); + be22.setBlockId(b22); + be22.setParentId(b21); + be22.setSolidId(b21); + + Mockito.when(dynamicPropertiesStore.getLatestBlockHeaderNumber()).thenReturn(2L); + Mockito.when(blockEventGet.getBlockEvent(1L)).thenReturn(be21); + Mockito.when(blockEventGet.getBlockEvent(2L)).thenReturn(be22); + method.invoke(blockEventLoad); + Assert.assertEquals(3, queue.size()); + Assert.assertEquals(b22, BlockEventCache.getHead().getBlockId()); + + Event event = queue.poll(); + Assert.assertEquals(b1, event.getBlockEvent().getBlockId()); + Assert.assertEquals(true, event.isRemove()); + + event = queue.poll(); + Assert.assertEquals(b21, event.getBlockEvent().getBlockId()); + Assert.assertEquals(false, event.isRemove()); + + event = queue.poll(); + Assert.assertEquals(b22, event.getBlockEvent().getBlockId()); + Assert.assertEquals(false, event.isRemove()); + } +} diff --git a/framework/src/test/java/org/tron/core/event/EventPluginLoaderTest.java b/framework/src/test/java/org/tron/core/event/EventPluginLoaderTest.java new file mode 100644 index 00000000000..658d42f38d9 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/EventPluginLoaderTest.java @@ -0,0 +1,43 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.logsfilter.EventPluginLoader; +import org.tron.common.logsfilter.IPluginEventListener; +import org.tron.common.utils.ReflectUtils; + +public class EventPluginLoaderTest { + + @Test + public void testIsBusy() { + + EventPluginLoader eventPluginLoader = EventPluginLoader.getInstance(); + ReflectUtils.setFieldValue(eventPluginLoader, "useNativeQueue", true); + boolean flag = eventPluginLoader.isBusy(); + Assert.assertFalse(flag); + + ReflectUtils.setFieldValue(eventPluginLoader, "useNativeQueue", false); + + IPluginEventListener p1 = mock(IPluginEventListener.class); + List list = new ArrayList<>(); + list.add(p1); + ReflectUtils.setFieldValue(eventPluginLoader, "eventListeners", list); + + Mockito.when(p1.getPendingSize()).thenReturn(100); + flag = eventPluginLoader.isBusy(); + Assert.assertFalse(flag); + + Mockito.when(p1.getPendingSize()).thenReturn(60000); + flag = eventPluginLoader.isBusy(); + Assert.assertTrue(flag); + + Mockito.when(p1.getPendingSize()).thenThrow(new AbstractMethodError()); + flag = eventPluginLoader.isBusy(); + Assert.assertFalse(flag); + } +} diff --git a/framework/src/test/java/org/tron/core/event/EventServiceTest.java b/framework/src/test/java/org/tron/core/event/EventServiceTest.java new file mode 100644 index 00000000000..ff7aafb1d1a --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/EventServiceTest.java @@ -0,0 +1,48 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.logsfilter.EventPluginLoader; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.db.Manager; +import org.tron.core.services.event.BlockEventCache; +import org.tron.core.services.event.BlockEventLoad; +import org.tron.core.services.event.EventService; +import org.tron.core.services.event.HistoryEventService; +import org.tron.core.services.event.RealtimeEventService; +import org.tron.core.services.event.SolidEventService; + +public class EventServiceTest { + + @Test + public void test() { + BlockCapsule.BlockId b1 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 1); + BlockEventCache.init(b1); + + EventService eventService = new EventService(); + HistoryEventService historyEventService = new HistoryEventService(); + RealtimeEventService realtimeEventService = new RealtimeEventService(); + SolidEventService solidEventService = new SolidEventService(); + BlockEventLoad blockEventLoad = new BlockEventLoad(); + + ReflectUtils.setFieldValue(eventService, "historyEventService", historyEventService); + ReflectUtils.setFieldValue(eventService, "solidEventService", solidEventService); + ReflectUtils.setFieldValue(eventService, "realtimeEventService", realtimeEventService); + ReflectUtils.setFieldValue(eventService, "blockEventLoad", blockEventLoad); + + Manager manager = mock(Manager.class); + ReflectUtils.setFieldValue(eventService, "manager", manager); + Mockito.when(manager.isEventPluginLoaded()).thenReturn(true); + + eventService.init(); + eventService.close(); + + EventPluginLoader instance = mock(EventPluginLoader.class); + Mockito.when(instance.getVersion()).thenReturn(1); + ReflectUtils.setFieldValue(eventService, "instance", instance); + eventService.close(); + } +} diff --git a/framework/src/test/java/org/tron/core/event/HistoryEventServiceTest.java b/framework/src/test/java/org/tron/core/event/HistoryEventServiceTest.java new file mode 100644 index 00000000000..49f77ccf597 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/HistoryEventServiceTest.java @@ -0,0 +1,96 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Method; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.logsfilter.EventPluginLoader; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.db.Manager; +import org.tron.core.services.event.BlockEventGet; +import org.tron.core.services.event.BlockEventLoad; +import org.tron.core.services.event.HistoryEventService; +import org.tron.core.services.event.RealtimeEventService; +import org.tron.core.services.event.SolidEventService; +import org.tron.core.services.event.bo.BlockEvent; +import org.tron.core.store.DynamicPropertiesStore; + +public class HistoryEventServiceTest { + + HistoryEventService historyEventService = new HistoryEventService(); + + @Test + public void test() throws Exception { + EventPluginLoader instance = mock(EventPluginLoader.class); + Mockito.when(instance.isUseNativeQueue()).thenReturn(true); + Mockito.when(instance.isUseNativeQueue()).thenReturn(false); + + ReflectUtils.setFieldValue(historyEventService, "instance", instance); + + DynamicPropertiesStore dynamicPropertiesStore = mock(DynamicPropertiesStore.class); + ChainBaseManager chainBaseManager = mock(ChainBaseManager.class); + Manager manager = mock(Manager.class); + ReflectUtils.setFieldValue(historyEventService, "manager", manager); + Mockito.when(manager.getChainBaseManager()).thenReturn(chainBaseManager); + Mockito.when(manager.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStore); + Mockito.when(chainBaseManager.getHeadBlockId()).thenReturn(new BlockCapsule.BlockId()); + + SolidEventService solidEventService = new SolidEventService(); + RealtimeEventService realtimeEventService = new RealtimeEventService(); + BlockEventLoad blockEventLoad = new BlockEventLoad(); + ReflectUtils.setFieldValue(blockEventLoad, "instance", instance); + + ReflectUtils.setFieldValue(historyEventService, "solidEventService", solidEventService); + ReflectUtils.setFieldValue(historyEventService, "realtimeEventService", realtimeEventService); + ReflectUtils.setFieldValue(historyEventService, "blockEventLoad", blockEventLoad); + historyEventService.init(); + historyEventService.close(); + solidEventService.close(); + realtimeEventService.close(); + blockEventLoad.close(); + + solidEventService = mock(SolidEventService.class); + ReflectUtils.setFieldValue(historyEventService, "solidEventService", solidEventService); + realtimeEventService = mock(RealtimeEventService.class); + ReflectUtils.setFieldValue(historyEventService, "realtimeEventService", realtimeEventService); + blockEventLoad = mock(BlockEventLoad.class); + ReflectUtils.setFieldValue(historyEventService, "blockEventLoad", blockEventLoad); + + Mockito.when(instance.getStartSyncBlockNum()).thenReturn(0L); + + Mockito.when(dynamicPropertiesStore.getLatestSolidifiedBlockNum()).thenReturn(0L); + Mockito.when(chainBaseManager.getBlockIdByNum(0L)) + .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 0)); + historyEventService.init(); + + BlockEvent be2 = new BlockEvent(); + BlockCapsule.BlockId b2 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 2); + be2.setBlockId(b2); + + BlockEventGet blockEventGet = mock(BlockEventGet.class); + ReflectUtils.setFieldValue(historyEventService, "blockEventGet", blockEventGet); + Mockito.when(blockEventGet.getBlockEvent(1)).thenReturn(be2); + + Mockito.when(instance.getStartSyncBlockNum()).thenReturn(1L); + Mockito.when(dynamicPropertiesStore.getLatestSolidifiedBlockNum()).thenReturn(1L); + + Mockito.when(chainBaseManager.getBlockIdByNum(1L)) + .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1)); + + Mockito.when(instance.isUseNativeQueue()).thenReturn(true); + + Method method1 = historyEventService.getClass().getDeclaredMethod("syncEvent"); + method1.setAccessible(true); + method1.invoke(historyEventService); + + Mockito.when(instance.isUseNativeQueue()).thenReturn(false); + Mockito.when(instance.isBusy()).thenReturn(true); + historyEventService.init(); + Thread.sleep(1000); + historyEventService.close(); + } +} diff --git a/framework/src/test/java/org/tron/core/event/RealtimeEventServiceTest.java b/framework/src/test/java/org/tron/core/event/RealtimeEventServiceTest.java new file mode 100644 index 00000000000..91dcea71322 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/RealtimeEventServiceTest.java @@ -0,0 +1,118 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import org.eclipse.jetty.util.BlockingArrayQueue; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.logsfilter.EventPluginLoader; +import org.tron.common.logsfilter.capsule.BlockLogTriggerCapsule; +import org.tron.common.logsfilter.capsule.TransactionLogTriggerCapsule; +import org.tron.common.logsfilter.capsule.TriggerCapsule; +import org.tron.common.logsfilter.trigger.ContractEventTrigger; +import org.tron.common.logsfilter.trigger.ContractLogTrigger; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.db.Manager; +import org.tron.core.services.event.BlockEventCache; +import org.tron.core.services.event.RealtimeEventService; +import org.tron.core.services.event.bo.BlockEvent; +import org.tron.core.services.event.bo.Event; +import org.tron.core.services.event.bo.SmartContractTrigger; + +public class RealtimeEventServiceTest { + + RealtimeEventService realtimeEventService = new RealtimeEventService(); + + @Test + public void test() throws Exception { + BlockEvent be1 = new BlockEvent(); + BlockCapsule.BlockId b1 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 1); + be1.setBlockId(b1); + be1.setParentId(b1); + be1.setSolidId(b1); + BlockEventCache.init(b1); + + BlockEvent be2 = new BlockEvent(); + BlockCapsule.BlockId b2 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 2); + be2.setBlockId(b2); + be2.setParentId(b1); + be2.setSolidId(b1); + BlockEventCache.add(be2); + Assert.assertEquals(be2, BlockEventCache.getHead()); + Assert.assertEquals(be2, BlockEventCache.getBlockEvent(b2)); + + Event event = new Event(be2, true); + + realtimeEventService.add(event); + realtimeEventService.work(); + + EventPluginLoader instance = mock(EventPluginLoader.class); + ReflectUtils.setFieldValue(realtimeEventService, "instance", instance); + + BlockingQueue queue = new BlockingArrayQueue<>(); + Manager manager = mock(Manager.class); + Mockito.when(manager.getTriggerCapsuleQueue()).thenReturn(queue); + ReflectUtils.setFieldValue(realtimeEventService, "manager", manager); + + BlockCapsule blockCapsule = new BlockCapsule(0L, Sha256Hash.ZERO_HASH, 0L, + ByteString.copyFrom(BlockEventCacheTest.getBlockId())); + be2.setBlockLogTriggerCapsule(new BlockLogTriggerCapsule(blockCapsule)); + Mockito.when(instance.isBlockLogTriggerEnable()).thenReturn(true); + Mockito.when(instance.isBlockLogTriggerSolidified()).thenReturn(false); + + realtimeEventService.add(event); + realtimeEventService.work(); + + Assert.assertEquals(0, queue.size()); + + event = new Event(be2, false); + realtimeEventService.add(event); + realtimeEventService.work(); + + Assert.assertEquals(1, queue.size()); + + be2.setBlockLogTriggerCapsule(null); + queue.poll(); + + List list = new ArrayList<>(); + list.add(mock(TransactionLogTriggerCapsule.class)); + be2.setTransactionLogTriggerCapsules(list); + + Mockito.when(instance.isTransactionLogTriggerEnable()).thenReturn(true); + Mockito.when(instance.isTransactionLogTriggerSolidified()).thenReturn(false); + realtimeEventService.flush(be2, event.isRemove()); + Assert.assertEquals(1, queue.size()); + + be2.setTransactionLogTriggerCapsules(null); + + SmartContractTrigger contractTrigger = new SmartContractTrigger(); + be2.setSmartContractTrigger(contractTrigger); + + contractTrigger.getContractEventTriggers().add(mock(ContractEventTrigger.class)); + Mockito.when(instance.isContractLogTriggerEnable()).thenReturn(true); + try { + realtimeEventService.flush(be2, event.isRemove()); + } catch (Exception e) { + Assert.assertTrue(e instanceof NullPointerException); + } + + contractTrigger.getContractEventTriggers().clear(); + + realtimeEventService.flush(be2, event.isRemove()); + + contractTrigger.getContractLogTriggers().add(mock(ContractLogTrigger.class)); + Mockito.when(instance.isContractEventTriggerEnable()).thenReturn(true); + try { + realtimeEventService.flush(be2, event.isRemove()); + } catch (Exception e) { + Assert.assertTrue(e instanceof NullPointerException); + } + } +} diff --git a/framework/src/test/java/org/tron/core/event/SolidEventServiceTest.java b/framework/src/test/java/org/tron/core/event/SolidEventServiceTest.java new file mode 100644 index 00000000000..de0300e31d7 --- /dev/null +++ b/framework/src/test/java/org/tron/core/event/SolidEventServiceTest.java @@ -0,0 +1,125 @@ +package org.tron.core.event; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import org.eclipse.jetty.util.BlockingArrayQueue; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.logsfilter.EventPluginLoader; +import org.tron.common.logsfilter.capsule.BlockLogTriggerCapsule; +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.trigger.ContractEventTrigger; +import org.tron.common.logsfilter.trigger.ContractLogTrigger; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.db.Manager; +import org.tron.core.services.event.BlockEventCache; +import org.tron.core.services.event.SolidEventService; +import org.tron.core.services.event.bo.BlockEvent; +import org.tron.core.services.event.bo.SmartContractTrigger; + +public class SolidEventServiceTest { + + SolidEventService solidEventService = new SolidEventService(); + + @Test + public void test() throws Exception { + BlockEvent be0 = new BlockEvent(); + BlockCapsule.BlockId b0 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 1); + be0.setBlockId(b0); + be0.setParentId(b0); + be0.setSolidId(new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 100)); + BlockEventCache.init(b0); + BlockEventCache.add(be0); + solidEventService.work(); + + BlockEvent be1 = new BlockEvent(); + BlockCapsule.BlockId b1 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 1); + be1.setBlockId(b1); + be1.setParentId(b1); + be1.setSolidId(b1); + BlockEventCache.init(b1); + + BlockEvent be2 = new BlockEvent(); + BlockCapsule.BlockId b2 = new BlockCapsule.BlockId(BlockEventCacheTest.getBlockId(), 2); + be2.setBlockId(b2); + be2.setParentId(b1); + be2.setSolidId(b1); + BlockEventCache.add(be2); + Assert.assertEquals(be2, BlockEventCache.getHead()); + Assert.assertEquals(be2, BlockEventCache.getBlockEvent(b2)); + + solidEventService.flush(be2); + + EventPluginLoader instance = mock(EventPluginLoader.class); + ReflectUtils.setFieldValue(solidEventService, "instance", instance); + + BlockingQueue queue = new BlockingArrayQueue<>(); + Manager manager = mock(Manager.class); + Mockito.when(manager.getTriggerCapsuleQueue()).thenReturn(queue); + ReflectUtils.setFieldValue(solidEventService, "manager", manager); + + BlockCapsule blockCapsule = new BlockCapsule(0L, Sha256Hash.ZERO_HASH, 0L, + ByteString.copyFrom(BlockEventCacheTest.getBlockId())); + be2.setBlockLogTriggerCapsule(new BlockLogTriggerCapsule(blockCapsule)); + Mockito.when(instance.isBlockLogTriggerEnable()).thenReturn(true); + Mockito.when(instance.isBlockLogTriggerSolidified()).thenReturn(true); + + solidEventService.flush(be2); + + Assert.assertEquals(1, queue.size()); + + be2.setBlockLogTriggerCapsule(null); + queue.poll(); + + List list = new ArrayList<>(); + list.add(mock(TransactionLogTriggerCapsule.class)); + be2.setTransactionLogTriggerCapsules(list); + + Mockito.when(instance.isTransactionLogTriggerEnable()).thenReturn(true); + Mockito.when(instance.isTransactionLogTriggerSolidified()).thenReturn(true); + solidEventService.flush(be2); + Assert.assertEquals(1, queue.size()); + + be2.setTransactionLogTriggerCapsules(null); + + SmartContractTrigger contractTrigger = new SmartContractTrigger(); + be2.setSmartContractTrigger(contractTrigger); + + contractTrigger.getContractEventTriggers().add(mock(ContractEventTrigger.class)); + Mockito.when(instance.isSolidityLogTriggerEnable()).thenReturn(true); + try { + solidEventService.flush(be2); + } catch (Exception e) { + Assert.assertTrue(e instanceof NullPointerException); + } + + contractTrigger.getContractEventTriggers().clear(); + + solidEventService.flush(be2); + + contractTrigger.getContractLogTriggers().add(mock(ContractLogTrigger.class)); + Mockito.when(instance.isSolidityEventTriggerEnable()).thenReturn(true); + try { + solidEventService.flush(be2); + } catch (Exception e) { + Assert.assertTrue(e instanceof NullPointerException); + } + + be2.setSmartContractTrigger(null); + + Mockito.when(instance.isSolidityTriggerEnable()).thenReturn(true); + be2.setSolidityTriggerCapsule(new SolidityTriggerCapsule(1)); + queue.clear(); + solidEventService.flush(be2); + Assert.assertEquals(1, queue.size()); + } +} diff --git a/framework/src/test/java/org/tron/core/exception/TronErrorTest.java b/framework/src/test/java/org/tron/core/exception/TronErrorTest.java new file mode 100644 index 00000000000..b4c3dc4b07f --- /dev/null +++ b/framework/src/test/java/org/tron/core/exception/TronErrorTest.java @@ -0,0 +1,117 @@ +package org.tron.core.exception; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mockStatic; + +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; +import com.typesafe.config.ConfigObject; +import java.io.IOException; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.mockito.MockedStatic; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.tron.common.log.LogService; +import org.tron.common.parameter.RateLimiterInitialization; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.zksnark.JLibrustzcash; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.services.http.GetBlockServlet; +import org.tron.core.services.http.RateLimiterServlet; +import org.tron.core.zen.ZksnarkInitService; + +@RunWith(MockitoJUnitRunner.class) +public class TronErrorTest { + + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @After + public void clearMocks() { + Mockito.clearAllCaches(); + Args.clearParam(); + } + + @Test + public void testTronError() { + TronError tronError = new TronError("message", TronError.ErrCode.WITNESS_KEYSTORE_LOAD); + Assert.assertEquals(tronError.getErrCode(), TronError.ErrCode.WITNESS_KEYSTORE_LOAD); + Assert.assertEquals(tronError.getErrCode().toString(), "WITNESS_KEYSTORE_LOAD(-1)"); + Assert.assertEquals(tronError.getErrCode().getCode(), -1); + tronError = new TronError("message", new Throwable(), TronError.ErrCode.API_SERVER_INIT); + Assert.assertEquals(tronError.getErrCode(), TronError.ErrCode.API_SERVER_INIT); + tronError = new TronError(new Throwable(), TronError.ErrCode.LEVELDB_INIT); + Assert.assertEquals(tronError.getErrCode(), TronError.ErrCode.LEVELDB_INIT); + } + + @Test + public void ZksnarkInitTest() { + try (MockedStatic mock = mockStatic(JLibrustzcash.class)) { + mock.when(JLibrustzcash::isOpenZen).thenReturn(true); + mock.when(() -> JLibrustzcash.librustzcashInitZksnarkParams(any())) + .thenAnswer(invocation -> { + throw new ZksnarkException("Zksnark init failed"); + }); + TronError thrown = assertThrows(TronError.class, + ZksnarkInitService::librustzcashInitZksnarkParams); + assertEquals(TronError.ErrCode.ZCASH_INIT, thrown.getErrCode()); + } + } + + @Test + public void LogLoadTest() throws IOException { + LogService.load("non-existent.xml"); + Path path = temporaryFolder.newFile("logback.xml").toPath(); + TronError thrown = assertThrows(TronError.class, () -> LogService.load(path.toString())); + assertEquals(TronError.ErrCode.LOG_LOAD, thrown.getErrCode()); + } + + @Test + public void witnessInitTest() { + TronError thrown = assertThrows(TronError.class, () -> { + Args.setParam(new String[]{"--witness"}, Constant.TEST_CONF); + }); + assertEquals(TronError.ErrCode.WITNESS_INIT, thrown.getErrCode()); + } + + @Test + public void rateLimiterServletInitTest() { + Args.setParam(new String[]{}, Constant.TEST_CONF); + RateLimiterInitialization rateLimiter = new RateLimiterInitialization(); + Args.getInstance().setRateLimiterInitialization(rateLimiter); + Map item = new HashMap<>(); + item.put("strategy", "strategy"); + item.put("paramString", "params"); + item.put("component", "GetBlockServlet"); + ConfigObject config = ConfigFactory.parseMap(item).root(); + rateLimiter.setHttpMap( + Collections.singletonList(new RateLimiterInitialization.HttpRateLimiterItem(config))); + RateLimiterServlet servlet = new GetBlockServlet(); + TronError thrown = assertThrows(TronError.class, () -> + ReflectUtils.invokeMethod(servlet, "addRateContainer")); + assertEquals(TronError.ErrCode.RATE_LIMITER_INIT, thrown.getErrCode()); + } + + @Test + public void shutdownBlockTimeInitTest() { + Map params = new HashMap<>(); + params.put(Constant.NODE_SHUTDOWN_BLOCK_TIME, "0"); + params.put("storage.db.directory", "database"); + Config config = ConfigFactory.defaultOverrides().withFallback( + ConfigFactory.parseMap(params)); + TronError thrown = assertThrows(TronError.class, () -> Args.setParam(config)); + assertEquals(TronError.ErrCode.AUTO_STOP_PARAMS, thrown.getErrCode()); + } +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java b/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java new file mode 100644 index 00000000000..570e7ed3498 --- /dev/null +++ b/framework/src/test/java/org/tron/core/jsonrpc/ApiUtilTest.java @@ -0,0 +1,46 @@ +package org.tron.core.jsonrpc; + +import static org.tron.common.utils.Commons.decodeFromBase58Check; +import static org.tron.keystore.Wallet.generateRandomBytes; + +import com.google.protobuf.ByteString; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.utils.ByteArray; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.services.jsonrpc.JsonRpcApiUtil; +import org.tron.protos.Protocol.Block; +import org.tron.protos.Protocol.BlockHeader; +import org.tron.protos.Protocol.BlockHeader.raw; +import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; + +public class ApiUtilTest { + + @Test + public void testGetBlockID() { + byte[] mockedHash = generateRandomBytes(128); + // common parent block + BlockCapsule blockCapsule = new BlockCapsule(Block.newBuilder().setBlockHeader( + BlockHeader.newBuilder().setRawData( + raw.newBuilder().setParentHash(ByteString.copyFrom(mockedHash)) + .setNumber(0))).build()); + String blockIdStr = JsonRpcApiUtil.getBlockID(blockCapsule.getInstance()); + Assert.assertEquals(2 + 64, blockIdStr.length()); + } + + @Test + public void testTriggerCallContract() { + byte[] address = decodeFromBase58Check("TEPRbQxXQEpHpeEx8tK5xHVs7NWudAAZgu"); + //nile usdt + byte[] contractAddress = decodeFromBase58Check("TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf"); + long callValue = 100; + //transfer to address TVjsyZ7fYF3qLF6BQgPmTEZy1xrNNyVAAA with 10*10^6 + byte[] data = ByteArray.fromHexString("a9059cbb000000000000000000000000d8dd39e2dea27a4000" + + "1884901735e3940829bb440000000000000000000000000000000000000000000000000000000000989680"); + long tokenValue = 10; + String tokenId = "1000001"; + TriggerSmartContract triggerSmartContract = JsonRpcApiUtil.triggerCallContract(address, + contractAddress, callValue, data, tokenValue, tokenId); + Assert.assertNotNull(triggerSmartContract); + } +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/BloomTest.java b/framework/src/test/java/org/tron/core/jsonrpc/BloomTest.java index 2964e24232f..19e232b0f93 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/BloomTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/BloomTest.java @@ -6,8 +6,8 @@ import java.util.ArrayList; import java.util.List; import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; import org.tron.common.bloom.Bloom; import org.tron.common.crypto.Hash; import org.tron.common.runtime.vm.DataWord; diff --git a/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java b/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java index bbc49835bd5..578d5869e31 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/BuildTransactionTest.java @@ -1,31 +1,26 @@ package org.tron.core.jsonrpc; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.ContractCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.services.jsonrpc.types.BuildArguments; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Transaction.Contract.ContractType; import org.tron.protos.contract.SmartContractOuterClass.SmartContract; @Slf4j -public class BuildTransactionTest { +public class BuildTransactionTest extends BaseTest { - private static String dbPath = "output_build_transaction_test"; private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "first"; @@ -33,24 +28,19 @@ public class BuildTransactionTest { private static final String CONTRACT_ADDRESS; private static final long SOURCE_PERCENT = 10L; - private static TronApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; + @Resource + private Wallet wallet; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; CONTRACT_ADDRESS = Wallet.getAddressPreFixString() + "f859b5c93f789f4bcffbe7cc95a71e28e5e6a5bd"; } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); - + @Before + public void init() { AccountCapsule accountCapsule = new AccountCapsule( ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), @@ -76,17 +66,6 @@ public static void init() { new ContractCapsule(builder.build())); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testTransferContract() { BuildArguments buildArguments = new BuildArguments(); 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 ea0c0354bb0..1de106f68e8 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/ConcurrentHashMapTest.java @@ -1,5 +1,8 @@ package org.tron.core.jsonrpc; +import static org.tron.common.math.Maths.random; +import static org.tron.common.math.Maths.round; + import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -17,7 +20,7 @@ public class ConcurrentHashMapTest { private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random(true) * (maxInt - minInt) + minInt, true); } /** diff --git a/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java b/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java index f221d0c95ac..bef0b5a1593 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonRpcTest.java @@ -19,6 +19,7 @@ import org.tron.common.utils.ByteUtil; import org.tron.common.utils.Commons; import org.tron.core.exception.JsonRpcInvalidParamsException; +import org.tron.core.services.jsonrpc.JsonRpcApiUtil; import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; import org.tron.core.services.jsonrpc.filters.LogBlockQuery; import org.tron.core.services.jsonrpc.filters.LogFilter; @@ -190,6 +191,7 @@ public void testLogFilter() { } catch (JsonRpcInvalidParamsException e) { Assert.fail(); } + try { new LogFilter(new FilterRequest(null, null, null, new String[] {"0x0"}, null)); } catch (JsonRpcInvalidParamsException e) { @@ -240,124 +242,20 @@ public void testLogFilter() { } } - /** - * test fromBlock and toBlock parameters - */ - @Test - public void testLogFilterWrapper() { - - // fromBlock and toBlock are both empty - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest(null, null, null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 100); - Assert.assertEquals(logFilterWrapper.getToBlock(), Long.MAX_VALUE); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - - // fromBlock is not empty and smaller than currentMaxBlockNum, toBlock is empty - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("0x14", null, null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 20); - Assert.assertEquals(logFilterWrapper.getToBlock(), Long.MAX_VALUE); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - - // fromBlock is not empty and bigger than currentMaxBlockNum, toBlock is empty - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("0x78", null, null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 120); - Assert.assertEquals(logFilterWrapper.getToBlock(), Long.MAX_VALUE); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - - // fromBlock is empty, toBlock is not empty and smaller than currentMaxBlockNum - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest(null, "0x14", null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 20); - Assert.assertEquals(logFilterWrapper.getToBlock(), 20); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - - // fromBlock is empty, toBlock is not empty and bigger than currentMaxBlockNum - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest(null, "0x78", null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 100); - Assert.assertEquals(logFilterWrapper.getToBlock(), 120); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - - // fromBlock is not empty, toBlock is not empty - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("0x14", "0x78", null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 20); - Assert.assertEquals(logFilterWrapper.getToBlock(), 120); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("0x78", "0x14", null, null, null), 100, null); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals("please verify: fromBlock <= toBlock", e.getMessage()); - } - - //fromBlock or toBlock is not hex num - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("earliest", null, null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 0); - Assert.assertEquals(logFilterWrapper.getToBlock(), Long.MAX_VALUE); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("latest", null, null, null, null), 100, null); - Assert.assertEquals(logFilterWrapper.getFromBlock(), 100); - Assert.assertEquals(logFilterWrapper.getToBlock(), Long.MAX_VALUE); - } catch (JsonRpcInvalidParamsException e) { - Assert.fail(); - } - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("pending", null, null, null, null), 100, null); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals("TAG pending not supported", e.getMessage()); - } - try { - LogFilterWrapper logFilterWrapper = - new LogFilterWrapper(new FilterRequest("test", null, null, null, null), 100, null); - } catch (JsonRpcInvalidParamsException e) { - Assert.assertEquals("Incorrect hex syntax", e.getMessage()); - } - } - private int[] getBloomIndex(String s) { Bloom bloom = Bloom.create(Hash.sha3(ByteArray.fromHexString(s))); BitSet bs = BitSet.valueOf(bloom.getData()); - int[] bitIndex = new int[3]; //must same as the number of hash function in Bloom - int nonZeroCount = 0; + List bitIndexList = new ArrayList<>(); for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { // operate on index i here if (i == Integer.MAX_VALUE) { break; // or (i+1) would overflow } - bitIndex[nonZeroCount++] = i; + bitIndexList.add(i); } - return bitIndex; + return bitIndexList.stream().mapToInt(Integer::intValue).toArray(); } @Test @@ -386,7 +284,8 @@ public void testGetConditions() { topics, null), 100, - null); + null, + false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, null, 100, null); int[][][] conditions = logBlockQuery.getConditions(); @@ -416,4 +315,49 @@ public void testGetConditions() { Assert.fail(); } } + + @Test + public void testGetConditionWithHashCollision() { + try { + List addressList = new ArrayList<>(); + addressList.add("0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85"); + addressList.add("0x3038114c1a1e72c5bfa8b003bc3650ad2ba254a0"); + + Object[] topics = new Object[0]; + + LogFilterWrapper logFilterWrapper = + new LogFilterWrapper(new FilterRequest(null, + null, + addressList, + topics, + null), + 100, + null, + false); + + LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, null, 100, null); + int[][][] conditions = logBlockQuery.getConditions(); + //level = depth(address) + depth(topics), skip null + Assert.assertEquals(1, conditions.length); + //elements number + Assert.assertEquals(2, conditions[0].length); + + Assert.assertEquals(3, conditions[0][0].length); + //Hash collision, only two nonZero position + Assert.assertEquals(2, conditions[0][1].length); + + Assert.assertArrayEquals(conditions[0][0], + getBloomIndex("0x57f1887a8bf19b14fc0df6fd9b2acc9af147ea85")); + Assert.assertArrayEquals(conditions[0][1], + getBloomIndex("0x3038114c1a1e72c5bfa8b003bc3650ad2ba254a0")); + + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + } + + @Test + public void testGenerateFilterId() { + Assert.assertEquals(32, JsonRpcApiUtil.generateFilterId().length()); + } } 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 8ac70c4661e..0f2214c5c9c 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/JsonrpcServiceTest.java @@ -1,28 +1,48 @@ package org.tron.core.jsonrpc; -import com.google.protobuf.Any; +import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.getByJsonBlockId; + +import com.alibaba.fastjson.JSON; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; import com.google.protobuf.ByteString; -import java.io.File; +import io.prometheus.client.CollectorRegistry; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; +import org.apache.http.client.methods.CloseableHttpResponse; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.util.EntityUtils; import org.bouncycastle.util.encoders.Hex; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.prometheus.Metrics; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; +import org.tron.core.capsule.utils.BlockUtil; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; +import org.tron.core.exception.JsonRpcInvalidParamsException; import org.tron.core.services.NodeInfoService; +import org.tron.core.services.interfaceJsonRpcOnPBFT.JsonRpcServiceOnPBFT; +import org.tron.core.services.interfaceJsonRpcOnSolidity.JsonRpcServiceOnSolidity; +import org.tron.core.services.jsonrpc.FullNodeJsonRpcHttpService; +import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; import org.tron.core.services.jsonrpc.TronJsonRpcImpl; +import org.tron.core.services.jsonrpc.filters.LogFilterWrapper; import org.tron.core.services.jsonrpc.types.BlockResult; import org.tron.core.services.jsonrpc.types.TransactionResult; import org.tron.protos.Protocol; @@ -31,94 +51,113 @@ @Slf4j -public class JsonrpcServiceTest { - private static String dbPath = "output_jsonrpc_service_test"; +public class JsonrpcServiceTest extends BaseTest { + private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "first"; + private static final long LATEST_BLOCK_NUM = 10_000L; + private static final long LATEST_SOLIDIFIED_BLOCK_NUM = 4L; private static TronJsonRpcImpl tronJsonRpc; - private static TronApplicationContext context; - private static NodeInfoService nodeInfoService; + @Resource + private NodeInfoService nodeInfoService; - private static BlockCapsule blockCapsule; + private static BlockCapsule blockCapsule0; + private static BlockCapsule blockCapsule1; + private static BlockCapsule blockCapsule2; private static TransactionCapsule transactionCapsule1; - private static TransactionCapsule transactionCapsule2; + @Resource + private Wallet wallet; - static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + @Resource + private FullNodeJsonRpcHttpService fullNodeJsonRpcHttpService; - OWNER_ADDRESS = - Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - nodeInfoService = context.getBean("nodeInfoService", NodeInfoService.class); - } + @Resource + private JsonRpcServiceOnPBFT jsonRpcServiceOnPBFT; - @BeforeClass - public static void init() { - Manager dbManager = context.getBean(Manager.class); - Wallet wallet = context.getBean(Wallet.class); + @Resource + private JsonRpcServiceOnSolidity jsonRpcServiceOnSolidity; + static { + Args.setParam(new String[] {"--output-directory", dbPath()}, Constant.TEST_CONF); + CommonParameter.getInstance().setJsonRpcHttpFullNodeEnable(true); + CommonParameter.getInstance().setJsonRpcHttpFullNodePort(PublicMethod.chooseRandomPort()); + CommonParameter.getInstance().setJsonRpcHttpPBFTNodeEnable(true); + CommonParameter.getInstance().setJsonRpcHttpPBFTPort(PublicMethod.chooseRandomPort()); + CommonParameter.getInstance().setJsonRpcHttpSolidityNodeEnable(true); + CommonParameter.getInstance().setJsonRpcHttpSolidityPort(PublicMethod.chooseRandomPort()); + CommonParameter.getInstance().setMetricsPrometheusEnable(true); + CommonParameter.getInstance().setMetricsPrometheusPort(PublicMethod.chooseRandomPort()); + Metrics.init(); + + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + } + + @Before + public void init() { AccountCapsule accountCapsule = - new AccountCapsule( - ByteString.copyFromUtf8(OWNER_ADDRESS_ACCOUNT_NAME), + new AccountCapsule(ByteString.copyFromUtf8(OWNER_ADDRESS_ACCOUNT_NAME), ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), - Protocol.AccountType.Normal, - 10000_000_000L); + Protocol.AccountType.Normal, 10000_000_000L); dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); - blockCapsule = new BlockCapsule( - 1, - Sha256Hash.wrap(ByteString.copyFrom( - ByteArray.fromHexString( - "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))), - 1, + blockCapsule0 = BlockUtil.newGenesisBlockCapsule(); + blockCapsule1 = new BlockCapsule(LATEST_BLOCK_NUM, Sha256Hash.wrap(ByteString.copyFrom( + ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b81"))), 1, + ByteString.copyFromUtf8("testAddress")); + blockCapsule2 = new BlockCapsule(LATEST_SOLIDIFIED_BLOCK_NUM, Sha256Hash.wrap( + ByteString.copyFrom(ByteArray.fromHexString( + "9938a342238077182498b464ac029222ae169360e540d1fd6aee7c2ae9575a06"))), 1, ByteString.copyFromUtf8("testAddress")); - TransferContract transferContract1 = TransferContract.newBuilder() - .setAmount(1L) - .setOwnerAddress(ByteString.copyFrom("0x0000000000000000000".getBytes())) - .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( - (Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086")))) - .build(); - TransferContract transferContract2 = TransferContract.newBuilder() - .setAmount(2L) - .setOwnerAddress(ByteString.copyFrom("0x0000000000000000000".getBytes())) - .setToAddress(ByteString.copyFrom(ByteArray.fromHexString( - (Wallet.getAddressPreFixString() + "ED738B3A0FE390EAA71B768B6D02CDBD18FB207B")))) + TransferContract transferContract1 = TransferContract.newBuilder().setAmount(1L) + .setOwnerAddress(ByteString.copyFrom("0x0000000000000000000".getBytes())).setToAddress( + ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "A389132D6639FBDA4FBC8B659264E6B7C90DB086")))) + .build(); + TransferContract transferContract2 = TransferContract.newBuilder().setAmount(2L) + .setOwnerAddress(ByteString.copyFrom("0x0000000000000000000".getBytes())).setToAddress( + ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "ED738B3A0FE390EAA71B768B6D02CDBD18FB207B")))) + .build(); + TransferContract transferContract3 = TransferContract.newBuilder().setAmount(3L) + .setOwnerAddress(ByteString.copyFrom("0x0000000000000000000".getBytes())).setToAddress( + ByteString.copyFrom(ByteArray.fromHexString( + (Wallet.getAddressPreFixString() + "ED738B3A0FE390EAA71B768B6D02CDBD18FB207B")))) .build(); - transactionCapsule1 = - new TransactionCapsule(transferContract1, ContractType.TransferContract); - transactionCapsule1.setBlockNum(blockCapsule.getNum()); - transactionCapsule2 = - new TransactionCapsule(transferContract2, ContractType.TransferContract); - transactionCapsule2.setBlockNum(2L); + transactionCapsule1 = new TransactionCapsule(transferContract1, ContractType.TransferContract); + transactionCapsule1.setBlockNum(blockCapsule1.getNum()); + TransactionCapsule transactionCapsule2 = new TransactionCapsule(transferContract2, + ContractType.TransferContract); + transactionCapsule2.setBlockNum(blockCapsule1.getNum()); + TransactionCapsule transactionCapsule3 = new TransactionCapsule(transferContract3, + ContractType.TransferContract); + transactionCapsule3.setBlockNum(blockCapsule2.getNum()); - blockCapsule.addTransaction(transactionCapsule1); - blockCapsule.addTransaction(transactionCapsule2); - dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(1L); - dbManager.getBlockIndexStore().put(blockCapsule.getBlockId()); - dbManager.getBlockStore().put(blockCapsule.getBlockId().getBytes(), blockCapsule); + blockCapsule1.addTransaction(transactionCapsule1); + blockCapsule1.addTransaction(transactionCapsule2); + blockCapsule2.addTransaction(transactionCapsule3); + + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(LATEST_BLOCK_NUM); + dbManager.getBlockIndexStore().put(blockCapsule1.getBlockId()); + dbManager.getBlockStore().put(blockCapsule1.getBlockId().getBytes(), blockCapsule1); + + dbManager.getDynamicPropertiesStore().saveLatestSolidifiedBlockNum(LATEST_SOLIDIFIED_BLOCK_NUM); + dbManager.getBlockIndexStore().put(blockCapsule2.getBlockId()); + dbManager.getBlockStore().put(blockCapsule2.getBlockId().getBytes(), blockCapsule2); dbManager.getTransactionStore() .put(transactionCapsule1.getTransactionId().getBytes(), transactionCapsule1); dbManager.getTransactionStore() .put(transactionCapsule2.getTransactionId().getBytes(), transactionCapsule2); + dbManager.getTransactionStore() + .put(transactionCapsule3.getTransactionId().getBytes(), transactionCapsule3); tronJsonRpc = new TronJsonRpcImpl(nodeInfoService, wallet, dbManager); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - @Test public void testWeb3Sha3() { String result = ""; @@ -157,11 +196,11 @@ public void testGetBlockTransactionCountByHash() { try { result = tronJsonRpc.ethGetBlockTransactionCountByHash( - Hex.toHexString((blockCapsule.getBlockId().getBytes()))); + Hex.toHexString((blockCapsule1.getBlockId().getBytes()))); } catch (Exception e) { Assert.fail(); } - Assert.assertEquals(ByteArray.toJsonHex(blockCapsule.getTransactions().size()), result); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getTransactions().size()), result); } @@ -191,15 +230,15 @@ public void testGetBlockTransactionCountByNumber() { } catch (Exception e) { Assert.fail(); } - Assert.assertEquals(ByteArray.toJsonHex(blockCapsule.getTransactions().size()), result); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getTransactions().size()), result); try { - result = tronJsonRpc - .ethGetBlockTransactionCountByNumber(ByteArray.toJsonHex(blockCapsule.getNum())); + result = tronJsonRpc.ethGetBlockTransactionCountByNumber( + ByteArray.toJsonHex(blockCapsule1.getNum())); } catch (Exception e) { Assert.fail(); } - Assert.assertEquals(ByteArray.toJsonHex(blockCapsule.getTransactions().size()), result); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getTransactions().size()), result); } @@ -207,33 +246,76 @@ public void testGetBlockTransactionCountByNumber() { public void testGetBlockByHash() { BlockResult blockResult = null; try { - blockResult = tronJsonRpc - .ethGetBlockByHash(Hex.toHexString((blockCapsule.getBlockId().getBytes())), false); + blockResult = + tronJsonRpc.ethGetBlockByHash(Hex.toHexString((blockCapsule1.getBlockId().getBytes())), + false); } catch (Exception e) { Assert.fail(); } - Assert.assertEquals(ByteArray.toJsonHex(blockCapsule.getNum()), blockResult.getNumber()); - Assert - .assertEquals(blockCapsule.getTransactions().size(), blockResult.getTransactions().length); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getNum()), blockResult.getNumber()); + Assert.assertEquals(blockCapsule1.getTransactions().size(), + blockResult.getTransactions().length); } @Test public void testGetBlockByNumber() { BlockResult blockResult = null; + + // by number try { - blockResult = tronJsonRpc - .ethGetBlockByNumber(ByteArray.toJsonHex(blockCapsule.getNum()), false); + blockResult = + tronJsonRpc.ethGetBlockByNumber(ByteArray.toJsonHex(blockCapsule1.getNum()), false); } catch (Exception e) { Assert.fail(); } + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getNum()), blockResult.getNumber()); + Assert.assertEquals(blockCapsule1.getTransactions().size(), + blockResult.getTransactions().length); + Assert.assertEquals("0x0000000000000000", blockResult.getNonce()); - Assert.assertEquals(ByteArray.toJsonHex(blockCapsule.getNum()), blockResult.getNumber()); - Assert - .assertEquals(blockCapsule.getTransactions().size(), blockResult.getTransactions().length); - Assert.assertNull(blockResult.getNonce()); + // earliest + try { + blockResult = tronJsonRpc.ethGetBlockByNumber("earliest", false); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(ByteArray.toJsonHex(0L), blockResult.getNumber()); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule0.getNum()), blockResult.getNumber()); - } + // latest + try { + blockResult = tronJsonRpc.ethGetBlockByNumber("latest", false); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(ByteArray.toJsonHex(LATEST_BLOCK_NUM), blockResult.getNumber()); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getNum()), blockResult.getNumber()); + // finalized + try { + blockResult = tronJsonRpc.ethGetBlockByNumber("finalized", false); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(ByteArray.toJsonHex(LATEST_SOLIDIFIED_BLOCK_NUM), blockResult.getNumber()); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule2.getNum()), blockResult.getNumber()); + + // pending + try { + tronJsonRpc.ethGetBlockByNumber("pending", false); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG pending not supported", e.getMessage()); + } + + // invalid + try { + tronJsonRpc.ethGetBlockByNumber("0x", false); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("invalid block number", e.getMessage()); + } + } @Test public void testGetTransactionByHash() { @@ -256,4 +338,634 @@ public void testGetTransactionByHash() { transactionResult.getBlockNumber()); } -} \ No newline at end of file + @Test + public void testGetBlockByNumber2() { + fullNodeJsonRpcHttpService.start(); + JsonArray params = new JsonArray(); + params.add(ByteArray.toJsonHex(blockCapsule1.getNum())); + params.add(false); + JsonObject requestBody = new JsonObject(); + requestBody.addProperty("jsonrpc", "2.0"); + requestBody.addProperty("method", "eth_getBlockByNumber"); + requestBody.add("params", params); + requestBody.addProperty("id", 1); + CloseableHttpResponse response; + try (CloseableHttpClient httpClient = HttpClients.createDefault()) { + HttpPost httpPost = new HttpPost("http://127.0.0.1/" + + CommonParameter.getInstance().getJsonRpcHttpFullNodePort() + "/jsonrpc"); + httpPost.addHeader("Content-Type", "application/json"); + httpPost.setEntity(new StringEntity(requestBody.toString())); + response = httpClient.execute(httpPost); + String resp = EntityUtils.toString(response.getEntity()); + BlockResult blockResult = JSON.parseObject(resp).getObject("result", BlockResult.class); + Assert.assertEquals(ByteArray.toJsonHex(blockCapsule1.getNum()), blockResult.getNumber()); + Assert.assertEquals(blockCapsule1.getTransactions().size(), + blockResult.getTransactions().length); + Assert.assertEquals("0x0000000000000000", blockResult.getNonce()); + response.close(); + Assert.assertEquals(1, CollectorRegistry.defaultRegistry.getSampleValue( + "tron:jsonrpc_service_latency_seconds_count", new String[] {"method"}, + new String[] {"eth_getBlockByNumber"}).intValue()); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } finally { + fullNodeJsonRpcHttpService.stop(); + } + } + + @Test + public void testServicesInit() { + try { + jsonRpcServiceOnPBFT.start(); + jsonRpcServiceOnSolidity.start(); + } finally { + jsonRpcServiceOnPBFT.stop(); + jsonRpcServiceOnSolidity.stop(); + } + } + + @Test + public void testGetByJsonBlockId() { + long blkNum = 0; + + try { + getByJsonBlockId("pending", wallet); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG pending not supported", e.getMessage()); + } + + try { + blkNum = getByJsonBlockId(null, wallet); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(-1, blkNum); + + try { + blkNum = getByJsonBlockId("latest", wallet); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(-1, blkNum); + + try { + blkNum = getByJsonBlockId("finalized", wallet); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(LATEST_SOLIDIFIED_BLOCK_NUM, blkNum); + + try { + blkNum = getByJsonBlockId("0xa", wallet); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals(10L, blkNum); + + try { + getByJsonBlockId("abc", wallet); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("Incorrect hex syntax", e.getMessage()); + } + + try { + getByJsonBlockId("0xxabc", wallet); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("For input string: \"xabc\"", e.getMessage()); + } + } + + @Test + public void testGetTrxBalance() { + String balance = ""; + + try { + tronJsonRpc.getTrxBalance("", "earliest"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getTrxBalance("", "pending"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getTrxBalance("", "finalized"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + balance = tronJsonRpc.getTrxBalance("0xabd4b9367799eaa3197fecb144eb71de1e049abc", + "latest"); + } catch (Exception e) { + Assert.fail(); + } + Assert.assertEquals("0x2540be400", balance); + } + + @Test + public void testGetStorageAt() { + try { + tronJsonRpc.getStorageAt("", "", "earliest"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getStorageAt("", "", "pending"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getStorageAt("", "", "finalized"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + } + + @Test + public void testGetABIOfSmartContract() { + try { + tronJsonRpc.getABIOfSmartContract("", "earliest"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getABIOfSmartContract("", "pending"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getABIOfSmartContract("", "finalized"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + } + + @Test + public void testGetCall() { + try { + tronJsonRpc.getCall(null, "earliest"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getCall(null, "pending"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + + try { + tronJsonRpc.getCall(null, "finalized"); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("TAG [earliest | pending | finalized] not supported", + e.getMessage()); + } + } + + /** + * test fromBlock and toBlock parameters + */ + @Test + public void testLogFilterWrapper() { + + // fromBlock and toBlock are both empty + try { + LogFilterWrapper logFilterWrapper = + new LogFilterWrapper(new FilterRequest(null, null, null, null, null), 100, null, false); + Assert.assertEquals(100, logFilterWrapper.getFromBlock()); + Assert.assertEquals(Long.MAX_VALUE, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + // fromBlock is not empty and smaller than currentMaxBlockNum, toBlock is empty + try { + LogFilterWrapper logFilterWrapper = + new LogFilterWrapper(new FilterRequest("0x14", null, null, null, null), 100, null, false); + Assert.assertEquals(20, logFilterWrapper.getFromBlock()); + Assert.assertEquals(Long.MAX_VALUE, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + // fromBlock is not empty and bigger than currentMaxBlockNum, toBlock is empty + try { + LogFilterWrapper logFilterWrapper = + new LogFilterWrapper(new FilterRequest("0x78", null, null, null, null), 100, null, false); + Assert.assertEquals(120, logFilterWrapper.getFromBlock()); + Assert.assertEquals(Long.MAX_VALUE, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + // fromBlock is empty, toBlock is not empty and smaller than currentMaxBlockNum + try { + LogFilterWrapper logFilterWrapper = + new LogFilterWrapper(new FilterRequest(null, "0x14", null, null, null), 100, null, false); + Assert.assertEquals(20, logFilterWrapper.getFromBlock()); + Assert.assertEquals(20, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + // fromBlock is empty, toBlock is not empty and bigger than currentMaxBlockNum + try { + LogFilterWrapper logFilterWrapper = + new LogFilterWrapper(new FilterRequest(null, "0x78", null, null, null), 100, null, false); + Assert.assertEquals(100, logFilterWrapper.getFromBlock()); + Assert.assertEquals(120, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + // fromBlock is not empty, toBlock is not empty + try { + LogFilterWrapper logFilterWrapper = new LogFilterWrapper(new FilterRequest("0x14", "0x78", + null, null, null), 100, null, false); + Assert.assertEquals(20, logFilterWrapper.getFromBlock()); + Assert.assertEquals(120, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("0x78", "0x14", + null, null, null), 100, null, false); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals("please verify: fromBlock <= toBlock", e.getMessage()); + } + + //fromBlock or toBlock is not hex num + try { + LogFilterWrapper logFilterWrapper = new LogFilterWrapper(new FilterRequest("earliest", null, + null, null, null), 100, null, false); + Assert.assertEquals(0, logFilterWrapper.getFromBlock()); + Assert.assertEquals(Long.MAX_VALUE, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + LogFilterWrapper logFilterWrapper = new LogFilterWrapper(new FilterRequest("latest", null, + null, null, null), 100, null, false); + Assert.assertEquals(100, logFilterWrapper.getFromBlock()); + Assert.assertEquals(Long.MAX_VALUE, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("pending", null, null, null, null), + 100, null, false); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals("TAG pending not supported", e.getMessage()); + } + try { + LogFilterWrapper logFilterWrapper = new LogFilterWrapper(new FilterRequest("finalized", null, + null, null, null), 100, wallet, false); + Assert.assertEquals(LATEST_SOLIDIFIED_BLOCK_NUM, logFilterWrapper.getFromBlock()); + Assert.assertEquals(Long.MAX_VALUE, logFilterWrapper.getToBlock()); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("test", null, null, null, null), + 100, null, false); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals("Incorrect hex syntax", e.getMessage()); + } + + // to = 8000 + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, true); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + e.getMessage()); + } + + try { + new LogFilterWrapper(new FilterRequest("0x0", "latest", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + try { + new LogFilterWrapper(new FilterRequest("0x0", "latest", null, + null, null), LATEST_BLOCK_NUM, null, true); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + e.getMessage()); + } + + // from = 100, current = 5_000, to = Long.MAX_VALUE + try { + new LogFilterWrapper(new FilterRequest("0x64", "latest", null, + null, null), 5_000, null, true); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("0x64", "latest", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (Exception e) { + Assert.fail(); + } + + // from = 100 + try { + new LogFilterWrapper(new FilterRequest("0x64", "latest", null, + null, null), LATEST_BLOCK_NUM, null, true); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + e.getMessage()); + } + try { + new LogFilterWrapper(new FilterRequest("0x64", "latest", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (Exception e) { + Assert.fail(); + } + + // from = 9_000 + try { + new LogFilterWrapper(new FilterRequest("0x2328", "latest", null, + null, null), LATEST_BLOCK_NUM, null, true); + } catch (Exception e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("0x2328", "latest", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (Exception e) { + Assert.fail(); + } + + try { + new LogFilterWrapper(new FilterRequest("latest", "latest", null, + null, null), LATEST_BLOCK_NUM, null, true); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("latest", "latest", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + int oldMaxBlockRange = Args.getInstance().getJsonRpcMaxBlockRange(); + Args.getInstance().setJsonRpcMaxBlockRange(10_000); + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, true); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + Args.getInstance().setJsonRpcMaxBlockRange(0); + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, true); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + Args.getInstance().setJsonRpcMaxBlockRange(-2); + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, true); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + new LogFilterWrapper(new FilterRequest("0x0", "0x1f40", null, + null, null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + // reset + Args.getInstance().setJsonRpcMaxBlockRange(oldMaxBlockRange); + } + + @Test + public void testMaxSubTopics() { + List topics = new ArrayList<>(); + topics.add(new ArrayList<>(Collections.singletonList( + "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"))); + topics.add(new ArrayList<>(Collections.EMPTY_LIST)); + List subTopics = new ArrayList<>(); + for (int i = 0; i < Args.getInstance().getJsonRpcMaxSubTopics() + 1; i++) { + subTopics.add("0x0000000000000000000000414de17123a3c706ab197957e131350b2537dd4883"); + } + topics.add(subTopics); + + try { + new LogFilterWrapper(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null), LATEST_BLOCK_NUM, null, false); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max topics: " + Args.getInstance().getJsonRpcMaxSubTopics(), + e.getMessage()); + } + + try { + tronJsonRpc.getLogs(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null)); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max topics: " + Args.getInstance().getJsonRpcMaxSubTopics(), + e.getMessage()); + } catch (Exception e) { + Assert.fail(); + } + + try { + tronJsonRpc.newFilter(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null)); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max topics: " + Args.getInstance().getJsonRpcMaxSubTopics(), + e.getMessage()); + } catch (Exception e) { + Assert.fail(); + } + + int oldMaxSubTopics = Args.getInstance().getJsonRpcMaxSubTopics(); + Args.getInstance().setJsonRpcMaxSubTopics(2_000); + try { + new LogFilterWrapper(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + + Args.getInstance().setJsonRpcMaxSubTopics(0); + try { + new LogFilterWrapper(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + tronJsonRpc.newFilter(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null)); + } catch (Exception e) { + Assert.fail(); + } + + Args.getInstance().setJsonRpcMaxSubTopics(-2); + try { + new LogFilterWrapper(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null), LATEST_BLOCK_NUM, null, false); + } catch (JsonRpcInvalidParamsException e) { + Assert.fail(); + } + try { + tronJsonRpc.newFilter(new FilterRequest("0xbb8", "0x1f40", + null, topics.toArray(), null)); + } catch (Exception e) { + Assert.fail(); + } + + Args.getInstance().setJsonRpcMaxSubTopics(oldMaxSubTopics); + } + + @Test + public void testMethodBlockRange() { + try { + tronJsonRpc.getLogs(new FilterRequest("0x0", "0x1f40", null, + null, null)); + Assert.fail("Expected to be thrown"); + } catch (JsonRpcInvalidParamsException e) { + Assert.assertEquals( + "exceed max block range: " + Args.getInstance().jsonRpcMaxBlockRange, + e.getMessage()); + } catch (Exception e) { + Assert.fail(); + } + + try { + tronJsonRpc.newFilter(new FilterRequest("0x0", "0x1f40", null, + null, null)); + } catch (Exception e) { + Assert.fail(); + } + + try { + tronJsonRpc.getLogs(new FilterRequest("0x0", "0x1", null, + null, null)); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testNewFilterFinalizedBlock() { + + try { + tronJsonRpc.newFilter(new FilterRequest(null, null, null, null, null)); + } catch (Exception e) { + Assert.fail(); + } + + try { + tronJsonRpc.newFilter(new FilterRequest("finalized", null, null, null, null)); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("invalid block range params", e.getMessage()); + } + + try { + tronJsonRpc.newFilter(new FilterRequest(null, "finalized", null, null, null)); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("invalid block range params", e.getMessage()); + } + + try { + tronJsonRpc.newFilter(new FilterRequest("finalized", "latest", null, null, null)); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("invalid block range params", e.getMessage()); + } + + try { + tronJsonRpc.newFilter(new FilterRequest("0x1", "finalized", null, null, null)); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("invalid block range params", e.getMessage()); + } + + try { + tronJsonRpc.newFilter(new FilterRequest("finalized", "finalized", null, null, null)); + Assert.fail("Expected to be thrown"); + } catch (Exception e) { + Assert.assertEquals("invalid block range params", e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java b/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java index 4fa40e42807..111370bfffd 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/SectionBloomStoreTest.java @@ -1,23 +1,19 @@ package org.tron.core.jsonrpc; -import java.io.File; import java.util.ArrayList; import java.util.BitSet; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import javax.annotation.Resource; +import org.junit.Assert; import org.junit.Test; -import org.testng.Assert; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.runtime.vm.DataWord; import org.tron.common.runtime.vm.LogInfo; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.capsule.TransactionRetCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.EventBloomException; import org.tron.core.services.jsonrpc.TronJsonRpc.FilterRequest; @@ -27,28 +23,13 @@ import org.tron.protos.Protocol.TransactionInfo; import org.tron.protos.Protocol.TransactionInfo.Log; -public class SectionBloomStoreTest { +public class SectionBloomStoreTest extends BaseTest { - private static final String dbPath = "output-sectionBloomStore-test"; - static SectionBloomStore sectionBloomStore; - private static TronApplicationContext context; + @Resource + SectionBloomStore sectionBloomStore; static { - Args.setParam(new String[] {"--output-directory", dbPath}, - Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - sectionBloomStore = context.getBean(SectionBloomStore.class); - } - - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[] {"--output-directory", dbPath()}, Constant.TEST_CONF); } @Test @@ -151,7 +132,7 @@ public void testWriteAndQuery() { try { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("earliest", "latest", ByteArray.toJsonHex(address1), null, null), - currentMaxBlockNum, null); + currentMaxBlockNum, null, false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, currentMaxBlockNum, sectionExecutor); @@ -168,7 +149,7 @@ public void testWriteAndQuery() { try { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("earliest", "latest", addressList, null, null), - currentMaxBlockNum, null); + currentMaxBlockNum, null, false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, currentMaxBlockNum, sectionExecutor); @@ -184,7 +165,7 @@ public void testWriteAndQuery() { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("earliest", "latest", null, new String[] {ByteArray.toHexString(topic1)}, null), - currentMaxBlockNum, null); + currentMaxBlockNum, null, false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, currentMaxBlockNum, sectionExecutor); @@ -200,7 +181,7 @@ public void testWriteAndQuery() { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("earliest", "latest", null, new String[] {ByteArray.toHexString(topic2)}, null), - currentMaxBlockNum, null); + currentMaxBlockNum, null, false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, currentMaxBlockNum, sectionExecutor); @@ -218,7 +199,7 @@ public void testWriteAndQuery() { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("earliest", "latest", null, new Object[] {topicList}, null), - currentMaxBlockNum, null); + currentMaxBlockNum, null, false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, currentMaxBlockNum, sectionExecutor); @@ -245,7 +226,7 @@ public void testWriteAndQuery() { LogFilterWrapper logFilterWrapper = new LogFilterWrapper( new FilterRequest("earliest", "latest", null, new Object[] {ByteArray.toJsonHex(topic1), ByteArray.toJsonHex(topic2)}, null), - currentMaxBlockNum, null); + currentMaxBlockNum, null, false); LogBlockQuery logBlockQuery = new LogBlockQuery(logFilterWrapper, sectionBloomStore, currentMaxBlockNum, sectionExecutor); 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 778860b8879..d460440184c 100644 --- a/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java +++ b/framework/src/test/java/org/tron/core/jsonrpc/WalletCursorTest.java @@ -1,21 +1,17 @@ package org.tron.core.jsonrpc; import com.google.protobuf.ByteString; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.AccountCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.db2.core.Chainbase.Cursor; import org.tron.core.services.NodeInfoService; import org.tron.core.services.jsonrpc.TronJsonRpcImpl; @@ -24,30 +20,27 @@ import org.tron.protos.Protocol; @Slf4j -public class WalletCursorTest { - private static String dbPath = "output_wallet_cursor_test"; +public class WalletCursorTest extends BaseTest { private static final String OWNER_ADDRESS; private static final String OWNER_ADDRESS_ACCOUNT_NAME = "first"; - - private static TronApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; - private static NodeInfoService nodeInfoService; + @Resource + private Wallet wallet; + @Resource + private NodeInfoService nodeInfoService; + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, Constant.TEST_CONF); OWNER_ADDRESS = Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; - nodeInfoService = context.getBean("nodeInfoService", NodeInfoService.class); } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); - + @Before + public void init() { + if (init) { + return; + } AccountCapsule accountCapsule = new AccountCapsule( ByteString.copyFromUtf8(OWNER_ADDRESS_ACCOUNT_NAME), @@ -55,17 +48,7 @@ public static void init() { Protocol.AccountType.Normal, 10000_000_000L); dbManager.getAccountStore().put(accountCapsule.getAddress().toByteArray(), accountCapsule); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } @Test 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 dfe658080fc..e36029c6141 100644 --- a/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java +++ b/framework/src/test/java/org/tron/core/metrics/MetricsApiServiceTest.java @@ -1,16 +1,17 @@ package org.tron.core.metrics; -import java.io.File; +import java.io.IOException; import lombok.extern.slf4j.Slf4j; import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @@ -21,7 +22,8 @@ @Slf4j public class MetricsApiServiceTest { - private static String dbPath = "output-metrics"; + @ClassRule + public static TemporaryFolder temporaryFolder = new TemporaryFolder(); private static String dbDirectory = "metrics-database"; private static String indexDirectory = "metrics-index"; private static int port = 10001; @@ -32,7 +34,8 @@ public class MetricsApiServiceTest { @Before - public void init() { + public void init() throws IOException { + String dbPath = temporaryFolder.newFolder().toString(); Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); Args.setParam( @@ -41,19 +44,15 @@ public void init() { "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory }, - "config.conf" + Constant.TEST_CONF ); CommonParameter parameter = Args.getInstance(); parameter.setNodeListenPort(port); - parameter.getSeedNode().getIpList().clear(); + parameter.getSeedNode().getAddressList().clear(); parameter.setNodeExternalIp("127.0.0.1"); context = new TronApplicationContext(DefaultConfig.class); appT = ApplicationFactory.create(context); - rpcApiService = context.getBean(RpcApiService.class); metricsApiService = context.getBean(MetricsApiService.class); - appT.addService(rpcApiService); - appT.initServices(parameter); - appT.startServices(); appT.startup(); } @@ -105,6 +104,5 @@ public void testProcessMessage() { @After public void destroy() { context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } } 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 new file mode 100644 index 00000000000..195e4749209 --- /dev/null +++ b/framework/src/test/java/org/tron/core/metrics/prometheus/PrometheusApiServiceTest.java @@ -0,0 +1,173 @@ +package org.tron.core.metrics.prometheus; + +import com.google.common.collect.Maps; +import com.google.protobuf.ByteString; +import io.prometheus.client.CollectorRegistry; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.crypto.ECKey; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.prometheus.MetricLabels; +import org.tron.common.prometheus.Metrics; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.Utils; +import org.tron.consensus.dpos.DposSlot; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.consensus.ConsensusService; +import org.tron.core.net.TronNetDelegate; +import org.tron.protos.Protocol; + +@Slf4j(topic = "metric") +public class PrometheusApiServiceTest extends BaseTest { + static LocalDateTime localDateTime = LocalDateTime.now(); + @Resource + private DposSlot dposSlot; + final int blocks = 512; + private final String key = PublicMethod.getRandomPrivateKey(); + private final byte[] privateKey = ByteArray.fromHexString(key); + private static final AtomicInteger port = new AtomicInteger(0); + private final long time = ZonedDateTime.of(localDateTime, + ZoneId.systemDefault()).toInstant().toEpochMilli(); + @Resource + private TronNetDelegate tronNetDelegate; + @Resource + private ConsensusService consensusService; + @Resource + private ChainBaseManager chainManager; + + static { + Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF); + Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); + initParameter(Args.getInstance()); + Metrics.init(); + } + + protected static void initParameter(CommonParameter parameter) { + parameter.setMetricsPrometheusEnable(true); + } + + protected void check() throws Exception { + Double memoryBytes = CollectorRegistry.defaultRegistry.getSampleValue( + "system_total_physical_memory_bytes"); + Assert.assertNotNull(memoryBytes); + Assert.assertTrue(memoryBytes.intValue() > 0); + + Double cpus = CollectorRegistry.defaultRegistry.getSampleValue("system_available_cpus"); + Assert.assertNotNull(cpus); + Assert.assertEquals(cpus.intValue(), Runtime.getRuntime().availableProcessors()); + + Double pushBlock = CollectorRegistry.defaultRegistry.getSampleValue( + "tron:block_process_latency_seconds_count", + new String[] {"sync"}, new String[] {"false"}); + Assert.assertNotNull(pushBlock); + Assert.assertEquals(pushBlock.intValue(), blocks + 1); + Double errorLogs = CollectorRegistry.defaultRegistry.getSampleValue( + "tron:error_info_total", new String[] {"net"}, new String[] {MetricLabels.UNDEFINED}); + Assert.assertNull(errorLogs); + } + + @Before + public void init() throws Exception { + logger.info("Full node running."); + consensusService.start(); + chainBaseManager = dbManager.getChainBaseManager(); + byte[] address = PublicMethod.getAddressByteByPrivateKey(key); + ByteString addressByte = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressByte); + chainBaseManager.getWitnessStore().put(addressByte.toByteArray(), witnessCapsule); + chainBaseManager.addWitness(addressByte); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + chainBaseManager.getAccountStore().put(addressByte.toByteArray(), accountCapsule); + + } + + private void generateBlock(Map witnessAndAccount) throws Exception { + + BlockCapsule block = + createTestBlockCapsule( + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp() + 3000, + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1, + chainBaseManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(), + witnessAndAccount); + + tronNetDelegate.processBlock(block, false); + } + + @Test + public void testMetric() throws Exception { + + final ECKey ecKey = ECKey.fromPrivate(privateKey); + Assert.assertNotNull(ecKey); + byte[] address = ecKey.getAddress(); + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); + chainBaseManager.addWitness(ByteString.copyFrom(address)); + + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); + + tronNetDelegate.processBlock(new BlockCapsule(block), false); + + Map witnessAndAccount = addTestWitnessAndAccount(); + witnessAndAccount.put(ByteString.copyFrom(address), key); + for (int i = 0; i < blocks; i++) { + generateBlock(witnessAndAccount); + } + check(); + } + + private Map addTestWitnessAndAccount() { + chainBaseManager.getWitnesses().clear(); + return IntStream.range(0, 2) + .mapToObj( + i -> { + ECKey ecKey = new ECKey(Utils.getRandom()); + String privateKey = ByteArray.toHexString(ecKey.getPrivKey().toByteArray()); + ByteString address = ByteString.copyFrom(ecKey.getAddress()); + + WitnessCapsule witnessCapsule = new WitnessCapsule(address); + chainBaseManager.getWitnessStore().put(address.toByteArray(), witnessCapsule); + chainBaseManager.addWitness(address); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(address).build()); + chainBaseManager.getAccountStore().put(address.toByteArray(), accountCapsule); + + return Maps.immutableEntry(address, privateKey); + }) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + private BlockCapsule createTestBlockCapsule(long time, + long number, ByteString hash, + Map witnessAddressMap) { + ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); + BlockCapsule blockCapsule = new BlockCapsule(number, Sha256Hash.wrap(hash), time, + witnessAddress); + blockCapsule.generatedByMyself = true; + blockCapsule.setMerkleRoot(); + blockCapsule.sign(ByteArray.fromHexString(witnessAddressMap.get(witnessAddress))); + return blockCapsule; + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/net/BaseNet.java b/framework/src/test/java/org/tron/core/net/BaseNet.java index cfd71080e4a..65771bae952 100644 --- a/framework/src/test/java/org/tron/core/net/BaseNet.java +++ b/framework/src/test/java/org/tron/core/net/BaseNet.java @@ -14,40 +14,44 @@ import io.netty.handler.timeout.ReadTimeoutHandler; import io.netty.handler.timeout.WriteTimeoutHandler; import java.io.File; +import java.io.IOException; import java.util.Collection; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; -import org.junit.After; -import org.junit.Before; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.rules.TemporaryFolder; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.ReflectUtils; import org.tron.core.Constant; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.net.peer.PeerConnection; -import org.tron.core.services.RpcApiService; @Slf4j -public abstract class BaseNet { +public class BaseNet { - private static String dbPath = "output-net"; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); private static String dbDirectory = "net-database"; private static String indexDirectory = "net-index"; private static int port = 10000; - protected TronApplicationContext context; + protected static TronApplicationContext context; - private RpcApiService rpcApiService; - private Application appT; - private TronNetDelegate tronNetDelegate; + private static Application appT; + private static TronNetDelegate tronNetDelegate; - private ExecutorService executorService = Executors.newFixedThreadPool(1); + private static ExecutorService executorService = Executors.newFixedThreadPool(1); public static Channel connect(ByteToMessageDecoder decoder) throws InterruptedException { NioEventLoopGroup group = new NioEventLoopGroup(1); @@ -73,50 +77,58 @@ protected void initChannel(Channel ch) throws Exception { return b.connect(Constant.LOCAL_HOST, port).sync().channel(); } - @Before - public void init() throws Exception { - executorService.execute(new Runnable() { - @Override - public void run() { - logger.info("Full node running."); + @BeforeClass + public static void init() throws Exception { + executorService.execute(() -> { + logger.info("Full node running."); + try { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", temporaryFolder.newFolder().toString(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory }, "config.conf" ); - CommonParameter parameter = Args.getInstance(); - parameter.setNodeListenPort(port); - parameter.getSeedNode().getIpList().clear(); - parameter.setNodeExternalIp(Constant.LOCAL_HOST); - context = new TronApplicationContext(DefaultConfig.class); - appT = ApplicationFactory.create(context); - rpcApiService = context.getBean(RpcApiService.class); - appT.addService(rpcApiService); - appT.initServices(parameter); - appT.startServices(); - appT.startup(); - tronNetDelegate = context.getBean(TronNetDelegate.class); - rpcApiService.blockUntilShutdown(); + } catch (IOException e) { + Assert.fail("create temp db directory failed"); } + CommonParameter parameter = Args.getInstance(); + parameter.setNodeListenPort(port); + parameter.getSeedNode().getAddressList().clear(); + parameter.setNodeExternalIp(Constant.LOCAL_HOST); + parameter.setRpcEnable(true); + parameter.setRpcPort(PublicMethod.chooseRandomPort()); + parameter.setRpcSolidityEnable(false); + parameter.setRpcPBFTEnable(false); + parameter.setFullNodeHttpEnable(false); + parameter.setSolidityNodeHttpEnable(false); + parameter.setPBFTHttpEnable(false); + context = new TronApplicationContext(DefaultConfig.class); + appT = ApplicationFactory.create(context); + appT.startup(); + try { + Thread.sleep(2000); + } catch (InterruptedException e) { + //ignore + } + tronNetDelegate = context.getBean(TronNetDelegate.class); + appT.blockUntilShutdown(); }); int tryTimes = 0; - while (++tryTimes < 100 && tronNetDelegate == null) { - Thread.sleep(3000); - } + do { + Thread.sleep(3000); //coverage consumerInvToSpread,consumerInvToFetch in AdvService.init + } while (++tryTimes < 100 && tronNetDelegate == null); } - @After - public void destroy() { + @AfterClass + public static void destroy() { Collection peerConnections = ReflectUtils .invokeMethod(tronNetDelegate, "getActivePeer"); for (PeerConnection peer : peerConnections) { - peer.close(); + peer.getChannel().close(); } - + Args.clearParam(); context.destroy(); - FileUtil.deleteDir(new File(dbPath)); } } diff --git a/framework/src/test/java/org/tron/core/net/BaseNetTest.java b/framework/src/test/java/org/tron/core/net/BaseNetTest.java index fee2695a80a..fd0847c1f08 100644 --- a/framework/src/test/java/org/tron/core/net/BaseNetTest.java +++ b/framework/src/test/java/org/tron/core/net/BaseNetTest.java @@ -9,10 +9,8 @@ public class BaseNetTest extends BaseNet { @Test - public void test() throws Exception { + public void test() { new NodeInfoServiceTest(context).test(); - new UdpTest(context).test(); - new TcpTest(context).test(); new DelegationServiceTest(context).test(); } } diff --git a/framework/src/test/java/org/tron/core/net/DisconnectMessageTest.java b/framework/src/test/java/org/tron/core/net/DisconnectMessageTest.java index 0155e5e5356..8ba255ccf08 100644 --- a/framework/src/test/java/org/tron/core/net/DisconnectMessageTest.java +++ b/framework/src/test/java/org/tron/core/net/DisconnectMessageTest.java @@ -4,13 +4,11 @@ import org.tron.protos.Protocol.DisconnectMessageOrBuilder; public class DisconnectMessageTest extends com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:protocol.DisconnectMessage) DisconnectMessageOrBuilder { public static final int REASON_FIELD_NUMBER = 1; public static final int NAME_FIELD_NUMBER = 2; private static final long serialVersionUID = 0L; - // @@protoc_insertion_point(class_scope:protocol.DisconnectMessage) private static final DisconnectMessageTest DEFAULT_INSTANCE; private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { diff --git a/framework/src/test/java/org/tron/core/net/MessageTest.java b/framework/src/test/java/org/tron/core/net/MessageTest.java index 6d344dd61bc..5b81d18a599 100644 --- a/framework/src/test/java/org/tron/core/net/MessageTest.java +++ b/framework/src/test/java/org/tron/core/net/MessageTest.java @@ -1,10 +1,17 @@ package org.tron.core.net; +import java.util.ArrayList; import org.junit.Assert; import org.junit.Test; -import org.tron.common.overlay.message.DisconnectMessage; +import org.tron.common.overlay.message.Message; import org.tron.core.exception.P2pException; import org.tron.core.net.message.MessageTypes; +import org.tron.core.net.message.adv.FetchInvDataMessage; +import org.tron.core.net.message.adv.InventoryMessage; +import org.tron.core.net.message.adv.TransactionsMessage; +import org.tron.core.net.message.base.DisconnectMessage; +import org.tron.core.net.service.statistics.MessageStatistics; +import org.tron.protos.Protocol.Inventory.InventoryType; import org.tron.protos.Protocol.ReasonCode; public class MessageTest { @@ -35,4 +42,91 @@ public void test2() throws Exception { System.out.println("spend time : " + (endTime - startTime)); } + @Test + public void testMessageStatistics() { + MessageStatistics messageStatistics = new MessageStatistics(); + Message message1 = new Message(MessageTypes.P2P_HELLO.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message2 = new Message(MessageTypes.P2P_PING.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message3 = new Message(MessageTypes.P2P_PONG.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message4 = new Message(MessageTypes.P2P_DISCONNECT.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message5 = new Message(MessageTypes.SYNC_BLOCK_CHAIN.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message6 = new Message(MessageTypes.BLOCK_CHAIN_INVENTORY.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message7 = new Message(MessageTypes.TRX.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + Message message8 = new Message(MessageTypes.BLOCK.asByte(), null) { + @Override + public Class getAnswerMessage() { + return null; + } + }; + InventoryMessage message9 = new InventoryMessage(new ArrayList<>(), InventoryType.TRX); + FetchInvDataMessage message10 = new FetchInvDataMessage(new ArrayList<>(), InventoryType.TRX); + TransactionsMessage message11 = new TransactionsMessage(new ArrayList<>()); + + messageStatistics.addTcpInMessage(message1); + messageStatistics.addTcpOutMessage(message1); + messageStatistics.addTcpInMessage(message2); + messageStatistics.addTcpOutMessage(message2); + messageStatistics.addTcpInMessage(message3); + messageStatistics.addTcpOutMessage(message3); + messageStatistics.addTcpInMessage(message4); + messageStatistics.addTcpOutMessage(message4); + messageStatistics.addTcpInMessage(message5); + messageStatistics.addTcpOutMessage(message5); + try { + Thread.sleep(2000);// so that gap > 1 in MessageCount.update method + } catch (InterruptedException e) { + //ignore + } + messageStatistics.addTcpInMessage(message6); + messageStatistics.addTcpOutMessage(message6); + messageStatistics.addTcpInMessage(message7); + messageStatistics.addTcpOutMessage(message7); + messageStatistics.addTcpInMessage(message8); + messageStatistics.addTcpOutMessage(message8); + messageStatistics.addTcpInMessage(message9); + messageStatistics.addTcpOutMessage(message9); + messageStatistics.addTcpInMessage(message10); + messageStatistics.addTcpOutMessage(message10); + messageStatistics.addTcpInMessage(message11); + messageStatistics.addTcpOutMessage(message11); + + Assert.assertEquals(11, messageStatistics.tronInMessage.getTotalCount()); + Assert.assertEquals(11, messageStatistics.tronOutMessage.getTotalCount()); + } + } diff --git a/framework/src/test/java/org/tron/core/net/NodeTest.java b/framework/src/test/java/org/tron/core/net/NodeTest.java new file mode 100644 index 00000000000..5f0e2c38b2b --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/NodeTest.java @@ -0,0 +1,99 @@ +package org.tron.core.net; + +import static org.tron.core.net.message.handshake.HelloMessage.getEndpointFromNode; + +import com.typesafe.config.Config; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.Constant; +import org.tron.core.config.Configuration; +import org.tron.core.config.args.Args; +import org.tron.p2p.discover.Node; +import org.tron.p2p.dns.update.DnsType; +import org.tron.p2p.dns.update.PublishConfig; +import org.tron.p2p.utils.NetUtil; +import org.tron.protos.Discover.Endpoint; + +@Slf4j +public class NodeTest { + + @Test + public void testIpV4() { + InetSocketAddress address1 = NetUtil.parseInetSocketAddress("192.168.0.1:18888"); + Assert.assertNotNull(address1); + try { + NetUtil.parseInetSocketAddress("192.168.0.1"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + } + + @Test + public void testIpV6() { + try { + NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb:18888"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + InetSocketAddress address2 = NetUtil.parseInetSocketAddress("[fe80::216:3eff:fe0e:23bb]:18888"); + Assert.assertNotNull(address2); + try { + NetUtil.parseInetSocketAddress("fe80::216:3eff:fe0e:23bb"); + Assert.fail(); + } catch (RuntimeException e) { + Assert.assertTrue(true); + } + } + + @Test + public void testIpStack() { + Set ipSet = new HashSet<>(Collections.singletonList("192.168.0.1")); + Assert.assertTrue(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Collections.singletonList("127.0.0.1")); + Assert.assertTrue(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Collections.singletonList("fe80:0:0:0:0:0:0:1")); + Assert.assertFalse(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Arrays.asList("127.0.0.1", "fe80:0:0:0:0:0:0:1")); + Assert.assertTrue(TronNetService.hasIpv4Stack(ipSet)); + ipSet = new HashSet<>(Collections.emptyList()); + Assert.assertFalse(TronNetService.hasIpv4Stack(ipSet)); + } + + @Test + public void testEndpointFromNode() { + Node node = new Node(null, null, null, 18888); + Endpoint endpoint = getEndpointFromNode(node); + Assert.assertTrue(endpoint.getNodeId().isEmpty()); + Assert.assertTrue(endpoint.getAddress().isEmpty()); + Assert.assertTrue(endpoint.getAddressIpv6().isEmpty()); + } + + @Test + public void testPublishConfig() { + Config config = Configuration.getByFileName(Constant.TEST_CONF, Constant.TEST_CONF); + + PublishConfig publishConfig = new PublishConfig(); + Assert.assertFalse(publishConfig.isDnsPublishEnable()); + + publishConfig.setDnsPublishEnable(true); + Assert.assertTrue(publishConfig.isDnsPublishEnable()); + Args.loadDnsPublishParameters(config, publishConfig); + Assert.assertTrue(publishConfig.isDnsPublishEnable()); + Assert.assertEquals(5, publishConfig.getMaxMergeSize()); + Assert.assertEquals(DnsType.AwsRoute53, publishConfig.getDnsType()); + } + + @After + public void destroy() { + Args.clearParam(); + } +} diff --git a/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java b/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java new file mode 100644 index 00000000000..e0c816a537a --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java @@ -0,0 +1,132 @@ +package org.tron.core.net; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.net.message.TronMessage; +import org.tron.core.net.message.adv.FetchInvDataMessage; +import org.tron.core.net.message.adv.InventoryMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.service.statistics.PeerStatistics; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Inventory.InventoryType; + +public class P2pEventHandlerImplTest { + + @Test + public void testProcessInventoryMessage() throws Exception { + String[] a = new String[0]; + Args.setParam(a, Constant.TESTNET_CONF); + CommonParameter parameter = CommonParameter.getInstance(); + parameter.setMaxTps(10); + + PeerStatistics peerStatistics = new PeerStatistics(); + + PeerConnection peer = mock(PeerConnection.class); + Mockito.when(peer.getPeerStatistics()).thenReturn(peerStatistics); + + P2pEventHandlerImpl p2pEventHandler = new P2pEventHandlerImpl(); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + int count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement + .getCount(10); + + Assert.assertEquals(0, count); + + List list = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + InventoryMessage msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.TRX); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); + + Assert.assertEquals(10, count); + + list.clear(); + for (int i = 0; i < 100; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.TRX); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); + + Assert.assertEquals(110, count); + + list.clear(); + for (int i = 0; i < 100; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.TRX); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInTrxInventoryElement.getCount(10); + + Assert.assertEquals(110, count); + + list.clear(); + for (int i = 0; i < 200; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.BLOCK); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInBlockInventoryElement.getCount(10); + + Assert.assertEquals(200, count); + + list.clear(); + for (int i = 0; i < 100; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + + msg = new InventoryMessage(list, Protocol.Inventory.InventoryType.BLOCK); + + method.invoke(p2pEventHandler, peer, msg.getSendBytes()); + + count = peer.getPeerStatistics().messageStatistics.tronInBlockInventoryElement.getCount(10); + + Assert.assertEquals(300, count); + + } + + @Test + public void testUpdateLastInteractiveTime() throws Exception { + String[] a = new String[0]; + Args.setParam(a, Constant.TESTNET_CONF); + + PeerConnection peer = new PeerConnection(); + P2pEventHandlerImpl p2pEventHandler = new P2pEventHandlerImpl(); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("updateLastInteractiveTime", PeerConnection.class, TronMessage.class); + method.setAccessible(true); + + long t1 = System.currentTimeMillis(); + FetchInvDataMessage message = new FetchInvDataMessage(new ArrayList<>(), InventoryType.BLOCK); + method.invoke(p2pEventHandler, peer, message); + Assert.assertTrue(peer.getLastInteractiveTime() >= t1); + } +} diff --git a/framework/src/test/java/org/tron/core/net/TcpTest.java b/framework/src/test/java/org/tron/core/net/TcpTest.java deleted file mode 100644 index 32eb64c8e7e..00000000000 --- a/framework/src/test/java/org/tron/core/net/TcpTest.java +++ /dev/null @@ -1,272 +0,0 @@ -package org.tron.core.net; - -import static org.tron.core.net.message.MessageTypes.P2P_DISCONNECT; -import static org.tron.core.net.message.MessageTypes.P2P_HELLO; -import static org.tron.protos.Protocol.ReasonCode.DUPLICATE_PEER; -import static org.tron.protos.Protocol.ReasonCode.FORKED; -import static org.tron.protos.Protocol.ReasonCode.INCOMPATIBLE_CHAIN; -import static org.tron.protos.Protocol.ReasonCode.INCOMPATIBLE_VERSION; - -import com.google.common.cache.CacheBuilder; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.Channel; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.ArrayUtils; -import org.junit.Assert; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.overlay.discover.node.Node; -import org.tron.common.overlay.message.DisconnectMessage; -import org.tron.common.overlay.message.HelloMessage; -import org.tron.common.overlay.message.Message; -import org.tron.common.overlay.message.P2pMessage; -import org.tron.common.overlay.message.P2pMessageFactory; -import org.tron.common.overlay.server.ChannelManager; -import org.tron.common.overlay.server.SyncPool; -import org.tron.common.utils.ReflectUtils; -import org.tron.core.ChainBaseManager; -import org.tron.core.capsule.BlockCapsule; -import org.tron.core.capsule.BlockCapsule.BlockId; -import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -import org.tron.core.net.message.BlockMessage; -import org.tron.core.net.peer.PeerConnection; -import org.tron.protos.Protocol.Block; - -@Slf4j -public class TcpTest { - - Node node = Node.instanceOf("127.0.0.1:" + Args.getInstance().getNodeListenPort()); - private ChannelManager channelManager; - private Manager manager; - private ChainBaseManager chainBaseManager; - private SyncPool pool; - private TronNetDelegate tronNetDelegate; - private int tryTimes = 10; - private int sleepTime = 1000; - private boolean finish = false; - - public TcpTest(TronApplicationContext context) { - channelManager = context.getBean(ChannelManager.class); - manager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - pool = context.getBean(SyncPool.class); - tronNetDelegate = context.getBean(TronNetDelegate.class); - } - - public void normalTest() throws InterruptedException { - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal)); - HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), - chainBaseManager.getGenesisBlockId(), chainBaseManager.getSolidBlockId(), - chainBaseManager.getHeadBlockId()); - sendMessage(channel, message); - validResultCloseConnect(channel); - } - - public void errorGenesisBlockIdTest() throws InterruptedException { - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.errorGenesisBlock)); - BlockId genesisBlockId = new BlockId(); - HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), genesisBlockId, - chainBaseManager.getSolidBlockId(), chainBaseManager.getHeadBlockId()); - sendMessage(channel, message); - validResultCloseConnect(channel); - } - - public void errorVersionTest() throws InterruptedException { - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.errorVersion)); - Args.getInstance().setNodeP2pVersion(1); - HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), - chainBaseManager.getGenesisBlockId(), chainBaseManager.getSolidBlockId(), - chainBaseManager.getHeadBlockId()); - Args.getInstance().setNodeP2pVersion(2); - sendMessage(channel, message); - validResultCloseConnect(channel); - } - - public void errorSolidBlockIdTest() throws InterruptedException { - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.errorSolid)); - HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), - chainBaseManager.getGenesisBlockId(), new BlockId(), chainBaseManager.getHeadBlockId()); - sendMessage(channel, message); - validResultCloseConnect(channel); - } - - public void repeatConnectTest() throws InterruptedException { - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal)); - HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), - chainBaseManager.getGenesisBlockId(), chainBaseManager.getSolidBlockId(), - chainBaseManager.getHeadBlockId()); - sendMessage(channel, message); - validResultUnCloseConnect(); - Channel repeatChannel = BaseNet.connect(new HandshakeHandler(TestType.repeatConnect)); - sendMessage(repeatChannel, message); - validResultCloseConnect(repeatChannel); - clearConnect(channel); - } - - public void unHandshakeTest() throws InterruptedException { - List beforeActivePeers = - ReflectUtils.getFieldValue(pool, "activePeers"); - int beforeSize = beforeActivePeers.size(); - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal)); - BlockMessage message = new BlockMessage(new BlockCapsule(Block.getDefaultInstance())); - sendMessage(channel, message); - List afterActivePeers = - ReflectUtils.getFieldValue(pool, "activePeers"); - int afterSize = afterActivePeers.size(); - Assert.assertEquals(beforeSize, afterSize); - clearConnect(channel); - } - - public void errorMsgTest() throws InterruptedException { - Channel channel = BaseNet.connect(new HandshakeHandler(TestType.normal)); - HelloMessage message = new HelloMessage(node, System.currentTimeMillis(), - chainBaseManager.getGenesisBlockId(), chainBaseManager.getSolidBlockId(), - chainBaseManager.getHeadBlockId()); - sendMessage(channel, message); - validResultUnCloseConnect(); - List beforeActivePeers = - ReflectUtils.getFieldValue(pool, "activePeers"); - int beforeSize = beforeActivePeers.size(); - logger.info("beforeSize : {}", beforeSize); - channel.writeAndFlush( - Unpooled.wrappedBuffer(ArrayUtils.add("nihao".getBytes(), 0, (byte) 1))) - .addListener((ChannelFutureListener) future -> { - if (future.isSuccess()) { - logger.info("send msg success"); - } else { - logger.error("send msg fail", future.cause()); - } - }); - Thread.sleep(2000); - List afterActivePeers = - ReflectUtils.getFieldValue(pool, "activePeers"); - int afterSize = afterActivePeers.size(); - logger.info("afterSize : {}", afterSize); - Assert.assertEquals(beforeSize, afterSize + 1); - clearConnect(channel); - } - - private void sendMessage(Channel channel, Message message) { - channel.writeAndFlush(message.getSendData()) - .addListener((ChannelFutureListener) future -> { - if (future.isSuccess()) { - logger.info("send msg success"); - } else { - logger.error("send msg fail", future.cause()); - } - }); - } - - private void validResultCloseConnect(Channel channel) throws InterruptedException { - int trys = 0; - while (!finish && ++trys < tryTimes) { - Thread.sleep(sleepTime); - } - Assert.assertEquals(finish, true); - finish = false; - channel.close(); - Thread.sleep(sleepTime); - Collection peerConnections = ReflectUtils - .invokeMethod(tronNetDelegate, "getActivePeer"); - for (PeerConnection peer : peerConnections) { - peer.close(); - } - ReflectUtils.setFieldValue(channelManager, "recentlyDisconnected", - CacheBuilder.newBuilder().maximumSize(1000) - .expireAfterWrite(30, TimeUnit.SECONDS).recordStats().build()); - } - - private void validResultUnCloseConnect() throws InterruptedException { - int n = 0; - while (!finish && ++n < tryTimes) { - Thread.sleep(sleepTime); - } - Assert.assertEquals(finish, true); - finish = false; - } - - private void clearConnect(Channel channel) throws InterruptedException { - channel.close(); - Thread.sleep(sleepTime); - Collection peerConnections = ReflectUtils - .invokeMethod(tronNetDelegate, "getActivePeer"); - for (PeerConnection peer : peerConnections) { - peer.close(); - } - ReflectUtils.setFieldValue(channelManager, "recentlyDisconnected", - CacheBuilder.newBuilder().maximumSize(1000) - .expireAfterWrite(30, TimeUnit.SECONDS).recordStats().build()); - } - - public void test() throws InterruptedException { - logger.info("begin normal test "); - normalTest(); - logger.info("begin errorGenesisBlockId test "); - errorGenesisBlockIdTest(); - logger.info("begin errorVersion test "); - errorVersionTest(); - logger.info("begin errorSolidBlockId test "); - errorSolidBlockIdTest(); - logger.info("begin repeatConnect test"); - repeatConnectTest(); - logger.info("begin unHandshake test"); - unHandshakeTest(); - logger.info("begin errorMsg test"); - errorMsgTest(); - } - - private enum TestType { - normal, errorGenesisBlock, errorVersion, errorSolid, repeatConnect - } - - private class HandshakeHandler extends ByteToMessageDecoder { - - private P2pMessageFactory messageFactory = new P2pMessageFactory(); - - private TestType testType; - - public HandshakeHandler(TestType testType) { - this.testType = testType; - } - - @Override - protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List out) - throws Exception { - byte[] encoded = new byte[buffer.readableBytes()]; - buffer.readBytes(encoded); - P2pMessage msg = messageFactory.create(encoded); - switch (testType) { - case normal: - Assert.assertEquals(msg.getType(), P2P_HELLO); - break; - case errorGenesisBlock: - Assert.assertEquals(msg.getType(), P2P_DISCONNECT); - Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), INCOMPATIBLE_CHAIN); - break; - case errorVersion: - Assert.assertEquals(msg.getType(), P2P_DISCONNECT); - Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), INCOMPATIBLE_VERSION); - break; - case errorSolid: - Assert.assertEquals(msg.getType(), P2P_DISCONNECT); - Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), FORKED); - break; - case repeatConnect: - Assert.assertEquals(msg.getType(), P2P_DISCONNECT); - Assert.assertEquals(((DisconnectMessage) msg).getReasonCode(), DUPLICATE_PEER); - break; - default: - break; - } - - finish = true; - } - } -} diff --git a/framework/src/test/java/org/tron/core/net/TronNetDelegateTest.java b/framework/src/test/java/org/tron/core/net/TronNetDelegateTest.java new file mode 100644 index 00000000000..6550766d702 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/TronNetDelegateTest.java @@ -0,0 +1,52 @@ +package org.tron.core.net; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Field; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.args.Args; + +public class TronNetDelegateTest { + + @Test + public void test() throws Exception { + Args.setParam(new String[] {}, Constant.TEST_CONF); + CommonParameter parameter = Args.getInstance(); + Args.logConfig(); + parameter.setUnsolidifiedBlockCheck(true); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 10000L); + + TronNetDelegate tronNetDelegate = new TronNetDelegate(); + + ChainBaseManager chainBaseManager = mock(ChainBaseManager.class); + Mockito.when(chainBaseManager.getHeadBlockNum()).thenReturn(10000L); + Mockito.when(chainBaseManager.getSolidBlockId()).thenReturn(blockId); + + Field field = tronNetDelegate.getClass().getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(tronNetDelegate, chainBaseManager); + + Assert.assertTrue(!tronNetDelegate.isBlockUnsolidified()); + + blockId = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1L); + Mockito.when(chainBaseManager.getSolidBlockId()).thenReturn(blockId); + Assert.assertTrue(tronNetDelegate.isBlockUnsolidified()); + + parameter.setUnsolidifiedBlockCheck(false); + tronNetDelegate = new TronNetDelegate(); + + field = tronNetDelegate.getClass().getDeclaredField("unsolidifiedBlockCheck"); + field.setAccessible(true); + field.set(tronNetDelegate, false); + + Assert.assertTrue(!tronNetDelegate.isBlockUnsolidified()); + } +} diff --git a/framework/src/test/java/org/tron/core/net/UdpTest.java b/framework/src/test/java/org/tron/core/net/UdpTest.java deleted file mode 100644 index 6d90e4e748a..00000000000 --- a/framework/src/test/java/org/tron/core/net/UdpTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.tron.core.net; - -import java.net.DatagramPacket; -import java.net.DatagramSocket; -import java.net.InetAddress; -import java.util.Arrays; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.net.udp.message.Message; -import org.tron.common.net.udp.message.discover.FindNodeMessage; -import org.tron.common.net.udp.message.discover.NeighborsMessage; -import org.tron.common.net.udp.message.discover.PingMessage; -import org.tron.common.net.udp.message.discover.PongMessage; -import org.tron.common.overlay.discover.node.Node; -import org.tron.common.overlay.discover.node.NodeManager; -import org.tron.core.config.args.Args; - -@Slf4j -public class UdpTest { - - private NodeManager nodeManager; - private int port = Args.getInstance().getNodeListenPort(); - //private volatile boolean finishFlag = false; - //private long timeOut = 30_000; - - public UdpTest(TronApplicationContext context) { - nodeManager = context.getBean(NodeManager.class); - } - - public void test() throws Exception { - /* - Thread thread = new Thread(() -> { - try { - discover(); - } catch (Exception e) { - logger.info("Discover test failed.", e); - } - }); - thread.start(); - - long time = System.currentTimeMillis(); - while (!finishFlag && System.currentTimeMillis() - time < timeOut) { - Thread.sleep(1000); - } - if (!finishFlag) { - thread.interrupt(); - Assert.assertTrue(false); - } - */ - } - - public void discover() throws Exception { - - InetAddress server = InetAddress.getByName("127.0.0.1"); - - Node from = Node.instanceOf("127.0.0.1:10002"); - Node peer1 = Node.instanceOf("127.0.0.1:10003"); - Node peer2 = Node.instanceOf("127.0.0.1:10004"); - - Assert.assertTrue(!nodeManager.hasNodeHandler(peer1)); - Assert.assertTrue(!nodeManager.hasNodeHandler(peer2)); - Assert.assertTrue(nodeManager.getTable().getAllNodes().isEmpty()); - - PingMessage pingMessage = new PingMessage(from, nodeManager.getPublicHomeNode()); - DatagramPacket pingPacket = new DatagramPacket(pingMessage.getSendData(), - pingMessage.getSendData().length, server, port); - - FindNodeMessage findNodeMessage = new FindNodeMessage(from, Node.getNodeId()); - DatagramPacket findNodePacket = new DatagramPacket(findNodeMessage.getSendData(), - findNodeMessage.getSendData().length, server, port); - - DatagramSocket socket = new DatagramSocket(); - - // send ping msg - socket.send(pingPacket); - byte[] data = new byte[1024]; - DatagramPacket packet = new DatagramPacket(data, data.length); - - boolean pingFlag = false; - boolean pongFlag = false; - boolean findNodeFlag = false; - boolean neighborsFlag = false; - while (true) { - socket.receive(packet); - byte[] bytes = Arrays.copyOfRange(data, 0, packet.getLength()); - Message msg = Message.parse(bytes); - Assert.assertTrue( - Arrays.equals(msg.getFrom().getId(), nodeManager.getPublicHomeNode().getId())); - if (!pingFlag) { - pingFlag = true; - Assert.assertTrue(msg instanceof PingMessage); - Assert.assertTrue(Arrays.equals(((PingMessage) msg).getTo().getId(), from.getId())); - PongMessage pongMessage = new PongMessage(from); - DatagramPacket pongPacket = new DatagramPacket(pongMessage.getSendData(), - pongMessage.getSendData().length, server, port); - socket.send(pongPacket); - } else if (!pongFlag) { - pongFlag = true; - Assert.assertTrue(msg instanceof PongMessage); - } else if (!findNodeFlag) { - findNodeFlag = true; - Assert.assertTrue(msg instanceof FindNodeMessage); - List peers = Lists.newArrayList(peer1, peer2); - NeighborsMessage neighborsMessage = new NeighborsMessage(from, peers, msg.getTimestamp()); - DatagramPacket neighborsPacket = new DatagramPacket(neighborsMessage.getSendData(), - neighborsMessage.getSendData().length, server, port); - socket.send(neighborsPacket); - socket.send(findNodePacket); - } else if (!neighborsFlag) { - Assert.assertTrue(msg instanceof NeighborsMessage); - break; - } - } - - Assert.assertTrue(nodeManager.hasNodeHandler(peer1)); - Assert.assertTrue(nodeManager.hasNodeHandler(peer2)); - Assert.assertTrue(nodeManager.getTable().getAllNodes().size() == 1); - - socket.close(); - - //finishFlag = true; - } -} - diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java index f5edf091a13..48e7d730520 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/BlockMsgHandlerTest.java @@ -1,43 +1,65 @@ package org.tron.core.net.messagehandler; +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyBoolean; + import com.google.common.collect.ImmutableList; import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; import java.util.List; -import org.junit.After; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.mockito.Mockito; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; import org.tron.common.utils.Sha256Hash; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; +import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.config.Parameter; import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; -import org.tron.core.net.message.BlockMessage; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.message.adv.BlockMessage; import org.tron.core.net.peer.Item; import org.tron.core.net.peer.PeerConnection; +import org.tron.p2p.connection.Channel; import org.tron.protos.Protocol.Inventory.InventoryType; import org.tron.protos.Protocol.Transaction; -public class BlockMsgHandlerTest { +@Slf4j +public class BlockMsgHandlerTest extends BaseTest { - protected TronApplicationContext context; + @Resource private BlockMsgHandler handler; + @Resource private PeerConnection peer; /** * init context. */ - @Before - public void init() { - Args.setParam(new String[]{"--output-directory", "output-directory", "--debug"}, + @BeforeClass + public static void init() { + Args.setParam(new String[] {"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - handler = context.getBean(BlockMsgHandler.class); - peer = context.getBean(PeerConnection.class); + } + + @Before + public void before() 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()); + peer.setChannel(c1); } @Test @@ -50,7 +72,7 @@ public void testProcessMessage() { msg = new BlockMessage(blockCapsule); handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("no request")); + assertEquals("no request", e.getMessage()); } try { @@ -70,7 +92,7 @@ public void testProcessMessage() { handler.processMessage(peer, msg); } catch (P2pException e) { //System.out.println(e); - Assert.assertTrue(e.getMessage().equals("block size over limit")); + assertEquals("block size over limit", e.getMessage()); } try { @@ -82,7 +104,7 @@ public void testProcessMessage() { handler.processMessage(peer, msg); } catch (P2pException e) { //System.out.println(e); - Assert.assertTrue(e.getMessage().equals("block time error")); + assertEquals("block time error", e.getMessage()); } try { @@ -104,13 +126,45 @@ public void testProcessMessage() { .put(new Item(msg.getBlockId(), InventoryType.BLOCK), System.currentTimeMillis()); handler.processMessage(peer, msg); } catch (NullPointerException | P2pException e) { - System.out.println(e); + logger.error("error", e); } } - @After - public void destroy() { - Args.clearParam(); - context.destroy(); + @Test + public void testProcessBlock() { + TronNetDelegate tronNetDelegate = Mockito.mock(TronNetDelegate.class); + + try { + Field field = handler.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(handler, tronNetDelegate); + + BlockCapsule blockCapsule0 = new BlockCapsule(1, + Sha256Hash.wrap(ByteString + .copyFrom(ByteArray + .fromHexString( + "9938a342238077182498b464ac0292229938a342238077182498b464ac029222"))), + 1234, + ByteString.copyFrom("1234567".getBytes())); + + peer.getAdvInvReceive() + .put(new Item(blockCapsule0.getBlockId(), InventoryType.BLOCK), + System.currentTimeMillis()); + + Mockito.doReturn(true).when(tronNetDelegate).validBlock(any(BlockCapsule.class)); + Mockito.doReturn(true).when(tronNetDelegate).containBlock(any(BlockId.class)); + Mockito.doReturn(blockCapsule0.getBlockId()).when(tronNetDelegate).getHeadBlockId(); + Mockito.doNothing().when(tronNetDelegate).processBlock(any(BlockCapsule.class), anyBoolean()); + List peers = new ArrayList<>(); + peers.add(peer); + Mockito.doReturn(peers).when(tronNetDelegate).getActivePeer(); + + Method method = handler.getClass() + .getDeclaredMethod("processBlock", PeerConnection.class, BlockCapsule.class); + method.setAccessible(true); + method.invoke(handler, peer, blockCapsule0); + } catch (Exception e) { + Assert.fail(); + } } } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java index ee99a7dde6f..dab76cfcb46 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandlerTest.java @@ -9,7 +9,8 @@ import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.config.Parameter.NetConstants; import org.tron.core.exception.P2pException; -import org.tron.core.net.message.ChainInventoryMessage; +import org.tron.core.net.message.keepalive.PingMessage; +import org.tron.core.net.message.sync.ChainInventoryMessage; import org.tron.core.net.peer.PeerConnection; public class ChainInventoryMsgHandlerTest { @@ -20,11 +21,11 @@ public class ChainInventoryMsgHandlerTest { private List blockIds = new ArrayList<>(); @Test - public void testProcessMessage() { + public void testProcessMessage() throws Exception { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("not send syncBlockChainMsg")); + Assert.assertEquals("not send syncBlockChainMsg", e.getMessage()); } peer.setSyncChainRequested(new Pair<>(new LinkedList<>(), System.currentTimeMillis())); @@ -32,7 +33,7 @@ public void testProcessMessage() { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("blockIds is empty")); + Assert.assertEquals("blockIds is empty", e.getMessage()); } long size = NetConstants.SYNC_FETCH_BATCH_NUM + 2; @@ -44,7 +45,7 @@ public void testProcessMessage() { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("big blockIds size: " + size)); + Assert.assertEquals(e.getMessage(), "big blockIds size: " + size); } blockIds.clear(); @@ -57,8 +58,10 @@ public void testProcessMessage() { try { handler.processMessage(peer, msg); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("remain: 100, blockIds size: " + size)); + Assert.assertEquals(e.getMessage(), "remain: 100, blockIds size: " + size); } + Assert.assertNotNull(msg.toString()); + Assert.assertNull(msg.getAnswerMessage()); } } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java index e885741c29c..5fd6d6725ba 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/FetchInvDataMsgHandlerTest.java @@ -1,5 +1,96 @@ package org.tron.core.net.messagehandler; +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import java.lang.reflect.Field; +import java.util.LinkedList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.Parameter; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.message.adv.BlockMessage; +import org.tron.core.net.message.adv.FetchInvDataMessage; +import org.tron.core.net.peer.Item; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.service.adv.AdvService; +import org.tron.protos.Protocol; + public class FetchInvDataMsgHandlerTest { + @Test + public void testProcessMessage() throws Exception { + FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler(); + PeerConnection peer = Mockito.mock(PeerConnection.class); + TronNetDelegate tronNetDelegate = Mockito.mock(TronNetDelegate.class); + AdvService advService = Mockito.mock(AdvService.class); + + Field field = FetchInvDataMsgHandler.class.getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(fetchInvDataMsgHandler, tronNetDelegate); + + Mockito.when(tronNetDelegate.allowPBFT()).thenReturn(false); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + List blockIds = new LinkedList<>(); + blockIds.add(blockId); + + Cache advInvSpread = CacheBuilder.newBuilder().maximumSize(20000) + .expireAfterWrite(1, TimeUnit.HOURS).recordStats().build(); + Mockito.when(peer.getAdvInvSpread()).thenReturn(advInvSpread); + Mockito.when(peer.isNeedSyncFromUs()).thenReturn(true); + Mockito.when(peer.isSyncFinish()).thenReturn(false); + Mockito.when(peer.getBlockBothHave()).thenReturn(blockId); + Cache syncBlockIdCache = CacheBuilder.newBuilder() + .maximumSize(2 * Parameter.NetConstants.SYNC_FETCH_BATCH_NUM).recordStats().build(); + Mockito.when(peer.getSyncBlockIdCache()).thenReturn(syncBlockIdCache); + Mockito.when(peer.getLastSyncBlockId()).thenReturn(blockId); + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + Mockito.when(advService.getMessage(new Item(blockId, Protocol.Inventory.InventoryType.BLOCK))) + .thenReturn(new BlockMessage(blockCapsule)); + ReflectUtils.setFieldValue(fetchInvDataMsgHandler, "advService", advService); + + fetchInvDataMsgHandler.processMessage(peer, + new FetchInvDataMessage(blockIds, Protocol.Inventory.InventoryType.BLOCK)); + Assert.assertNotNull(syncBlockIdCache.getIfPresent(blockId)); + } + + @Test + public void testSyncFetchCheck() { + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 10000L); + List blockIds = new LinkedList<>(); + blockIds.add(blockId); + FetchInvDataMessage msg = + new FetchInvDataMessage(blockIds, Protocol.Inventory.InventoryType.BLOCK); + + PeerConnection peer = Mockito.mock(PeerConnection.class); + Mockito.when(peer.isNeedSyncFromUs()).thenReturn(true); + Cache advInvSpread = CacheBuilder.newBuilder().maximumSize(100) + .expireAfterWrite(1, TimeUnit.HOURS).recordStats().build(); + Mockito.when(peer.getAdvInvSpread()).thenReturn(advInvSpread); + + FetchInvDataMsgHandler fetchInvDataMsgHandler = new FetchInvDataMsgHandler(); + + try { + Mockito.when(peer.getLastSyncBlockId()) + .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1000L)); + fetchInvDataMsgHandler.processMessage(peer, msg); + } catch (Exception e) { + Assert.assertEquals(e.getMessage(), "maxBlockNum: 1000, blockNum: 10000"); + } + + try { + Mockito.when(peer.getLastSyncBlockId()) + .thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 20000L)); + fetchInvDataMsgHandler.processMessage(peer, msg); + } catch (Exception e) { + Assert.assertEquals(e.getMessage(), "minBlockNum: 16000, blockNum: 10000"); + } + } } diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java index 23a44ac3444..0864c872bc3 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/InventoryMsgHandlerTest.java @@ -1,20 +1,32 @@ package org.tron.core.net.messagehandler; +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.InetSocketAddress; import java.util.ArrayList; import org.junit.Test; -import org.tron.core.net.message.InventoryMessage; +import org.mockito.Mockito; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.message.adv.InventoryMessage; import org.tron.core.net.peer.PeerConnection; +import org.tron.p2p.connection.Channel; import org.tron.protos.Protocol.Inventory.InventoryType; public class InventoryMsgHandlerTest { - private InventoryMsgHandler handler = new InventoryMsgHandler(); - private PeerConnection peer = new PeerConnection(); - @Test - public void testProcessMessage() { - InventoryMessage msg = new InventoryMessage(new ArrayList<>(), InventoryType.TRX); + public void testProcessMessage() throws Exception { + InventoryMsgHandler handler = new InventoryMsgHandler(); + Args.setParam(new String[] {}, Constant.TEST_CONF); + Args.logConfig(); + InventoryMessage msg = new InventoryMessage(new ArrayList<>(), InventoryType.TRX); + PeerConnection peer = new PeerConnection(); + peer.setChannel(getChannel("1.0.0.3", 1000)); peer.setNeedSyncFromPeer(true); peer.setNeedSyncFromUs(true); handler.processMessage(peer, msg); @@ -27,5 +39,31 @@ public void testProcessMessage() { peer.setNeedSyncFromUs(true); handler.processMessage(peer, msg); + peer.setNeedSyncFromUs(false); + + TronNetDelegate tronNetDelegate = mock(TronNetDelegate.class); + Mockito.when(tronNetDelegate.isBlockUnsolidified()).thenReturn(true); + + Field field = handler.getClass().getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(handler, tronNetDelegate); + + handler.processMessage(peer, msg); + } + + private Channel getChannel(String host, int port) throws Exception { + Channel channel = new Channel(); + InetSocketAddress inetSocketAddress = new InetSocketAddress(host, port); + + Field field = channel.getClass().getDeclaredField("inetSocketAddress"); + field.setAccessible(true); + field.set(channel, inetSocketAddress); + + InetAddress inetAddress = inetSocketAddress.getAddress(); + field = channel.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(channel, inetAddress); + + return channel; } } 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 new file mode 100644 index 00000000000..7ff29b54bb7 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/messagehandler/MessageHandlerTest.java @@ -0,0 +1,114 @@ +package org.tron.core.net.messagehandler; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.pbft.message.PbftMessage; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.TronNetService; +import org.tron.core.net.message.keepalive.PingMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; + +public class MessageHandlerTest { + + private static TronApplicationContext context; + private PeerConnection peer; + private static P2pEventHandlerImpl p2pEventHandler; + private static ApplicationContext ctx; + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + + @BeforeClass + public static void init() throws Exception { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); + + TronNetService tronNetService = context.getBean(TronNetService.class); + Parameter.p2pConfig = new P2pConfig(); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", Parameter.p2pConfig); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + context.destroy(); + } + + @Before + public void clearPeers() { + try { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + } catch (NoSuchFieldException | IllegalAccessException e) { + //ignore + } + } + + @Test + public void testPbft() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + p2pEventHandler.onConnect(c1); + Assert.assertEquals(1, PeerManager.getPeers().size()); + Assert.assertFalse(c1.isDisconnect()); + + peer = PeerManager.getPeers().get(0); + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + PbftMessage pbftMessage = PbftMessage.fullNodePrePrepareBlockMsg(blockCapsule, 0L); + p2pEventHandler.onMessage(peer.getChannel(), pbftMessage.getSendBytes()); + + InetSocketAddress a2 = new InetSocketAddress("127.0.0.1", 10002); + Channel c2 = mock(Channel.class); + Mockito.when(c2.getInetSocketAddress()).thenReturn(a2); + Mockito.when(c2.getInetAddress()).thenReturn(a2.getAddress()); + p2pEventHandler.onMessage(c2, pbftMessage.getSendBytes()); + + Assert.assertEquals(1, PeerManager.getPeers().size()); + } + + @Test + public void testPing() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + + PingMessage pingMessage = new PingMessage(); + p2pEventHandler.onMessage(c1, pingMessage.getSendBytes()); + Assert.assertEquals(1, PeerManager.getPeers().size()); + } +} diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/PbftDataSyncHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/PbftDataSyncHandlerTest.java new file mode 100644 index 00000000000..e5d242a6c4d --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/messagehandler/PbftDataSyncHandlerTest.java @@ -0,0 +1,58 @@ +package org.tron.core.net.messagehandler; + +import com.alibaba.fastjson.JSON; +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Map; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.PbftSignCapsule; +import org.tron.core.db.PbftSignDataStore; +import org.tron.core.net.message.pbft.PbftCommitMessage; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.protos.Protocol; + +public class PbftDataSyncHandlerTest { + @Test + public void testProcessMessage() throws Exception { + PbftDataSyncHandler pbftDataSyncHandler = new PbftDataSyncHandler(); + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + Protocol.PBFTMessage.Raw.Builder rawBuilder = Protocol.PBFTMessage.Raw.newBuilder(); + rawBuilder.setViewN(blockCapsule.getNum()) + .setEpoch(0) + .setDataType(Protocol.PBFTMessage.DataType.BLOCK) + .setMsgType(Protocol.PBFTMessage.MsgType.PREPREPARE) + .setData(blockCapsule.getBlockId().getByteString()); + Protocol.PBFTMessage.Raw raw = rawBuilder.build(); + PbftSignCapsule pbftSignCapsule = new PbftSignCapsule(raw.toByteString(), new ArrayList<>()); + PbftCommitMessage pbftCommitMessage = new PbftCommitMessage(pbftSignCapsule); + + DynamicPropertiesStore dynamicPropertiesStore = Mockito.mock(DynamicPropertiesStore.class); + PbftSignDataStore pbftSignDataStore = Mockito.mock(PbftSignDataStore.class); + ChainBaseManager chainBaseManager = Mockito.mock(ChainBaseManager.class); + Mockito.when(chainBaseManager.getDynamicPropertiesStore()).thenReturn(dynamicPropertiesStore); + Mockito.when(dynamicPropertiesStore.allowPBFT()).thenReturn(true); + Mockito.when(dynamicPropertiesStore.getMaintenanceTimeInterval()).thenReturn(600L); + Mockito.when(chainBaseManager.getPbftSignDataStore()).thenReturn(pbftSignDataStore); + + Field field = PbftDataSyncHandler.class.getDeclaredField("chainBaseManager"); + field.setAccessible(true); + field.set(pbftDataSyncHandler, chainBaseManager); + + pbftDataSyncHandler.processMessage(null, pbftCommitMessage); + Assert.assertEquals(Protocol.PBFTMessage.Raw.parseFrom( + pbftCommitMessage.getPBFTCommitResult().getData()).getViewN(), 1); + + pbftDataSyncHandler.processPBFTCommitData(blockCapsule); + Field field1 = PbftDataSyncHandler.class.getDeclaredField("pbftCommitMessageCache"); + field1.setAccessible(true); + Map map = JSON.parseObject(JSON.toJSONString(field1.get(pbftDataSyncHandler)), Map.class); + Assert.assertFalse(map.containsKey(0)); + } +} 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 new file mode 100644 index 00000000000..8b9d1969cfc --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/messagehandler/PbftMsgHandlerTest.java @@ -0,0 +1,130 @@ +package org.tron.core.net.messagehandler; + +import static org.mockito.Mockito.mock; + +import com.google.protobuf.ByteString; +import java.io.File; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import org.bouncycastle.util.encoders.Hex; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.crypto.SignInterface; +import org.tron.common.crypto.SignUtils; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.consensus.base.Param; +import org.tron.consensus.pbft.message.PbftMessage; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.consensus.PbftBaseImpl; +import org.tron.core.exception.P2pException; +import org.tron.core.net.TronNetService; +import org.tron.core.net.message.MessageTypes; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.protos.Protocol; + + +public class PbftMsgHandlerTest { + private static TronApplicationContext context; + private PeerConnection peer; + private static String dbPath = "output-pbft-message-handler-test"; + + + @BeforeClass + public static void init() { + Args.setParam(new String[] {"--output-directory", dbPath, "--debug"}, + Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + + TronNetService tronNetService = context.getBean(TronNetService.class); + Parameter.p2pConfig = new P2pConfig(); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", Parameter.p2pConfig); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + context.destroy(); + FileUtil.deleteDir(new File(dbPath)); + } + + @Before + public void clearPeers() { + try { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + } catch (NoSuchFieldException | IllegalAccessException e) { + //ignore + } + } + + @Test + public void testPbft() throws Exception { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(context, c1); + Assert.assertEquals(1, PeerManager.getPeers().size()); + Assert.assertFalse(c1.isDisconnect()); + + peer = PeerManager.getPeers().get(0); + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), ByteString.EMPTY); + PbftMessage pbftMessage = new PbftMessage(); + Protocol.PBFTMessage.Raw.Builder rawBuilder = Protocol.PBFTMessage.Raw.newBuilder(); + Protocol.PBFTMessage.Builder builder = Protocol.PBFTMessage.newBuilder(); + rawBuilder.setViewN(blockCapsule.getNum()) + .setEpoch(0) + .setDataType(Protocol.PBFTMessage.DataType.BLOCK) + .setMsgType(Protocol.PBFTMessage.MsgType.PREPREPARE) + .setData(blockCapsule.getBlockId().getByteString()); + Protocol.PBFTMessage.Raw raw = rawBuilder.build(); + builder.setRawData(raw); + SignInterface sign = SignUtils.fromPrivate(Hex.decode(PublicMethod.getRandomPrivateKey()), + true); + builder.setSignature(ByteString.copyFrom(sign.Base64toBytes(sign.signHash( + Sha256Hash.hash(true, raw.toByteArray()))))); + Protocol.PBFTMessage message = builder.build(); + pbftMessage.setType(MessageTypes.PBFT_MSG.asByte()); + pbftMessage.setPbftMessage(message); + pbftMessage.setData(message.toByteArray()); + pbftMessage.setSwitch(blockCapsule.isSwitch()); + Param.getInstance().setPbftInterface(context.getBean(PbftBaseImpl.class)); + peer.setNeedSyncFromPeer(false); + //Mockito.doNothing().when(pbftMessage).analyzeSignature(); + try { + context.getBean(PbftMsgHandler.class).processMessage(peer, pbftMessage); + } catch (P2pException e) { + Assert.assertEquals(P2pException.TypeEnum.BAD_MESSAGE, e.getType()); + } + + DynamicPropertiesStore dynamicPropertiesStore = context.getBean(DynamicPropertiesStore.class); + dynamicPropertiesStore.saveAllowPBFT(1); + try { + context.getBean(PbftMsgHandler.class).processMessage(peer, pbftMessage); + } catch (P2pException e) { + Assert.assertEquals(P2pException.TypeEnum.BAD_MESSAGE, e.getType()); + } + + Assert.assertEquals(1, PeerManager.getPeers().size()); + } +} diff --git a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java index 9749c59d911..e654e1c9cc2 100644 --- a/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java +++ b/framework/src/test/java/org/tron/core/net/messagehandler/SyncBlockChainMsgHandlerTest.java @@ -1,24 +1,96 @@ package org.tron.core.net.messagehandler; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +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.Rule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.BlockCapsule.BlockId; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; import org.tron.core.exception.P2pException; -import org.tron.core.net.message.SyncBlockChainMessage; +import org.tron.core.net.message.sync.BlockInventoryMessage; +import org.tron.core.net.message.sync.SyncBlockChainMessage; import org.tron.core.net.peer.PeerConnection; +import org.tron.p2p.connection.Channel; public class SyncBlockChainMsgHandlerTest { - private SyncBlockChainMsgHandler handler = new SyncBlockChainMsgHandler(); - private PeerConnection peer = new PeerConnection(); + private TronApplicationContext context; + private SyncBlockChainMsgHandler handler; + private PeerConnection peer; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void init() throws Exception { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + handler = context.getBean(SyncBlockChainMsgHandler.class); + peer = context.getBean(PeerConnection.class); + 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); + + field = c1.getClass().getDeclaredField("inetAddress"); + field.setAccessible(true); + field.set(c1, a1.getAddress()); + + peer.setChannel(c1); + } @Test - public void testProcessMessage() { + public void testProcessMessage() throws Exception { try { handler.processMessage(peer, new SyncBlockChainMessage(new ArrayList<>())); } catch (P2pException e) { - Assert.assertTrue(e.getMessage().equals("SyncBlockChain blockIds is empty")); + Assert.assertEquals("SyncBlockChain blockIds is empty", e.getMessage()); } + + List blockIds = new ArrayList<>(); + blockIds.add(new BlockCapsule.BlockId()); + SyncBlockChainMessage message = new SyncBlockChainMessage(blockIds); + Method method = handler.getClass().getDeclaredMethod( + "check", PeerConnection.class, SyncBlockChainMessage.class); + method.setAccessible(true); + boolean f = (boolean)method.invoke(handler, peer, message); + Assert.assertNotNull(message.getAnswerMessage()); + Assert.assertNotNull(message.toString()); + Assert.assertNotNull(((BlockInventoryMessage) message).getAnswerMessage()); + Assert.assertFalse(f); + + Method method1 = handler.getClass().getDeclaredMethod( + "getLostBlockIds", List.class, BlockId.class); + method1.setAccessible(true); + try { + method1.invoke(handler, blockIds, new BlockCapsule.BlockId()); + } catch (InvocationTargetException e) { + Assert.assertEquals("unForkId is null", e.getTargetException().getMessage()); + } + + Method method2 = handler.getClass().getDeclaredMethod( + "getBlockIds", Long.class, BlockId.class); + method2.setAccessible(true); + List list = (List) method2.invoke(handler, 0L, new BlockCapsule.BlockId()); + Assert.assertEquals(1, list.size()); + } + + @After + public void destroy() { + Args.clearParam(); } } 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 new file mode 100644 index 00000000000..54e5f78d85a --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/messagehandler/TransactionsMsgHandlerTest.java @@ -0,0 +1,150 @@ +package org.tron.core.net.messagehandler; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +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.LinkedBlockingQueue; + +import lombok.Getter; +import org.joda.time.DateTime; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.BaseTest; +import org.tron.common.runtime.TvmTestUtils; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.net.TronNetDelegate; +import org.tron.core.net.message.adv.TransactionMessage; +import org.tron.core.net.message.adv.TransactionsMessage; +import org.tron.core.net.peer.Item; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.service.adv.AdvService; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +public class TransactionsMsgHandlerTest extends BaseTest { + @BeforeClass + public static void init() { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, + Constant.TEST_CONF); + + } + + @Test + public void testProcessMessage() { + TransactionsMsgHandler transactionsMsgHandler = new TransactionsMsgHandler(); + try { + Assert.assertFalse(transactionsMsgHandler.isBusy()); + + transactionsMsgHandler.init(); + + PeerConnection peer = Mockito.mock(PeerConnection.class); + TronNetDelegate tronNetDelegate = Mockito.mock(TronNetDelegate.class); + AdvService advService = Mockito.mock(AdvService.class); + + Field field = TransactionsMsgHandler.class.getDeclaredField("tronNetDelegate"); + field.setAccessible(true); + field.set(transactionsMsgHandler, tronNetDelegate); + + BalanceContract.TransferContract transferContract = BalanceContract.TransferContract + .newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString("121212a9cf"))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString("232323a9cf"))).build(); + + long transactionTimestamp = DateTime.now().minusDays(4).getMillis(); + Protocol.Transaction trx = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder().setTimestamp(transactionTimestamp) + .setRefBlockNum(1) + .addContract( + Protocol.Transaction.Contract.newBuilder() + .setType(Protocol.Transaction.Contract.ContractType.TransferContract) + .setParameter(Any.pack(transferContract)).build()).build()) + .build(); + Map advInvRequest = new ConcurrentHashMap<>(); + Item item = new Item(new TransactionMessage(trx).getMessageId(), + Protocol.Inventory.InventoryType.TRX); + advInvRequest.put(item, 0L); + 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); + transactionsMsgHandler.close(); + BlockingQueue smartContractQueue = + new LinkedBlockingQueue(2); + smartContractQueue.offer(new TrxEvent(null, null)); + smartContractQueue.offer(new TrxEvent(null, null)); + Field field1 = TransactionsMsgHandler.class.getDeclaredField("smartContractQueue"); + field1.setAccessible(true); + field1.set(transactionsMsgHandler, smartContractQueue); + Protocol.Transaction trx1 = TvmTestUtils.generateTriggerSmartContractAndGetTransaction( + ByteArray.fromHexString("121212a9cf"), + ByteArray.fromHexString("121212a9cf"), + ByteArray.fromHexString("123456"), + 100, 100000000, 0, 0); + Map advInvRequest1 = new ConcurrentHashMap<>(); + Item item1 = new Item(new TransactionMessage(trx1).getMessageId(), + Protocol.Inventory.InventoryType.TRX); + advInvRequest1.put(item1, 0L); + Mockito.when(peer.getAdvInvRequest()).thenReturn(advInvRequest1); + List transactionList1 = new ArrayList<>(); + transactionList1.add(trx1); + transactionsMsgHandler.processMessage(peer, new TransactionsMessage(transactionList1)); + Assert.assertNull(advInvRequest.get(item1)); + + // test 0 contract + Protocol.Transaction trx2 = Protocol.Transaction.newBuilder().setRawData( + Protocol.Transaction.raw.newBuilder().setTimestamp(transactionTimestamp) + .setRefBlockNum(1).build()) + .build(); + List transactionList2 = new ArrayList<>(); + transactionList2.add(trx2); + try { + transactionsMsgHandler.processMessage(peer, new TransactionsMessage(transactionList2)); + } catch (Exception ep) { + Assert.assertTrue(true); + } + Map advInvRequest2 = new ConcurrentHashMap<>(); + Item item2 = new Item(new TransactionMessage(trx2).getMessageId(), + Protocol.Inventory.InventoryType.TRX); + advInvRequest2.put(item2, 0L); + Mockito.when(peer.getAdvInvRequest()).thenReturn(advInvRequest2); + try { + transactionsMsgHandler.processMessage(peer, new TransactionsMessage(transactionList2)); + } catch (Exception ep) { + Assert.assertTrue(true); + } + } catch (Exception e) { + Assert.fail(); + } finally { + transactionsMsgHandler.close(); + } + } + + class TrxEvent { + + @Getter + private PeerConnection peer; + @Getter + private TransactionMessage msg; + @Getter + private long time; + + public TrxEvent(PeerConnection peer, TransactionMessage msg) { + this.peer = peer; + this.msg = msg; + this.time = System.currentTimeMillis(); + } + } +} diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java new file mode 100644 index 00000000000..5a67cd8f609 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/peer/PeerConnectionTest.java @@ -0,0 +1,309 @@ +package org.tron.core.net.peer; + +import static org.mockito.Mockito.mock; + +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.overlay.message.Message; +import org.tron.common.utils.Pair; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.net.message.adv.InventoryMessage; +import org.tron.core.net.message.handshake.HelloMessage; +import org.tron.core.net.message.keepalive.PingMessage; +import org.tron.core.net.message.keepalive.PongMessage; +import org.tron.core.net.service.adv.AdvService; +import org.tron.core.net.service.sync.SyncService; +import org.tron.p2p.connection.Channel; +import org.tron.protos.Protocol; + +public class PeerConnectionTest { + + @Test + public void testVariableDefaultValue() { + PeerConnection peerConnection = new PeerConnection(); + Assert.assertTrue(!peerConnection.isBadPeer()); + Assert.assertTrue(!peerConnection.isFetchAble()); + Assert.assertTrue(peerConnection.isIdle()); + Assert.assertTrue(!peerConnection.isRelayPeer()); + Assert.assertTrue(peerConnection.isNeedSyncFromPeer()); + Assert.assertTrue(peerConnection.isNeedSyncFromUs()); + Assert.assertTrue(!peerConnection.isSyncFinish()); + } + + @Test + public void testOnDisconnect() { + PeerConnection peerConnection = new PeerConnection(); + + SyncService syncService = mock(SyncService.class); + ReflectUtils.setFieldValue(peerConnection, "syncService", syncService); + + AdvService advService = mock(AdvService.class); + ReflectUtils.setFieldValue(peerConnection, "advService", advService); + + Item item = new Item(Sha256Hash.ZERO_HASH, Protocol.Inventory.InventoryType.TRX); + Long time = System.currentTimeMillis(); + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + peerConnection.getAdvInvReceive().put(item, time); + peerConnection.getAdvInvSpread().put(item, time); + peerConnection.getSyncBlockIdCache().put(item.getHash(), time); + peerConnection.getSyncBlockToFetch().add(blockId); + peerConnection.getSyncBlockRequested().put(blockId, time); + peerConnection.getSyncBlockInProcess().add(blockId); + + peerConnection.onDisconnect(); + + Assert.assertEquals(0, peerConnection.getAdvInvReceive().size()); + Assert.assertEquals(0, peerConnection.getAdvInvSpread().size()); + Assert.assertEquals(0, peerConnection.getSyncBlockIdCache().size()); + Assert.assertEquals(0, peerConnection.getSyncBlockToFetch().size()); + Assert.assertEquals(0, peerConnection.getSyncBlockRequested().size()); + Assert.assertEquals(0, peerConnection.getSyncBlockInProcess().size()); + } + + @Test + public void testIsIdle() { + PeerConnection peerConnection = new PeerConnection(); + boolean f = peerConnection.isIdle(); + Assert.assertTrue(f); + + Item item = new Item(Sha256Hash.ZERO_HASH, Protocol.Inventory.InventoryType.TRX); + Long time = System.currentTimeMillis(); + peerConnection.getAdvInvRequest().put(item, time); + f = peerConnection.isIdle(); + Assert.assertTrue(!f); + + peerConnection.getAdvInvRequest().clear(); + f = peerConnection.isIdle(); + Assert.assertTrue(f); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + peerConnection.getSyncBlockRequested().put(blockId, time); + f = peerConnection.isIdle(); + Assert.assertTrue(!f); + + peerConnection.getSyncBlockRequested().clear(); + f = peerConnection.isIdle(); + Assert.assertTrue(f); + + peerConnection.setSyncChainRequested(new Pair<>(new LinkedList<>(), time)); + f = peerConnection.isIdle(); + Assert.assertTrue(!f); + } + + @Test + public void testIsSyncIdle() { + PeerConnection peerConnection = new PeerConnection(); + boolean f = peerConnection.isSyncIdle(); + Assert.assertTrue(f); + + Item item = new Item(Sha256Hash.ZERO_HASH, Protocol.Inventory.InventoryType.TRX); + Long time = System.currentTimeMillis(); + peerConnection.getAdvInvRequest().put(item, time); + f = peerConnection.isSyncIdle(); + Assert.assertTrue(f); + + peerConnection.getAdvInvRequest().clear(); + f = peerConnection.isSyncIdle(); + Assert.assertTrue(f); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + peerConnection.getSyncBlockRequested().put(blockId, time); + f = peerConnection.isSyncIdle(); + Assert.assertTrue(!f); + + peerConnection.getSyncBlockRequested().clear(); + f = peerConnection.isSyncIdle(); + Assert.assertTrue(f); + + peerConnection.setSyncChainRequested(new Pair<>(new LinkedList<>(), time)); + f = peerConnection.isSyncIdle(); + Assert.assertTrue(!f); + } + + @Test + public void testOnConnect() { + PeerConnection peerConnection = new PeerConnection(); + SyncService syncService = mock(SyncService.class); + ReflectUtils.setFieldValue(peerConnection, "syncService", syncService); + + HelloMessage m1 = mock(HelloMessage.class); + BlockCapsule.BlockId b1 = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1); + Mockito.when(m1.getHeadBlockId()).thenReturn(b1); + + HelloMessage m2 = mock(HelloMessage.class); + BlockCapsule.BlockId b2 = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 2); + Mockito.when(m2.getHeadBlockId()).thenReturn(b2); + + Assert.assertTrue(peerConnection.isNeedSyncFromUs()); + Assert.assertTrue(peerConnection.isNeedSyncFromPeer()); + + ReflectUtils.setFieldValue(peerConnection, "helloMessageReceive", m1); + ReflectUtils.setFieldValue(peerConnection, "helloMessageSend", m2); + peerConnection.onConnect(); + Assert.assertTrue(peerConnection.isNeedSyncFromUs()); + Assert.assertTrue(!peerConnection.isNeedSyncFromPeer()); + + peerConnection.setNeedSyncFromPeer(true); + peerConnection.setNeedSyncFromUs(true); + ReflectUtils.setFieldValue(peerConnection, "helloMessageReceive", m2); + ReflectUtils.setFieldValue(peerConnection, "helloMessageSend", m1); + peerConnection.onConnect(); + Assert.assertTrue(!peerConnection.isNeedSyncFromUs()); + Assert.assertTrue(peerConnection.isNeedSyncFromPeer()); + + peerConnection.setNeedSyncFromPeer(true); + peerConnection.setNeedSyncFromUs(true); + ReflectUtils.setFieldValue(peerConnection, "helloMessageReceive", m1); + ReflectUtils.setFieldValue(peerConnection, "helloMessageSend", m1); + peerConnection.onConnect(); + Assert.assertTrue(!peerConnection.isNeedSyncFromUs()); + Assert.assertTrue(!peerConnection.isNeedSyncFromPeer()); + } + + @Test + public void testSetChannel() { + PeerConnection peerConnection = new PeerConnection(); + + InetSocketAddress inetSocketAddress = + new InetSocketAddress("127.0.0.2", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + + List relayNodes = new ArrayList<>(); + ReflectUtils.setFieldValue(peerConnection, "relayNodes", relayNodes); + + peerConnection.setChannel(c1); + Assert.assertTrue(!peerConnection.isRelayPeer()); + + relayNodes.add(inetSocketAddress); + peerConnection.setChannel(c1); + Assert.assertTrue(peerConnection.isRelayPeer()); + } + + @Test + public void testIsSyncFinish() { + PeerConnection peerConnection = new PeerConnection(); + boolean f = peerConnection.isSyncFinish(); + Assert.assertTrue(!f); + + peerConnection.setNeedSyncFromUs(false); + f = peerConnection.isSyncFinish(); + Assert.assertTrue(!f); + + peerConnection.setNeedSyncFromPeer(false); + f = peerConnection.isSyncFinish(); + Assert.assertTrue(f); + } + + @Test + public void testCheckAndPutAdvInvRequest() { + PeerConnection peerConnection = new PeerConnection(); + Item item = new Item(Sha256Hash.ZERO_HASH, Protocol.Inventory.InventoryType.TRX); + Long time = System.currentTimeMillis(); + boolean f = peerConnection.checkAndPutAdvInvRequest(item, time); + Assert.assertTrue(f); + + f = peerConnection.checkAndPutAdvInvRequest(item, time); + Assert.assertTrue(!f); + } + + @Test + public void testEquals() { + List relayNodes = new ArrayList<>(); + + PeerConnection p1 = new PeerConnection(); + InetSocketAddress inetSocketAddress1 = + new InetSocketAddress("127.0.0.2", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); + ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); + + PeerConnection p2 = new PeerConnection(); + InetSocketAddress inetSocketAddress2 = + new InetSocketAddress("127.0.0.2", 10002); + Channel c2 = new Channel(); + ReflectUtils.setFieldValue(c2, "inetSocketAddress", inetSocketAddress2); + ReflectUtils.setFieldValue(c2, "inetAddress", inetSocketAddress2.getAddress()); + ReflectUtils.setFieldValue(p2, "relayNodes", relayNodes); + p2.setChannel(c2); + + PeerConnection p3 = new PeerConnection(); + InetSocketAddress inetSocketAddress3 = + new InetSocketAddress("127.0.0.2", 10002); + Channel c3 = new Channel(); + ReflectUtils.setFieldValue(c3, "inetSocketAddress", inetSocketAddress3); + ReflectUtils.setFieldValue(c3, "inetAddress", inetSocketAddress3.getAddress()); + ReflectUtils.setFieldValue(p3, "relayNodes", relayNodes); + p3.setChannel(c3); + + Assert.assertTrue(p1.equals(p1)); + Assert.assertTrue(!p1.equals(p2)); + Assert.assertTrue(p2.equals(p3)); + } + + @Test + public void testHashCode() { + List relayNodes = new ArrayList<>(); + + PeerConnection p1 = new PeerConnection(); + InetSocketAddress inetSocketAddress1 = + new InetSocketAddress("127.0.0.2", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); + ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); + + PeerConnection p2 = new PeerConnection(); + InetSocketAddress inetSocketAddress2 = + new InetSocketAddress("127.0.0.2", 10002); + Channel c2 = new Channel(); + ReflectUtils.setFieldValue(c2, "inetSocketAddress", inetSocketAddress2); + ReflectUtils.setFieldValue(c2, "inetAddress", inetSocketAddress2.getAddress()); + ReflectUtils.setFieldValue(p2, "relayNodes", relayNodes); + p2.setChannel(c2); + + PeerConnection p3 = new PeerConnection(); + InetSocketAddress inetSocketAddress3 = + new InetSocketAddress("127.0.0.2", 10002); + Channel c3 = new Channel(); + ReflectUtils.setFieldValue(c3, "inetSocketAddress", inetSocketAddress3); + ReflectUtils.setFieldValue(c3, "inetAddress", inetSocketAddress3.getAddress()); + ReflectUtils.setFieldValue(p3, "relayNodes", relayNodes); + p3.setChannel(c3); + + Assert.assertTrue(p1.hashCode() != p2.hashCode()); + Assert.assertTrue(p2.hashCode() == p3.hashCode()); + } + + @Test + public void testNeedToLog() throws Exception { + Message msg = new PingMessage(); + boolean f = PeerConnection.needToLog(msg); + Assert.assertTrue(!f); + + msg = new PongMessage(); + f = PeerConnection.needToLog(msg); + Assert.assertTrue(!f); + + msg = new InventoryMessage(new ArrayList<>(), Protocol.Inventory.InventoryType.TRX); + f = PeerConnection.needToLog(msg); + Assert.assertTrue(!f); + + msg = new InventoryMessage(new ArrayList<>(), Protocol.Inventory.InventoryType.BLOCK); + f = PeerConnection.needToLog(msg); + Assert.assertTrue(f); + } + +} 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 new file mode 100644 index 00000000000..b8c03de1029 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/peer/PeerManagerTest.java @@ -0,0 +1,166 @@ +package org.tron.core.net.peer; + +import static org.mockito.Mockito.mock; + +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.utils.ReflectUtils; +import org.tron.p2p.connection.Channel; + +public class PeerManagerTest { + List relayNodes = new ArrayList<>(); + + @Test + public void testAdd() throws Exception { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + PeerConnection p1 = new PeerConnection(); + InetSocketAddress inetSocketAddress1 = + new InetSocketAddress("127.0.0.2", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); + ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); + + ApplicationContext ctx = mock(ApplicationContext.class); + Mockito.when(ctx.getBean(PeerConnection.class)).thenReturn(p1); + + PeerConnection p = PeerManager.add(ctx, c1); + Assert.assertTrue(p != null); + + p = PeerManager.add(ctx, c1); + Assert.assertTrue(p == null); + } + + @Test + public void testRemove() throws Exception { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + PeerConnection p1 = new PeerConnection(); + InetSocketAddress inetSocketAddress1 = + new InetSocketAddress("127.0.0.2", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); + ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); + + ApplicationContext ctx = mock(ApplicationContext.class); + Mockito.when(ctx.getBean(PeerConnection.class)).thenReturn(p1); + + PeerConnection p = PeerManager.remove(c1); + Assert.assertTrue(p == null); + + PeerManager.add(ctx, c1); + p = PeerManager.remove(c1); + Assert.assertTrue(p != null); + } + + @Test + public void testGetPeerConnection() throws Exception { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + PeerConnection p1 = new PeerConnection(); + InetSocketAddress inetSocketAddress1 = + new InetSocketAddress("127.0.0.2", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); + ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); + + ApplicationContext ctx = mock(ApplicationContext.class); + Mockito.when(ctx.getBean(PeerConnection.class)).thenReturn(p1); + + PeerManager.add(ctx, c1); + PeerConnection p = PeerManager.getPeerConnection(c1); + Assert.assertTrue(p != null); + } + + @Test + public void testGetPeers() throws Exception { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + PeerConnection p1 = new PeerConnection(); + InetSocketAddress inetSocketAddress1 = + new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress1); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress1.getAddress()); + ReflectUtils.setFieldValue(p1, "relayNodes", relayNodes); + p1.setChannel(c1); + + ApplicationContext ctx = mock(ApplicationContext.class); + Mockito.when(ctx.getBean(PeerConnection.class)).thenReturn(p1); + + PeerConnection p = PeerManager.add(ctx, c1); + Assert.assertTrue(p != null); + + List peers = PeerManager.getPeers(); + Assert.assertEquals(1, peers.size()); + + PeerConnection p2 = new PeerConnection(); + InetSocketAddress inetSocketAddress2 = + new InetSocketAddress("127.0.0.2", 10001); + Channel c2 = new Channel(); + ReflectUtils.setFieldValue(c2, "inetSocketAddress", inetSocketAddress2); + ReflectUtils.setFieldValue(c2, "inetAddress", inetSocketAddress2.getAddress()); + ReflectUtils.setFieldValue(p2, "relayNodes", relayNodes); + p2.setChannel(c2); + + ApplicationContext ctx2 = mock(ApplicationContext.class); + Mockito.when(ctx2.getBean(PeerConnection.class)).thenReturn(p2); + + p = PeerManager.add(ctx2, c2); + Assert.assertTrue(p != null); + + peers = PeerManager.getPeers(); + Assert.assertEquals(2, peers.size()); + } + + @Test + public void testSortPeers() throws Exception { + PeerConnection p1 = new PeerConnection(); + PeerConnection p2 = new PeerConnection(); + + List peers = new ArrayList<>(); + peers.add(p1); + peers.add(p2); + + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(peers)); + + PeerManager.sortPeers(); + + Channel c1 = new Channel(); + c1.updateAvgLatency(100000L); + ReflectUtils.setFieldValue(p1, "channel", c1); + + Channel c2 = new Channel(); + c2.updateAvgLatency(1000L); + ReflectUtils.setFieldValue(p2, "channel", c2); + + PeerManager.sortPeers(); + + Assert.assertEquals(PeerManager.getPeers().get(0), p2); + } + +} diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java new file mode 100644 index 00000000000..80b1abdc35d --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckMockTest.java @@ -0,0 +1,26 @@ +package org.tron.core.net.peer; + +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.spy; + +import org.junit.After; +import org.junit.Test; +import org.mockito.Mockito; + +public class PeerStatusCheckMockTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + @Test + public void testInitException() throws InterruptedException { + PeerStatusCheck peerStatusCheck = spy(new PeerStatusCheck()); + doThrow(new RuntimeException("test exception")).when(peerStatusCheck).statusCheck(); + peerStatusCheck.init(); + + // the initialDelay of scheduleWithFixedDelay is 5s + Thread.sleep(5000L); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckTest.java b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckTest.java new file mode 100644 index 00000000000..53e678c7ca4 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/peer/PeerStatusCheckTest.java @@ -0,0 +1,73 @@ +package org.tron.core.net.peer; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.spy; + +import io.netty.channel.ChannelHandlerContext; +import java.io.IOException; +import java.net.InetSocketAddress; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule.BlockId; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.Parameter.NetConstants; +import org.tron.core.config.args.Args; +import org.tron.p2p.connection.Channel; + + +public class PeerStatusCheckTest { + + protected TronApplicationContext context; + private PeerStatusCheck service; + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void init() throws IOException { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + service = context.getBean(PeerStatusCheck.class); + } + + /** + * destroy. + */ + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + + @Test + public void testCheck() { + int maxConnection = 30; + Assert.assertEquals(maxConnection, Args.getInstance().getMaxConnections()); + Assert.assertEquals(0, PeerManager.getPeers().size()); + + for (int i = 0; i < maxConnection; i++) { + InetSocketAddress inetSocketAddress = new InetSocketAddress("201.0.0." + i, 10001); + Channel c1 = spy(Channel.class); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + ReflectUtils.setFieldValue(c1, "ctx", spy(ChannelHandlerContext.class)); + Mockito.doNothing().when(c1).send((byte[]) any()); + + PeerManager.add(context, c1); + } + + PeerManager.getPeers().get(0).getSyncBlockRequested() + .put(new BlockId(), System.currentTimeMillis() - NetConstants.SYNC_TIME_OUT - 1000); + ReflectUtils.invokeMethod(service, "statusCheck"); + + Assert.assertEquals(maxConnection - 1L, PeerManager.getPeers().size()); + } +} diff --git a/framework/src/test/java/org/tron/core/net/service/nodepersist/DBNodeTest.java b/framework/src/test/java/org/tron/core/net/service/nodepersist/DBNodeTest.java new file mode 100644 index 00000000000..171701762ee --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/service/nodepersist/DBNodeTest.java @@ -0,0 +1,52 @@ +package org.tron.core.net.service.nodepersist; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import com.beust.jcommander.internal.Lists; +import org.junit.Before; +import org.junit.Test; + +public class DBNodeTest { + private DBNode dbNode1; + private DBNode dbNode2; + + @Before + public void setUp() { + dbNode1 = new DBNode("localhost", 3306); + dbNode2 = new DBNode(); + } + + @Test + public void testConstructorWithParameters() { + assertEquals("localhost", dbNode1.getHost()); + assertEquals(3306, dbNode1.getPort()); + } + + @Test + public void testDefaultConstructor() { + assertNull(dbNode2.getHost()); + assertEquals(0, dbNode2.getPort()); + } + + @Test + public void testSetAndGetHost() { + dbNode2.setHost("127.0.0.1"); + assertEquals("127.0.0.1", dbNode2.getHost()); + } + + @Test + public void testSetAndGetPort() { + dbNode2.setPort(5432); + assertEquals(5432, dbNode2.getPort()); + } + + + @Test + public void testDBNodes() { + DBNodes dbNodes = new DBNodes(); + dbNodes.setNodes(Lists.newArrayList(dbNode1, dbNode2)); + assertEquals(3306, dbNodes.getNodes().get(0).getPort()); + assertEquals(0, dbNodes.getNodes().get(1).getPort()); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java b/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java index 194649774c5..04a6315f522 100644 --- a/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java +++ b/framework/src/test/java/org/tron/core/net/services/AdvServiceTest.java @@ -1,13 +1,19 @@ package org.tron.core.net.services; -import com.google.common.collect.Lists; -import java.util.List; -import org.junit.After; +import static org.mockito.Mockito.mock; + +import java.io.IOException; +import java.net.InetSocketAddress; + +import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; import org.tron.common.application.TronApplicationContext; -import org.tron.common.overlay.server.SyncPool; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ReflectUtils; import org.tron.common.utils.Sha256Hash; @@ -15,38 +21,38 @@ import org.tron.core.capsule.BlockCapsule; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.net.message.BlockMessage; -import org.tron.core.net.message.TransactionMessage; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.message.adv.BlockMessage; +import org.tron.core.net.message.adv.TransactionMessage; import org.tron.core.net.peer.Item; import org.tron.core.net.peer.PeerConnection; -import org.tron.core.net.service.AdvService; +import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.service.adv.AdvService; +import org.tron.p2p.connection.Channel; import org.tron.protos.Protocol; import org.tron.protos.Protocol.Inventory.InventoryType; -//@Ignore public class AdvServiceTest { - - protected TronApplicationContext context; - private AdvService service; - private PeerConnection peer; - private SyncPool syncPool; - - /** - * init context. - */ - @Before - public void init() { - Args.setParam(new String[]{"--output-directory", "output-directory", "--debug"}, - Constant.TEST_CONF); + private static TronApplicationContext context; + private static AdvService service; + private static P2pEventHandlerImpl p2pEventHandler; + private static ApplicationContext ctx; + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @BeforeClass + public static void init() throws IOException { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); context = new TronApplicationContext(DefaultConfig.class); service = context.getBean(AdvService.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); } - /** - * destroy. - */ - @After - public void destroy() { + @AfterClass + public static void after() { Args.clearParam(); context.destroy(); } @@ -55,7 +61,6 @@ public void destroy() { public void test() { testAddInv(); testBroadcast(); - //testFastSend(); testTrxBroadcast(); } @@ -69,72 +74,67 @@ private void testAddInv() { Item itemBlock = new Item(Sha256Hash.ZERO_HASH, InventoryType.BLOCK); flag = service.addInv(itemBlock); + Assert.assertFalse(flag); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 1000L); + itemBlock = new Item(blockId, InventoryType.BLOCK); + flag = service.addInv(itemBlock); Assert.assertTrue(flag); flag = service.addInv(itemBlock); Assert.assertFalse(flag); + blockId = new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 10000L); + itemBlock = new Item(blockId, InventoryType.BLOCK); service.addInvToCache(itemBlock); flag = service.addInv(itemBlock); Assert.assertFalse(flag); } private void testBroadcast() { + InetSocketAddress inetSocketAddress = + new InetSocketAddress("127.0.0.2", 10001); - try { - peer = context.getBean(PeerConnection.class); - syncPool = context.getBean(SyncPool.class); - - List peers = Lists.newArrayList(); - peers.add(peer); - ReflectUtils.setFieldValue(syncPool, "activePeers", peers); - BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, - System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); - BlockMessage msg = new BlockMessage(blockCapsule); - service.broadcast(msg); - Item item = new Item(blockCapsule.getBlockId(), InventoryType.BLOCK); - Assert.assertNotNull(service.getMessage(item)); - - peer.close(); - syncPool.close(); - } catch (NullPointerException e) { - System.out.println(e); - } - } - /* - private void testFastSend() { - - try { - peer = context.getBean(PeerConnection.class); - syncPool = context.getBean(SyncPool.class); - - List peers = Lists.newArrayList(); - peers.add(peer); - ReflectUtils.setFieldValue(syncPool, "activePeers", peers); - BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, - System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); - BlockMessage msg = new BlockMessage(blockCapsule); - service.fastForward(msg); - Item item = new Item(blockCapsule.getBlockId(), InventoryType.BLOCK); - //Assert.assertNull(service.getMessage(item)); - - peer.getAdvInvRequest().put(item, System.currentTimeMillis()); - service.onDisconnect(peer); - - peer.close(); - syncPool.close(); - } catch (NullPointerException e) { - System.out.println(e); - } + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(inetSocketAddress); + Mockito.when(c1.getInetAddress()).thenReturn(inetSocketAddress.getAddress()); + + PeerConnection peer = PeerManager.add(ctx, c1); + peer.setChannel(c1); + peer.setNeedSyncFromUs(false); + peer.setNeedSyncFromPeer(false); + + BlockCapsule blockCapsule = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + BlockMessage msg = new BlockMessage(blockCapsule); + service.broadcast(msg); + Item item = new Item(blockCapsule.getBlockId(), InventoryType.BLOCK); + Assert.assertNotNull(service.getMessage(item)); + Assert.assertNotNull(peer.getAdvInvSpread().getIfPresent(item)); } - */ private void testTrxBroadcast() { - Protocol.Transaction trx = Protocol.Transaction.newBuilder().build(); + Protocol.Transaction trx = Protocol.Transaction.newBuilder() + .setRawData( + Protocol.Transaction.raw.newBuilder() + .setRefBlockNum(1) + .setExpiration(System.currentTimeMillis() + 3000).build()).build(); CommonParameter.getInstance().setValidContractProtoThreadNum(1); TransactionMessage msg = new TransactionMessage(trx); service.broadcast(msg); Item item = new Item(msg.getMessageId(), InventoryType.TRX); Assert.assertNotNull(service.getMessage(item)); + + Protocol.Transaction expiredTrx = Protocol.Transaction.newBuilder() + .setRawData( + Protocol.Transaction.raw.newBuilder() + .setRefBlockNum(1) + .setExpiration(System.currentTimeMillis() - 1).build()) + .build(); + CommonParameter.getInstance().setValidContractProtoThreadNum(1); + TransactionMessage msg1 = new TransactionMessage(expiredTrx); + service.broadcast(msg); + Item item1 = new Item(msg1.getMessageId(), InventoryType.TRX); + Assert.assertNull(service.getMessage(item1)); } } diff --git a/framework/src/test/java/org/tron/core/net/services/EffectiveCheckServiceTest.java b/framework/src/test/java/org/tron/core/net/services/EffectiveCheckServiceTest.java new file mode 100644 index 00000000000..9104b087d26 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/EffectiveCheckServiceTest.java @@ -0,0 +1,72 @@ +package org.tron.core.net.services; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.TronNetService; +import org.tron.core.net.service.effective.EffectiveCheckService; +import org.tron.p2p.P2pConfig; + +public class EffectiveCheckServiceTest { + + protected TronApplicationContext context; + private EffectiveCheckService service; + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void init() throws IOException { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + service = context.getBean(EffectiveCheckService.class); + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + + @Test + public void testNoIpv4() throws Exception { + TronNetService tronNetService = context.getBean(TronNetService.class); + Method privateMethod = tronNetService.getClass() + .getDeclaredMethod("updateConfig", P2pConfig.class); + privateMethod.setAccessible(true); + P2pConfig config = new P2pConfig(); + config.setIp(null); + P2pConfig newConfig = (P2pConfig) privateMethod.invoke(tronNetService, config); + Assert.assertNotNull(newConfig.getIp()); + } + + @Test + public void testFind() { + TronNetService tronNetService = context.getBean(TronNetService.class); + P2pConfig p2pConfig = new P2pConfig(); + p2pConfig.setIp("127.0.0.1"); + p2pConfig.setPort(34567); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", p2pConfig); + TronNetService.getP2pService().start(p2pConfig); + + service.triggerNext(); + Assert.assertNull(service.getCur()); + + ReflectUtils.invokeMethod(service, "resetCount"); + InetSocketAddress cur = new InetSocketAddress("192.168.0.1", 34567); + service.setCur(cur); + service.onDisconnect(cur); + } +} 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 new file mode 100644 index 00000000000..f4fabce5d64 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/HandShakeServiceTest.java @@ -0,0 +1,310 @@ +package org.tron.core.net.services; + +import static org.mockito.Mockito.mock; +import static org.tron.core.net.message.handshake.HelloMessage.getEndpointFromNode; + +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Random; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.ReflectUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.TronNetService; +import org.tron.core.net.message.handshake.HelloMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; +import org.tron.program.Version; +import org.tron.protos.Discover.Endpoint; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.HelloMessage.Builder; + +public class HandShakeServiceTest { + + private static TronApplicationContext context; + private PeerConnection peer; + private static P2pEventHandlerImpl p2pEventHandler; + private static ApplicationContext ctx; + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @BeforeClass + public static void init() throws Exception { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); + + TronNetService tronNetService = context.getBean(TronNetService.class); + Parameter.p2pConfig = new P2pConfig(); + ReflectUtils.setFieldValue(tronNetService, "p2pConfig", Parameter.p2pConfig); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + context.destroy(); + } + + @Before + public void clearPeers() { + try { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + } catch (NoSuchFieldException | IllegalAccessException e) { + //ignore + } + } + + @Test + public void testOkHelloMessage() + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + //ok + Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); + HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + + Assert.assertEquals(Version.getVersion(), + new String(helloMessage.getHelloMessage().getCodeVersion().toByteArray())); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + + //dup hello message + peer.setHelloMessageReceive(helloMessage); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + + //dup peer + peer.setHelloMessageReceive(null); + Mockito.when(c1.isDisconnect()).thenReturn(true); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } + + @Test + public void testInvalidHelloMessage() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + //block hash is empty + try { + BlockCapsule.BlockId hid = ChainBaseManager.getChainBaseManager().getHeadBlockId(); + Protocol.HelloMessage.BlockId hBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(ByteString.copyFrom(new byte[0])) + .setNumber(hid.getNum()) + .build(); + builder.setHeadBlockId(hBlockId); + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertTrue(!helloMessage.valid()); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testInvalidHelloMessage2() throws Exception { + Protocol.HelloMessage.Builder builder = getTestHelloMessageBuilder(); + Assert.assertTrue(new HelloMessage(builder.build().toByteArray()).valid()); + + builder.setAddress(ByteString.copyFrom(new byte[201])); + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertFalse(helloMessage.valid()); + + builder.setAddress(ByteString.copyFrom(new byte[200])); + helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertTrue(helloMessage.valid()); + + builder.setSignature(ByteString.copyFrom(new byte[201])); + helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertFalse(helloMessage.valid()); + + builder.setSignature(ByteString.copyFrom(new byte[200])); + helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertTrue(helloMessage.valid()); + + builder.setCodeVersion(ByteString.copyFrom(new byte[201])); + helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertFalse(helloMessage.valid()); + + builder.setCodeVersion(ByteString.copyFrom(new byte[200])); + helloMessage = new HelloMessage(builder.build().toByteArray()); + Assert.assertTrue(helloMessage.valid()); + } + + + @Test + public void testRelayHelloMessage() throws NoSuchMethodException { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + //address is empty + Args.getInstance().fastForward = true; + clearPeers(); + Node node2 = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, 10002); + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + Args.getInstance().fastForward = false; + } + + @Test + public void testLowAndGenesisBlockNum() throws NoSuchMethodException { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method = p2pEventHandler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + Node node2 = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, 10002); + + //lowestBlockNum > headBlockNum + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + builder.setLowestBlockNum(ChainBaseManager.getChainBaseManager().getLowestBlockNum() + 1); + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + + //genesisBlock is not equal + builder = getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + BlockCapsule.BlockId gid = ChainBaseManager.getChainBaseManager().getGenesisBlockId(); + Protocol.HelloMessage.BlockId gBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(gid.getByteString()) + .setNumber(gid.getNum() + 1) + .build(); + builder.setGenesisBlockId(gBlockId); + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + + //solidityBlock <= us, but not contained + builder = getHelloMessageBuilder(node2, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + BlockCapsule.BlockId sid = ChainBaseManager.getChainBaseManager().getSolidBlockId(); + + Random gen = new Random(); + byte[] randomHash = new byte[Sha256Hash.LENGTH]; + gen.nextBytes(randomHash); + + Protocol.HelloMessage.BlockId sBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(ByteString.copyFrom(randomHash)) + .setNumber(sid.getNum()) + .build(); + builder.setSolidBlockId(sBlockId); + try { + HelloMessage helloMessage = new HelloMessage(builder.build().toByteArray()); + method.invoke(p2pEventHandler, peer, helloMessage.getSendBytes()); + } catch (Exception e) { + Assert.fail(); + } + } + + private Protocol.HelloMessage.Builder getHelloMessageBuilder(Node from, long timestamp, + ChainBaseManager chainBaseManager) { + Endpoint fromEndpoint = getEndpointFromNode(from); + + BlockCapsule.BlockId gid = chainBaseManager.getGenesisBlockId(); + Protocol.HelloMessage.BlockId gBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(gid.getByteString()) + .setNumber(gid.getNum()) + .build(); + + BlockCapsule.BlockId sid = chainBaseManager.getSolidBlockId(); + Protocol.HelloMessage.BlockId sBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(sid.getByteString()) + .setNumber(sid.getNum()) + .build(); + + BlockCapsule.BlockId hid = chainBaseManager.getHeadBlockId(); + Protocol.HelloMessage.BlockId hBlockId = Protocol.HelloMessage.BlockId.newBuilder() + .setHash(hid.getByteString()) + .setNumber(hid.getNum()) + .build(); + Builder builder = Protocol.HelloMessage.newBuilder(); + builder.setFrom(fromEndpoint); + builder.setVersion(Args.getInstance().getNodeP2pVersion()); + builder.setTimestamp(timestamp); + builder.setGenesisBlockId(gBlockId); + builder.setSolidBlockId(sBlockId); + builder.setHeadBlockId(hBlockId); + builder.setNodeType(chainBaseManager.getNodeType().getType()); + builder.setLowestBlockNum(chainBaseManager.isLiteNode() + ? chainBaseManager.getLowestBlockNum() : 0); + + return builder; + } + + private Protocol.HelloMessage.Builder getTestHelloMessageBuilder() { + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), null, a1.getPort()); + Protocol.HelloMessage.Builder builder = + getHelloMessageBuilder(node, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + return builder; + } +} diff --git a/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java new file mode 100644 index 00000000000..5e22e538e80 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/RelayServiceTest.java @@ -0,0 +1,171 @@ +package org.tron.core.net.services; + +import static org.mockito.Mockito.mock; + +import com.google.common.collect.Lists; +import com.google.protobuf.ByteString; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import javax.annotation.Resource; + +import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.BaseTest; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.message.adv.BlockMessage; +import org.tron.core.net.message.handshake.HelloMessage; +import org.tron.core.net.peer.Item; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.service.relay.RelayService; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.discover.Node; +import org.tron.p2p.utils.NetUtil; +import org.tron.protos.Protocol; + +@Slf4j(topic = "net") +public class RelayServiceTest extends BaseTest { + + @Resource + private RelayService service; + @Resource + private PeerConnection peer; + @Resource + private P2pEventHandlerImpl p2pEventHandler; + + /** + * init context. + */ + @BeforeClass + public static void init() { + Args.setParam(new String[]{"--output-directory", dbPath(), "--debug"}, + Constant.TEST_CONF); + } + + @Test + public void test() throws Exception { + initWitness(); + testGetNextWitnesses(); + testBroadcast(); + testCheckHelloMessage(); + } + + private void initWitness() { + byte[] key = Hex.decode("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"); + WitnessCapsule witnessCapsule = chainBaseManager.getWitnessStore().get(key); + witnessCapsule.setVoteCount(1000); + chainBaseManager.getWitnessStore().put(key, witnessCapsule); + List list = new ArrayList<>(); + List witnesses = chainBaseManager.getWitnessStore().getAllWitnesses(); + witnesses.sort(Comparator.comparingLong(w -> -w.getVoteCount())); + witnesses.forEach(witness -> list.add(witness.getAddress())); + chainBaseManager.getWitnessScheduleStore().saveActiveWitnesses(list); + } + + public void testGetNextWitnesses() throws Exception { + Method method = service.getClass().getDeclaredMethod( + "getNextWitnesses", ByteString.class, Integer.class); + method.setAccessible(true); + Set s1 = (Set) method.invoke( + service, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"), 3); + Assert.assertEquals(3, s1.size()); + assertContains(s1, "A0299F3DB80A24B20A254B89CE639D59132F157F13"); + assertContains(s1, "A0807337F180B62A77576377C1D0C9C24DF5C0DD62"); + assertContains(s1, "A05430A3F089154E9E182DDD6FE136A62321AF22A7"); + + Set s2 = (Set) method.invoke( + service, getFromHexString("A0FAB5FBF6AFB681E4E37E9D33BDDB7E923D6132E5"), 3); + Assert.assertEquals(3, s2.size()); + assertContains(s2, "A014EEBE4D30A6ACB505C8B00B218BDC4733433C68"); + assertContains(s2, "A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"); + assertContains(s2, "A0299F3DB80A24B20A254B89CE639D59132F157F13"); + + Set s3 = (Set) method.invoke( + service, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"), 1); + Assert.assertEquals(1, s3.size()); + assertContains(s3, "A0299F3DB80A24B20A254B89CE639D59132F157F13"); + } + + private void testBroadcast() { + try { + peer.setAddress(getFromHexString("A0299F3DB80A24B20A254B89CE639D59132F157F13")); + peer.setNeedSyncFromPeer(false); + peer.setNeedSyncFromUs(false); + + List peers = Lists.newArrayList(); + peers.add(peer); + ReflectUtils.setFieldValue(p2pEventHandler, "activePeers", peers); + BlockCapsule blockCapsule = new BlockCapsule(chainBaseManager.getHeadBlockNum() + 1, + chainBaseManager.getHeadBlockId(), + 0, getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F")); + BlockMessage msg = new BlockMessage(blockCapsule); + service.broadcast(msg); + Item item = new Item(blockCapsule.getBlockId(), Protocol.Inventory.InventoryType.BLOCK); + Assert.assertEquals(1, peer.getAdvInvSpread().size()); + Assert.assertNotNull(peer.getAdvInvSpread().getIfPresent(item)); + peer.getChannel().close(); + } catch (NullPointerException e) { + System.out.println(e); + } + } + + private void assertContains(Set set, String string) { + ByteString bytes = getFromHexString(string); + Assert.assertTrue(set.contains(bytes)); + } + + private ByteString getFromHexString(String s) { + return ByteString.copyFrom(Hex.decode(s)); + } + + private void testCheckHelloMessage() { + ByteString address = getFromHexString("A04711BF7AFBDF44557DEFBDF4C4E7AA6138C6331F"); + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Node node = new Node(NetUtil.getNodeId(), a1.getAddress().getHostAddress(), + null, a1.getPort()); + HelloMessage helloMessage = new HelloMessage(node, System.currentTimeMillis(), + ChainBaseManager.getChainBaseManager()); + helloMessage.setHelloMessage(helloMessage.getHelloMessage().toBuilder() + .setAddress(address).build()); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + Channel c2 = mock(Channel.class); + Mockito.when(c2.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c2.getInetAddress()).thenReturn(a1.getAddress()); + Args.getInstance().fastForward = true; + ApplicationContext ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, + "ctx"); + PeerConnection peer1 = PeerManager.add(ctx, c1); + assert peer1 != null; + peer1.setAddress(address); + PeerConnection peer2 = PeerManager.add(ctx, c2); + assert peer2 != null; + peer2.setAddress(address); + try { + Field field = service.getClass().getDeclaredField("witnessScheduleStore"); + field.setAccessible(true); + field.set(service, chainBaseManager.getWitnessScheduleStore()); + boolean res = service.checkHelloMessage(helloMessage, c1); + Assert.assertFalse(res); + } catch (Exception e) { + logger.info("{}", e.getMessage()); + } + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/net/services/ResilienceServiceTest.java b/framework/src/test/java/org/tron/core/net/services/ResilienceServiceTest.java new file mode 100644 index 00000000000..ce723e5c991 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/ResilienceServiceTest.java @@ -0,0 +1,205 @@ +package org.tron.core.net.services; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.spy; + +import io.netty.channel.ChannelHandlerContext; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.util.HashSet; +import java.util.Set; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.service.effective.ResilienceService; +import org.tron.p2p.connection.Channel; + +public class ResilienceServiceTest { + + protected TronApplicationContext context; + private ResilienceService service; + private ChainBaseManager chainBaseManager; + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Before + public void init() throws IOException { + Args.setParam(new String[] {"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + chainBaseManager = context.getBean(ChainBaseManager.class); + service = context.getBean(ResilienceService.class); + } + + @Test + public void testDisconnectRandom() { + int maxConnection = 30; + Assert.assertEquals(maxConnection, Args.getInstance().getMaxConnections()); + clearPeers(); + Assert.assertEquals(0, PeerManager.getPeers().size()); + + for (int i = 0; i < maxConnection + 1; i++) { + InetSocketAddress inetSocketAddress = new InetSocketAddress("201.0.0." + i, 10001); + Channel c1 = spy(Channel.class); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + ReflectUtils.setFieldValue(c1, "ctx", spy(ChannelHandlerContext.class)); + Mockito.doNothing().when(c1).send((byte[]) any()); + + PeerManager.add(context, c1); + } + for (PeerConnection peer : PeerManager.getPeers() + .subList(0, ResilienceService.minBroadcastPeerSize)) { + peer.setNeedSyncFromPeer(false); + peer.setNeedSyncFromUs(false); + peer.setLastInteractiveTime(System.currentTimeMillis() - 1000); + } + for (PeerConnection peer : PeerManager.getPeers() + .subList(ResilienceService.minBroadcastPeerSize, maxConnection + 1)) { + peer.setNeedSyncFromPeer(false); + peer.setNeedSyncFromUs(true); + } + int size1 = (int) PeerManager.getPeers().stream() + .filter(peer -> !peer.isNeedSyncFromUs() && !peer.isNeedSyncFromPeer()) + .count(); + Assert.assertEquals(ResilienceService.minBroadcastPeerSize, size1); + Assert.assertEquals(maxConnection + 1, PeerManager.getPeers().size()); + + //disconnect from broadcasting peer + ReflectUtils.invokeMethod(service, "disconnectRandom"); + size1 = (int) PeerManager.getPeers().stream() + .filter(peer -> !peer.isNeedSyncFromUs() && !peer.isNeedSyncFromPeer()) + .count(); + Assert.assertEquals(ResilienceService.minBroadcastPeerSize - 1, size1); + Assert.assertEquals(maxConnection, PeerManager.getPeers().size()); + + //disconnect from syncing peer + ReflectUtils.invokeMethod(service, "disconnectRandom"); + size1 = (int) PeerManager.getPeers().stream() + .filter(peer -> !peer.isNeedSyncFromUs() && !peer.isNeedSyncFromPeer()) + .count(); + Assert.assertEquals(ResilienceService.minBroadcastPeerSize - 1, size1); + Assert.assertEquals(maxConnection - 1, PeerManager.getPeers().size()); + } + + @Test + public void testDisconnectLan() { + int minConnection = 8; + Assert.assertEquals(minConnection, Args.getInstance().getMinConnections()); + clearPeers(); + Assert.assertEquals(0, PeerManager.getPeers().size()); + + for (int i = 0; i < 9; i++) { + InetSocketAddress inetSocketAddress = new InetSocketAddress("201.0.0." + i, 10001); + Channel c1 = spy(Channel.class); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + ReflectUtils.setFieldValue(c1, "isActive", true); + ReflectUtils.setFieldValue(c1, "ctx", spy(ChannelHandlerContext.class)); + Mockito.doNothing().when(c1).send((byte[]) any()); + + PeerManager.add(context, c1); + } + for (PeerConnection peer : PeerManager.getPeers()) { + peer.setNeedSyncFromPeer(false); + peer.setNeedSyncFromUs(false); + } + Assert.assertEquals(9, PeerManager.getPeers().size()); + + boolean isLan = ReflectUtils.invokeMethod(service, "isLanNode"); + Assert.assertTrue(isLan); + + PeerConnection p1 = PeerManager.getPeers().get(1); + InetSocketAddress address1 = p1.getChannel().getInetSocketAddress(); + p1.setLastInteractiveTime( + System.currentTimeMillis() - Args.getInstance().inactiveThreshold * 1000L - 1000); + PeerConnection p2 = PeerManager.getPeers().get(2); + InetSocketAddress address2 = p2.getChannel().getInetSocketAddress(); + p2.setLastInteractiveTime( + System.currentTimeMillis() - Args.getInstance().inactiveThreshold * 1000L - 2000); + + ReflectUtils.invokeMethod(service, "disconnectLan"); + Assert.assertEquals(8, PeerManager.getPeers().size()); + Set addressSet = new HashSet<>(); + PeerManager.getPeers() + .forEach(p -> addressSet.add(p.getChannel().getInetSocketAddress())); + Assert.assertTrue(addressSet.contains(address1)); + Assert.assertFalse(addressSet.contains(address2)); + + ReflectUtils.invokeMethod(service, "disconnectLan"); + Assert.assertEquals(7, PeerManager.getPeers().size()); + addressSet.clear(); + PeerManager.getPeers() + .forEach(p -> addressSet.add(p.getChannel().getInetSocketAddress())); + Assert.assertFalse(addressSet.contains(address1)); + + ReflectUtils.invokeMethod(service, "disconnectLan"); + Assert.assertEquals(7, PeerManager.getPeers().size()); + } + + @Test + public void testDisconnectIsolated2() { + int maxConnection = 30; + Assert.assertEquals(maxConnection, Args.getInstance().getMaxConnections()); + clearPeers(); + Assert.assertEquals(0, PeerManager.getPeers().size()); + + int addSize = (int) (maxConnection * ResilienceService.retentionPercent) + 2; //26 + for (int i = 0; i < addSize; i++) { + InetSocketAddress inetSocketAddress = new InetSocketAddress("201.0.0." + i, 10001); + Channel c1 = spy(Channel.class); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + // 1 ~ 3 is active, 4 ~ 26 is not active + ReflectUtils.setFieldValue(c1, "isActive", i <= 2); + ReflectUtils.setFieldValue(c1, "ctx", spy(ChannelHandlerContext.class)); + Mockito.doNothing().when(c1).send((byte[]) any()); + + PeerManager.add(context, c1); + } + PeerManager.getPeers().get(10).setNeedSyncFromUs(false); + PeerManager.getPeers().get(10).setNeedSyncFromPeer(false); + chainBaseManager.setLatestSaveBlockTime( + System.currentTimeMillis() - ResilienceService.blockNotChangeThreshold - 100L); + boolean isIsolated = ReflectUtils.invokeMethod(service, "isIsolateLand2"); + Assert.assertTrue(isIsolated); + + ReflectUtils.invokeMethod(service, "disconnectIsolated2"); + int activeNodeSize = (int) PeerManager.getPeers().stream() + .filter(p -> p.getChannel().isActive()) + .count(); + int passiveSize = (int) PeerManager.getPeers().stream() + .filter(p -> !p.getChannel().isActive()) + .count(); + Assert.assertEquals(2, activeNodeSize); + Assert.assertEquals((int) (maxConnection * ResilienceService.retentionPercent), + activeNodeSize + passiveSize); + Assert.assertEquals((int) (maxConnection * ResilienceService.retentionPercent), + PeerManager.getPeers().size()); + } + + private void clearPeers() { + for (PeerConnection p : PeerManager.getPeers()) { + PeerManager.remove(p.getChannel()); + } + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java b/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java new file mode 100644 index 00000000000..c2883fb349d --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/SyncServiceTest.java @@ -0,0 +1,231 @@ +package org.tron.core.net.services; + +import static org.mockito.Mockito.mock; + +import com.google.common.cache.Cache; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetSocketAddress; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Map; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.springframework.context.ApplicationContext; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.message.adv.BlockMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.core.net.peer.TronState; +import org.tron.core.net.service.sync.SyncService; +import org.tron.p2p.connection.Channel; +import org.tron.protos.Protocol; + +public class SyncServiceTest { + protected TronApplicationContext context; + private SyncService service; + private PeerConnection peer; + private P2pEventHandlerImpl p2pEventHandler; + private ApplicationContext ctx; + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + private InetSocketAddress inetSocketAddress = + new InetSocketAddress("127.0.0.2", 10001); + + public SyncServiceTest() { + } + + /** + * init context. + */ + @Before + public void init() throws Exception { + Args.setParam(new String[]{"--output-directory", + temporaryFolder.newFolder().toString(), "--debug"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + service = context.getBean(SyncService.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); + ctx = (ApplicationContext) ReflectUtils.getFieldObject(p2pEventHandler, "ctx"); + } + + /** + * destroy. + */ + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + + @Test + public void testStartSync() { + try { + ReflectUtils.setFieldValue(service, "fetchFlag", true); + ReflectUtils.setFieldValue(service, "handleFlag", true); + service.init(); + Assert.assertTrue((boolean) ReflectUtils.getFieldObject(service, "fetchFlag")); + Assert.assertTrue((boolean) ReflectUtils.getFieldObject(service, "handleFlag")); + peer = context.getBean(PeerConnection.class); + Assert.assertNull(peer.getSyncChainRequested()); + + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + + peer.setChannel(c1); + + ReflectUtils.setFieldValue(peer, "tronState", TronState.SYNCING); + + service.startSync(peer); + + ReflectUtils.setFieldValue(peer, "tronState", TronState.INIT); + + service.startSync(peer); + } catch (Exception e) { + // no need to deal with + } + service.close(); + } + + @Test + public void testProcessBlock() { + peer = context.getBean(PeerConnection.class); + Assert.assertNull(peer.getSyncChainRequested()); + Channel c1 = new Channel(); + ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress); + ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress()); + peer.setChannel(c1); + service.processBlock(peer, + new BlockMessage(new BlockCapsule(Protocol.Block.newBuilder().build()))); + boolean fetchFlag = (boolean) ReflectUtils.getFieldObject(service, "fetchFlag"); + boolean handleFlag = (boolean) ReflectUtils.getFieldObject(service, "handleFlag"); + Assert.assertTrue(fetchFlag); + Assert.assertTrue(handleFlag); + } + + @Test + public void testOnDisconnect() { + Cache requestBlockIds = + (Cache) ReflectUtils.getFieldObject(service, "requestBlockIds"); + peer = context.getBean(PeerConnection.class); + Assert.assertNull(peer.getSyncChainRequested()); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(inetSocketAddress); + Mockito.when(c1.getInetAddress()).thenReturn(inetSocketAddress.getAddress()); + peer.setChannel(c1); + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + requestBlockIds.put(blockId, peer); + peer.getSyncBlockRequested().put(blockId, System.currentTimeMillis()); + service.onDisconnect(peer); + Assert.assertTrue(requestBlockIds.getIfPresent(blockId) == null); + } + + @Test + public void testStartFetchSyncBlock() throws Exception { + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + BlockCapsule.BlockId blockId = new BlockCapsule.BlockId(); + + Method method = service.getClass().getDeclaredMethod("startFetchSyncBlock"); + method.setAccessible(true); + + Cache requestBlockIds = + (Cache) + ReflectUtils.getFieldObject(service, "requestBlockIds"); + + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(inetSocketAddress); + Mockito.when(c1.getInetAddress()).thenReturn(inetSocketAddress.getAddress()); + + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + Method method1 = PeerManager.class.getDeclaredMethod("check"); + method1.setAccessible(true); + method1.invoke(PeerManager.class); + Method method2 = PeerManager.class.getDeclaredMethod("logPeerStats"); + method2.setAccessible(true); + method2.invoke(PeerManager.class); + + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) == null); + + peer.getSyncBlockToFetch().add(blockId); + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockToFetch().size() == 1); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) == null); + + peer.setFetchAble(true); + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockToFetch().size() == 1); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) != null); + Assert.assertTrue(requestBlockIds.getIfPresent(blockId) != null); + + peer.getSyncBlockRequested().remove(blockId); + method.invoke(service); + Assert.assertTrue(peer.getSyncBlockRequested().get(blockId) == null); + } + + @Test + public void testHandleSyncBlock() throws Exception { + + Field field = PeerManager.class.getDeclaredField("peers"); + field.setAccessible(true); + field.set(PeerManager.class, Collections.synchronizedList(new ArrayList<>())); + + Method method = service.getClass().getDeclaredMethod("handleSyncBlock"); + method.setAccessible(true); + + Map blockJustReceived = + (Map) + ReflectUtils.getFieldObject(service, "blockJustReceived"); + Protocol.BlockHeader.raw.Builder blockHeaderRawBuild = Protocol.BlockHeader.raw.newBuilder(); + Protocol.BlockHeader.raw blockHeaderRaw = blockHeaderRawBuild + .setNumber(100000) + .build(); + + // block header + Protocol.BlockHeader.Builder blockHeaderBuild = Protocol.BlockHeader.newBuilder(); + Protocol.BlockHeader blockHeader = blockHeaderBuild.setRawData(blockHeaderRaw).build(); + + BlockCapsule blockCapsule = new BlockCapsule(Protocol.Block.newBuilder() + .setBlockHeader(blockHeader).build()); + + BlockCapsule.BlockId blockId = blockCapsule.getBlockId(); + + + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + PeerManager.add(ctx, c1); + peer = PeerManager.getPeers().get(0); + + blockJustReceived.put(new BlockMessage(blockCapsule), peer); + + peer.getSyncBlockToFetch().add(blockId); + + Cache requestBlockIds = + (Cache) + ReflectUtils.getFieldObject(service, "requestBlockIds"); + + requestBlockIds.put(blockId, peer); + + method.invoke(service); + + Assert.assertTrue(requestBlockIds.getIfPresent(blockId) == null); + } +} diff --git a/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java b/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java new file mode 100644 index 00000000000..a940a14d392 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/services/TronStatsManagerTest.java @@ -0,0 +1,63 @@ +package org.tron.core.net.services; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.InetSocketAddress; + +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.net.service.statistics.NodeStatistics; +import org.tron.core.net.service.statistics.TronStatsManager; +import org.tron.protos.Protocol; + +public class TronStatsManagerTest { + + @Test + public void testOnDisconnect() { + InetSocketAddress inetSocketAddress = + new InetSocketAddress("127.0.0.2", 10001); + + InetAddress inetAddress = inetSocketAddress.getAddress(); + + NodeStatistics statistics = TronStatsManager.getNodeStatistics(inetAddress); + + Assert.assertTrue(null != statistics); + Assert.assertEquals(Protocol.ReasonCode.UNKNOWN, statistics.getDisconnectReason()); + } + + @Test + public void testWork() throws Exception { + TronStatsManager manager = new TronStatsManager(); + Field field1 = manager.getClass().getDeclaredField("TCP_TRAFFIC_IN"); + field1.setAccessible(true); + field1.set(manager, 1L); + + Field field2 = manager.getClass().getDeclaredField("TCP_TRAFFIC_OUT"); + field2.setAccessible(true); + field2.set(manager, 1L); + + Field field3 = manager.getClass().getDeclaredField("UDP_TRAFFIC_IN"); + field3.setAccessible(true); + field3.set(manager, 1L); + + Field field4 = manager.getClass().getDeclaredField("UDP_TRAFFIC_OUT"); + field4.setAccessible(true); + field4.set(manager, 1L); + + Assert.assertEquals(field1.get(manager), 1L); + Assert.assertEquals(field2.get(manager), 1L); + Assert.assertEquals(field3.get(manager), 1L); + Assert.assertEquals(field4.get(manager), 1L); + + Method method = manager.getClass().getDeclaredMethod("work"); + method.setAccessible(true); + method.invoke(manager); + + Assert.assertEquals(field1.get(manager), 0L); + Assert.assertEquals(field2.get(manager), 0L); + Assert.assertEquals(field3.get(manager), 0L); + Assert.assertEquals(field4.get(manager), 0L); + } + +} diff --git a/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java b/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java index 16c1205a818..3d5096a5702 100755 --- a/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java +++ b/framework/src/test/java/org/tron/core/pbft/PbftApiTest.java @@ -3,60 +3,47 @@ import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.google.protobuf.ByteString; -import java.io.File; import java.io.IOException; +import java.util.Objects; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; import org.apache.http.client.methods.CloseableHttpResponse; 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.junit.After; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; -import org.tron.common.utils.FileUtil; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; import org.tron.common.utils.Utils; import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.BlockGenerate; import org.tron.core.db.CommonDataBase; -import org.tron.core.db.Manager; import org.tron.core.db2.ISession; -import org.tron.core.exception.HeaderNotFound; import org.tron.core.services.interfaceOnPBFT.http.PBFT.HttpApiOnPBFTService; import org.tron.core.store.DynamicPropertiesStore; @Slf4j -public class PbftApiTest extends BlockGenerate { +public class PbftApiTest extends BaseTest { + @Resource + private HttpApiOnPBFTService httpApiOnPBFTService; - private static Manager dbManager; - private static TronApplicationContext context; - private static String dbPath = "output_pbftAPI_test"; - - @Before - public void init() { - Args.setParam(new String[]{"-d", dbPath, "-w"}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - dbManager = context.getBean(Manager.class); - setManager(dbManager); - } - - @After - public void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + CommonParameter.getInstance().setPBFTHttpEnable(true); + CommonParameter.getInstance().setPBFTHttpPort(PublicMethod.chooseRandomPort()); } @Test - public void pbftapi() throws IOException, InterruptedException, HeaderNotFound { + public void pbftapi() throws IOException { ChainBaseManager chainBaseManager = dbManager.getChainBaseManager(); DynamicPropertiesStore dynamicPropertiesStore = chainBaseManager.getDynamicPropertiesStore(); CommonDataBase commonDataBase = chainBaseManager.getCommonDataBase(); @@ -75,17 +62,19 @@ public void pbftapi() throws IOException, InterruptedException, HeaderNotFound { Assert.assertTrue(dynamicPropertiesStore.getLatestBlockHeaderNumber() >= 10); commonDataBase.saveLatestPbftBlockNum(6); - HttpApiOnPBFTService httpApiOnPBFTService = context.getBean(HttpApiOnPBFTService.class); httpApiOnPBFTService.start(); - CloseableHttpResponse response = null; + CloseableHttpResponse response; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { - HttpGet httpGet = new HttpGet("http://127.0.0.1:8092/walletpbft/getnowblock"); + HttpGet httpGet = new HttpGet("http://127.0.0.1/" + + CommonParameter.getInstance().getPBFTHttpPort() + "/walletpbft/getnowblock"); response = httpClient.execute(httpGet); String responseString = EntityUtils.toString(response.getEntity()); JSONObject jsonObject = JSON.parseObject(responseString); - long num = jsonObject.getJSONObject("block_header").getJSONObject("raw_data") - .getLongValue("number"); - Assert.assertEquals(commonDataBase.getLatestPbftBlockNum(), num); + if (Objects.nonNull(jsonObject)) { + long num = jsonObject.getJSONObject("block_header").getJSONObject("raw_data") + .getLongValue("number"); + Assert.assertEquals(commonDataBase.getLatestPbftBlockNum(), num); + } response.close(); } httpApiOnPBFTService.stop(); diff --git a/framework/src/test/java/org/tron/core/pbft/PbftTest.java b/framework/src/test/java/org/tron/core/pbft/PbftTest.java index a5d74ad7a37..33a46516988 100644 --- a/framework/src/test/java/org/tron/core/pbft/PbftTest.java +++ b/framework/src/test/java/org/tron/core/pbft/PbftTest.java @@ -29,6 +29,7 @@ public void testPbftSrMessage() { ByteString.copyFrom(ByteArray.fromHexString("41df309fef25b311e7895562bd9e11aab2a58816d2"))); PbftMessage pbftSrMessage = PbftMessage .prePrepareSRLMsg(blockCapsule, srList, 1, miner); + PbftMessage.fullNodePrePrepareSRLMsg(blockCapsule, srList, 1); System.out.println(pbftSrMessage); } diff --git a/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java b/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java new file mode 100644 index 00000000000..c2caafd393c --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/ComputeRewardTest.java @@ -0,0 +1,304 @@ +package org.tron.core.services; + +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.protobuf.ByteString; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.error.TronDBException; +import org.tron.common.es.ExecutorServiceManager; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.ReflectUtils; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BytesCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.exception.TronError; +import org.tron.core.service.MortgageService; +import org.tron.core.service.RewardViCalService; +import org.tron.core.store.AccountStore; +import org.tron.core.store.DelegationStore; +import org.tron.core.store.DynamicPropertiesStore; +import org.tron.core.store.RewardViStore; +import org.tron.core.store.WitnessStore; +import org.tron.protos.Protocol; + +public class ComputeRewardTest { + + private static final byte[] OWNER_ADDRESS = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1bf0"); + + private static final byte[] OWNER_ADDRESS_2 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1bf1"); + + private static final byte[] OWNER_ADDRESS_3 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1bf2"); + + private static final byte[] SR_ADDRESS_1 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c00"); + private static final byte[] SR_ADDRESS_2 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c01"); + private static final byte[] SR_ADDRESS_3 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c02"); + private static final byte[] SR_ADDRESS_4 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c03"); + private static final byte[] SR_ADDRESS_5 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c04"); + private static final byte[] SR_ADDRESS_6 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c05"); + private static final byte[] SR_ADDRESS_7 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c06"); + private static final byte[] SR_ADDRESS_8 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c07"); + private static final byte[] SR_ADDRESS_9 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c08"); + private static final byte[] SR_ADDRESS_10 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c09"); + private static final byte[] SR_ADDRESS_11 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c10"); + private static final byte[] SR_ADDRESS_12 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c11"); + private static final byte[] SR_ADDRESS_13 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c12"); + private static final byte[] SR_ADDRESS_14 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c13"); + private static final byte[] SR_ADDRESS_15 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c14"); + private static final byte[] SR_ADDRESS_16 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c15"); + private static final byte[] SR_ADDRESS_17 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c16"); + private static final byte[] SR_ADDRESS_18 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c17"); + private static final byte[] SR_ADDRESS_19 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c18"); + private static final byte[] SR_ADDRESS_20 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c19"); + private static final byte[] SR_ADDRESS_21 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c20"); + private static final byte[] SR_ADDRESS_22 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c21"); + private static final byte[] SR_ADDRESS_23 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c22"); + private static final byte[] SR_ADDRESS_24 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c23"); + private static final byte[] SR_ADDRESS_25 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c24"); + private static final byte[] SR_ADDRESS_26 = ByteArray.fromHexString( + "4105b9e8af8ee371cad87317f442d155b39fbd1c25"); + + private static TronApplicationContext context; + private static DynamicPropertiesStore propertiesStore; + private static DelegationStore delegationStore; + private static AccountStore accountStore; + private static RewardViCalService rewardViCalService; + private static WitnessStore witnessStore; + private static MortgageService mortgageService; + private static RewardViStore rewardViStore; + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @After + public void destroy() { + context.destroy(); + Args.clearParam(); + } + + /** + * Init data. + */ + @Before + public void init() throws IOException { + Args.setParam(new String[]{"--output-directory", temporaryFolder.newFolder().toString(), + "--p2p-disable", "true"}, Constant.TEST_CONF); + context = new TronApplicationContext(DefaultConfig.class); + propertiesStore = context.getBean(DynamicPropertiesStore.class); + delegationStore = context.getBean(DelegationStore.class); + accountStore = context.getBean(AccountStore.class); + rewardViCalService = context.getBean(RewardViCalService.class); + witnessStore = context.getBean(WitnessStore.class); + mortgageService = context.getBean(MortgageService.class); + rewardViStore = context.getBean(RewardViStore.class); + setUp(); + } + + private void setUp() { + // mock flush service + Map flushServices = new HashMap<>(); + flushServices.put("propertiesStore", MoreExecutors.listeningDecorator( + ExecutorServiceManager.newSingleThreadExecutor( + "flush-service-propertiesStore"))); + flushServices.put("delegationStore", MoreExecutors.listeningDecorator( + ExecutorServiceManager.newSingleThreadExecutor( + "flush-service-delegationStore"))); + flushServices.put("accountStore", MoreExecutors.listeningDecorator( + ExecutorServiceManager.newSingleThreadExecutor("flush-service-accountStore"))); + flushServices.put("witnessStore", MoreExecutors.listeningDecorator( + ExecutorServiceManager.newSingleThreadExecutor("flush-service-witnessStore"))); + + List> futures = new ArrayList<>(flushServices.size()); + + try { + flushServices.get("propertiesStore").submit(() -> { + propertiesStore.saveChangeDelegation(1); + propertiesStore.saveCurrentCycleNumber(4); + propertiesStore.saveNewRewardAlgorithmEffectiveCycle(); + propertiesStore.saveLatestBlockHeaderNumber(1); + }).get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TronDBException(e); + } catch (ExecutionException e) { + throw new TronDBException(e); + } + + try { + Thread.sleep(1000 * 6); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TronDBException(e); + } + + List votes = new ArrayList<>(32); + votes.add(new Vote(46188095536L, 5, 1496122605L, SR_ADDRESS_1)); + votes.add(new Vote(48618386224L, 5, 1582867684L, SR_ADDRESS_2)); + votes.add(new Vote(13155856728L, 5, 586969566L, SR_ADDRESS_3)); + votes.add(new Vote(41883707392L, 5, 1342484905L, SR_ADDRESS_4)); + votes.add(new Vote(62017323832L, 5, 2061119522L, SR_ADDRESS_5)); + votes.add(new Vote(19227712L, 3, 722417L, SR_ADDRESS_6)); + votes.add(new Vote(46634987592L, 3, 1599681706L, SR_ADDRESS_7)); + votes.add(new Vote(49112700L, 3, 1753127L, SR_ADDRESS_8)); + votes.add(new Vote(40835355868L, 6, 1467015537L, SR_ADDRESS_9)); + votes.add(new Vote(10045616L, 5, 362326L, SR_ADDRESS_10)); + votes.add(new Vote(34534983616L, 5, 1217718846L, SR_ADDRESS_11)); + votes.add(new Vote(32387926028L, 5, 1292557190L, SR_ADDRESS_12)); + votes.add(new Vote(36516086396L, 5, 1295716573L, SR_ADDRESS_13)); + votes.add(new Vote(48411501224L, 5, 1575483226L, SR_ADDRESS_14)); + votes.add(new Vote(154785960L, 5, 6905922L, SR_ADDRESS_15)); + votes.add(new Vote(59057915168L, 6, 1956059729L, SR_ADDRESS_16)); + votes.add(new Vote(62921824L, 3, 2245904L, SR_ADDRESS_17)); + votes.add(new Vote(1180144L, 3, 42148L, SR_ADDRESS_18)); + votes.add(new Vote(104313216L, 5, 4654248L, SR_ADDRESS_19)); + votes.add(new Vote(20429168760L, 1, 759569195L, SR_ADDRESS_20)); + votes.add(new Vote(4706184L, 3, 168069L, SR_ADDRESS_21)); + votes.add(new Vote(55804071064L, 5, 1839919389L, SR_ADDRESS_22)); + votes.add(new Vote(6074042856L, 6, 216802459L, SR_ADDRESS_23)); + votes.add(new Vote(40729360L, 5, 1817205L, SR_ADDRESS_24)); + votes.add(new Vote(31250017036L, 5, 1242358644L, SR_ADDRESS_25)); + votes.add(new Vote(15003660L, 5, 669546L, SR_ADDRESS_26)); + + futures.add(flushServices.get("delegationStore").submit(() -> { + delegationStore.setBeginCycle(OWNER_ADDRESS, 2); + delegationStore.setEndCycle(OWNER_ADDRESS, 3); + delegationStore.setBeginCycle(OWNER_ADDRESS_2, 1); + delegationStore.setEndCycle(OWNER_ADDRESS_2, 2); + delegationStore.setBeginCycle(OWNER_ADDRESS_3, 5); + for (Vote vote : votes) { + delegationStore.addReward(3, vote.srAddress, vote.totalReward); + delegationStore.setWitnessVote(3, vote.srAddress, vote.totalVotes); + } + })); + + futures.add(flushServices.get("witnessStore").submit(() -> { + for (Vote vote : votes) { + witnessStore.put(vote.srAddress, new WitnessCapsule(Protocol.Witness.newBuilder() + .setAddress(ByteString.copyFrom(vote.srAddress)) + .setVoteCount(vote.totalVotes) + .build())); + } + })); + + futures.add(flushServices.get("accountStore").submit(() -> { + Protocol.Account.Builder accountBuilder = Protocol.Account.newBuilder(); + accountBuilder.setAddress(ByteString.copyFrom(OWNER_ADDRESS)); + for (Vote vote : votes) { + accountBuilder.addVotes(Protocol.Vote.newBuilder() + .setVoteAddress(ByteString.copyFrom(vote.srAddress)) + .setVoteCount(vote.userVotes)); + + } + accountStore.put(OWNER_ADDRESS, new AccountCapsule(accountBuilder.build())); + })); + Future future = Futures.allAsList(futures); + try { + future.get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TronDBException(e); + } catch (ExecutionException e) { + throw new TronDBException(e); + } + try { + flushServices.get("propertiesStore").submit(() -> { + propertiesStore.saveAllowOldRewardOpt(1); + propertiesStore.saveLatestBlockHeaderNumber(3); + propertiesStore.saveCurrentCycleNumber(5); + }).get(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new TronDBException(e); + } catch (ExecutionException e) { + throw new TronDBException(e); + } + } + + @Test + public void query() { + Assert.assertEquals(3189, mortgageService.queryReward(OWNER_ADDRESS)); + // mock root is error + rewardViStore.put("test".getBytes(), "test".getBytes()); + ReflectUtils.invokeMethod(rewardViCalService,"maybeRun"); + + // mock no need + propertiesStore.saveCurrentCycleNumber(0); + // reset + propertiesStore.put("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes(), + new BytesCapsule(ByteArray.fromLong(Long.MAX_VALUE))); + // set + propertiesStore.saveNewRewardAlgorithmEffectiveCycle(); + ReflectUtils.invokeMethod(rewardViCalService,"maybeRun"); + + // mock maybeRun exception + propertiesStore.saveCurrentCycleNumber(4); + // reset + propertiesStore.put("NEW_REWARD_ALGORITHM_EFFECTIVE_CYCLE".getBytes(), + new BytesCapsule(ByteArray.fromLong(Long.MAX_VALUE))); + // set + propertiesStore.saveNewRewardAlgorithmEffectiveCycle(); + propertiesStore.saveCurrentCycleNumber(5); + rewardViStore.close(); + TronError thrown = Assert.assertThrows(TronError.class, () -> + ReflectUtils.invokeMethod(rewardViCalService,"maybeRun")); + Assert.assertEquals(TronError.ErrCode.REWARD_VI_CALCULATOR, thrown.getErrCode()); + } + + static class Vote { + long totalVotes; + long userVotes; + long totalReward; + byte[] srAddress; + + public Vote(long totalReward, long userVotes, long totalVotes, byte[] srAddress) { + this.totalVotes = totalVotes; + this.userVotes = userVotes; + this.totalReward = totalReward; + this.srAddress = srAddress; + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java index dc99cb8f4af..5c898eb42d6 100644 --- a/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/DelegationServiceTest.java @@ -1,7 +1,7 @@ package org.tron.core.services; import static org.tron.common.utils.Commons.decodeFromBase58Check; -import static stest.tron.wallet.common.client.Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET; +import static org.tron.common.utils.client.Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET; import com.google.protobuf.ByteString; import io.grpc.ManagedChannelBuilder; @@ -33,7 +33,7 @@ public DelegationServiceTest(TronApplicationContext context) { public static void testGrpc() { WalletBlockingStub walletStub = WalletGrpc .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build()); BytesMessage.Builder builder = BytesMessage.newBuilder(); builder.setValue(ByteString.copyFromUtf8("TLTDZBcPoJ8tZ6TTEeEqEvwYFk2wgotSfD")); @@ -107,6 +107,7 @@ private void testWithdraw() { public void test() { manager.getDynamicPropertiesStore().saveChangeDelegation(1); + manager.getDynamicPropertiesStore().saveConsensusLogicOptimization(1); byte[] sr27 = decodeFromBase58Check("TLTDZBcPoJ8tZ6TTEeEqEvwYFk2wgotSfD"); manager.getDelegationStore().setBrokerage(0, sr27, 10); manager.getDelegationStore().setBrokerage(1, sr27, 20); diff --git a/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java b/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java index 6a8e211a1ed..be0a96f632b 100644 --- a/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/NodeInfoServiceTest.java @@ -1,31 +1,33 @@ package org.tron.core.services; +import static org.mockito.Mockito.mock; + import com.alibaba.fastjson.JSON; import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; +import java.net.InetSocketAddress; import lombok.extern.slf4j.Slf4j; import org.junit.Assert; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletGrpc.WalletBlockingStub; +import org.mockito.Mockito; import org.tron.common.application.TronApplicationContext; import org.tron.common.entity.NodeInfo; import org.tron.common.utils.Sha256Hash; import org.tron.core.capsule.BlockCapsule; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.p2p.connection.Channel; import org.tron.program.Version; -import stest.tron.wallet.common.client.Configuration; + @Slf4j public class NodeInfoServiceTest { private NodeInfoService nodeInfoService; private WitnessProductBlockService witnessProductBlockService; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); + private P2pEventHandlerImpl p2pEventHandler; public NodeInfoServiceTest(TronApplicationContext context) { nodeInfoService = context.getBean("nodeInfoService", NodeInfoService.class); witnessProductBlockService = context.getBean(WitnessProductBlockService.class); + p2pEventHandler = context.getBean(P2pEventHandlerImpl.class); } public void test() { @@ -35,18 +37,19 @@ public void test() { 200, ByteString.EMPTY); witnessProductBlockService.validWitnessProductTwoBlock(blockCapsule1); witnessProductBlockService.validWitnessProductTwoBlock(blockCapsule2); + + //add peer + InetSocketAddress a1 = new InetSocketAddress("127.0.0.1", 10001); + Channel c1 = mock(Channel.class); + Mockito.when(c1.getInetSocketAddress()).thenReturn(a1); + Mockito.when(c1.getInetAddress()).thenReturn(a1.getAddress()); + p2pEventHandler.onConnect(c1); + + //test setConnectInfo NodeInfo nodeInfo = nodeInfoService.getNodeInfo(); Assert.assertEquals(nodeInfo.getConfigNodeInfo().getCodeVersion(), Version.getVersion()); Assert.assertEquals(nodeInfo.getCheatWitnessInfoMap().size(), 1); logger.info("{}", JSON.toJSONString(nodeInfo)); } - public void testGrpc() { - WalletBlockingStub walletStub = WalletGrpc - .newBlockingStub(ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build()); - logger.info("getNodeInfo: {}", walletStub.getNodeInfo(EmptyMessage.getDefaultInstance())); - } - } diff --git a/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java b/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java index 10faf6e19ca..300a38a0916 100644 --- a/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java +++ b/framework/src/test/java/org/tron/core/services/ProposalServiceTest.java @@ -1,40 +1,43 @@ package org.tron.core.services; +import static org.tron.core.utils.ProposalUtil.ProposalType.CONSENSUS_LOGIC_OPTIMIZATION; import static org.tron.core.utils.ProposalUtil.ProposalType.ENERGY_FEE; +import static org.tron.core.utils.ProposalUtil.ProposalType.TRANSACTION_FEE; import static org.tron.core.utils.ProposalUtil.ProposalType.WITNESS_127_PAY_PER_BLOCK; -import java.io.File; import java.util.HashSet; import java.util.Set; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; +import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; import org.tron.core.Constant; import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ProposalService; -import org.tron.core.db.Manager; import org.tron.core.utils.ProposalUtil.ProposalType; import org.tron.protos.Protocol.Proposal; @Slf4j -public class ProposalServiceTest { +public class ProposalServiceTest extends BaseTest { - private static TronApplicationContext context; - private static Manager manager; - private static String dbPath = "output_proposal_test"; + private static boolean init; @BeforeClass public static void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - manager = context.getBean(Manager.class); - manager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(5); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + + } + + @Before + public void before() { + if (init) { + return; + } + dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderNumber(5); + init = true; } @Test @@ -46,12 +49,12 @@ public void test() { Proposal proposal = Proposal.newBuilder().putParameters(1, 1).build(); ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); - boolean result = ProposalService.process(manager, proposalCapsule); + boolean result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); // proposal = Proposal.newBuilder().putParameters(1000, 1).build(); proposalCapsule = new ProposalCapsule(proposal); - result = ProposalService.process(manager, proposalCapsule); + result = ProposalService.process(dbManager, proposalCapsule); Assert.assertFalse(result); // for (ProposalType proposalType : ProposalType.values()) { @@ -61,37 +64,71 @@ public void test() { proposal = Proposal.newBuilder().putParameters(proposalType.getCode(), 1).build(); } proposalCapsule = new ProposalCapsule(proposal); - result = ProposalService.process(manager, proposalCapsule); + result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); } } @Test public void testUpdateEnergyFee() { - String preHistory = manager.getDynamicPropertiesStore().getEnergyPriceHistory(); + String preHistory = dbManager.getDynamicPropertiesStore().getEnergyPriceHistory(); long newPrice = 500; Proposal proposal = Proposal.newBuilder().putParameters(ENERGY_FEE.getCode(), newPrice).build(); ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); - boolean result = ProposalService.process(manager, proposalCapsule); + boolean result = ProposalService.process(dbManager, proposalCapsule); Assert.assertTrue(result); - long currentPrice = manager.getDynamicPropertiesStore().getEnergyFee(); + long currentPrice = dbManager.getDynamicPropertiesStore().getEnergyFee(); Assert.assertEquals(currentPrice, newPrice); - String currentHistory = manager.getDynamicPropertiesStore().getEnergyPriceHistory(); + String currentHistory = dbManager.getDynamicPropertiesStore().getEnergyPriceHistory(); Assert.assertEquals(preHistory + "," + proposalCapsule.getExpirationTime() + ":" + newPrice, currentHistory); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + @Test + public void testUpdateTransactionFee() { + String preHistory = dbManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + + long newPrice = 1500; + Proposal proposal = + Proposal.newBuilder().putParameters(TRANSACTION_FEE.getCode(), newPrice).build(); + ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); + proposalCapsule.setExpirationTime(1627279200000L); + boolean result = ProposalService.process(dbManager, proposalCapsule); + Assert.assertTrue(result); + + long currentPrice = dbManager.getDynamicPropertiesStore().getTransactionFee(); + Assert.assertEquals(currentPrice, newPrice); + + String expResult = preHistory + "," + proposalCapsule.getExpirationTime() + ":" + newPrice; + String currentHistory = dbManager.getDynamicPropertiesStore().getBandwidthPriceHistory(); + Assert.assertEquals(expResult, currentHistory); + } + + @Test + public void testUpdateConsensusLogicOptimization() { + long v = dbManager.getDynamicPropertiesStore().getConsensusLogicOptimization(); + Assert.assertEquals(v, 0); + Assert.assertTrue(!dbManager.getDynamicPropertiesStore().allowConsensusLogicOptimization()); + Assert.assertFalse(dbManager.getDynamicPropertiesStore().allowWitnessSortOptimization()); + Assert.assertFalse(dbManager.getDynamicPropertiesStore().disableJavaLangMath()); + + long value = 1; + Proposal proposal = + Proposal.newBuilder().putParameters(CONSENSUS_LOGIC_OPTIMIZATION.getCode(), value).build(); + ProposalCapsule proposalCapsule = new ProposalCapsule(proposal); + proposalCapsule.setExpirationTime(1627279200000L); + boolean result = ProposalService.process(dbManager, proposalCapsule); + Assert.assertTrue(result); + + v = dbManager.getDynamicPropertiesStore().getConsensusLogicOptimization(); + Assert.assertEquals(v, value); + + Assert.assertTrue(dbManager.getDynamicPropertiesStore().allowConsensusLogicOptimization()); + Assert.assertTrue(dbManager.getDynamicPropertiesStore().allowWitnessSortOptimization()); + Assert.assertTrue(dbManager.getDynamicPropertiesStore().disableJavaLangMath()); } + } \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java new file mode 100644 index 00000000000..3ae090d3caf --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/RpcApiServicesTest.java @@ -0,0 +1,1211 @@ +package org.tron.core.services; + +import static org.junit.Assert.assertNotNull; +import static org.tron.common.parameter.CommonParameter.getInstance; +import static org.tron.common.utils.client.WalletClient.decodeFromBase58Check; +import static org.tron.protos.Protocol.Transaction.Contract.ContractType.TransferContract; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.io.IOException; +import java.util.Objects; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.junit.runners.MethodSorters; +import org.tron.api.DatabaseGrpc; +import org.tron.api.DatabaseGrpc.DatabaseBlockingStub; +import org.tron.api.GrpcAPI.BlockLimit; +import org.tron.api.GrpcAPI.BlockReq; +import org.tron.api.GrpcAPI.BytesMessage; +import org.tron.api.GrpcAPI.CanDelegatedMaxSizeRequestMessage; +import org.tron.api.GrpcAPI.CanWithdrawUnfreezeAmountRequestMessage; +import org.tron.api.GrpcAPI.DelegatedResourceMessage; +import org.tron.api.GrpcAPI.DiversifierMessage; +import org.tron.api.GrpcAPI.EmptyMessage; +import org.tron.api.GrpcAPI.ExpandedSpendingKeyMessage; +import org.tron.api.GrpcAPI.GetAvailableUnfreezeCountRequestMessage; +import org.tron.api.GrpcAPI.IncomingViewingKeyDiversifierMessage; +import org.tron.api.GrpcAPI.IncomingViewingKeyMessage; +import org.tron.api.GrpcAPI.IvkDecryptAndMarkParameters; +import org.tron.api.GrpcAPI.IvkDecryptParameters; +import org.tron.api.GrpcAPI.IvkDecryptTRC20Parameters; +import org.tron.api.GrpcAPI.NumberMessage; +import org.tron.api.GrpcAPI.OvkDecryptParameters; +import org.tron.api.GrpcAPI.OvkDecryptTRC20Parameters; +import org.tron.api.GrpcAPI.PaginatedMessage; +import org.tron.api.GrpcAPI.PrivateParameters; +import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk; +import org.tron.api.GrpcAPI.ViewingKeyMessage; +import org.tron.api.WalletGrpc; +import org.tron.api.WalletGrpc.WalletBlockingStub; +import org.tron.api.WalletSolidityGrpc; +import org.tron.api.WalletSolidityGrpc.WalletSolidityBlockingStub; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.db.Manager; +import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; +import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Account; +import org.tron.protos.Protocol.Block; +import org.tron.protos.Protocol.BlockHeader.raw; +import org.tron.protos.Protocol.MarketOrderPair; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.contract.AccountContract.AccountCreateContract; +import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; +import org.tron.protos.contract.AccountContract.AccountUpdateContract; +import org.tron.protos.contract.AccountContract.SetAccountIdContract; +import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; +import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; +import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; +import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; +import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.BalanceContract.AccountBalanceRequest; +import org.tron.protos.contract.BalanceContract.AccountIdentifier; +import org.tron.protos.contract.BalanceContract.BlockBalanceTrace.BlockIdentifier; +import org.tron.protos.contract.BalanceContract.CancelAllUnfreezeV2Contract; +import org.tron.protos.contract.BalanceContract.DelegateResourceContract; +import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; +import org.tron.protos.contract.BalanceContract.FreezeBalanceV2Contract; +import org.tron.protos.contract.BalanceContract.UnDelegateResourceContract; +import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; +import org.tron.protos.contract.BalanceContract.UnfreezeBalanceV2Contract; +import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; +import org.tron.protos.contract.BalanceContract.WithdrawExpireUnfreezeContract; +import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract; +import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract; +import org.tron.protos.contract.ExchangeContract.ExchangeTransactionContract; +import org.tron.protos.contract.ExchangeContract.ExchangeWithdrawContract; +import org.tron.protos.contract.MarketContract.MarketCancelOrderContract; +import org.tron.protos.contract.MarketContract.MarketSellAssetContract; +import org.tron.protos.contract.ProposalContract.ProposalApproveContract; +import org.tron.protos.contract.ProposalContract.ProposalCreateContract; +import org.tron.protos.contract.ProposalContract.ProposalDeleteContract; +import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; +import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; +import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; +import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract; +import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract; +import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; +import org.tron.protos.contract.WitnessContract.VoteWitnessContract; +import org.tron.protos.contract.WitnessContract.WitnessCreateContract; +import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; + +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class RpcApiServicesTest { + private static TronApplicationContext context; + private static DatabaseBlockingStub databaseBlockingStubFull = null; + private static DatabaseBlockingStub databaseBlockingStubSolidity = null; + private static DatabaseBlockingStub databaseBlockingStubPBFT = null; + private static WalletBlockingStub blockingStubFull = null; + private static WalletSolidityBlockingStub blockingStubSolidity = null; + private static WalletSolidityBlockingStub blockingStubPBFT = null; + @ClassRule + public static TemporaryFolder temporaryFolder = new TemporaryFolder(); + private static ByteString ownerAddress; + private static ByteString sk; + private static ByteString ask; + private static ByteString nsk; + private static ByteString ovk; + private static ByteString ak; + private static ByteString nk; + private static ByteString ivk; + private static ByteString d; + + @BeforeClass + public static void init() throws IOException { + Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + String OWNER_ADDRESS = Wallet.getAddressPreFixString() + + "548794500882809695a8a687866e76d4271a1abc"; + getInstance().setRpcEnable(true); + getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + getInstance().setRpcSolidityEnable(true); + getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort()); + getInstance().setRpcPBFTEnable(true); + getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort()); + getInstance().setMetricsPrometheusPort(PublicMethod.chooseRandomPort()); + getInstance().setMetricsPrometheusEnable(true); + getInstance().setP2pDisable(true); + String fullNode = String.format("%s:%d", getInstance().getNodeLanIp(), + getInstance().getRpcPort()); + String solidityNode = String.format("%s:%d", getInstance().getNodeLanIp(), + getInstance().getRpcOnSolidityPort()); + String pBFTNode = String.format("%s:%d", getInstance().getNodeLanIp(), + getInstance().getRpcOnPBFTPort()); + + ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullNode) + .usePlaintext() + .build(); + ManagedChannel channelPBFT = ManagedChannelBuilder.forTarget(pBFTNode) + .usePlaintext() + .build(); + ManagedChannel channelSolidity = ManagedChannelBuilder.forTarget(solidityNode) + .usePlaintext() + .build(); + context = new TronApplicationContext(DefaultConfig.class); + databaseBlockingStubFull = DatabaseGrpc.newBlockingStub(channelFull); + databaseBlockingStubSolidity = DatabaseGrpc.newBlockingStub(channelSolidity); + databaseBlockingStubPBFT = DatabaseGrpc.newBlockingStub(channelPBFT); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); + blockingStubPBFT = WalletSolidityGrpc.newBlockingStub(channelPBFT); + + Manager manager = context.getBean(Manager.class); + + ownerAddress = ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)); + AccountCapsule ownerCapsule = new AccountCapsule(ByteString.copyFromUtf8("owner"), + ownerAddress, Protocol.AccountType.Normal, 10_000_000_000L); + manager.getAccountStore().put(ownerCapsule.createDbKey(), ownerCapsule); + manager.getDynamicPropertiesStore().saveAllowShieldedTransaction(1); + manager.getDynamicPropertiesStore().saveAllowShieldedTRC20Transaction(1); + Application appTest = ApplicationFactory.create(context); + appTest.startup(); + } + + @AfterClass + public static void destroy() { + context.close(); + Args.clearParam(); + } + + @Test + public void testGetBlockByNum() { + NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertNotNull(databaseBlockingStubFull.getBlockByNum(message)); + assertNotNull(databaseBlockingStubSolidity.getBlockByNum(message)); + assertNotNull(databaseBlockingStubPBFT.getBlockByNum(message)); + assertNotNull(blockingStubFull.getBlockByNum(message)); + assertNotNull(blockingStubSolidity.getBlockByNum(message)); + assertNotNull(blockingStubPBFT.getBlockByNum(message)); + + assertNotNull(blockingStubFull.getBlockByNum2(message)); + assertNotNull(blockingStubSolidity.getBlockByNum2(message)); + assertNotNull(blockingStubPBFT.getBlockByNum2(message)); + } + + @Test + public void testGetDynamicProperties() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(databaseBlockingStubFull.getDynamicProperties(message)); + assertNotNull(databaseBlockingStubSolidity.getDynamicProperties(message)); + assertNotNull(databaseBlockingStubPBFT.getDynamicProperties(message)); + } + + @Test + public void testGetAccount() { + Account account = Account.newBuilder().setAddress(ownerAddress).build(); + assertNotNull(blockingStubFull.getAccount(account)); + assertNotNull(blockingStubSolidity.getAccount(account)); + assertNotNull(blockingStubPBFT.getAccount(account)); + } + + @Test + public void testGetAccountById() { + Account account = Account.newBuilder().setAccountId(ownerAddress).build(); + assertNotNull(blockingStubFull.getAccountById(account)); + assertNotNull(blockingStubSolidity.getAccountById(account)); + assertNotNull(blockingStubPBFT.getAccountById(account)); + } + + @Test + public void testListWitnesses() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.listWitnesses(message)); + assertNotNull(blockingStubSolidity.listWitnesses(message)); + assertNotNull(blockingStubPBFT.listWitnesses(message)); + } + + @Test + public void testGetAssetIssueList() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getAssetIssueList(message)); + assertNotNull(blockingStubSolidity.getAssetIssueList(message)); + assertNotNull(blockingStubPBFT.getAssetIssueList(message)); + } + + @Test + public void testGetPaginatedAssetIssueList() { + PaginatedMessage paginatedMessage = PaginatedMessage.newBuilder() + .setOffset(0).setLimit(5).build(); + assertNotNull(blockingStubFull.getPaginatedAssetIssueList(paginatedMessage)); + assertNotNull(blockingStubSolidity.getPaginatedAssetIssueList(paginatedMessage)); + assertNotNull(blockingStubPBFT.getPaginatedAssetIssueList(paginatedMessage)); + } + + @Test + public void testGetAssetIssueByName() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getAssetIssueByName(message)); + assertNotNull(blockingStubSolidity.getAssetIssueByName(message)); + assertNotNull(blockingStubPBFT.getAssetIssueByName(message)); + } + + @Test + public void testGetAssetIssueListByName() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getAssetIssueListByName(message)); + assertNotNull(blockingStubSolidity.getAssetIssueListByName(message)); + assertNotNull(blockingStubPBFT.getAssetIssueListByName(message)); + } + + @Test + public void testGetAssetIssueById() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getAssetIssueById(message)); + assertNotNull(blockingStubSolidity.getAssetIssueById(message)); + assertNotNull(blockingStubPBFT.getAssetIssueById(message)); + } + + @Test + public void testGetBlockReference() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(databaseBlockingStubFull.getBlockReference(message)); + assertNotNull(databaseBlockingStubSolidity.getBlockReference(message)); + assertNotNull(databaseBlockingStubPBFT.getBlockReference(message)); + } + + @Test + public void testGetNowBlock() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(databaseBlockingStubFull.getNowBlock(message)); + assertNotNull(databaseBlockingStubSolidity.getNowBlock(message)); + assertNotNull(databaseBlockingStubPBFT.getNowBlock(message)); + assertNotNull(blockingStubFull.getNowBlock(message)); + assertNotNull(blockingStubSolidity.getNowBlock(message)); + assertNotNull(blockingStubPBFT.getNowBlock(message)); + + assertNotNull(blockingStubFull.getNowBlock2(message)); + assertNotNull(blockingStubSolidity.getNowBlock2(message)); + assertNotNull(blockingStubPBFT.getNowBlock2(message)); + } + + @Test + public void testGetDelegatedResource() { + DelegatedResourceMessage message = DelegatedResourceMessage.newBuilder() + .setFromAddress(ownerAddress) + .setToAddress(ownerAddress).build(); + assertNotNull(blockingStubFull.getDelegatedResource(message)); + assertNotNull(blockingStubSolidity.getDelegatedResource(message)); + assertNotNull(blockingStubPBFT.getDelegatedResource(message)); + + assertNotNull(blockingStubFull.getDelegatedResourceV2(message)); + assertNotNull(blockingStubSolidity.getDelegatedResourceV2(message)); + assertNotNull(blockingStubPBFT.getDelegatedResourceV2(message)); + } + + @Test + public void testGetDelegatedResourceAccountIndex() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getDelegatedResourceAccountIndex(message)); + assertNotNull(blockingStubSolidity.getDelegatedResourceAccountIndex(message)); + assertNotNull(blockingStubPBFT.getDelegatedResourceAccountIndex(message)); + + assertNotNull(blockingStubFull.getDelegatedResourceAccountIndexV2(message)); + assertNotNull(blockingStubSolidity.getDelegatedResourceAccountIndexV2(message)); + assertNotNull(blockingStubPBFT.getDelegatedResourceAccountIndexV2(message)); + } + + @Test + public void testGetCanDelegatedMaxSize() { + CanDelegatedMaxSizeRequestMessage message = CanDelegatedMaxSizeRequestMessage.newBuilder() + .setType(0).setOwnerAddress(ownerAddress).build(); + assertNotNull(blockingStubFull.getCanDelegatedMaxSize(message)); + assertNotNull(blockingStubSolidity.getCanDelegatedMaxSize(message)); + assertNotNull(blockingStubPBFT.getCanDelegatedMaxSize(message)); + } + + @Test + public void testGetAvailableUnfreezeCount() { + GetAvailableUnfreezeCountRequestMessage message = GetAvailableUnfreezeCountRequestMessage + .newBuilder().setOwnerAddress(ownerAddress).build(); + assertNotNull(blockingStubFull.getAvailableUnfreezeCount(message)); + assertNotNull(blockingStubSolidity.getAvailableUnfreezeCount(message)); + assertNotNull(blockingStubPBFT.getAvailableUnfreezeCount(message)); + } + + @Test + public void testGetCanWithdrawUnfreezeAmount() { + CanWithdrawUnfreezeAmountRequestMessage message = CanWithdrawUnfreezeAmountRequestMessage + .newBuilder().setOwnerAddress(ownerAddress).setTimestamp(0).build(); + assertNotNull(blockingStubFull.getCanWithdrawUnfreezeAmount(message)); + assertNotNull(blockingStubSolidity.getCanWithdrawUnfreezeAmount(message)); + assertNotNull(blockingStubPBFT.getCanWithdrawUnfreezeAmount(message)); + } + + @Test + public void testGetExchangeById() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getExchangeById(message)); + assertNotNull(blockingStubSolidity.getExchangeById(message)); + assertNotNull(blockingStubPBFT.getExchangeById(message)); + } + + @Test + public void testListExchanges() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.listExchanges(message)); + assertNotNull(blockingStubSolidity.listExchanges(message)); + assertNotNull(blockingStubPBFT.listExchanges(message)); + } + + @Test + public void testGetTransactionCountByBlockNum() { + NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertNotNull(blockingStubFull.getTransactionCountByBlockNum(message)); + assertNotNull(blockingStubSolidity.getTransactionCountByBlockNum(message)); + assertNotNull(blockingStubPBFT.getTransactionCountByBlockNum(message)); + } + + @Test + public void testListNodes() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.listNodes(message)); + } + + @Test + public void testGetTransactionById() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getTransactionById(message)); + assertNotNull(blockingStubSolidity.getTransactionById(message)); + assertNotNull(blockingStubPBFT.getTransactionById(message)); + } + + @Test + public void testGetTransactionInfoById() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getTransactionInfoById(message)); + assertNotNull(blockingStubSolidity.getTransactionInfoById(message)); + assertNotNull(blockingStubPBFT.getTransactionInfoById(message)); + } + + @Test + public void testGetRewardInfo() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getRewardInfo(message)); + assertNotNull(blockingStubSolidity.getRewardInfo(message)); + assertNotNull(blockingStubPBFT.getRewardInfo(message)); + } + + @Test + public void testGetBrokerageInfo() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getBrokerageInfo(message)); + assertNotNull(blockingStubSolidity.getBrokerageInfo(message)); + assertNotNull(blockingStubPBFT.getBrokerageInfo(message)); + } + + @Test + public void testGetBurnTrx() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getBurnTrx(message)); + assertNotNull(blockingStubSolidity.getBurnTrx(message)); + assertNotNull(blockingStubPBFT.getBurnTrx(message)); + } + + // @Test + // public void testGetMerkleTreeVoucherInfo() { + // OutputPoint outputPoint = OutputPoint.newBuilder().build(); + // OutputPointInfo message = OutputPointInfo.newBuilder() + // .addOutPoints(outputPoint).setBlockNum(0).build(); + // assertNotNull(blockingStubFull.getMerkleTreeVoucherInfo(message)); + // assertNotNull(blockingStubSolidity.getMerkleTreeVoucherInfo(message)); + // assertNotNull(blockingStubPBFT.getMerkleTreeVoucherInfo(message)); + // } + + @Test + public void testScanNoteByIvk() { + IvkDecryptParameters message = IvkDecryptParameters.newBuilder() + .setStartBlockIndex(0) + .setEndBlockIndex(1) + .build(); + assertNotNull(blockingStubFull.scanNoteByIvk(message)); + assertNotNull(blockingStubSolidity.scanNoteByIvk(message)); + assertNotNull(blockingStubPBFT.scanNoteByIvk(message)); + } + + @Test + public void testScanAndMarkNoteByIvk() { + IvkDecryptAndMarkParameters message = IvkDecryptAndMarkParameters.newBuilder() + .setStartBlockIndex(0) + .setEndBlockIndex(1) + .build(); + assertNotNull(blockingStubFull.scanAndMarkNoteByIvk(message)); + assertNotNull(blockingStubSolidity.scanAndMarkNoteByIvk(message)); + assertNotNull(blockingStubPBFT.scanAndMarkNoteByIvk(message)); + } + + @Test + public void test08ScanNoteByOvk() { + OvkDecryptParameters message = OvkDecryptParameters.newBuilder() + .setStartBlockIndex(0) + .setEndBlockIndex(1) + .setOvk(ovk) + .build(); + assertNotNull(blockingStubFull.scanNoteByOvk(message)); + assertNotNull(blockingStubSolidity.scanNoteByOvk(message)); + assertNotNull(blockingStubPBFT.scanNoteByOvk(message)); + } + + // @Test + // public void testIsSpend() { + // NoteParameters message = NoteParameters.newBuilder() + // .build(); + // assertNotNull(blockingStubFull.isSpend(message)); + // assertNotNull(blockingStubSolidity.isSpend(message)); + // assertNotNull(blockingStubPBFT.isSpend(message)); + // } + + @Test + public void testScanShieldedTRC20NotesByIvk() { + IvkDecryptTRC20Parameters message = IvkDecryptTRC20Parameters.newBuilder() + .setStartBlockIndex(1) + .setEndBlockIndex(10) + .build(); + assertNotNull(blockingStubFull.scanShieldedTRC20NotesByIvk(message)); + assertNotNull(blockingStubSolidity.scanShieldedTRC20NotesByIvk(message)); + assertNotNull(blockingStubPBFT.scanShieldedTRC20NotesByIvk(message)); + } + + @Test + public void testScanShieldedTRC20NotesByOvk() { + OvkDecryptTRC20Parameters message = OvkDecryptTRC20Parameters.newBuilder() + .setStartBlockIndex(1) + .setEndBlockIndex(10) + .build(); + assertNotNull(blockingStubFull.scanShieldedTRC20NotesByOvk(message)); + assertNotNull(blockingStubSolidity.scanShieldedTRC20NotesByOvk(message)); + assertNotNull(blockingStubPBFT.scanShieldedTRC20NotesByOvk(message)); + } + + // @Test + // public void testIsShieldedTRC20ContractNoteSpent() { + // NfTRC20Parameters message = NfTRC20Parameters.newBuilder().build(); + // assertNotNull(blockingStubFull.isShieldedTRC20ContractNoteSpent(message)); + // assertNotNull(blockingStubSolidity.isShieldedTRC20ContractNoteSpent(message)); + // assertNotNull(blockingStubPBFT.isShieldedTRC20ContractNoteSpent(message)); + // } + + // @Test + // public void testGetTriggerInputForShieldedTRC20Contract() { + // ShieldedTRC20TriggerContractParameters message = + // ShieldedTRC20TriggerContractParameters.newBuilder() + // .setAmount("1000") + // .build(); + // assertNotNull(blockingStubFull.getTriggerInputForShieldedTRC20Contract(message)); + // } + + @Test + public void testUpdateBrokerage() { + UpdateBrokerageContract message = UpdateBrokerageContract.newBuilder() + .setOwnerAddress(ownerAddress).setBrokerage(1).build(); + assertNotNull(blockingStubFull.updateBrokerage(message)); + } + + @Test + public void testCreateCommonTransaction() { + UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); + updateBrokerageContract.setOwnerAddress( + ByteString.copyFrom(Objects + .requireNonNull(decodeFromBase58Check("TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz")))) + .setBrokerage(10); + Transaction.Builder transaction = Transaction.newBuilder(); + Transaction.raw.Builder raw = Transaction.raw.newBuilder(); + Transaction.Contract.Builder contract = Transaction.Contract.newBuilder(); + contract.setType(Transaction.Contract.ContractType.UpdateBrokerageContract) + .setParameter(Any.pack(updateBrokerageContract.build())); + raw.addContract(contract.build()); + transaction.setRawData(raw.build()); + assertNotNull(blockingStubFull.createCommonTransaction(transaction.build())); + } + + @Test + public void testGetTransactionInfoByBlockNum() { + NumberMessage message = NumberMessage.newBuilder().setNum(1).build(); + assertNotNull(blockingStubFull.getTransactionInfoByBlockNum(message)); + assertNotNull(blockingStubSolidity.getTransactionInfoByBlockNum(message)); + } + + @Test + public void testMarketSellAsset() { + String sellTokenId = "123"; + long sellTokenQuant = 100000000L; + String buyTokenId = "456"; + long buyTokenQuant = 200000000L; + MarketSellAssetContract message = MarketSellAssetContract.newBuilder() + .setOwnerAddress(ownerAddress) + .setBuyTokenQuantity(buyTokenQuant) + .setBuyTokenId(ByteString.copyFrom(buyTokenId.getBytes())) + .setSellTokenQuantity(sellTokenQuant) + .setSellTokenId(ByteString.copyFrom(sellTokenId.getBytes())) + .build(); + assertNotNull(blockingStubFull.marketSellAsset(message)); + } + + @Test + public void testMarketCancelOrder() { + MarketCancelOrderContract message = MarketCancelOrderContract.newBuilder() + .setOwnerAddress(ownerAddress) + .setOrderId(ByteString.copyFromUtf8("123")) + .build(); + assertNotNull(blockingStubFull.marketCancelOrder(message)); + } + + @Test + public void testGetMarketOrderByAccount() { + BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + assertNotNull(blockingStubFull.getMarketOrderByAccount(message)); + assertNotNull(blockingStubSolidity.getMarketOrderByAccount(message)); + assertNotNull(blockingStubPBFT.getMarketOrderByAccount(message)); + } + + // @Test + // public void testGetMarketOrderById() { + // BytesMessage message = BytesMessage.newBuilder().setValue(ownerAddress).build(); + // assertNotNull(blockingStubFull.getMarketOrderById(message)); + // assertNotNull(blockingStubSolidity.getMarketOrderById(message)); + // assertNotNull(blockingStubPBFT.getMarketOrderById(message)); + // } + + @Test + public void testGetMarketPriceByPair() { + MarketOrderPair marketOrderPair = getMarketOrderPair(); + assertNotNull(blockingStubFull.getMarketPriceByPair(marketOrderPair)); + assertNotNull(blockingStubSolidity.getMarketPriceByPair(marketOrderPair)); + assertNotNull(blockingStubPBFT.getMarketPriceByPair(marketOrderPair)); + } + + @Test + public void testGetMarketOrderListByPair() { + MarketOrderPair marketOrderPair = getMarketOrderPair(); + assertNotNull(blockingStubFull.getMarketOrderListByPair(marketOrderPair)); + assertNotNull(blockingStubSolidity.getMarketOrderListByPair(marketOrderPair)); + assertNotNull(blockingStubPBFT.getMarketOrderListByPair(marketOrderPair)); + } + + private static MarketOrderPair getMarketOrderPair() { + ByteString buyTokenId = ByteString.copyFrom(Objects + .requireNonNull(ByteArray.fromString("_"))); + ByteString sellTokenId = ByteString.copyFrom(Objects + .requireNonNull(ByteArray.fromString("_"))); + return MarketOrderPair.newBuilder() + .setBuyTokenId(buyTokenId) + .setSellTokenId(sellTokenId).build(); + } + + @Test + public void testGetMarketPairList() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getMarketPairList(message)); + assertNotNull(blockingStubSolidity.getMarketPairList(message)); + assertNotNull(blockingStubPBFT.getMarketPairList(message)); + } + + @Test + public void testGetTransactionFromPending() { + BalanceContract.TransferContract tc = + BalanceContract.TransferContract.newBuilder() + .setAmount(10) + .setOwnerAddress(ByteString.copyFromUtf8("aaa")) + .setToAddress(ByteString.copyFromUtf8("bbb")) + .build(); + TransactionCapsule trx = new TransactionCapsule(tc, TransferContract); + BytesMessage message = BytesMessage.newBuilder() + .setValue(trx.getTransactionId().getByteString()).build(); + assertNotNull(blockingStubFull.getTransactionFromPending(message)); + } + + @Test + public void testGetTransactionListFromPending() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getTransactionListFromPending(message)); + } + + @Test + public void testGetPendingSize() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getPendingSize(message)); + } + + @Test + public void testGetBlock() { + BlockReq message = BlockReq.newBuilder().setIdOrNum("0").build(); + assertNotNull(blockingStubFull.getBlock(message)); + assertNotNull(blockingStubSolidity.getBlock(message)); + assertNotNull(blockingStubPBFT.getBlock(message)); + } + + @Test + public void testGetAccountBalance() { + AccountIdentifier accountIdentifier = AccountIdentifier.newBuilder() + .setAddress(ownerAddress).build(); + BlockIdentifier blockIdentifier = getBlockIdentifier(); + AccountBalanceRequest message = AccountBalanceRequest.newBuilder() + .setAccountIdentifier(accountIdentifier) + .setBlockIdentifier(blockIdentifier) + .build(); + assertNotNull(blockingStubFull.getAccountBalance(message)); + } + + @Test + public void testGetBlockBalanceTrace() { + BlockIdentifier blockIdentifier = getBlockIdentifier(); + assertNotNull(blockingStubFull.getBlockBalanceTrace(blockIdentifier)); + } + + private static BlockIdentifier getBlockIdentifier() { + Block nowBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); + raw rawData = nowBlock.getBlockHeader().getRawData(); + BlockCapsule.BlockId blockId = + new BlockCapsule.BlockId(Sha256Hash.of(getInstance().isECKeyCryptoEngine(), + rawData.toByteArray()), + rawData.getNumber()); + return BlockIdentifier.newBuilder() + .setNumber(rawData.getNumber()) + .setHash(blockId.getByteString()) + .build(); + } + + @Test + public void testCreateTransaction() { + BalanceContract.TransferContract transferContract = BalanceContract.TransferContract + .newBuilder() + .setOwnerAddress(ownerAddress) + .setToAddress(ownerAddress) + .setAmount(1000) + .build(); + assertNotNull(blockingStubFull.createTransaction(transferContract)); + assertNotNull(blockingStubFull.createTransaction2(transferContract)); + } + + @Test + public void testGetTransactionSignWeight() { + UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); + updateBrokerageContract.setOwnerAddress( + ByteString.copyFrom(Objects + .requireNonNull(decodeFromBase58Check("TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz")))) + .setBrokerage(10); + Transaction.Builder transaction = Transaction.newBuilder(); + Transaction.raw.Builder raw = Transaction.raw.newBuilder(); + Transaction.Contract.Builder contract = Transaction.Contract.newBuilder(); + contract.setType(Transaction.Contract.ContractType.UpdateBrokerageContract) + .setParameter(Any.pack(updateBrokerageContract.build())); + raw.addContract(contract.build()); + transaction.setRawData(raw.build()); + assertNotNull(blockingStubFull.getTransactionSignWeight(transaction.build())); + } + + @Test + public void testGetTransactionApprovedList() { + UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); + updateBrokerageContract.setOwnerAddress( + ByteString.copyFrom(Objects + .requireNonNull(decodeFromBase58Check("TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz")))) + .setBrokerage(10); + Transaction.Builder transaction = Transaction.newBuilder(); + Transaction.raw.Builder raw = Transaction.raw.newBuilder(); + Transaction.Contract.Builder contract = Transaction.Contract.newBuilder(); + contract.setType(Transaction.Contract.ContractType.UpdateBrokerageContract) + .setParameter(Any.pack(updateBrokerageContract.build())); + raw.addContract(contract.build()); + transaction.setRawData(raw.build()); + assertNotNull(blockingStubFull.getTransactionApprovedList(transaction.build())); + } + + @Test + public void testCreateAssetIssue() { + AssetIssueContract assetIssueContract = AssetIssueContract.newBuilder() + .build(); + assertNotNull(blockingStubFull.createAssetIssue(assetIssueContract)); + assertNotNull(blockingStubFull.createAssetIssue2(assetIssueContract)); + } + + @Test + public void testUnfreezeAsset() { + UnfreezeAssetContract message = UnfreezeAssetContract.newBuilder().build(); + assertNotNull(blockingStubFull.unfreezeAsset(message)); + assertNotNull(blockingStubFull.unfreezeAsset2(message)); + } + + @Test + public void testVoteWitnessAccount() { + VoteWitnessContract message = VoteWitnessContract.newBuilder().build(); + assertNotNull(blockingStubFull.voteWitnessAccount(message)); + assertNotNull(blockingStubFull.voteWitnessAccount2(message)); + } + + @Test + public void testUpdateSetting() { + UpdateSettingContract message = UpdateSettingContract.newBuilder().build(); + assertNotNull(blockingStubFull.updateSetting(message)); + } + + @Test + public void testUpdateEnergyLimit() { + UpdateEnergyLimitContract message = UpdateEnergyLimitContract.newBuilder().build(); + assertNotNull(blockingStubFull.updateEnergyLimit(message)); + } + + @Test + public void testClearContractABI() { + ClearABIContract message = ClearABIContract.newBuilder().build(); + assertNotNull(blockingStubFull.clearContractABI(message)); + } + + @Test + public void testCreateWitness() { + WitnessCreateContract message = WitnessCreateContract.newBuilder().build(); + assertNotNull(blockingStubFull.createWitness(message)); + assertNotNull(blockingStubFull.createWitness2(message)); + } + + @Test + public void testCreateAccount() { + AccountCreateContract message = AccountCreateContract.newBuilder().build(); + assertNotNull(blockingStubFull.createAccount(message)); + assertNotNull(blockingStubFull.createAccount2(message)); + } + + @Test + public void testUpdateWitness() { + WitnessUpdateContract message = WitnessUpdateContract.newBuilder().build(); + assertNotNull(blockingStubFull.updateWitness(message)); + assertNotNull(blockingStubFull.updateWitness2(message)); + } + + @Test + public void testUpdateAccount() { + AccountUpdateContract message = AccountUpdateContract.newBuilder().build(); + assertNotNull(blockingStubFull.updateAccount(message)); + assertNotNull(blockingStubFull.updateAccount2(message)); + } + + @Test + public void testSetAccountId() { + SetAccountIdContract message = SetAccountIdContract.newBuilder().build(); + assertNotNull(blockingStubFull.setAccountId(message)); + } + + @Test + public void testUpdateAsset() { + UpdateAssetContract message = UpdateAssetContract.newBuilder().build(); + assertNotNull(blockingStubFull.updateAsset(message)); + assertNotNull(blockingStubFull.updateAsset2(message)); + } + + @Test + public void testFreezeBalance2() { + FreezeBalanceContract message = FreezeBalanceContract.newBuilder().build(); + assertNotNull(blockingStubFull.freezeBalance(message)); + assertNotNull(blockingStubFull.freezeBalance2(message)); + } + + @Test + public void testFreezeBalanceV2() { + FreezeBalanceV2Contract message = FreezeBalanceV2Contract.newBuilder().build(); + assertNotNull(blockingStubFull.freezeBalanceV2(message)); + } + + @Test + public void testUnfreezeBalance() { + UnfreezeBalanceContract message = UnfreezeBalanceContract.newBuilder().build(); + assertNotNull(blockingStubFull.unfreezeBalance(message)); + assertNotNull(blockingStubFull.unfreezeBalance2(message)); + } + + @Test + public void testUnfreezeBalanceV2() { + UnfreezeBalanceV2Contract message = UnfreezeBalanceV2Contract.newBuilder().build(); + assertNotNull(blockingStubFull.unfreezeBalanceV2(message)); + } + + @Test + public void testWithdrawBalance() { + WithdrawBalanceContract message = WithdrawBalanceContract.newBuilder().build(); + assertNotNull(blockingStubFull.withdrawBalance(message)); + assertNotNull(blockingStubFull.withdrawBalance2(message)); + } + + @Test + public void testWithdrawExpireUnfreeze() { + WithdrawExpireUnfreezeContract message = WithdrawExpireUnfreezeContract.newBuilder().build(); + assertNotNull(blockingStubFull.withdrawExpireUnfreeze(message)); + } + + @Test + public void testDelegateResource() { + DelegateResourceContract message = DelegateResourceContract.newBuilder().build(); + assertNotNull(blockingStubFull.delegateResource(message)); + } + + @Test + public void testUnDelegateResource() { + UnDelegateResourceContract message = UnDelegateResourceContract.newBuilder().build(); + assertNotNull(blockingStubFull.unDelegateResource(message)); + } + + @Test + public void testCancelAllUnfreezeV2() { + CancelAllUnfreezeV2Contract message = CancelAllUnfreezeV2Contract.newBuilder().build(); + assertNotNull(blockingStubFull.cancelAllUnfreezeV2(message)); + } + + @Test + public void testProposalCreate() { + ProposalCreateContract message = ProposalCreateContract.newBuilder().build(); + assertNotNull(blockingStubFull.proposalCreate(message)); + } + + @Test + public void testProposalApprove() { + ProposalApproveContract message = ProposalApproveContract.newBuilder().build(); + assertNotNull(blockingStubFull.proposalApprove(message)); + } + + @Test + public void testProposalDelete() { + ProposalDeleteContract message = ProposalDeleteContract.newBuilder().build(); + assertNotNull(blockingStubFull.proposalDelete(message)); + } + + @Test + public void testExchangeCreate() { + ExchangeCreateContract message = ExchangeCreateContract.newBuilder().build(); + assertNotNull(blockingStubFull.exchangeCreate(message)); + } + + @Test + public void testExchangeInject() { + ExchangeInjectContract message = ExchangeInjectContract.newBuilder().build(); + assertNotNull(blockingStubFull.exchangeInject(message)); + } + + @Test + public void testExchangeWithdraw() { + ExchangeWithdrawContract message = ExchangeWithdrawContract.newBuilder().build(); + assertNotNull(blockingStubFull.exchangeWithdraw(message)); + } + + @Test + public void testExchangeTransaction() { + ExchangeTransactionContract message = ExchangeTransactionContract.newBuilder().build(); + assertNotNull(blockingStubFull.exchangeTransaction(message)); + } + + @Test + public void testTransferAsset() { + TransferAssetContract message = TransferAssetContract.newBuilder().build(); + assertNotNull(blockingStubFull.transferAsset(message)); + assertNotNull(blockingStubFull.transferAsset2(message)); + } + + @Test + public void testParticipateAssetIssue() { + ParticipateAssetIssueContract message = ParticipateAssetIssueContract.newBuilder().build(); + assertNotNull(blockingStubFull.participateAssetIssue(message)); + assertNotNull(blockingStubFull.participateAssetIssue2(message)); + } + + @Test + public void testGetAssetIssueByAccount() { + Account message = Account.newBuilder().build(); + assertNotNull(blockingStubFull.getAssetIssueByAccount(message)); + } + + @Test + public void testGetAccountNet() { + Account message = Account.newBuilder().build(); + assertNotNull(blockingStubFull.getAccountNet(message)); + } + + @Test + public void testGetAccountResource() { + Account message = Account.newBuilder().build(); + assertNotNull(blockingStubFull.getAccountResource(message)); + } + + @Test + public void testGetBlockById() { + BytesMessage message = BytesMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getBlockById(message)); + } + + @Test + public void testGetProposalById() { + BytesMessage message = BytesMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getProposalById(message)); + } + + @Test + public void testGetBlockByLimitNext() { + BlockLimit message = BlockLimit.newBuilder().build(); + assertNotNull(blockingStubFull.getBlockByLimitNext(message)); + assertNotNull(blockingStubFull.getBlockByLimitNext2(message)); + } + + @Test + public void testGetBlockByLatestNum() { + NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertNotNull(blockingStubFull.getBlockByLatestNum(message)); + assertNotNull(blockingStubFull.getBlockByLatestNum2(message)); + } + + @Test + public void testDeployContract() { + CreateSmartContract message = CreateSmartContract.newBuilder().build(); + assertNotNull(blockingStubFull.deployContract(message)); + } + + @Test + public void testTotalTransaction() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.totalTransaction(message)); + } + + @Test + public void testGetNextMaintenanceTime() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getNextMaintenanceTime(message)); + } + + @Test + public void testTriggerContract() { + TriggerSmartContract message = TriggerSmartContract.newBuilder().build(); + assertNotNull(blockingStubFull.estimateEnergy(message)); + assertNotNull(blockingStubSolidity.estimateEnergy(message)); + assertNotNull(blockingStubPBFT.estimateEnergy(message)); + } + + @Test + public void testEstimateEnergy() { + TriggerSmartContract message = TriggerSmartContract.newBuilder().build(); + assertNotNull(blockingStubFull.estimateEnergy(message)); + } + + @Test + public void testTriggerConstantContract() { + TriggerSmartContract message = TriggerSmartContract.newBuilder().build(); + assertNotNull(blockingStubFull.triggerConstantContract(message)); + } + + @Test + public void testGetContract() { + BytesMessage message = BytesMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getContract(message)); + } + + @Test + public void testGetContractInfo() { + BytesMessage message = BytesMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getContractInfo(message)); + } + + @Test + public void testListProposals() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.listProposals(message)); + } + + @Test + public void testGetBandwidthPrices() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getBandwidthPrices(message)); + assertNotNull(blockingStubSolidity.getBandwidthPrices(message)); + assertNotNull(blockingStubPBFT.getBandwidthPrices(message)); + } + + @Test + public void testGetEnergyPrices() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getEnergyPrices(message)); + assertNotNull(blockingStubSolidity.getEnergyPrices(message)); + assertNotNull(blockingStubPBFT.getEnergyPrices(message)); + } + + @Test + public void testGetMemoFee() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getMemoFee(message)); + } + + @Test + public void testGetPaginatedProposalList() { + PaginatedMessage message = PaginatedMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getPaginatedProposalList(message)); + } + + @Test + public void testGetPaginatedExchangeList() { + PaginatedMessage message = PaginatedMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getPaginatedExchangeList(message)); + } + + @Test + public void testGetChainParameters() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getChainParameters(message)); + } + + @Test + public void testGetNodeInfo() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getNodeInfo(message)); + } + + @Test + public void testAccountPermissionUpdate() { + AccountPermissionUpdateContract message = AccountPermissionUpdateContract.newBuilder().build(); + assertNotNull(blockingStubFull.accountPermissionUpdate(message)); + } + + @Test + public void testCreateShieldedTransaction() { + PrivateParameters message = PrivateParameters.newBuilder().build(); + assertNotNull(blockingStubFull.createShieldedTransaction(message)); + } + + @Test + public void testCreateShieldedTransactionWithoutSpendAuthSig() { + PrivateParametersWithoutAsk message = PrivateParametersWithoutAsk.newBuilder().build(); + assertNotNull(blockingStubFull.createShieldedTransactionWithoutSpendAuthSig(message)); + } + + @Test + public void testGetNewShieldedAddress() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getNewShieldedAddress(message)); + } + + @Test + public void test01GetSpendingKey() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + BytesMessage spendingKey = blockingStubFull.getSpendingKey(message); + assertNotNull(spendingKey); + sk = spendingKey.getValue(); + } + + @Test + public void testGetRcm() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getRcm(message)); + } + + @Test + public void test02GetExpandedSpendingKey() { + BytesMessage message = BytesMessage.newBuilder().setValue(sk).build(); + ExpandedSpendingKeyMessage eskMessage = blockingStubFull.getExpandedSpendingKey(message); + assertNotNull(eskMessage); + ask = eskMessage.getAsk(); + nsk = eskMessage.getNsk(); + ovk = eskMessage.getOvk(); + } + + @Test + public void test03GetAkFromAsk() { + BytesMessage message = BytesMessage.newBuilder().setValue(ask).build(); + BytesMessage akMessage = blockingStubFull.getAkFromAsk(message); + assertNotNull(akMessage); + ak = akMessage.getValue(); + } + + @Test + public void test04GetNkFromNsk() { + BytesMessage message = BytesMessage.newBuilder().setValue(nsk).build(); + BytesMessage nkFromNsk = blockingStubFull.getNkFromNsk(message); + assertNotNull(nkFromNsk); + nk = nkFromNsk.getValue(); + } + + @Test + public void test05GetIncomingViewingKey() { + ViewingKeyMessage viewingKeyMessage = ViewingKeyMessage.newBuilder() + .setAk(ak) + .setNk(nk) + .build(); + IncomingViewingKeyMessage incomingViewingKey = blockingStubFull + .getIncomingViewingKey(viewingKeyMessage); + assertNotNull(incomingViewingKey); + ivk = incomingViewingKey.getIvk(); + } + + @Test + public void test06GetDiversifier() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + DiversifierMessage diversifier = blockingStubFull.getDiversifier(message); + assertNotNull(diversifier); + d = diversifier.getD(); + } + + @Test + public void test07GetZenPaymentAddress() { + DiversifierMessage diversifierMessage = DiversifierMessage.newBuilder().setD(d).build(); + IncomingViewingKeyMessage incomingViewingKey = IncomingViewingKeyMessage.newBuilder() + .setIvk(ivk).build(); + IncomingViewingKeyDiversifierMessage message = IncomingViewingKeyDiversifierMessage + .newBuilder() + .setD(diversifierMessage) + .setIvk(incomingViewingKey) + .build(); + assertNotNull(blockingStubFull.getZenPaymentAddress(message)); + } + + // @Test + // public void testCreateShieldNullifier() { + // NfParameters message = NfParameters + // .newBuilder().build(); + // assertNotNull(blockingStubFull.createShieldNullifier(message)); + // } + + // @Test + // public void testCreateSpendAuthSig() { + // SpendAuthSigParameters message = SpendAuthSigParameters + // .newBuilder().build(); + // assertNotNull(blockingStubFull.createSpendAuthSig(message)); + // } + + // @Test + // public void testGetShieldTransactionHash() { + // Transaction message = Transaction + // .newBuilder().build(); + // assertNotNull(blockingStubFull.getShieldTransactionHash(message)); + // } + + // @Test + // public void testCreateShieldedContractParameters() { + // PrivateShieldedTRC20Parameters message = PrivateShieldedTRC20Parameters + // .newBuilder().build(); + // assertNotNull(blockingStubFull.createShieldedContractParameters(message)); + // } + + // @Test + // public void testCreateShieldedContractParametersWithoutAsk() throws ZksnarkException { + // SpendingKey sk = SpendingKey.random(); + // ExpandedSpendingKey expsk = sk.expandedSpendingKey(); + // byte[] ovk = expsk.getOvk(); + // PrivateShieldedTRC20ParametersWithoutAsk message = PrivateShieldedTRC20ParametersWithoutAsk + // .newBuilder() + // .setOvk(ByteString.copyFrom(ovk)) + // .setFromAmount(BigInteger.valueOf(50).toString()) + // .setShieldedTRC20ContractAddress(ownerAddress) + // .build(); + // assertNotNull(blockingStubFull + // .createShieldedContractParametersWithoutAsk(message)); + // } +} diff --git a/framework/src/test/java/org/tron/core/services/WalletApiTest.java b/framework/src/test/java/org/tron/core/services/WalletApiTest.java new file mode 100644 index 00000000000..8890d4bfd9e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/WalletApiTest.java @@ -0,0 +1,62 @@ +package org.tron.core.services; + +import io.grpc.ManagedChannelBuilder; +import java.io.IOException; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.api.GrpcAPI.EmptyMessage; +import org.tron.api.WalletGrpc; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.utils.PublicMethod; +import org.tron.core.Constant; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; + + +@Slf4j +public class WalletApiTest { + + @ClassRule + public static TemporaryFolder temporaryFolder = new TemporaryFolder(); + + private static TronApplicationContext context; + private static Application appT; + + + @BeforeClass + public static void init() throws IOException { + Args.setParam(new String[]{ "-d", temporaryFolder.newFolder().toString(), + "--p2p-disable", "true"}, Constant.TEST_CONF); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcEnable(true); + context = new TronApplicationContext(DefaultConfig.class); + appT = ApplicationFactory.create(context); + appT.startup(); + } + + @Test + public void listNodesTest() { + String fullNode = String.format("%s:%d", "127.0.0.1", + Args.getInstance().getRpcPort()); + WalletGrpc.WalletBlockingStub walletStub = WalletGrpc + .newBlockingStub(ManagedChannelBuilder.forTarget(fullNode) + .usePlaintext() + .build()); + Assert.assertTrue(walletStub.listNodes(EmptyMessage.getDefaultInstance()) + .getNodesList().isEmpty()); + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java b/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java index 4a288b4402c..420d890aa48 100644 --- a/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/HttpApiAccessFilterTest.java @@ -1,86 +1,56 @@ package org.tron.core.services.filter; import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.annotation.Resource; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.services.interfaceOnPBFT.http.PBFT.HttpApiOnPBFTService; import org.tron.core.services.interfaceOnSolidity.http.solidity.HttpApiOnSolidityService; -public class HttpApiAccessFilterTest { +public class HttpApiAccessFilterTest extends BaseTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); + @Resource + private FullNodeHttpApiService httpApiService; + @Resource + private HttpApiOnSolidityService httpApiOnSolidityService; + @Resource + private HttpApiOnPBFTService httpApiOnPBFTService; + @Resource + private HttpApiAccessFilter httpApiAccessFilter; + private static final CloseableHttpClient httpClient = HttpClients.createDefault(); - private static TronApplicationContext context; - private static Application appTest; - private static CloseableHttpClient httpClient = HttpClients.createDefault(); - private static String dbPath = "output_http_api_access_filter_test"; - - /** - * init dependencies. - */ - @BeforeClass - public static void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); - context = new TronApplicationContext(DefaultConfig.class); - appTest = ApplicationFactory.create(context); - - FullNodeHttpApiService httpApiService = context - .getBean(FullNodeHttpApiService.class); - HttpApiOnSolidityService httpApiOnSolidityService = context - .getBean(HttpApiOnSolidityService.class); - HttpApiOnPBFTService httpApiOnPBFTService = context - .getBean(HttpApiOnPBFTService.class); - - appTest.addService(httpApiService); - appTest.addService(httpApiOnSolidityService); - appTest.addService(httpApiOnPBFTService); - appTest.initServices(Args.getInstance()); - appTest.startServices(); - appTest.startup(); - } - - /** - * destroy the context. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.getInstance().setFullNodeHttpEnable(true); + Args.getInstance().setFullNodeHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setPBFTHttpEnable(true); + Args.getInstance().setPBFTHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setSolidityNodeHttpEnable(true); + Args.getInstance().setSolidityHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setP2pDisable(true); } @Test public void testHttpFilter() { + appT.startup(); List disabledApiList = new ArrayList<>(); disabledApiList.add("getaccount"); disabledApiList.add("getnowblock"); @@ -113,7 +83,7 @@ public void testHttpFilter() { response); Args.getInstance().setDisabledApiList(emptyList); - int statusCode = getReuqestCode(url); + int statusCode = getRequestCode(url); Assert.assertEquals(HttpStatus.SC_OK, statusCode); } } @@ -122,12 +92,12 @@ public void testHttpFilter() { private String sendGetRequest(String url) { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Java client"); - HttpResponse response = null; + HttpResponse response; try { response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); @@ -139,10 +109,10 @@ private String sendGetRequest(String url) { return null; } - private int getReuqestCode(String url) { + private int getRequestCode(String url) { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Java client"); - HttpResponse response = null; + HttpResponse response; try { response = httpClient.execute(request); @@ -153,4 +123,31 @@ private int getReuqestCode(String url) { return 0; } + + @Test + public void testIsDisabled() throws Exception { + List list = new ArrayList<>(); + list.add("getnowblock"); + CommonParameter.getInstance().setDisabledApiList(list); + Method privateMethod = httpApiAccessFilter.getClass() + .getDeclaredMethod("isDisabled", String.class); + privateMethod.setAccessible(true); + + String url = "/wallet/getnowblock"; + boolean f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertTrue(f); + + url = "/wallet/a/../b/../getnowblock"; + f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertTrue(f); + + url = "/wallet/a/b/../getnowblock"; + f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertFalse(f); + + url = "/wallet/getblock"; + f = (boolean) privateMethod.invoke(httpApiAccessFilter,url); + Assert.assertFalse(f); + } + } diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java index 472096cf24b..84869ea0750 100644 --- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryGrpcInterceptorTest.java @@ -3,23 +3,25 @@ import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; -import java.io.File; -import org.junit.After; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.DatabaseGrpc; +import org.junit.rules.TemporaryFolder; import org.tron.api.GrpcAPI; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.core.ChainBaseManager; import org.tron.core.Constant; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; @@ -27,99 +29,113 @@ import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; +@Slf4j public class LiteFnQueryGrpcInterceptorTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - - private TronApplicationContext context; - private ManagedChannel channelFull = null; - private ManagedChannel channelpBFT = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubpBFT = null; - private DatabaseGrpc.DatabaseBlockingStub databaseBlockingStub = null; - private RpcApiService rpcApiService; - private RpcApiServiceOnSolidity rpcApiServiceOnSolidity; - private RpcApiServiceOnPBFT rpcApiServiceOnPBFT; - private Application appTest; - - private String dbPath = "output_grpc_filter_test"; + private static TronApplicationContext context; + private static ManagedChannel channelFull = null; + private static ManagedChannel channelSolidity = null; + private static ManagedChannel channelpBFT = null; + private static WalletGrpc.WalletBlockingStub blockingStubFull = null; + private static WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; + private static WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubpBFT = null; + private static ChainBaseManager chainBaseManager; + private static final String ERROR_MSG = + "UNAVAILABLE: this API is closed because this node is a lite fullnode"; @Rule public ExpectedException thrown = ExpectedException.none(); + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + /** * init logic. */ - @Before - public void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - String fullnode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), + @BeforeClass + public static void init() throws IOException { + Args.setParam(new String[]{"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + Args.getInstance().setRpcEnable(true); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcSolidityEnable(true); + Args.getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcPBFTEnable(true); + Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setP2pDisable(true); + String fullnode = String.format("%s:%d", Args.getInstance().getNodeLanIp(), Args.getInstance().getRpcPort()); - String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), - Args.getInstance().getRpcOnPBFTPort()); + String solidityNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(), + Args.getInstance().getRpcOnSolidityPort()); + String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(), + Args.getInstance().getRpcOnPBFTPort()); channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) + .usePlaintext() .build(); + channelSolidity = ManagedChannelBuilder.forTarget(solidityNode) + .usePlaintext() + .build(); channelpBFT = ManagedChannelBuilder.forTarget(pBFTNode) - .usePlaintext(true) + .usePlaintext() .build(); context = new TronApplicationContext(DefaultConfig.class); + context.registerShutdownHook(); blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull); + blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); blockingStubpBFT = WalletSolidityGrpc.newBlockingStub(channelpBFT); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull); - databaseBlockingStub = DatabaseGrpc.newBlockingStub(channelFull); - rpcApiService = context.getBean(RpcApiService.class); - rpcApiServiceOnSolidity = context.getBean(RpcApiServiceOnSolidity.class); - rpcApiServiceOnPBFT = context.getBean(RpcApiServiceOnPBFT.class); - appTest = ApplicationFactory.create(context); - appTest.addService(rpcApiService); - appTest.addService(rpcApiServiceOnSolidity); - appTest.addService(rpcApiServiceOnPBFT); - appTest.initServices(Args.getInstance()); - appTest.startServices(); + chainBaseManager = context.getBean(ChainBaseManager.class); + Application appTest = ApplicationFactory.create(context); appTest.startup(); } /** * destroy the context. */ - @After - public void destroy() { - Args.clearParam(); - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); + @AfterClass + public static void destroy() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + if (channelSolidity != null) { + channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + if (channelpBFT != null) { + channelpBFT.shutdown().awaitTermination(5, TimeUnit.SECONDS); } + context.close(); + Args.clearParam(); } @Test public void testGrpcApiThrowStatusRuntimeException() { final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - Args.getInstance().setLiteFullNode(true); + chainBaseManager.setNodeType(ChainBaseManager.NodeType.LITE); thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("UNAVAILABLE: this API is closed because this node is a lite fullnode"); + thrown.expectMessage(ERROR_MSG); blockingStubFull.getBlockByNum(message); } + @Test + public void testGrpcSolidityThrowStatusRuntimeException() { + final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); + chainBaseManager.setNodeType(ChainBaseManager.NodeType.LITE); + thrown.expect(StatusRuntimeException.class); + thrown.expectMessage(ERROR_MSG); + blockingStubSolidity.getBlockByNum(message); + } + @Test public void testpBFTGrpcApiThrowStatusRuntimeException() { final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - Args.getInstance().setLiteFullNode(true); + chainBaseManager.setNodeType(ChainBaseManager.NodeType.LITE); thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("UNAVAILABLE: this API is closed because this node is a lite fullnode"); + thrown.expectMessage(ERROR_MSG); blockingStubpBFT.getBlockByNum(message); } @Test public void testGrpcInterceptor() { GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - Args.getInstance().setLiteFullNode(false); + chainBaseManager.setNodeType(ChainBaseManager.NodeType.FULL); Assert.assertNotNull(blockingStubFull.getBlockByNum(message)); } } diff --git a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java index d1d294475c9..0f0bdf1eb1f 100644 --- a/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/LiteFnQueryHttpFilterTest.java @@ -1,84 +1,58 @@ package org.tron.core.services.filter; +import static org.tron.core.ChainBaseManager.NodeType.FULL; +import static org.tron.core.ChainBaseManager.NodeType.LITE; + import java.io.BufferedReader; -import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.Set; +import lombok.extern.slf4j.Slf4j; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.junit.After; import org.junit.Assert; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.BaseTest; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.services.http.FullNodeHttpApiService; -import org.tron.core.services.interfaceOnPBFT.http.PBFT.HttpApiOnPBFTService; -import org.tron.core.services.interfaceOnSolidity.http.solidity.HttpApiOnSolidityService; - -public class LiteFnQueryHttpFilterTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); +@Slf4j +public class LiteFnQueryHttpFilterTest extends BaseTest { - private TronApplicationContext context; - private String ip = "127.0.0.1"; + private final String ip = "127.0.0.1"; private int fullHttpPort; - private Application appTest; - private CloseableHttpClient httpClient = HttpClients.createDefault(); + private final CloseableHttpClient httpClient = HttpClients.createDefault(); - private String dbPath = "output_grpc_filter_test"; + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); + Args.getInstance().setRpcEnable(false); + Args.getInstance().setRpcSolidityEnable(false); + Args.getInstance().setRpcPBFTEnable(false); + Args.getInstance().setFullNodeHttpEnable(true); + Args.getInstance().setFullNodeHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setPBFTHttpEnable(true); + Args.getInstance().setPBFTHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setSolidityNodeHttpEnable(true); + Args.getInstance().setSolidityHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setJsonRpcHttpFullNodeEnable(false); + Args.getInstance().setJsonRpcHttpSolidityNodeEnable(false); + Args.getInstance().setJsonRpcHttpPBFTNodeEnable(false); + Args.getInstance().setP2pDisable(true); + } /** * init dependencies. */ @Before public void init() { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - Args.getInstance().setFullNodeAllowShieldedTransactionArgs(false); - context = new TronApplicationContext(DefaultConfig.class); - appTest = ApplicationFactory.create(context); - FullNodeHttpApiService httpApiService = context - .getBean(FullNodeHttpApiService.class); - HttpApiOnSolidityService httpApiOnSolidityService = context - .getBean(HttpApiOnSolidityService.class); - HttpApiOnPBFTService httpApiOnPBFTService = context - .getBean(HttpApiOnPBFTService.class); - appTest.addService(httpApiService); - appTest.addService(httpApiOnSolidityService); - appTest.addService(httpApiOnPBFTService); - appTest.initServices(Args.getInstance()); - appTest.startServices(); - appTest.startup(); - } - - /** - * destroy the context. - */ - @After - public void destroy() { - Args.clearParam(); - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + appT.startup(); } @Test @@ -94,21 +68,20 @@ public void testHttpFilter() { } String url = String.format("http://%s:%d%s", ip, fullHttpPort, urlPath); // test lite fullnode with history query closed - Args.getInstance().setLiteFullNode(true); + chainBaseManager.setNodeType(LITE); Args.getInstance().setOpenHistoryQueryWhenLiteFN(false); String response = sendGetRequest(url); - Assert.assertEquals("this API is closed because this node is a lite fullnode", - response); + logger.info("response:{}", response); // test lite fullnode with history query opened - Args.getInstance().setLiteFullNode(false); + chainBaseManager.setNodeType(FULL); Args.getInstance().setOpenHistoryQueryWhenLiteFN(true); response = sendGetRequest(url); Assert.assertNotEquals("this API is closed because this node is a lite fullnode", response); // test normal fullnode - Args.getInstance().setLiteFullNode(false); + chainBaseManager.setNodeType(FULL); Args.getInstance().setOpenHistoryQueryWhenLiteFN(true); response = sendGetRequest(url); Assert.assertNotEquals("this API is closed because this node is a lite fullnode", @@ -120,12 +93,12 @@ public void testHttpFilter() { private String sendGetRequest(String url) { HttpGet request = new HttpGet(url); request.setHeader("User-Agent", "Java client"); - HttpResponse response = null; + HttpResponse response; try { response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); @@ -145,7 +118,7 @@ private String sendPostRequest(String url, String body) throws IOException { HttpResponse response = httpClient.execute(request); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); diff --git a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java index c3ef7265f65..900ca304e7d 100644 --- a/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java +++ b/framework/src/test/java/org/tron/core/services/filter/RpcApiAccessInterceptorTest.java @@ -1,67 +1,79 @@ package org.tron.core.services.filter; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.StatusRuntimeException; -import java.io.File; +import io.grpc.stub.ServerCallStreamObserver; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.Objects; +import lombok.extern.slf4j.Slf4j; import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; -import org.junit.Rule; +import org.junit.ClassRule; import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.GrpcAPI; +import org.junit.rules.TemporaryFolder; +import org.tron.api.GrpcAPI.BlockExtention; +import org.tron.api.GrpcAPI.BlockReq; +import org.tron.api.GrpcAPI.BytesMessage; +import org.tron.api.GrpcAPI.EmptyMessage; +import org.tron.api.GrpcAPI.NumberMessage; +import org.tron.api.GrpcAPI.TransactionIdList; import org.tron.api.WalletGrpc; import org.tron.api.WalletSolidityGrpc; import org.tron.common.application.Application; import org.tron.common.application.ApplicationFactory; import org.tron.common.application.TronApplicationContext; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.core.Constant; import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; import org.tron.core.services.interfaceOnPBFT.RpcApiServiceOnPBFT; import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; +import org.tron.protos.Protocol.Transaction; +@Slf4j public class RpcApiAccessInterceptorTest { - private static final Logger logger = LoggerFactory.getLogger("Test"); - private static TronApplicationContext context; - private static WalletGrpc.WalletBlockingStub blockingStubFull = null; private static WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; private static WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPBFT = null; - private static Application appTest; - - private static String dbPath = "output_rpc_api_access_filter_test"; - - @Rule - public ExpectedException thrown = ExpectedException.none(); + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); /** * init logic. */ @BeforeClass - public static void init() { - Args.setParam(new String[] {"-d", dbPath}, Constant.TEST_CONF); - String fullNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), + public static void init() throws IOException { + Args.setParam(new String[] {"-d", temporaryFolder.newFolder().toString()}, Constant.TEST_CONF); + Args.getInstance().setRpcEnable(true); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcSolidityEnable(true); + Args.getInstance().setRpcOnSolidityPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcPBFTEnable(true); + Args.getInstance().setRpcOnPBFTPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setP2pDisable(true); + String fullNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(), Args.getInstance().getRpcPort()); - String solidityNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), + String solidityNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(), Args.getInstance().getRpcOnSolidityPort()); - String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeDiscoveryBindIp(), + String pBFTNode = String.format("%s:%d", Args.getInstance().getNodeLanIp(), Args.getInstance().getRpcOnPBFTPort()); ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullNode) .usePlaintext() .build(); - ManagedChannel channelpBFT = ManagedChannelBuilder.forTarget(pBFTNode) + ManagedChannel channelPBFT = ManagedChannelBuilder.forTarget(pBFTNode) .usePlaintext() .build(); ManagedChannel channelSolidity = ManagedChannelBuilder.forTarget(solidityNode) @@ -72,19 +84,9 @@ public static void init() { blockingStubFull = WalletGrpc.newBlockingStub(channelFull); blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubPBFT = WalletSolidityGrpc.newBlockingStub(channelpBFT); + blockingStubPBFT = WalletSolidityGrpc.newBlockingStub(channelPBFT); - RpcApiService rpcApiService = context.getBean(RpcApiService.class); - RpcApiServiceOnSolidity rpcApiServiceOnSolidity = - context.getBean(RpcApiServiceOnSolidity.class); - RpcApiServiceOnPBFT rpcApiServiceOnPBFT = context.getBean(RpcApiServiceOnPBFT.class); - - appTest = ApplicationFactory.create(context); - appTest.addService(rpcApiService); - appTest.addService(rpcApiServiceOnSolidity); - appTest.addService(rpcApiServiceOnPBFT); - appTest.initServices(Args.getInstance()); - appTest.startServices(); + Application appTest = ApplicationFactory.create(context); appTest.startup(); } @@ -93,15 +95,8 @@ public static void init() { */ @AfterClass public static void destroy() { + context.close(); Args.clearParam(); - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } } @Test @@ -111,12 +106,116 @@ public void testAccessDisabledFullNode() { disabledApiList.add("getblockbynum"); Args.getInstance().setDisabledApiList(disabledApiList); - final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("this API is unavailable due to config"); - blockingStubFull.getBlockByNum(message); + final NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertThrows("this API is unavailable due to config", StatusRuntimeException.class, + () -> blockingStubFull.getBlockByNum(message)); + } + + @Test + public void testRpcApiService() { + RpcApiService rpcApiService = context.getBean(RpcApiService.class); + ServerCallStreamObserverTest serverCallStreamObserverTest = + new ServerCallStreamObserverTest<>(); + ServerCallStreamObserverTest serverCallStreamObserverTest1 = + new ServerCallStreamObserverTest<>(); + ServerCallStreamObserverTest serverCallStreamObserverTest2 = + new ServerCallStreamObserverTest<>(); + ServerCallStreamObserverTest serverCallStreamObserverTest3 = + new ServerCallStreamObserverTest<>(); + rpcApiService.getBlockCommon(BlockReq.getDefaultInstance(), serverCallStreamObserverTest); + assertTrue("Get block Common failed!", serverCallStreamObserverTest.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getBrokerageInfoCommon(BytesMessage.newBuilder().build(), + serverCallStreamObserverTest1); + assertTrue("Get brokerage info Common failed!", + serverCallStreamObserverTest1.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getBurnTrxCommon(EmptyMessage.newBuilder().build(), + serverCallStreamObserverTest1); + assertTrue("Get burn trx common failed!", + serverCallStreamObserverTest1.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getPendingSizeCommon(EmptyMessage.getDefaultInstance(), + serverCallStreamObserverTest1); + assertTrue("Get pending size common failed!", + serverCallStreamObserverTest1.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getRewardInfoCommon(BytesMessage.newBuilder().build(), + serverCallStreamObserverTest1); + assertTrue("Get reward info common failed!", + serverCallStreamObserverTest1.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionCountByBlockNumCommon( + NumberMessage.newBuilder().getDefaultInstanceForType(), + serverCallStreamObserverTest1); + assertTrue("Get transaction count by block num failed!", + serverCallStreamObserverTest1.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionFromPendingCommon(BytesMessage.newBuilder().build(), + serverCallStreamObserverTest2); + assertFalse("Get transaction from pending failed!", + serverCallStreamObserverTest2.isReady()); + serverCallStreamObserverTest.isCancelled(); + rpcApiService.getTransactionListFromPendingCommon(EmptyMessage.newBuilder() + .getDefaultInstanceForType(), serverCallStreamObserverTest3); + assertTrue("Get transaction list from pending failed!", + serverCallStreamObserverTest3.isReady()); + } + + static class ServerCallStreamObserverTest extends ServerCallStreamObserver { + + Object ret; + + @Override + public boolean isCancelled() { + ret = null; + return true; + } + + @Override + public void setOnCancelHandler(Runnable onCancelHandler) { + } + + @Override + public void setCompression(String compression) { + } + + @Override + public boolean isReady() { + return Objects.nonNull(ret); + } + + @Override + public void setOnReadyHandler(Runnable onReadyHandler) { + } + + @Override + public void disableAutoInboundFlowControl() { + } + + @Override + public void request(int count) { + } + + @Override + public void setMessageCompression(boolean enable) { + } + + @Override + public void onNext(Object value) { + ret = value; + } + + @Override + public void onError(Throwable t) { + } + + @Override + public void onCompleted() { + } } + @Test public void testAccessDisabledSolidityNode() { List disabledApiList = new ArrayList<>(); @@ -124,10 +223,9 @@ public void testAccessDisabledSolidityNode() { disabledApiList.add("getblockbynum"); Args.getInstance().setDisabledApiList(disabledApiList); - final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("this API is unavailable due to config"); - blockingStubSolidity.getBlockByNum(message); + final NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertThrows("this API is unavailable due to config", StatusRuntimeException.class, + () -> blockingStubSolidity.getBlockByNum(message)); } @Test @@ -137,20 +235,19 @@ public void testAccessDisabledPBFTNode() { disabledApiList.add("getblockbynum"); Args.getInstance().setDisabledApiList(disabledApiList); - final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - thrown.expect(StatusRuntimeException.class); - thrown.expectMessage("this API is unavailable due to config"); - blockingStubPBFT.getBlockByNum(message); + final NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertThrows("this API is unavailable due to config", StatusRuntimeException.class, + () -> blockingStubPBFT.getBlockByNum(message)); } @Test public void testAccessNoDisabled() { Args.getInstance().setDisabledApiList(Collections.emptyList()); - final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - Assert.assertNotNull(blockingStubFull.getBlockByNum(message)); - Assert.assertNotNull(blockingStubSolidity.getBlockByNum(message)); - Assert.assertNotNull(blockingStubPBFT.getBlockByNum(message)); + final NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertNotNull(blockingStubFull.getBlockByNum(message)); + assertNotNull(blockingStubSolidity.getBlockByNum(message)); + assertNotNull(blockingStubPBFT.getBlockByNum(message)); } @Test @@ -159,10 +256,32 @@ public void testAccessDisabledNotIncluded() { disabledApiList.add("getaccount"); Args.getInstance().setDisabledApiList(disabledApiList); - final GrpcAPI.NumberMessage message = GrpcAPI.NumberMessage.newBuilder().setNum(0).build(); - Assert.assertNotNull(blockingStubFull.getBlockByNum(message)); - Assert.assertNotNull(blockingStubSolidity.getBlockByNum(message)); - Assert.assertNotNull(blockingStubPBFT.getBlockByNum(message)); + final NumberMessage message = NumberMessage.newBuilder().setNum(0).build(); + assertNotNull(blockingStubFull.getBlockByNum(message)); + assertNotNull(blockingStubSolidity.getBlockByNum(message)); + assertNotNull(blockingStubPBFT.getBlockByNum(message)); + } + + @Test + public void testGetBandwidthPrices() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getBandwidthPrices(message)); + assertNotNull(blockingStubSolidity.getBandwidthPrices(message)); + assertNotNull(blockingStubPBFT.getBandwidthPrices(message)); + } + + @Test + public void testGetEnergyPrices() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getEnergyPrices(message)); + assertNotNull(blockingStubSolidity.getEnergyPrices(message)); + assertNotNull(blockingStubPBFT.getEnergyPrices(message)); + } + + @Test + public void testGetMemoFee() { + EmptyMessage message = EmptyMessage.newBuilder().build(); + assertNotNull(blockingStubFull.getMemoFee(message)); } } 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 8b255a0f395..d6bf3850f30 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 @@ -25,8 +25,9 @@ import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; -import org.testng.annotations.Test; +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; @Slf4j @@ -47,7 +48,12 @@ public class BroadcastServletTest { public static void init() { // Allows for mocking URL connections URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class); - URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); + try { + URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); + } catch (Error e) { + logger.info("Ignore error: {}", e.getMessage()); + } + httpUrlStreamHandler = new HttpUrlStreamHandler(); given(urlStreamHandlerFactory.createURLStreamHandler("http")).willReturn(httpUrlStreamHandler); @@ -57,10 +63,9 @@ public static void init() { /** * set up. * - * @throws InterruptedException . */ @Before - public void setUp() throws InterruptedException { + public void setUp() { broadcastServlet = new BroadcastServlet(); this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); @@ -82,10 +87,8 @@ public void tearDown() { } @Test - public void testDoPost() throws IOException { + public void doPostTest() throws IOException { URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class); - URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); - httpUrlStreamHandler = new HttpUrlStreamHandler(); given(urlStreamHandlerFactory.createURLStreamHandler("http")).willReturn(httpUrlStreamHandler); @@ -98,7 +101,8 @@ public void testDoPost() throws IOException { final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:8090/wallet/broadcasttransaction"; + String href = "http://127.0.0.1/" + + PublicMethod.chooseRandomPort() + "/wallet/broadcasttransaction"; httpUrlStreamHandler.addConnection(new URL(href), httpUrlConnection); httpUrlConnection.setRequestMethod("POST"); httpUrlConnection.setRequestProperty("Content-Type", "application/json"); @@ -115,7 +119,7 @@ public void testDoPost() throws IOException { + "eapis.com/protocol.TransferContract\"},\"type\":\"TransferCon" + "tract\"}],\"ref_block_bytes\":\"267e\",\"ref_block_hash\":\"9a447d222e8" + "de9f2\",\"expiration\":1530893064000,\"timestamp\":1530893006233}}"; - httpUrlConnection.setRequestProperty("Content-Length", "" + postData.length()); + httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); when(httpUrlConnection.getOutputStream()).thenReturn(outContent); OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), @@ -140,14 +144,15 @@ public void testDoPost() throws IOException { 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); - StringBuffer sb = new StringBuffer(); - String text = null; + StringBuilder sb = new StringBuilder(); + String text; while ((text = bufferedReader.readLine()) != null) { sb.append(text); } diff --git a/framework/src/test/java/org/tron/core/services/http/ClearABIServletTest.java b/framework/src/test/java/org/tron/core/services/http/ClearABIServletTest.java new file mode 100644 index 00000000000..a3a051ec6c9 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/ClearABIServletTest.java @@ -0,0 +1,92 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.config.args.Args; +import org.tron.protos.contract.SmartContractOuterClass; + +public class ClearABIServletTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Resource + private ClearABIServlet clearABIServlet; + + private static final String SMART_CONTRACT_NAME = "smart_contract_test"; + private static String CONTRACT_ADDRESS = "A0B4750E2CD76E19DCA331BF5D089B71C3C2798548"; + private static String OWNER_ADDRESS; + private static final long SOURCE_ENERGY_LIMIT = 10L; + + + + private SmartContractOuterClass.SmartContract.Builder createContract( + String contractAddress, String contractName) { + OWNER_ADDRESS = + "A099357684BC659F5166046B56C95A0E99F1265CBD"; + SmartContractOuterClass.SmartContract.Builder builder = + SmartContractOuterClass.SmartContract.newBuilder(); + builder.setName(contractName); + builder.setOriginAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + builder.setContractAddress(ByteString.copyFrom(ByteArray.fromHexString(contractAddress))); + builder.setOriginEnergyLimit(SOURCE_ENERGY_LIMIT); + return builder; + } + + @Test + public void testClearABI() { + chainBaseManager.getDynamicPropertiesStore() + .saveAllowTvmConstantinople(1); + SmartContractOuterClass.SmartContract.Builder contract = + createContract(CONTRACT_ADDRESS, SMART_CONTRACT_NAME); + chainBaseManager.getContractStore().put( + ByteArray.fromHexString(CONTRACT_ADDRESS), + new ContractCapsule(contract.build())); + + String jsonParam = "{" + + " \"owner_address\": \"A099357684BC659F5166046B56C95A0E99F1265CBD\"," + + " \"contract_address\": \"A0B4750E2CD76E19DCA331BF5D089B71C3C2798548\"" + + "}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + + MockHttpServletResponse response = new MockHttpServletResponse(); + clearABIServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("raw_data")); + assertTrue(result.containsKey("txID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/CreateAccountServletTest.java b/framework/src/test/java/org/tron/core/services/http/CreateAccountServletTest.java new file mode 100644 index 00000000000..bbc00ce81f0 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/CreateAccountServletTest.java @@ -0,0 +1,75 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.config.args.Args; +import org.tron.protos.Protocol; + + +public class CreateAccountServletTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Resource + private CreateAccountServlet createAccountServlet; + + @Before + public void init() { + AccountCapsule accountCapsule = new AccountCapsule( + ByteString.copyFrom(ByteArray + .fromHexString("A099357684BC659F5166046B56C95A0E99F1265CD1")), + ByteString.copyFromUtf8("owner"), + Protocol.AccountType.forNumber(1)); + + chainBaseManager.getAccountStore().put(accountCapsule.createDbKey(), + accountCapsule); + } + + @Test + public void testCreate() { + String jsonParam = "{" + + "\"owner_address\": \"A099357684BC659F5166046B56C95A0E99F1265CD1\"," + + "\"account_address\": \"A0B4750E2CD76E19DCA331BF5D089B71C3C2798541\"" + + "}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + + MockHttpServletResponse response = new MockHttpServletResponse(); + createAccountServlet.doPost(request, response); + + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + Assert.assertTrue(result.containsKey("raw_data")); + Assert.assertTrue(result.containsKey("txID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/CreateAssetIssueServletTest.java b/framework/src/test/java/org/tron/core/services/http/CreateAssetIssueServletTest.java new file mode 100644 index 00000000000..4c70eb9252c --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/CreateAssetIssueServletTest.java @@ -0,0 +1,90 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.config.args.Args; +import org.tron.protos.Protocol; + +public class CreateAssetIssueServletTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Resource + private CreateAssetIssueServlet createAssetIssueServlet; + + @Before + public void init() { + AccountCapsule accountCapsule = new AccountCapsule( + ByteString.copyFrom(ByteArray + .fromHexString("A099357684BC659F5166046B56C95A0E99F1265CD1")), + ByteString.copyFromUtf8("owner"), + Protocol.AccountType.forNumber(1)); + accountCapsule.setBalance(10000000000L); + + chainBaseManager.getAccountStore().put(accountCapsule.createDbKey(), + accountCapsule); + } + + @Test + public void testCreate() { + String jsonParam = "{" + + " \"owner_address\": \"A099357684BC659F5166046B56C95A0E99F1265CD1\"," + + " \"name\": \"0x6173736574497373756531353330383934333132313538\"," + + " \"abbr\": \"0x6162627231353330383934333132313538\"," + + " \"total_supply\": 4321," + + " \"trx_num\": 1," + + " \"num\": 1," + + " \"start_time\": 1530894315158," + + " \"end_time\": 1533894312158," + + " \"description\": \"007570646174654e616d6531353330363038383733343633\"," + + " \"url\": \"007570646174654e616d6531353330363038383733343633\"," + + " \"free_asset_net_limit\": 10000," + + " \"public_free_asset_net_limit\": 10000," + + " \"frozen_supply\": {" + + " \"frozen_amount\": 1," + + " \"frozen_days\": 2" + + " }" + + "}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + + MockHttpServletResponse response = new MockHttpServletResponse(); + createAssetIssueServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + Assert.assertTrue(result.containsKey("raw_data")); + Assert.assertTrue(result.containsKey("txID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/CreateSpendAuthSigServletTest.java b/framework/src/test/java/org/tron/core/services/http/CreateSpendAuthSigServletTest.java new file mode 100644 index 00000000000..301e4472e69 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/CreateSpendAuthSigServletTest.java @@ -0,0 +1,60 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class CreateSpendAuthSigServletTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Resource + private CreateSpendAuthSigServlet createSpendAuthSigServlet; + + @Test + public void testCreateSpendAuthSig() { + String jsonParam = "{" + + " \"ask\": \"e3ebcba1531f6d9158d9c162660c5d7c04dadf77d" + + "85d7436a9c98b291ff69a09\"," + + " \"tx_hash\": \"3b78fee6e956f915ffe082284c5f18640edca9" + + "c57a5f227e5f7d7eb65ad61502\"," + + " \"alpha\": \"2608999c3a97d005a879ecdaa16fd29ae434fb67" + + "b177c5e875b0c829e6a1db04\"" + + "}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + + MockHttpServletResponse response = new MockHttpServletResponse(); + createSpendAuthSigServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + Assert.assertTrue(result.containsKey("value")); + String resultValue = (String) result.get("value"); + Assert.assertNotNull(resultValue); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/CreateWitnessServletTest.java b/framework/src/test/java/org/tron/core/services/http/CreateWitnessServletTest.java new file mode 100644 index 00000000000..6cd6e9e2482 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/CreateWitnessServletTest.java @@ -0,0 +1,88 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.Utils; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.args.Args; +import org.tron.protos.Protocol; + +public class CreateWitnessServletTest extends BaseTest { + + @Resource + private CreateWitnessServlet createWitnessServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + private static WitnessCapsule witnessCapsule; + private static AccountCapsule accountCapsule; + + @Before + public void init() { + ECKey ecKey = new ECKey(Utils.getRandom()); + ByteString address = ByteString.copyFrom(ecKey.getAddress()); + + accountCapsule = + new AccountCapsule(Protocol.Account + .newBuilder() + .setAddress(address).build()); + accountCapsule.setBalance(10000000L); + dbManager.getAccountStore().put(accountCapsule + .getAddress().toByteArray(), accountCapsule); + } + + @Test + public void testCreateWitness() { + chainBaseManager.getDynamicPropertiesStore() + .saveAccountUpgradeCost(1L); + String hexAddress = ByteArray + .toHexString(accountCapsule.getAddress().toByteArray()); + String jsonParam = "{\"owner_address\":\"" + + hexAddress + "\"," + + " \"url\": \"00757064617" + + "4654e616d6531353330363038383733343633\"}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + + MockHttpServletResponse response = new MockHttpServletResponse(); + createWitnessServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + Assert.assertTrue(result.containsKey("raw_data")); + Assert.assertTrue(result.containsKey("txID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + +} + + diff --git a/framework/src/test/java/org/tron/core/services/http/GetAccountByIdServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetAccountByIdServletTest.java new file mode 100644 index 00000000000..38c23a971ff --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetAccountByIdServletTest.java @@ -0,0 +1,47 @@ +package org.tron.core.services.http; + +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetAccountByIdServletTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Resource + private GetAccountByIdServlet getAccountByIdServlet; + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + if (isNotEmpty(contentType)) { + request.setContentType(contentType); + } + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Test + public void testGetAccountById() { + String jsonParam = "{\"account_id\": \"6161616162626262\"}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + + getAccountByIdServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetAssetIssueListServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetAssetIssueListServletTest.java new file mode 100644 index 00000000000..71a2d4fa5d5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetAssetIssueListServletTest.java @@ -0,0 +1,82 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetAssetIssueListServletTest extends BaseTest { + + @Resource + private GetAssetIssueListServlet getAssetIssueListServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + request.setContentType(contentType); + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Test + public void testGetAssetIssueListByJson() { + String jsonParam = "{\"visible\": true}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + getAssetIssueListServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject.parseObject(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAssetIssueListValue() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + try { + String params = "visible=true"; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + getAssetIssueListServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject.parseObject(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAssetIssueListEmptyParam() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + String params = "visible="; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + getAssetIssueListServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject.parseObject(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetBandwidthPricesServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetBandwidthPricesServletTest.java new file mode 100644 index 00000000000..40ef8ad068f --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetBandwidthPricesServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetBandwidthPricesServletTest extends BaseTest { + + @Resource + private GetBandwidthPricesServlet getBandwidthPricesServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBandwidthPricesServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getBandwidthPricesServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetBlockByIdServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetBlockByIdServletTest.java new file mode 100644 index 00000000000..8b213e12640 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetBlockByIdServletTest.java @@ -0,0 +1,51 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetBlockByIdServletTest extends BaseTest { + + @Resource + private GetBlockByIdServlet getBlockByIdServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Test + public void testGetBlockById() { + String jsonParam = "{\"value\": " + + "\"0000000002951a2f65db6725c2d0583f1ab9bdb1520eeedece99d9c98f3\"}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBlockByIdServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + request.addParameter("value", "0000000002951a2f65db6725c2d0583f1ab9bdb1520eeedece99d9c98f3"); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBlockByIdServlet.doGet(request, response); + Assert.assertEquals(200, response.getStatus()); + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetBlockByNumServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetBlockByNumServletTest.java new file mode 100644 index 00000000000..5ff84c54dbe --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetBlockByNumServletTest.java @@ -0,0 +1,69 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertTrue; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetBlockByNumServletTest extends BaseTest { + + @Resource + private GetBlockByNumServlet getBlockByNumServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Test + public void testGetBlockByNum() { + String jsonParam = "{\"number\": 1}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + + try { + getBlockByNumServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + assertTrue(result.containsKey("transactions")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + + @Test + public void testGet() { + String jsonParam = "{\"number\": 1}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + + try { + getBlockByNumServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + assertTrue(result.containsKey("transactions")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetBrokerageServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetBrokerageServletTest.java new file mode 100644 index 00000000000..ffe8cc6c22e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetBrokerageServletTest.java @@ -0,0 +1,109 @@ +package org.tron.core.services.http; + +import com.alibaba.fastjson.JSONObject; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetBrokerageServletTest extends BaseTest { + + @Resource + private GetBrokerageServlet getBrokerageServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + request.setContentType(contentType); + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Test + public void getBrokerageValueByJsonTest() { + int expect = 20; + String jsonParam = "{\"address\": \"27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh\"}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBrokerageServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int brokerage = (int)result.get("brokerage"); + Assert.assertEquals(expect, brokerage); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + + @Test + public void getBrokerageByJsonUTF8Test() { + int expect = 20; + String jsonParam = "{\"address\": \"27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh\"}"; + MockHttpServletRequest request = createRequest("application/json; charset=utf-8"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBrokerageServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int brokerage = (int)result.get("brokerage"); + Assert.assertEquals(expect, brokerage); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void getBrokerageValueTest() { + int expect = 20; + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + request.addParameter("address", "27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh"); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBrokerageServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int brokerage = (int)result.get("brokerage"); + Assert.assertEquals(expect, brokerage); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void getByBlankParamTest() { + int expect = 0; + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + request.addParameter("address", ""); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBrokerageServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int brokerage = (int)result.get("brokerage"); + Assert.assertEquals(expect, brokerage); + String content = (String) result.get("Error"); + Assert.assertNull(content); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetEnergyPricesServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetEnergyPricesServletTest.java new file mode 100644 index 00000000000..34e93c557f5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetEnergyPricesServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetEnergyPricesServletTest extends BaseTest { + + @Resource + private GetEnergyPricesServlet getEnergyPricesServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getEnergyPricesServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getEnergyPricesServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetMemoFeePricesServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetMemoFeePricesServletTest.java new file mode 100644 index 00000000000..a954f4f4f8f --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetMemoFeePricesServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetMemoFeePricesServletTest extends BaseTest { + + @Resource + private GetMemoFeePricesServlet getMemoFeePricesServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d",dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getMemoFeePricesServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getMemoFeePricesServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetNowBlockServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetNowBlockServletTest.java new file mode 100644 index 00000000000..3ee3d5a7052 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetNowBlockServletTest.java @@ -0,0 +1,121 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; +import static org.apache.http.entity.ContentType.APPLICATION_FORM_URLENCODED; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetNowBlockServletTest extends BaseTest { + + @Resource + private GetNowBlockServlet getNowBlockServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + if (isNotEmpty(contentType)) { + request.setContentType(contentType); + } + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Test + public void testGetNowBlockByJson() { + String jsonParam = "{\"visible\": true}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + getNowBlockServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetNowBlockByJson2() { + String jsonParam = "{\"visible\": true}"; + MockHttpServletRequest request = createRequest(APPLICATION_FORM_URLENCODED.getMimeType()); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + getNowBlockServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetNowBlockByEmpty() { + MockHttpServletRequest request = createRequest(APPLICATION_FORM_URLENCODED.getMimeType()); + request.setContent(EMPTY.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + getNowBlockServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetNowBlockValue() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + try { + String params = "visible=true"; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + getNowBlockServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetNowBlockEmptyParam() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + String params = "visible="; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + getNowBlockServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("blockID")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java new file mode 100644 index 00000000000..404e154a4c3 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetRewardServletTest.java @@ -0,0 +1,139 @@ +package org.tron.core.services.http; + +import static org.tron.common.utils.Commons.decodeFromBase58Check; + +import com.alibaba.fastjson.JSONObject; + +import java.io.File; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.utils.FileUtil; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; +import org.tron.core.db.Manager; +import org.tron.core.service.MortgageService; +import org.tron.core.store.DelegationStore; + +@Slf4j +public class GetRewardServletTest extends BaseTest { + + @Resource + private Manager manager; + + @Resource + private MortgageService mortgageService; + + @Resource + private DelegationStore delegationStore; + + @Resource + GetRewardServlet getRewardServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + request.setContentType(contentType); + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Before + public void init() { + manager.getDynamicPropertiesStore().saveChangeDelegation(1); + byte[] sr = decodeFromBase58Check("27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh"); + delegationStore.setBrokerage(0, sr, 10); + delegationStore.setWitnessVote(0, sr, 100000000); + } + + @Test + public void getRewardValueByJsonTest() { + int expect = 138181; + String jsonParam = "{\"address\": \"27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh\"}"; + MockHttpServletRequest request = createRequest("application/json"); + MockHttpServletResponse response = new MockHttpServletResponse(); + request.setContent(jsonParam.getBytes()); + try { + getRewardServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int reward = (int)result.get("reward"); + Assert.assertEquals(expect, reward); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void getRewardByJsonUTF8Test() { + int expect = 138181; + String jsonParam = "{\"address\": \"27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh\"}"; + MockHttpServletRequest request = createRequest("application/json; charset=utf-8"); + MockHttpServletResponse response = new MockHttpServletResponse(); + request.setContent(jsonParam.getBytes()); + try { + getRewardServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int reward = (int)result.get("reward"); + Assert.assertEquals(expect, reward); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void getRewardValueTest() { + int expect = 138181; + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + MockHttpServletResponse response = new MockHttpServletResponse(); + mortgageService.payStandbyWitness(); + request.addParameter("address", "27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh"); + getRewardServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int reward = (int)result.get("reward"); + Assert.assertEquals(expect, reward); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + + @Test + public void getByBlankParamTest() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + MockHttpServletResponse response = new MockHttpServletResponse(); + request.addParameter("address", ""); + GetRewardServlet getRewardServlet = new GetRewardServlet(); + getRewardServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + int reward = (int)result.get("reward"); + Assert.assertEquals(0, reward); + String content = (String) result.get("Error"); + Assert.assertNull(content); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServletTest.java new file mode 100644 index 00000000000..0a1a2e4ac5a --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByBlockNumServletTest.java @@ -0,0 +1,79 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONArray; +import com.alibaba.fastjson.JSONObject; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; + +import org.tron.core.capsule.TransactionInfoCapsule; +import org.tron.core.capsule.TransactionRetCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.db.TransactionStoreTest; + +public class GetTransactionInfoByBlockNumServletTest extends BaseTest { + + @Resource + private GetTransactionInfoByBlockNumServlet getTransactionInfoByBlockNumServlet; + private static final byte[] transactionId = TransactionStoreTest.randomBytes(32); + private static TransactionRetCapsule transactionRetCapsule; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Before + public void init() { + byte[] blockNum = ByteArray.fromLong(100); + TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); + + transactionInfoCapsule.setId(transactionId); + transactionInfoCapsule.setFee(1000L); + transactionInfoCapsule.setBlockNumber(100L); + transactionInfoCapsule.setBlockTimeStamp(200L); + + transactionRetCapsule = new TransactionRetCapsule(); + transactionRetCapsule.addTransactionInfo(transactionInfoCapsule.getInstance()); + chainBaseManager.getTransactionRetStore() + .put(blockNum, transactionRetCapsule); + } + + @Test + public void testGetTransactionInfoByBlockNum() { + String jsonParam = "{\"num\" : 100}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + + getTransactionInfoByBlockNumServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONArray array = JSONArray.parseArray(contentAsString); + Assert.assertEquals(1, array.size()); + JSONObject object = (JSONObject) array.get(0); + Assert.assertEquals(1000, object.get("fee")); + Assert.assertEquals(100, object.get("blockNumber")); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByIdServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByIdServletTest.java new file mode 100644 index 00000000000..900c41c7df8 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetTransactionInfoByIdServletTest.java @@ -0,0 +1,126 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.capsule.TransactionInfoCapsule; +import org.tron.core.capsule.TransactionRetCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.db.TransactionStore; +import org.tron.core.db.TransactionStoreTest; +import org.tron.core.store.TransactionRetStore; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; + +public class GetTransactionInfoByIdServletTest extends BaseTest { + + @Resource + private GetTransactionInfoByIdServlet getTransactionInfoByIdServlet; + @Resource + private TransactionStore transactionStore; + @Resource + private TransactionRetStore transactionRetStore; + + private static final String OWNER_ADDRESS = + Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + private static final String TO_ADDRESS = + Wallet.getAddressPreFixString() + "abd4b9367799eaa3197fecb144eb71de1e049abc"; + private static final long AMOUNT = 100; + private static final byte[] KEY_1 = TransactionStoreTest.randomBytes(21); + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Before + public void init() { + byte[] blockNum = ByteArray.fromLong(100); + TransactionInfoCapsule transactionInfoCapsule = new TransactionInfoCapsule(); + + transactionInfoCapsule.setId(KEY_1); + transactionInfoCapsule.setFee(1000L); + transactionInfoCapsule.setBlockNumber(100L); + transactionInfoCapsule.setBlockTimeStamp(200L); + + TransactionRetCapsule transactionRetCapsule = new TransactionRetCapsule(); + transactionRetCapsule.addTransactionInfo(transactionInfoCapsule.getInstance()); + chainBaseManager.getTransactionRetStore() + .put(blockNum, transactionRetCapsule); + transactionRetStore.put(blockNum, transactionRetCapsule); + + AccountCapsule owner = new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)), + ByteString.copyFromUtf8("owner"), + Protocol.AccountType.forNumber(1)); + owner.setBalance(1000000L); + + AccountCapsule to = new AccountCapsule( + ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS)), + ByteString.copyFromUtf8("to"), + Protocol.AccountType.forNumber(1)); + to.setBalance(1000000L); + + chainBaseManager.getAccountStore().put(owner.createDbKey(), + owner); + chainBaseManager.getAccountStore().put(to.createDbKey(), + to); + BalanceContract.TransferContract transferContract = + getContract(AMOUNT, OWNER_ADDRESS, TO_ADDRESS); + TransactionCapsule transactionCapsule = new TransactionCapsule(transferContract, + chainBaseManager.getAccountStore()); + transactionCapsule.setBlockNum(100L); + transactionStore.put(KEY_1, transactionCapsule); + } + + private BalanceContract.TransferContract getContract(long count, + String owneraddress, String toaddress) { + return BalanceContract.TransferContract.newBuilder() + .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(owneraddress))) + .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(toaddress))) + .setAmount(count) + .build(); + } + + @Test + public void testGetInfoById() { + String jsonParam = "{\"value\" : " + + "\"" + ByteArray.toHexString(KEY_1) + "\"}"; + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + + getTransactionInfoByIdServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + try { + String contentAsString = response.getContentAsString(); + JSONObject jsonObject = JSONObject.parseObject(contentAsString); + Assert.assertEquals(1000, jsonObject.get("fee")); + Assert.assertEquals(100, jsonObject.get("blockNumber")); + } catch (UnsupportedEncodingException e) { + Assert.fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/GetTransactionListFromPendingServletTest.java b/framework/src/test/java/org/tron/core/services/http/GetTransactionListFromPendingServletTest.java new file mode 100644 index 00000000000..614d520280d --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/GetTransactionListFromPendingServletTest.java @@ -0,0 +1,38 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import javax.annotation.Resource; + +import org.apache.http.client.methods.HttpGet; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + + +public class GetTransactionListFromPendingServletTest extends BaseTest { + + @Resource + private GetTransactionListFromPendingServlet getTransactionListFromPendingServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getTransactionListFromPendingServlet.doPost(request, response); + assertEquals(200, response.getStatus()); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/HttpServletTest.java b/framework/src/test/java/org/tron/core/services/http/HttpServletTest.java new file mode 100644 index 00000000000..dfd4c569e3e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/HttpServletTest.java @@ -0,0 +1,534 @@ +package org.tron.core.services.http; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +@Slf4j +public class HttpServletTest { + private AccountPermissionUpdateServlet accountPermissionUpdateServlet; + private BroadcastHexServlet broadcastHexServlet; + private BroadcastServlet broadcastServlet; + private ClearABIServlet clearABIServlet; + private CreateAccountServlet createAccountServlet; + private CreateAssetIssueServlet createAssetIssueServlet; + private CreateCommonTransactionServlet createCommonTransactionServlet; + private CreateShieldedContractParametersServlet createShieldedContractParametersServlet; + private CreateShieldedContractParametersWithoutAskServlet + createShieldedContractParametersWithoutAskServlet; + private CreateShieldedTransactionServlet createShieldedTransactionServlet; + private CreateShieldedTransactionWithoutSpendAuthSigServlet + createShieldedTransactionWithoutSpendAuthSigServlet; + private CreateShieldNullifierServlet createShieldNullifierServlet; + private CreateSpendAuthSigServlet createSpendAuthSigServlet; + private CreateWitnessServlet createWitnessServlet; + private DelegateResourceServlet delegateResourceServlet; + private DeployContractServlet deployContractServlet; + private EstimateEnergyServlet estimateEnergyServlet; + private ExchangeCreateServlet exchangeCreateServlet; + private ExchangeInjectServlet exchangeInjectServlet; + private ExchangeTransactionServlet exchangeTransactionServlet; + private ExchangeWithdrawServlet exchangeWithdrawServlet; + private FreezeBalanceServlet freezeBalanceServlet; + private FreezeBalanceV2Servlet freezeBalanceV2Servlet; + private GetAccountBalanceServlet getAccountBalanceServlet; + private GetAccountByIdServlet getAccountByIdServlet; + private GetAccountNetServlet getAccountNetServlet; + private GetAccountResourceServlet getAccountResourceServlet; + private GetAccountServlet getAccountServlet; + private GetAkFromAskServlet getAkFromAskServlet; + private GetAssetIssueByAccountServlet getAssetIssueByAccountServlet; + private GetAssetIssueByIdServlet getAssetIssueByIdServlet; + private GetAssetIssueByNameServlet getAssetIssueByNameServlet; + private GetAssetIssueListByNameServlet getAssetIssueListByNameServlet; + private GetAssetIssueListServlet getAssetIssueListServlet; + private GetAvailableUnfreezeCountServlet getAvailableUnfreezeCountServlet; + private GetBandwidthPricesServlet getBandwidthPricesServlet; + private GetBlockBalanceServlet getBlockBalanceServlet; + private GetBlockByIdServlet getBlockByIdServlet; + private GetBlockByLatestNumServlet getBlockByLatestNumServlet; + private GetBlockByLimitNextServlet getBlockByLimitNextServlet; + private GetBlockByNumServlet getBlockByNumServlet; + private GetBlockServlet getBlockServlet; + private GetBrokerageServlet getBrokerageServlet; + private GetBurnTrxServlet getBurnTrxServlet; + private GetCanDelegatedMaxSizeServlet getCanDelegatedMaxSizeServlet; + private GetCanWithdrawUnfreezeAmountServlet getCanWithdrawUnfreezeAmountServlet; + private GetChainParametersServlet getChainParametersServlet; + private GetContractInfoServlet getContractInfoServlet; + private GetContractServlet getContractServlet; + private GetDelegatedResourceAccountIndexServlet getDelegatedResourceAccountIndexServlet; + private GetDelegatedResourceAccountIndexV2Servlet getDelegatedResourceAccountIndexV2Servlet; + private GetDelegatedResourceServlet getDelegatedResourceServlet; + private GetDelegatedResourceV2Servlet getDelegatedResourceV2Servlet; + private GetDiversifierServlet getDiversifierServlet; + private GetEnergyPricesServlet getEnergyPricesServlet; + private GetExchangeByIdServlet getExchangeByIdServlet; + private GetExpandedSpendingKeyServlet getExpandedSpendingKeyServlet; + private GetIncomingViewingKeyServlet getIncomingViewingKeyServlet; + private GetMarketOrderByAccountServlet getMarketOrderByAccountServlet; + private GetMarketOrderByIdServlet getMarketOrderByIdServlet; + private GetMarketOrderListByPairServlet getMarketOrderListByPairServlet; + private GetMarketPairListServlet getMarketPairListServlet; + private GetMarketPriceByPairServlet getMarketPriceByPairServlet; + private GetMemoFeePricesServlet getMemoFeePricesServlet; + private GetMerkleTreeVoucherInfoServlet getMerkleTreeVoucherInfoServlet; + private GetNewShieldedAddressServlet getNewShieldedAddressServlet; + private GetNextMaintenanceTimeServlet getNextMaintenanceTimeServlet; + private GetNkFromNskServlet getNkFromNskServlet; + private GetNodeInfoServlet getNodeInfoServlet; + private GetNowBlockServlet getNowBlockServlet; + private GetPaginatedAssetIssueListServlet getPaginatedAssetIssueListServlet; + private GetPaginatedExchangeListServlet getPaginatedExchangeListServlet; + private GetPaginatedProposalListServlet getPaginatedProposalListServlet; + private GetPendingSizeServlet getPendingSizeServlet; + private GetProposalByIdServlet getProposalByIdServlet; + private GetRcmServlet getRcmServlet; + private GetRewardServlet getRewardServlet; + private GetShieldTransactionHashServlet getShieldTransactionHashServlet; + private GetSpendingKeyServlet getSpendingKeyServlet; + private GetTransactionApprovedListServlet getTransactionApprovedListServlet; + private GetTransactionByIdServlet getTransactionByIdServlet; + private GetTransactionCountByBlockNumServlet getTransactionCountByBlockNumServlet; + private GetTransactionFromPendingServlet getTransactionFromPendingServlet; + private GetTransactionInfoByBlockNumServlet getTransactionInfoByBlockNumServlet; + private GetTransactionInfoByIdServlet getTransactionInfoByIdServlet; + private GetTransactionListFromPendingServlet getTransactionListFromPendingServlet; + private GetTransactionReceiptByIdServlet getTransactionReceiptByIdServlet; + private GetTransactionSignWeightServlet getTransactionSignWeightServlet; + private GetTriggerInputForShieldedTRC20ContractServlet + getTriggerInputForShieldedTRC20ContractServlet; + private GetZenPaymentAddressServlet getZenPaymentAddressServlet; + private IsShieldedTRC20ContractNoteSpentServlet isShieldedTRC20ContractNoteSpentServlet; + private IsSpendServlet isSpendServlet; + private ListExchangesServlet listExchangesServlet; + private ListNodesServlet listNodesServlet; + private ListProposalsServlet listProposalsServlet; + private ListWitnessesServlet listWitnessesServlet; + private MarketCancelOrderServlet marketCancelOrderServlet; + private MarketSellAssetServlet marketSellAssetServlet; + private MetricsServlet metricsServlet; + private ParticipateAssetIssueServlet participateAssetIssueServlet; + private ProposalApproveServlet proposalApproveServlet; + private ProposalCreateServlet proposalCreateServlet; + private ProposalDeleteServlet proposalDeleteServlet; + private ScanAndMarkNoteByIvkServlet scanAndMarkNoteByIvkServlet; + private ScanNoteByIvkServlet scanNoteByIvkServlet; + private ScanNoteByOvkServlet scanNoteByOvkServlet; + private ScanShieldedTRC20NotesByIvkServlet scanShieldedTRC20NotesByIvkServlet; + private ScanShieldedTRC20NotesByOvkServlet scanShieldedTRC20NotesByOvkServlet; + private SetAccountIdServlet setAccountIdServlet; + private TotalTransactionServlet totalTransactionServlet; + private TransferAssetServlet transferAssetServlet; + private TransferServlet transferServlet; + private TriggerConstantContractServlet triggerConstantContractServlet; + private TriggerSmartContractServlet triggerSmartContractServlet; + private UnDelegateResourceServlet unDelegateResourceServlet; + private UnFreezeAssetServlet unFreezeAssetServlet; + private UnFreezeBalanceServlet unFreezeBalanceServlet; + private UnFreezeBalanceV2Servlet unFreezeBalanceV2Servlet; + private UpdateAccountServlet updateAccountServlet; + private UpdateAssetServlet updateAssetServlet; + private UpdateBrokerageServlet updateBrokerageServlet; + private UpdateEnergyLimitServlet updateEnergyLimitServlet; + private UpdateSettingServlet updateSettingServlet; + private UpdateWitnessServlet updateWitnessServlet; + private ValidateAddressServlet validateAddressServlet; + private VoteWitnessAccountServlet voteWitnessAccountServlet; + private WithdrawBalanceServlet withdrawBalanceServlet; + private WithdrawExpireUnfreezeServlet withdrawExpireUnfreezeServlet; + private CancelAllUnfreezeV2Servlet cancelAllUnfreezeV2Servlet; + private MockHttpServletRequest request; + private MockHttpServletResponse response; + + @Before + public void setUp() { + accountPermissionUpdateServlet = new AccountPermissionUpdateServlet(); + broadcastHexServlet = new BroadcastHexServlet(); + broadcastServlet = new BroadcastServlet(); + clearABIServlet = new ClearABIServlet(); + createAccountServlet = new CreateAccountServlet(); + createAssetIssueServlet = new CreateAssetIssueServlet(); + createCommonTransactionServlet = new CreateCommonTransactionServlet(); + createShieldedContractParametersServlet = new CreateShieldedContractParametersServlet(); + createShieldedContractParametersWithoutAskServlet = + new CreateShieldedContractParametersWithoutAskServlet(); + createShieldedTransactionServlet = new CreateShieldedTransactionServlet(); + createShieldedTransactionWithoutSpendAuthSigServlet = + new CreateShieldedTransactionWithoutSpendAuthSigServlet(); + createShieldNullifierServlet = new CreateShieldNullifierServlet(); + createSpendAuthSigServlet = new CreateSpendAuthSigServlet(); + createWitnessServlet = new CreateWitnessServlet(); + delegateResourceServlet = new DelegateResourceServlet(); + deployContractServlet = new DeployContractServlet(); + estimateEnergyServlet = new EstimateEnergyServlet(); + exchangeCreateServlet = new ExchangeCreateServlet(); + exchangeInjectServlet = new ExchangeInjectServlet(); + exchangeTransactionServlet = new ExchangeTransactionServlet(); + exchangeWithdrawServlet = new ExchangeWithdrawServlet(); + freezeBalanceServlet = new FreezeBalanceServlet(); + freezeBalanceV2Servlet = new FreezeBalanceV2Servlet(); + getAccountBalanceServlet = new GetAccountBalanceServlet(); + getAccountByIdServlet = new GetAccountByIdServlet(); + getAccountNetServlet = new GetAccountNetServlet(); + getAccountResourceServlet = new GetAccountResourceServlet(); + getAccountServlet = new GetAccountServlet(); + getAkFromAskServlet = new GetAkFromAskServlet(); + getAssetIssueByAccountServlet = new GetAssetIssueByAccountServlet(); + getAssetIssueByIdServlet = new GetAssetIssueByIdServlet(); + getAssetIssueByNameServlet = new GetAssetIssueByNameServlet(); + getAssetIssueListByNameServlet = new GetAssetIssueListByNameServlet(); + getAssetIssueListServlet = new GetAssetIssueListServlet(); + getAvailableUnfreezeCountServlet = new GetAvailableUnfreezeCountServlet(); + getBandwidthPricesServlet = new GetBandwidthPricesServlet(); + getBlockBalanceServlet = new GetBlockBalanceServlet(); + getBlockByIdServlet = new GetBlockByIdServlet(); + getBlockByLatestNumServlet = new GetBlockByLatestNumServlet(); + getBlockByLimitNextServlet = new GetBlockByLimitNextServlet(); + getBlockByNumServlet = new GetBlockByNumServlet(); + getBlockServlet = new GetBlockServlet(); + getBrokerageServlet = new GetBrokerageServlet(); + getBurnTrxServlet = new GetBurnTrxServlet(); + getCanDelegatedMaxSizeServlet = new GetCanDelegatedMaxSizeServlet(); + getCanWithdrawUnfreezeAmountServlet = new GetCanWithdrawUnfreezeAmountServlet(); + getChainParametersServlet = new GetChainParametersServlet(); + getContractInfoServlet = new GetContractInfoServlet(); + getContractServlet = new GetContractServlet(); + getDelegatedResourceAccountIndexServlet = new GetDelegatedResourceAccountIndexServlet(); + getDelegatedResourceAccountIndexV2Servlet = new GetDelegatedResourceAccountIndexV2Servlet(); + getDelegatedResourceServlet = new GetDelegatedResourceServlet(); + getDelegatedResourceV2Servlet = new GetDelegatedResourceV2Servlet(); + getDiversifierServlet = new GetDiversifierServlet(); + getEnergyPricesServlet = new GetEnergyPricesServlet(); + getExchangeByIdServlet = new GetExchangeByIdServlet(); + getExpandedSpendingKeyServlet = new GetExpandedSpendingKeyServlet(); + getIncomingViewingKeyServlet = new GetIncomingViewingKeyServlet(); + getMarketOrderByAccountServlet = new GetMarketOrderByAccountServlet(); + getMarketOrderByIdServlet = new GetMarketOrderByIdServlet(); + getMarketOrderListByPairServlet = new GetMarketOrderListByPairServlet(); + getMarketPairListServlet = new GetMarketPairListServlet(); + getMarketPriceByPairServlet = new GetMarketPriceByPairServlet(); + getMemoFeePricesServlet = new GetMemoFeePricesServlet(); + getMerkleTreeVoucherInfoServlet = new GetMerkleTreeVoucherInfoServlet(); + getNewShieldedAddressServlet = new GetNewShieldedAddressServlet(); + getNextMaintenanceTimeServlet = new GetNextMaintenanceTimeServlet(); + getNkFromNskServlet = new GetNkFromNskServlet(); + getNodeInfoServlet = new GetNodeInfoServlet(); + getNowBlockServlet = new GetNowBlockServlet(); + getPaginatedAssetIssueListServlet = new GetPaginatedAssetIssueListServlet(); + getPaginatedExchangeListServlet = new GetPaginatedExchangeListServlet(); + getPaginatedProposalListServlet = new GetPaginatedProposalListServlet(); + getPendingSizeServlet = new GetPendingSizeServlet(); + getProposalByIdServlet = new GetProposalByIdServlet(); + getRcmServlet = new GetRcmServlet(); + getRewardServlet = new GetRewardServlet(); + getShieldTransactionHashServlet = new GetShieldTransactionHashServlet(); + getSpendingKeyServlet = new GetSpendingKeyServlet(); + getTransactionApprovedListServlet = new GetTransactionApprovedListServlet(); + getTransactionByIdServlet = new GetTransactionByIdServlet(); + getTransactionCountByBlockNumServlet = new GetTransactionCountByBlockNumServlet(); + getTransactionFromPendingServlet = new GetTransactionFromPendingServlet(); + getTransactionInfoByBlockNumServlet = new GetTransactionInfoByBlockNumServlet(); + getTransactionInfoByIdServlet = new GetTransactionInfoByIdServlet(); + getTransactionListFromPendingServlet = new GetTransactionListFromPendingServlet(); + getTransactionReceiptByIdServlet = new GetTransactionReceiptByIdServlet(); + getTransactionSignWeightServlet = new GetTransactionSignWeightServlet(); + getTriggerInputForShieldedTRC20ContractServlet = + new GetTriggerInputForShieldedTRC20ContractServlet(); + getZenPaymentAddressServlet = new GetZenPaymentAddressServlet(); + isShieldedTRC20ContractNoteSpentServlet = new IsShieldedTRC20ContractNoteSpentServlet(); + isSpendServlet = new IsSpendServlet(); + listExchangesServlet = new ListExchangesServlet(); + listNodesServlet = new ListNodesServlet(); + listProposalsServlet = new ListProposalsServlet(); + listWitnessesServlet = new ListWitnessesServlet(); + marketCancelOrderServlet = new MarketCancelOrderServlet(); + marketSellAssetServlet = new MarketSellAssetServlet(); + metricsServlet = new MetricsServlet(); + participateAssetIssueServlet = new ParticipateAssetIssueServlet(); + proposalApproveServlet = new ProposalApproveServlet(); + proposalCreateServlet = new ProposalCreateServlet(); + proposalDeleteServlet = new ProposalDeleteServlet(); + scanAndMarkNoteByIvkServlet = new ScanAndMarkNoteByIvkServlet(); + scanNoteByIvkServlet = new ScanNoteByIvkServlet(); + scanNoteByOvkServlet = new ScanNoteByOvkServlet(); + scanShieldedTRC20NotesByIvkServlet = new ScanShieldedTRC20NotesByIvkServlet(); + scanShieldedTRC20NotesByOvkServlet = new ScanShieldedTRC20NotesByOvkServlet(); + setAccountIdServlet = new SetAccountIdServlet(); + totalTransactionServlet = new TotalTransactionServlet(); + transferAssetServlet = new TransferAssetServlet(); + transferServlet = new TransferServlet(); + triggerConstantContractServlet = new TriggerConstantContractServlet(); + triggerSmartContractServlet = new TriggerSmartContractServlet(); + unDelegateResourceServlet = new UnDelegateResourceServlet(); + unFreezeAssetServlet = new UnFreezeAssetServlet(); + unFreezeBalanceServlet = new UnFreezeBalanceServlet(); + unFreezeBalanceV2Servlet = new UnFreezeBalanceV2Servlet(); + updateAccountServlet = new UpdateAccountServlet(); + updateAssetServlet = new UpdateAssetServlet(); + updateBrokerageServlet = new UpdateBrokerageServlet(); + updateEnergyLimitServlet = new UpdateEnergyLimitServlet(); + updateSettingServlet = new UpdateSettingServlet(); + updateWitnessServlet = new UpdateWitnessServlet(); + validateAddressServlet = new ValidateAddressServlet(); + voteWitnessAccountServlet = new VoteWitnessAccountServlet(); + withdrawBalanceServlet = new WithdrawBalanceServlet(); + withdrawExpireUnfreezeServlet = new WithdrawExpireUnfreezeServlet(); + cancelAllUnfreezeV2Servlet = new CancelAllUnfreezeV2Servlet(); + request = new MockHttpServletRequest(); + request.setCharacterEncoding("UTF-8"); + response = new MockHttpServletResponse(); + } + + @Test + public void doGetTest() { + accountPermissionUpdateServlet.doGet(request, response); + clearABIServlet.doGet(request, response); + createAssetIssueServlet.doGet(request, response); + createShieldedContractParametersServlet.doGet(request, response); + createShieldedContractParametersWithoutAskServlet.doGet(request, response); + createShieldedTransactionServlet.doGet(request, response); + createShieldedTransactionWithoutSpendAuthSigServlet.doGet(request, response); + createShieldNullifierServlet.doGet(request, response); + createSpendAuthSigServlet.doGet(request, response); + createWitnessServlet.doGet(request, response); + deployContractServlet.doGet(request, response); + estimateEnergyServlet.doGet(request, response); + getAccountByIdServlet.doGet(request, response); + getAccountNetServlet.doGet(request, response); + getAccountResourceServlet.doGet(request, response); + getAccountServlet.doGet(request, response); + getAkFromAskServlet.doGet(request, response); + getAssetIssueByAccountServlet.doGet(request, response); + getAssetIssueByIdServlet.doGet(request, response); + getAssetIssueByNameServlet.doGet(request, response); + getAssetIssueListByNameServlet.doGet(request, response); + getAssetIssueListServlet.doGet(request, response); + getAvailableUnfreezeCountServlet.doGet(request, response); + getBandwidthPricesServlet.doGet(request, response); + getBlockByIdServlet.doGet(request, response); + getBlockByLatestNumServlet.doGet(request, response); + getBlockByLimitNextServlet.doGet(request, response); + getBlockByNumServlet.doGet(request, response); + getBlockServlet.doGet(request, response); + getBrokerageServlet.doGet(request, response); + getBurnTrxServlet.doGet(request, response); + getCanDelegatedMaxSizeServlet.doGet(request, response); + getCanWithdrawUnfreezeAmountServlet.doGet(request, response); + getChainParametersServlet.doGet(request, response); + getContractInfoServlet.doGet(request, response); + getContractServlet.doGet(request, response); + getDelegatedResourceAccountIndexServlet.doGet(request, response); + getDelegatedResourceAccountIndexV2Servlet.doGet(request, response); + getDelegatedResourceServlet.doGet(request, response); + getDelegatedResourceV2Servlet.doGet(request, response); + getDiversifierServlet.doGet(request, response); + getEnergyPricesServlet.doGet(request, response); + getExchangeByIdServlet.doGet(request, response); + getExpandedSpendingKeyServlet.doGet(request, response); + getIncomingViewingKeyServlet.doGet(request, response); + getMarketOrderByAccountServlet.doGet(request, response); + getMarketOrderByIdServlet.doGet(request, response); + getMarketOrderListByPairServlet.doGet(request, response); + getMarketPairListServlet.doGet(request, response); + getMarketPriceByPairServlet.doGet(request, response); + getMemoFeePricesServlet.doGet(request, response); + getMerkleTreeVoucherInfoServlet.doGet(request, response); + getNewShieldedAddressServlet.doGet(request, response); + getNextMaintenanceTimeServlet.doGet(request, response); + getNkFromNskServlet.doGet(request, response); + getNodeInfoServlet.doGet(request, response); + getNowBlockServlet.doGet(request, response); + getPaginatedAssetIssueListServlet.doGet(request, response); + getPaginatedExchangeListServlet.doGet(request, response); + getPaginatedProposalListServlet.doGet(request, response); + getPendingSizeServlet.doGet(request, response); + getProposalByIdServlet.doGet(request, response); + getRcmServlet.doGet(request, response); + getRewardServlet.doGet(request, response); + getShieldTransactionHashServlet.doGet(request, response); + getSpendingKeyServlet.doGet(request, response); + getTransactionApprovedListServlet.doGet(request, response); + getTransactionByIdServlet.doGet(request, response); + getTransactionCountByBlockNumServlet.doGet(request, response); + getTransactionFromPendingServlet.doGet(request, response); + getTransactionInfoByBlockNumServlet.doGet(request, response); + getTransactionInfoByIdServlet.doGet(request, response); + getTransactionListFromPendingServlet.doGet(request, response); + getTransactionReceiptByIdServlet.doGet(request, response); + getTransactionSignWeightServlet.doGet(request, response); + getTriggerInputForShieldedTRC20ContractServlet.doGet(request, response); + getZenPaymentAddressServlet.doGet(request, response); + isShieldedTRC20ContractNoteSpentServlet.doGet(request, response); + isSpendServlet.doGet(request, response); + listExchangesServlet.doGet(request, response); + listNodesServlet.doGet(request, response); + listProposalsServlet.doGet(request, response); + listWitnessesServlet.doGet(request, response); + marketCancelOrderServlet.doGet(request, response); + marketSellAssetServlet.doGet(request, response); + metricsServlet.doGet(request, response); + participateAssetIssueServlet.doGet(request, response); + proposalApproveServlet.doGet(request, response); + proposalCreateServlet.doGet(request, response); + proposalDeleteServlet.doGet(request, response); + scanAndMarkNoteByIvkServlet.doGet(request, response); + scanNoteByIvkServlet.doGet(request, response); + scanNoteByOvkServlet.doGet(request, response); + scanShieldedTRC20NotesByIvkServlet.doGet(request, response); + scanShieldedTRC20NotesByOvkServlet.doGet(request, response); + setAccountIdServlet.doGet(request, response); + totalTransactionServlet.doGet(request, response); + transferAssetServlet.doGet(request, response); + transferServlet.doGet(request, response); + triggerConstantContractServlet.doGet(request, response); + triggerSmartContractServlet.doGet(request, response); + unDelegateResourceServlet.doGet(request, response); + unFreezeAssetServlet.doGet(request, response); + unFreezeBalanceServlet.doGet(request, response); + unFreezeBalanceV2Servlet.doGet(request, response); + updateAccountServlet.doGet(request, response); + updateAssetServlet.doGet(request, response); + updateEnergyLimitServlet.doGet(request, response); + updateSettingServlet.doGet(request, response); + updateWitnessServlet.doGet(request, response); + validateAddressServlet.doGet(request, response); + voteWitnessAccountServlet.doGet(request, response); + withdrawBalanceServlet.doGet(request, response); + withdrawExpireUnfreezeServlet.doGet(request, response); + } + + + @Test + public void doPostTest() { + request.addParameter("owner_address", "TZ4UXDV5ZhNW7fb2AMSbgfAEZ7hWsnYS2g"); + accountPermissionUpdateServlet.doPost(request, response); + broadcastHexServlet.doPost(request, response); + broadcastServlet.doPost(request, response); + clearABIServlet.doPost(request, response); + createAccountServlet.doPost(request, response); + createAssetIssueServlet.doPost(request, response); + createCommonTransactionServlet.doPost(request, response); + createShieldedContractParametersServlet.doPost(request, response); + createShieldedContractParametersWithoutAskServlet.doPost(request, response); + createShieldedTransactionServlet.doPost(request, response); + createShieldedTransactionWithoutSpendAuthSigServlet.doPost(request, response); + createShieldNullifierServlet.doPost(request, response); + createSpendAuthSigServlet.doPost(request, response); + createWitnessServlet.doPost(request, response); + delegateResourceServlet.doPost(request, response); + deployContractServlet.doPost(request, response); + exchangeCreateServlet.doPost(request, response); + exchangeInjectServlet.doPost(request, response); + exchangeTransactionServlet.doPost(request, response); + exchangeWithdrawServlet.doPost(request, response); + freezeBalanceServlet.doPost(request, response); + freezeBalanceV2Servlet.doPost(request, response); + getAccountBalanceServlet.doPost(request, response); + getAccountByIdServlet.doPost(request, response); + getAccountNetServlet.doPost(request, response); + getAccountResourceServlet.doPost(request, response); + getAccountServlet.doPost(request, response); + getAkFromAskServlet.doPost(request, response); + getAssetIssueByAccountServlet.doPost(request, response); + getAssetIssueByIdServlet.doPost(request, response); + getAssetIssueByNameServlet.doPost(request, response); + getAssetIssueListByNameServlet.doPost(request, response); + getAssetIssueListServlet.doPost(request, response); + getAvailableUnfreezeCountServlet.doPost(request, response); + getBandwidthPricesServlet.doPost(request, response); + getBlockBalanceServlet.doPost(request, response); + getBlockByIdServlet.doPost(request, response); + getBlockByLatestNumServlet.doPost(request, response); + getBlockByLimitNextServlet.doPost(request, response); + getBlockByNumServlet.doPost(request, response); + getBlockServlet.doPost(request, response); + getBrokerageServlet.doPost(request, response); + getBurnTrxServlet.doPost(request, response); + getCanDelegatedMaxSizeServlet.doPost(request, response); + getCanWithdrawUnfreezeAmountServlet.doPost(request, response); + getChainParametersServlet.doPost(request, response); + getContractInfoServlet.doPost(request, response); + getContractServlet.doPost(request, response); + getDelegatedResourceAccountIndexServlet.doPost(request, response); + getDelegatedResourceAccountIndexV2Servlet.doPost(request, response); + getDelegatedResourceServlet.doPost(request, response); + getDelegatedResourceV2Servlet.doPost(request, response); + getDiversifierServlet.doPost(request, response); + getEnergyPricesServlet.doPost(request, response); + getExchangeByIdServlet.doPost(request, response); + getExpandedSpendingKeyServlet.doPost(request, response); + getIncomingViewingKeyServlet.doPost(request, response); + getMarketOrderByAccountServlet.doPost(request, response); + getMarketOrderByIdServlet.doPost(request, response); + getMarketOrderListByPairServlet.doPost(request, response); + getMarketPairListServlet.doPost(request, response); + getMarketPriceByPairServlet.doPost(request, response); + getMemoFeePricesServlet.doPost(request, response); + getMerkleTreeVoucherInfoServlet.doPost(request, response); + getNewShieldedAddressServlet.doPost(request, response); + getNextMaintenanceTimeServlet.doPost(request, response); + getNkFromNskServlet.doPost(request, response); + getNodeInfoServlet.doPost(request, response); + getNowBlockServlet.doPost(request, response); + getPaginatedAssetIssueListServlet.doPost(request, response); + getPaginatedExchangeListServlet.doPost(request, response); + getPaginatedProposalListServlet.doPost(request, response); + getPendingSizeServlet.doPost(request, response); + getProposalByIdServlet.doPost(request, response); + getRcmServlet.doPost(request, response); + getRewardServlet.doPost(request, response); + getShieldTransactionHashServlet.doPost(request, response); + getSpendingKeyServlet.doPost(request, response); + getTransactionApprovedListServlet.doPost(request, response); + getTransactionByIdServlet.doPost(request, response); + getTransactionCountByBlockNumServlet.doPost(request, response); + getTransactionFromPendingServlet.doPost(request, response); + getTransactionInfoByBlockNumServlet.doPost(request, response); + getTransactionInfoByIdServlet.doPost(request, response); + getTransactionListFromPendingServlet.doPost(request, response); + getTransactionReceiptByIdServlet.doPost(request, response); + getTransactionSignWeightServlet.doPost(request, response); + getTriggerInputForShieldedTRC20ContractServlet.doPost(request, response); + getZenPaymentAddressServlet.doPost(request, response); + isShieldedTRC20ContractNoteSpentServlet.doPost(request, response); + isSpendServlet.doPost(request, response); + listExchangesServlet.doPost(request, response); + listNodesServlet.doPost(request, response); + listProposalsServlet.doPost(request, response); + listWitnessesServlet.doPost(request, response); + marketCancelOrderServlet.doPost(request, response); + marketSellAssetServlet.doPost(request, response); + participateAssetIssueServlet.doPost(request, response); + proposalApproveServlet.doPost(request, response); + proposalCreateServlet.doPost(request, response); + proposalDeleteServlet.doPost(request, response); + scanAndMarkNoteByIvkServlet.doPost(request, response); + scanNoteByIvkServlet.doPost(request, response); + scanNoteByOvkServlet.doPost(request, response); + scanShieldedTRC20NotesByIvkServlet.doPost(request, response); + scanShieldedTRC20NotesByOvkServlet.doPost(request, response); + setAccountIdServlet.doPost(request, response); + totalTransactionServlet.doPost(request, response); + transferAssetServlet.doPost(request, response); + transferServlet.doPost(request, response); + unDelegateResourceServlet.doPost(request, response); + unFreezeAssetServlet.doPost(request, response); + unFreezeBalanceServlet.doPost(request, response); + unFreezeBalanceV2Servlet.doPost(request, response); + updateAccountServlet.doPost(request, response); + updateAssetServlet.doPost(request, response); + updateBrokerageServlet.doPost(request, response); + updateEnergyLimitServlet.doPost(request, response); + updateSettingServlet.doPost(request, response); + updateWitnessServlet.doPost(request, response); + validateAddressServlet.doPost(request, response); + voteWitnessAccountServlet.doPost(request, response); + withdrawBalanceServlet.doPost(request, response); + withdrawExpireUnfreezeServlet.doPost(request, response); + cancelAllUnfreezeV2Servlet.doPost(request, response); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java b/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java new file mode 100644 index 00000000000..a8525b0f526 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/JsonFormatTest.java @@ -0,0 +1,255 @@ +package org.tron.core.services.http; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; + +import java.io.CharArrayReader; +import java.io.IOException; +import java.io.StringWriter; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.junit.After; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.protos.Protocol; + +public class JsonFormatTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + @Test + public void testPrintErrorMsg() { + Exception ex = new Exception("test"); + String out = JsonFormat.printErrorMsg(ex); + assertEquals("{\"Error\":\"test\"}", out); + } + + @Test + public void testPrintWithHelloMessage() throws IOException { + Protocol.HelloMessage message = Protocol.HelloMessage.newBuilder() + .setAddress(ByteString.copyFrom("address".getBytes())) + .build(); + StringWriter output = new StringWriter(); + + JsonFormat.print(message, output, true); + assertNotNull(output.toString()); + } + + private UnknownFieldSet createValidUnknownFieldSet() { + UnknownFieldSet unknownFieldSet2 = UnknownFieldSet.newBuilder().build(); + UnknownFieldSet.Field unknownField1 = UnknownFieldSet.Field.newBuilder() + .addFixed32(123) + .addFixed64(12345L) + .addGroup(unknownFieldSet2) + .addLengthDelimited(ByteString.copyFrom("length".getBytes())) + .addVarint(12345678L) + .build(); + + return UnknownFieldSet.newBuilder() + .addField(1, unknownField1) + .build(); + } + + @Test + public void testPrintWithFields() throws IOException { + UnknownFieldSet unknownFieldSet = createValidUnknownFieldSet(); + StringWriter output = new StringWriter(); + JsonFormat.print(unknownFieldSet, output, true); + assertNotNull(output.toString()); + } + + @Test + public void testPrintToString() { + UnknownFieldSet unknownFieldSet = createValidUnknownFieldSet(); + String output = JsonFormat.printToString(unknownFieldSet, true); + assertNotNull(output); + } + + @Test + public void testUnsignedToString() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("unsignedToString", int.class); + privateMethod.setAccessible(true); + String out3 = (String)privateMethod.invoke(null, 100); + assertEquals("100", out3); + String out4 = (String)privateMethod.invoke(null, -100); + assertNotNull(out4); + } + + @Test + public void testToStringBuilderWithNonReadableInput() throws Exception { + String inputString = "Hello, World!"; + Readable input = new CharArrayReader(inputString.toCharArray()); + + Method privateMethod = JsonFormat.class.getDeclaredMethod("toStringBuilder", Readable.class); + privateMethod.setAccessible(true); + + StringBuilder out = (StringBuilder)privateMethod.invoke(null, input); + assertEquals(inputString, out.toString()); + } + + + @Test + public void testUnicodeEscaped() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("unicodeEscaped", char.class); + privateMethod.setAccessible(true); + + + char input1 = 0x09; + String out = (String)privateMethod.invoke(null, input1); + assertNotNull(out); + + char input2 = 0x99; + String out2 = (String)privateMethod.invoke(null, input2); + assertNotNull(out2); + + char input3 = 0x999; + String out3 = (String)privateMethod.invoke(null, input3); + assertNotNull(out3); + + char input4 = 0x1001; + String out4 = (String)privateMethod.invoke(null, input4); + assertNotNull(out4); + } + + @Test + public void testEscapeText() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("escapeText", String.class); + privateMethod.setAccessible(true); + + String input1 = "\b\f\n\r\t\\\"\\b\\f\\n\\r\\t\\\\\"test123"; + String out = (String)privateMethod.invoke(null, input1); + assertNotNull(out); + } + + @Test + public void testAppendEscapedUnicode() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("appendEscapedUnicode", + StringBuilder.class, char.class); + privateMethod.setAccessible(true); + + char input1 = 0x09; + StringBuilder out1 = new StringBuilder(); + + privateMethod.invoke(null, out1, input1); + assertNotNull(out1); + + char input2 = 0x99; + StringBuilder out2 = new StringBuilder(); + privateMethod.invoke(null, out2, input2); + assertNotNull(out2); + + char input3 = 0x999; + StringBuilder out3 = new StringBuilder(); + privateMethod.invoke(null, out3, input3); + assertNotNull(out3); + + char input4 = 0x1001; + StringBuilder out4 = new StringBuilder(); + privateMethod.invoke(null, out4, input4); + assertNotNull(out4); + } + + @Test + public void testUnescapeText() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("unescapeText", String.class); + privateMethod.setAccessible(true); + + String input = "\\u1234\\b\\f\\n\\r\\t\\\\\"test123";; + String out = (String)privateMethod.invoke(null, input); + assertNotNull(out); + } + + @Test + public void testDigitValue() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("digitValue", char.class); + privateMethod.setAccessible(true); + + char input = '1'; + int out = (int)privateMethod.invoke(null, input); + assertEquals(1, out); + + char input1 = 'b'; + int out1 = (int)privateMethod.invoke(null, input1); + assertEquals(11, out1); + + char input2 = 'B'; + int out2 = (int)privateMethod.invoke(null, input2); + assertEquals(11, out2); + } + + @Test + public void testParseUInt64() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("parseUInt64", String.class); + privateMethod.setAccessible(true); + + String input = "12312312312"; + long out = (long)privateMethod.invoke(null, input); + assertEquals(12312312312L, out); + + String input1 = "0x10"; + long out1 = (long)privateMethod.invoke(null, input1); + assertEquals(16L, out1); + + String input2 = "010"; + long out2 = (long)privateMethod.invoke(null, input2); + assertEquals(8L, out2); + + String input3 = "-12312312312"; + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null, input3); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + } + + @Test + public void testParseInteger() throws Exception { + Method privateMethod = JsonFormat.class.getDeclaredMethod("parseInteger", + String.class, boolean.class, boolean.class); + privateMethod.setAccessible(true); + + String input1 = "92233720368547758070"; + Throwable thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input1, true, true); + }); + Throwable cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input5 = "92233720368547758070"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input5, false, true); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input2 = "-92233720368547758"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input2, false, true); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input3 = "92233720368547758070"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input3, false, false); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + + String input4 = "-92233720368547758070"; + thrown = assertThrows(InvocationTargetException.class, () -> { + privateMethod.invoke(null,input4, true, false); + }); + cause = thrown.getCause(); + assertTrue(cause instanceof NumberFormatException); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/http/ListNodesServletTest.java b/framework/src/test/java/org/tron/core/services/http/ListNodesServletTest.java new file mode 100644 index 00000000000..1f491ca11db --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/ListNodesServletTest.java @@ -0,0 +1,82 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.fail; + +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class ListNodesServletTest extends BaseTest { + + @Resource + private ListNodesServlet listNodesServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + request.setContentType(contentType); + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Test + public void testListNodesByJson() { + String jsonParam = "{\"visible\": true}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + listNodesServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + assertNotNull(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testListNodesValue() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + try { + String params = "visible=true"; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + listNodesServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + assertNotNull(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testListNodesEmptyParam() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + String params = "visible="; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + listNodesServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + assertNotNull(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/ListProposalsServletTest.java b/framework/src/test/java/org/tron/core/services/http/ListProposalsServletTest.java new file mode 100644 index 00000000000..aa3a1817a3e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/ListProposalsServletTest.java @@ -0,0 +1,82 @@ +package org.tron.core.services.http; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.Assert.fail; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class ListProposalsServletTest extends BaseTest { + + @Resource + private ListProposalsServlet listProposalsServlet; + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + public MockHttpServletRequest createRequest(String contentType) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setMethod("POST"); + request.setContentType(contentType); + request.setCharacterEncoding("UTF-8"); + return request; + } + + @Test + public void testListProposalsByJson() { + String jsonParam = "{\"visible\": true}"; + MockHttpServletRequest request = createRequest("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + listProposalsServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject.parseObject(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testListProposalsValue() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + try { + String params = "visible=true"; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + listProposalsServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject.parseObject(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testListProposalsEmptyParam() { + MockHttpServletRequest request = createRequest("application/x-www-form-urlencoded"); + String params = "visible="; + request.setContent(params.getBytes(UTF_8)); + MockHttpServletResponse response = new MockHttpServletResponse(); + listProposalsServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject.parseObject(contentAsString); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + +} diff --git a/framework/src/test/java/org/tron/core/services/http/TriggerSmartContractServletTest.java b/framework/src/test/java/org/tron/core/services/http/TriggerSmartContractServletTest.java new file mode 100644 index 00000000000..c6fa5da76e4 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/TriggerSmartContractServletTest.java @@ -0,0 +1,88 @@ +package org.tron.core.services.http; + +import com.google.gson.JsonObject; +import lombok.extern.slf4j.Slf4j; +import org.apache.http.HttpResponse; +import org.bouncycastle.util.encoders.Hex; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.client.utils.HttpMethed; +import org.tron.core.Constant; +import org.tron.core.capsule.ContractCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.store.StoreFactory; +import org.tron.core.vm.repository.Repository; +import org.tron.core.vm.repository.RepositoryImpl; +import org.tron.protos.Protocol; +import org.tron.protos.contract.SmartContractOuterClass; + +@Slf4j +public class TriggerSmartContractServletTest extends BaseTest { + private static String httpNode; + private static final byte[] ownerAddr = Hex.decode("410000000000000000000000000000000000000000"); + private static final byte[] contractAddr = Hex.decode( + "41000000000000000000000000000000000000dEaD"); + + @BeforeClass + public static void init() throws Exception { + Args.setParam( + new String[]{"--output-directory", dbPath(), "--debug"}, Constant.TEST_CONF); + Args.getInstance().needSyncCheck = false; + Args.getInstance().setFullNodeHttpEnable(true); + Args.getInstance().setFullNodeHttpPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setP2pDisable(true); + httpNode = String.format("%s:%d", "127.0.0.1", + Args.getInstance().getFullNodeHttpPort()); + } + + @Before + public void before() { + // start services + appT.startup(); + + // create contract for testing + Repository rootRepository = RepositoryImpl.createRoot(StoreFactory.getInstance()); + rootRepository.createAccount(contractAddr, Protocol.AccountType.Contract); + rootRepository.createContract(contractAddr, new ContractCapsule( + SmartContractOuterClass.SmartContract.newBuilder().build())); + rootRepository.saveCode(contractAddr, Hex.decode( + "608060405260043610601c5760003560e01c8063f8a8fd6d146021575b600080fd5b60276029565b00" + + "5b3373ffffffffffffffffffffffffffffffffffffffff166108fc34908115029060405160006040518" + + "0830381858888f19350505050158015606e573d6000803e3d6000fd5b5056fea2646970667358221220" + + "45fe2c565cf16b27bb8cbafbe251a850a0bb5cd8806a186dbda12d57685ced6f64736f6c63430008120" + + "033")); + rootRepository.commit(); + } + + + @Test + public void testNormalCall() { + HttpMethed.waitToProduceOneBlock(httpNode); + JsonObject parameter = new JsonObject(); + parameter.addProperty("owner_address", ByteArray.toHexString(ownerAddr)); + parameter.addProperty("contract_address", ByteArray.toHexString(contractAddr)); + parameter.addProperty("function_selector", "test()"); + HttpResponse triggersmartcontract1 = invokeToLocal("triggersmartcontract", parameter); + HttpResponse triggersmartcontract2 = invokeToLocal("triggerconstantcontract", parameter); + HttpResponse triggersmartcontract3 = invokeToLocal("estimateenergy", parameter); + Assert.assertNotNull(triggersmartcontract1); + Assert.assertNotNull(triggersmartcontract2); + Assert.assertNotNull(triggersmartcontract3); + } + + public static HttpResponse invokeToLocal( + String method, JsonObject parameter) { + try { + final String requestUrl = "http://" + httpNode + "/wallet/" + method; + return HttpMethed.createConnect(requestUrl, parameter); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/http/UpdateAccountServletTest.java b/framework/src/test/java/org/tron/core/services/http/UpdateAccountServletTest.java new file mode 100644 index 00000000000..e5064e2013b --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/UpdateAccountServletTest.java @@ -0,0 +1,77 @@ +package org.tron.core.services.http; + +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpPost; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class UpdateAccountServletTest extends BaseTest { + + static { + Args.setParam( + new String[]{ + "--output-directory", dbPath(), + }, Constant.TEST_CONF + ); + } + + @Resource + private UpdateAccountServlet updateAccountServlet; + + private String getParam() { + return "{" + + " \"owner_address\": \"TXmVpin5vq5gdZsciyyjdZgKRUju4st1wM\"," + + " \"owner\": {" + + " \"type\": 0," + + " \"permission_name\": \"owner\"," + + " \"threshold\": 1," + + " \"keys\": [{" + + " \"address\": \"TXmVpin5vq5gdZsciyyjdZgKRUju4st1wM\"," + + " \"weight\": 1" + + " }]" + + " }," + + " \"witness\": {" + + " \"type\": 1," + + " \"permission_name\": \"witness\"," + + " \"threshold\": 1," + + " \"keys\": [{" + + " \"address\": \"TXmVpin5vq5gdZsciyyjdZgKRUju4st1wM\"," + + " \"weight\": 1" + + " }]" + + " }," + + " \"actives\": [{" + + " \"type\": 2," + + " \"permission_name\": \"active12323\"," + + " \"threshold\": 2," + + " \"operations\": " + + "\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," + + " \"keys\": [{" + + " \"address\": \"TXmVpin5vq5gdZsciyyjdZgKRUju4st1wM\"," + + " \"weight\": 1" + + " }, {" + + " \"address\": \"TXmVpin5vq5gdZsciyyjdZgKRUju4st1wM\"," + + " \"weight\": 1" + + " }]" + + " }]," + + " \"visible\": true}"; + } + + @Test + public void test() { + String jsonParam = getParam(); + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + request.setContentType("application/json"); + request.setContent(jsonParam.getBytes()); + MockHttpServletResponse response = new MockHttpServletResponse(); + + updateAccountServlet.doPost(request, response); + Assert.assertEquals(200, response.getStatus()); + } +} 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 new file mode 100644 index 00000000000..221c5a7a165 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/UtilMockTest.java @@ -0,0 +1,243 @@ +package org.tron.core.services.http; + +import com.alibaba.fastjson.JSONObject; +import com.google.protobuf.ByteString; + +import java.security.InvalidParameterException; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.junit.After; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.api.GrpcAPI; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.TransactionCapsule; +import org.tron.p2p.utils.ByteArray; +import org.tron.protos.Protocol; +import org.tron.protos.contract.BalanceContract; +import org.tron.protos.contract.SmartContractOuterClass; + +public class UtilMockTest { + @After + public void clearMocks() { + Mockito.framework().clearInlineMocks(); + } + + + @Test + public void testPrintTransactionFee() { + Protocol.ResourceReceipt resourceReceipt = Protocol.ResourceReceipt.newBuilder() + .build(); + Protocol.TransactionInfo result = Protocol.TransactionInfo.newBuilder() + .setReceipt(resourceReceipt) + .build(); + String transactionFee = JsonFormat.printToString(result, true); + String out = Util.printTransactionFee(transactionFee); + Assert.assertNotNull(out); + } + + @Test + public void testPrintBlockList() { + BlockCapsule blockCapsule1 = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + BlockCapsule blockCapsule2 = new BlockCapsule(1, Sha256Hash.ZERO_HASH, + System.currentTimeMillis(), Sha256Hash.ZERO_HASH.getByteString()); + GrpcAPI.BlockList list = GrpcAPI.BlockList.newBuilder() + .addBlock(blockCapsule1.getInstance()) + .addBlock(blockCapsule2.getInstance()) + .build(); + String out = Util.printBlockList(list, true); + Assert.assertNotNull(out); + } + + @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"; + BalanceContract.TransferContract.Builder builder2 = + BalanceContract.TransferContract.newBuilder() + .setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))) + .setToAddress( + ByteString.copyFrom(ByteArray.fromHexString(RECEIVER_ADDRESS))); + return new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.TransferContract); + } + + @Test + public void testPrintTransactionSignWeight() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + GrpcAPI.TransactionExtention transactionExtention = + GrpcAPI.TransactionExtention.newBuilder() + .setTransaction(transactionCapsule.getInstance()) + .build(); + GrpcAPI.TransactionSignWeight txSignWeight = + GrpcAPI.TransactionSignWeight.newBuilder() + .setTransaction(transactionExtention) + .build(); + + String out = Util.printTransactionSignWeight(txSignWeight, true); + Assert.assertNotNull(out); + } + + @Test + public void testPrintTransactionApprovedList() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + GrpcAPI.TransactionExtention transactionExtention = + GrpcAPI.TransactionExtention.newBuilder() + .setTransaction(transactionCapsule.getInstance()) + .build(); + GrpcAPI.TransactionApprovedList transactionApprovedList = + GrpcAPI.TransactionApprovedList.newBuilder() + .setTransaction(transactionExtention) + .build(); + String out = Util.printTransactionApprovedList( + transactionApprovedList, true); + Assert.assertNotNull(out); + } + + @Test + public void testGenerateContractAddress() { + final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + byte[] out = Util.generateContractAddress( + transactionCapsule.getInstance(), OWNER_ADDRESS.getBytes()); + Assert.assertNotNull(out); + } + + @Test + public void testPrintTransactionToJSON() { + final String OWNER_ADDRESS = "41548794500882809695a8a687866e76d4271a1abc"; + SmartContractOuterClass.CreateSmartContract.Builder builder2 = + SmartContractOuterClass.CreateSmartContract.newBuilder() + .setOwnerAddress( + ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS))); + TransactionCapsule transactionCapsule = new TransactionCapsule(builder2.build(), + Protocol.Transaction.Contract.ContractType.CreateSmartContract); + + JSONObject out = Util.printTransactionToJSON( + transactionCapsule.getInstance(), true); + Assert.assertNotNull(out); + } + + @Test + public void testGetContractType() { + String out = Util.getContractType("{\"contractType\":\"123\"}\n"); + Assert.assertEquals("123", out); + } + + @Test + public void testGetHexAddress() { + String out = Util.getHexAddress("TBxSocpujP6UGKV5ydXNVTDQz7fAgdmoaB"); + Assert.assertNotNull(out); + + Assert.assertNull(Util.getHexAddress(null)); + } + + @Test + public void testSetTransactionPermissionId() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + Protocol.Transaction out = Util.setTransactionPermissionId( + 123, transactionCapsule.getInstance()); + Assert.assertNotNull(out); + } + + @Test + public void testSetTransactionExtraData() { + TransactionCapsule transactionCapsule = getTransactionCapsuleExample(); + JSONObject jsonObject = JSONObject.parseObject("{\"extra_data\":\"test\"}"); + Protocol.Transaction out = Util.setTransactionExtraData(jsonObject, + transactionCapsule.getInstance(), true); + Assert.assertNotNull(out); + } + + @Test + public void testConvertOutput() { + Protocol.Account account = Protocol.Account.newBuilder().build(); + String out = Util.convertOutput(account); + Assert.assertNotNull(out); + + account = Protocol.Account.newBuilder() + .setAssetIssuedID(ByteString.copyFrom("asset_issued_ID".getBytes())) + .build(); + out = Util.convertOutput(account); + Assert.assertNotNull(out); + } + + @Test + public void testConvertLogAddressToTronAddress() { + List logs = new ArrayList<>(); + logs.add(Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom("address".getBytes())) + .setData(ByteString.copyFrom("data".getBytes())) + .addTopics(ByteString.copyFrom("topic".getBytes())) + .build()); + + Protocol.TransactionInfo.Builder builder = Protocol.TransactionInfo.newBuilder() + .addAllLog(logs); + List logList = + Util.convertLogAddressToTronAddress(builder.build()); + Assert.assertNotNull(logList.size() > 0); + } + + @Test + public void testValidateParameter() { + String contract = "{\"address\":\"owner_address\"}"; + Assert.assertThrows( + InvalidParameterException.class, + () -> { + Util.validateParameter(contract); + } + ); + String contract1 = + "{\"owner_address\":\"owner_address\"," + + " \"contract_address1\":\"contract_address\", \"data1\":\"data\"}"; + Assert.assertThrows( + InvalidParameterException.class, + () -> { + Util.validateParameter(contract1); + } + ); + String contract2 = + "{\"owner_address\":\"owner_address\", " + + "\"function_selector\":\"function_selector\", \"data\":\"data\"}"; + Assert.assertThrows( + InvalidParameterException.class, + () -> { + Util.validateParameter(contract2); + } + ); + } + + @Test + public void testGetJsonString() { + String str = ""; + String ret = Util.getJsonString(str); + Assert.assertTrue(StringUtils.isEmpty(ret)); + + String str1 = "{\"owner_address\":\"owner_address\"}"; + String ret1 = Util.getJsonString(str1); + Assert.assertTrue(str1.equals(ret1)); + + String str2 = "owner_address=owner_address&contract_address=contract_address"; + String ret2 = Util.getJsonString(str2); + String expect = + "{\"owner_address\":\"owner_address\"," + + "\"contract_address\":\"contract_address\"}"; + Assert.assertEquals(expect, ret2); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/http/UtilTest.java b/framework/src/test/java/org/tron/core/services/http/UtilTest.java new file mode 100644 index 00000000000..5d9d8092b22 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/http/UtilTest.java @@ -0,0 +1,169 @@ +package org.tron.core.services.http; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.api.GrpcAPI.TransactionApprovedList; +import org.tron.api.GrpcAPI.TransactionSignWeight; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.utils.TransactionUtil; +import org.tron.protos.Protocol; +import org.tron.protos.Protocol.Transaction; + +public class UtilTest extends BaseTest { + + private static final String OWNER_ADDRESS; + + @Resource + private Wallet wallet; + @Resource + private TransactionUtil transactionUtil; + + static { + OWNER_ADDRESS = Wallet.getAddressPreFixString() + "c076305e35aea1fe45a772fcaaab8a36e87bdb55"; + Args.setParam(new String[] {"-d", dbPath()}, Constant.TEST_CONF); + } + + @Before + public void setUp() { + byte[] owner = ByteArray.fromHexString(OWNER_ADDRESS); + AccountCapsule ownerCapsule = + new AccountCapsule( + ByteString.copyFromUtf8("owner"), + ByteString.copyFrom(owner), + Protocol.AccountType.Normal, + 10_000_000_000L); + ownerCapsule.setFrozenForBandwidth(1000000L, 1000000L); + dbManager.getAccountStore().put(ownerCapsule.getAddress().toByteArray(), ownerCapsule); + } + + @Test + public void testPackTransactionWithInvalidType() { + + String strTransaction = "{\n" + + " \"visible\": false,\n" + + " \"signature\": [\n" + + " \"5c23bddabccd3e4e5ebdf7d2f21dc58af9f88e0b99620374c5354e0dd9efb3a436167d95b70d2" + + "d825180bf90bc84525acb13a203f209afd5d397316f6b2c387c01\"\n" + + " ],\n" + + " \"txID\": \"fc33817936b06e50d4b6f1797e62f52d69af6c0da580a607241a9c03a48e390e\",\n" + + " \"raw_data\": {\n" + + " \"contract\": [\n" + + " {\n" + + " \"parameter\": {\n" + + " \"value\": {\n" + + " \"amount\": 10,\n" + + " \"owner_address\":\"41c076305e35aea1fe45a772fcaaab8a36e87bdb55\"," + + " \"to_address\": \"415624c12e308b03a1a6b21d9b86e3942fac1ab92b\"\n" + + " },\n" + + " \"type_url\": \"type.googleapis.com/protocol.TransferContract\"\n" + + " },\n" + + " \"type\": \"TransferContract11111\"\n" + + " }\n" + + " ],\n" + + " \"ref_block_bytes\": \"d8ed\",\n" + + " \"ref_block_hash\": \"2e066c3259e756f5\",\n" + + " \"expiration\": 1651906644000,\n" + + " \"timestamp\": 1651906586162\n" + + " },\n" + + " \"raw_data_hex\": \"0a02d8ed22082e066c3259e756f540a090bcea89305a65080112610a2d747970" + + "652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e74726163741230" + + "0a1541c076305e35aea1fe45a772fcaaab8a36e87bdb551215415624c12e308b03a1a6b21d9b86e3942fac1a" + + "b92b180a70b2ccb8ea8930\"\n" + + "}"; + Transaction transaction = Util.packTransaction(strTransaction, false); + TransactionApprovedList transactionApprovedList = + wallet.getTransactionApprovedList(transaction); + Assert.assertEquals("Invalid transaction: no valid contract", + transactionApprovedList.getResult().getMessage()); + + TransactionSignWeight txSignWeight = transactionUtil.getTransactionSignWeight(transaction); + Assert.assertEquals("Invalid transaction: no valid contract", + txSignWeight.getResult().getMessage()); + + + strTransaction = "{\n" + + " \"visible\": false,\n" + + " \"signature\": [\n" + + " \"5c23bddabccd3e4e5ebdf7d2f21dc58af9f88e0b99620374c5354e0dd9efb3a436167d95b70d2d" + + "825180bf90bc84525acb13a203f209afd5d397316f6b2c387c01\"\n" + + " ],\n" + + " \"txID\": \"fc33817936b06e50d4b6f1797e62f52d69af6c0da580a607241a9c03a48e390e\",\n" + + " \"raw_data\": {\n" + + " \"contract\": [\n" + + " {\n" + + " \"parameter\": {\n" + + " \"value\": {\n" + + " \"amount\": 10,\n" + + " \"owner_address\":\"41c076305e35aea1fe45a772fcaaab8a36e87bdb55\"," + + " \"to_address\": \"415624c12e308b03a1a6b21d9b86e3942fac1ab92b\"\n" + + " },\n" + + " \"type_url\": \"type.googleapis.com/protocol.TransferContract\"\n" + + " }\n" + + " }\n" + + " ],\n" + + " \"ref_block_bytes\": \"d8ed\",\n" + + " \"ref_block_hash\": \"2e066c3259e756f5\",\n" + + " \"expiration\": 1651906644000,\n" + + " \"timestamp\": 1651906586162\n" + + " },\n" + + " \"raw_data_hex\": \"0a02d8ed22082e066c3259e756f540a090bcea89305a65080112610a2d747970" + + "652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e74726163741230" + + "0a1541c076305e35aea1fe45a772fcaaab8a36e87bdb551215415624c12e308b03a1a6b21d9b86e3942fac1a" + + "b92b180a70b2ccb8ea8930\"\n" + + "}"; + transaction = Util.packTransaction(strTransaction, false); + transactionApprovedList = wallet.getTransactionApprovedList(transaction); + Assert.assertEquals("Invalid transaction: no valid contract", + transactionApprovedList.getResult().getMessage()); + + txSignWeight = transactionUtil.getTransactionSignWeight(transaction); + Assert.assertEquals("Invalid transaction: no valid contract", + txSignWeight.getResult().getMessage()); + } + + @Test + public void testPackTransaction() { + String strTransaction = "{\n" + + " \"visible\": false,\n" + + " \"signature\": [\n" + + " \"5c23bddabccd3e4e5ebdf7d2f21dc58af9f88e0b99620374c5354e0dd9efb3a436167d95b70d2" + + "d825180bf90bc84525acb13a203f209afd5d397316f6b2c387c01\"\n" + + " ],\n" + + " \"txID\": \"fc33817936b06e50d4b6f1797e62f52d69af6c0da580a607241a9c03a48e390e\",\n" + + " \"raw_data\": {\n" + + " \"contract\": [\n" + + " {\n" + + " \"parameter\": {\n" + + " \"value\": {\n" + + " \"amount\": 10,\n" + + " \"owner_address\":\"41c076305e35aea1fe45a772fcaaab8a36e87bdb55\"," + + " \"to_address\": \"415624c12e308b03a1a6b21d9b86e3942fac1ab92b\"\n" + + " },\n" + + " \"type_url\": \"type.googleapis.com/protocol.TransferContract\"\n" + + " },\n" + + " \"type\": \"TransferContract\"\n" + + " }\n" + + " ],\n" + + " \"ref_block_bytes\": \"d8ed\",\n" + + " \"ref_block_hash\": \"2e066c3259e756f5\",\n" + + " \"expiration\": 1651906644000,\n" + + " \"timestamp\": 1651906586162\n" + + " },\n" + + " \"raw_data_hex\": \"0a02d8ed22082e066c3259e756f540a090bcea89305a65080112610a2d747970" + + "652e676f6f676c65617069732e636f6d2f70726f746f636f6c2e5472616e73666572436f6e74726163741230" + + "0a1541c076305e35aea1fe45a772fcaaab8a36e87bdb551215415624c12e308b03a1a6b21d9b86e3942fac1a" + + "b92b180a70b2ccb8ea8930\"\n" + + "}"; + Transaction transaction = Util.packTransaction(strTransaction, false); + TransactionSignWeight txSignWeight = transactionUtil.getTransactionSignWeight(transaction); + Assert.assertNotNull(txSignWeight); + } +} 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 64d44955536..e1abb41d1e1 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 @@ -27,6 +27,7 @@ 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; @@ -48,7 +49,11 @@ public class GetTransactionByIdSolidityServletTest { public static void init() { // Allows for mocking URL connections URLStreamHandlerFactory urlStreamHandlerFactory = mock(URLStreamHandlerFactory.class); - URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); + try { + URL.setURLStreamHandlerFactory(urlStreamHandlerFactory); + } catch (Error e) { + logger.info("Ignore error: {}", e.getMessage()); + } httpUrlStreamHandler = new HttpUrlStreamHandler(); given(urlStreamHandlerFactory.createURLStreamHandler("http")).willReturn(httpUrlStreamHandler); @@ -59,7 +64,7 @@ public static void init() { */ @Before - public void setUp() throws InterruptedException { + public void setUp() { getTransactionByIdSolidityServlet = new GetTransactionByIdSolidityServlet(); this.request = mock(HttpServletRequest.class); this.response = mock(HttpServletResponse.class); @@ -87,7 +92,8 @@ public void doPostTest() throws IOException { final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:8091/walletsolidity/gettransactioninfobyid"; + 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"); @@ -96,7 +102,7 @@ public void doPostTest() throws IOException { httpUrlConnection.setDoOutput(true); String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", "" + postData.length()); + httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); when(httpUrlConnection.getOutputStream()).thenReturn(outContent); OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), @@ -121,14 +127,15 @@ public void doPostTest() throws IOException { 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); - StringBuffer sb = new StringBuffer(); - String text = null; + StringBuilder sb = new StringBuilder(); + String text; while ((text = bufferedReader.readLine()) != null) { sb.append(text); } @@ -141,7 +148,8 @@ public void doGetTest() throws IOException { final ByteArrayOutputStream outContent = new ByteArrayOutputStream(); System.setOut(new PrintStream(outContent)); - String href = "http://127.0.0.1:8091/walletsolidity/gettransactioninfobyid"; + 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"); @@ -150,7 +158,7 @@ public void doGetTest() throws IOException { httpUrlConnection.setDoOutput(true); String postData = "{\"value\": \"309b6fa3d01353e46f57dd8a8f27611f98e392b50d035cef21" + "3f2c55225a8bd2\"}"; - httpUrlConnection.setRequestProperty("Content-Length", "" + postData.length()); + httpUrlConnection.setRequestProperty("Content-Length", String.valueOf(postData.length())); when(httpUrlConnection.getOutputStream()).thenReturn(outContent); OutputStreamWriter out = new OutputStreamWriter(httpUrlConnection.getOutputStream(), @@ -175,14 +183,15 @@ public void doGetTest() throws IOException { 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); - StringBuffer sb = new StringBuffer(); - String text = null; + StringBuilder sb = new StringBuilder(); + String text; while ((text = bufferedReader.readLine()) != null) { sb.append(text); } diff --git a/framework/src/test/java/org/tron/core/services/interfaceOnPBFT/http/GetBandwidthPricesOnPBFTServletTest.java b/framework/src/test/java/org/tron/core/services/interfaceOnPBFT/http/GetBandwidthPricesOnPBFTServletTest.java new file mode 100644 index 00000000000..a8e07b743c5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/interfaceOnPBFT/http/GetBandwidthPricesOnPBFTServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetBandwidthPricesOnPBFTServletTest extends BaseTest { + + @Resource + private GetBandwidthPricesOnPBFTServlet getBandwidthPricesOnPBFTServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBandwidthPricesOnPBFTServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getBandwidthPricesOnPBFTServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/interfaceOnPBFT/http/GetEnergyPricesOnPBFTServletTest.java b/framework/src/test/java/org/tron/core/services/interfaceOnPBFT/http/GetEnergyPricesOnPBFTServletTest.java new file mode 100644 index 00000000000..8785618bdbe --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/interfaceOnPBFT/http/GetEnergyPricesOnPBFTServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.interfaceOnPBFT.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetEnergyPricesOnPBFTServletTest extends BaseTest { + + @Resource + private GetEnergyPricesOnPBFTServlet getEnergyPricesOnPBFTServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getEnergyPricesOnPBFTServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getEnergyPricesOnPBFTServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/interfaceOnSolidity/http/GetBandwidthPricesOnSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/interfaceOnSolidity/http/GetBandwidthPricesOnSolidityServletTest.java new file mode 100644 index 00000000000..4b1ace08970 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/interfaceOnSolidity/http/GetBandwidthPricesOnSolidityServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.interfaceOnSolidity.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetBandwidthPricesOnSolidityServletTest extends BaseTest { + + @Resource + private GetBandwidthPricesOnSolidityServlet getBandwidthPricesOnSolidityServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getBandwidthPricesOnSolidityServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getBandwidthPricesOnSolidityServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/interfaceOnSolidity/http/GetEnergyPricesOnSolidityServletTest.java b/framework/src/test/java/org/tron/core/services/interfaceOnSolidity/http/GetEnergyPricesOnSolidityServletTest.java new file mode 100644 index 00000000000..6a26f9bc861 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/interfaceOnSolidity/http/GetEnergyPricesOnSolidityServletTest.java @@ -0,0 +1,57 @@ +package org.tron.core.services.interfaceOnSolidity.http; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.tron.common.utils.client.utils.HttpMethed.createRequest; + +import com.alibaba.fastjson.JSONObject; +import java.io.UnsupportedEncodingException; +import javax.annotation.Resource; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.junit.BeforeClass; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GetEnergyPricesOnSolidityServletTest extends BaseTest { + + @Resource + private GetEnergyPricesOnSolidityServlet getEnergyPricesOnSolidityServlet; + + @BeforeClass + public static void init() { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testGet() { + MockHttpServletRequest request = createRequest(HttpGet.METHOD_NAME); + MockHttpServletResponse response = new MockHttpServletResponse(); + getEnergyPricesOnSolidityServlet.doPost(request, response); + try { + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } + + @Test + public void testPost() { + MockHttpServletRequest request = createRequest(HttpPost.METHOD_NAME); + try { + MockHttpServletResponse response = new MockHttpServletResponse(); + getEnergyPricesOnSolidityServlet.doPost(request, response); + String contentAsString = response.getContentAsString(); + JSONObject result = JSONObject.parseObject(contentAsString); + assertTrue(result.containsKey("prices")); + } catch (UnsupportedEncodingException e) { + fail(e.getMessage()); + } + } +} diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/BlockResultTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/BlockResultTest.java new file mode 100644 index 00000000000..2cd619a499a --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/BlockResultTest.java @@ -0,0 +1,46 @@ +package org.tron.core.services.jsonrpc; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.services.jsonrpc.types.BlockResult; +import org.tron.protos.Protocol; + +public class BlockResultTest extends BaseTest { + + @Resource + private Wallet wallet; + + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testBlockResult() { + Protocol.Transaction.raw.Builder raw = Protocol.Transaction.raw.newBuilder(); + Protocol.Transaction.Contract.Builder contract = Protocol.Transaction.Contract.newBuilder(); + contract.setType(Protocol.Transaction.Contract.ContractType.UpdateBrokerageContract); + raw.addContract(contract.build()); + + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData(raw).build(); + BlockCapsule blockCapsule = new BlockCapsule(Protocol.Block.newBuilder().setBlockHeader( + Protocol.BlockHeader.newBuilder().setRawData(Protocol.BlockHeader.raw.newBuilder() + .setParentHash(ByteString.copyFrom(ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b82"))) + .setNumber(0))).addTransactions(transaction).build()); + + BlockResult blockResult = new BlockResult(blockCapsule.getInstance(),true, wallet); + Assert.assertEquals(blockResult.getHash(), + "0x000000000000000036393ced0658419d3c251bc14ffab8d10c8b0898451054fa"); + Assert.assertEquals(blockResult.getTransactions().length, 1); + Assert.assertEquals(blockResult.getGasUsed(),"0x0"); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java new file mode 100644 index 00000000000..f9e264c515f --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/BuildArgumentsTest.java @@ -0,0 +1,73 @@ +package org.tron.core.services.jsonrpc; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.config.args.Args; +import org.tron.core.exception.JsonRpcInvalidParamsException; +import org.tron.core.exception.JsonRpcInvalidRequestException; +import org.tron.core.services.jsonrpc.types.BuildArguments; +import org.tron.core.services.jsonrpc.types.CallArguments; +import org.tron.protos.Protocol; + +public class BuildArgumentsTest extends BaseTest { + + @Resource + private Wallet wallet; + + private BuildArguments buildArguments; + + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Before + public void initBuildArgs() { + buildArguments = new BuildArguments( + "0x0000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000001","0x10","0.01","0x100", + "","0",9L,10000L,"",10L, + 2000L,"args",1,"",true); + } + + + @Test + public void testBuildArgument() { + CallArguments callArguments = new CallArguments( + "0x0000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000001","0x10","0.01","0x100", + "","0"); + BuildArguments buildArguments = new BuildArguments(callArguments); + Assert.assertEquals(buildArguments.getFrom(), + "0x0000000000000000000000000000000000000000"); + Assert.assertEquals(buildArguments.getTo(), + "0x0000000000000000000000000000000000000001"); + Assert.assertEquals(buildArguments.getGas(), "0x10"); + Assert.assertEquals(buildArguments.getGasPrice(), "0.01"); + } + + @Test + public void testGetContractType() + throws JsonRpcInvalidRequestException, JsonRpcInvalidParamsException { + Protocol.Transaction.Contract.ContractType contractType = + buildArguments.getContractType(wallet); + Assert.assertEquals(contractType, Protocol.Transaction.Contract.ContractType.TransferContract); + } + + @Test + public void testParseValue() throws JsonRpcInvalidParamsException { + long value = buildArguments.parseValue(); + Assert.assertEquals(value, 256L); + } + + @Test + public void testParseGas() throws JsonRpcInvalidParamsException { + long gas = buildArguments.parseGas(); + Assert.assertEquals(gas, 16L); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java new file mode 100644 index 00000000000..19dd76e5e07 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/CallArgumentsTest.java @@ -0,0 +1,47 @@ +package org.tron.core.services.jsonrpc; + +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.config.args.Args; +import org.tron.core.exception.JsonRpcInvalidParamsException; +import org.tron.core.exception.JsonRpcInvalidRequestException; +import org.tron.core.services.jsonrpc.types.CallArguments; +import org.tron.protos.Protocol; + +public class CallArgumentsTest extends BaseTest { + + @Resource + private Wallet wallet; + + private CallArguments callArguments; + + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Before + public void init() { + callArguments = new CallArguments("0x0000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000001","0x10","0.01","0x100", + "","0"); + } + + @Test + public void testGetContractType() + throws JsonRpcInvalidRequestException, JsonRpcInvalidParamsException { + Protocol.Transaction.Contract.ContractType contractType = callArguments.getContractType(wallet); + Assert.assertEquals(Protocol.Transaction.Contract.ContractType.TransferContract, contractType); + } + + @Test + public void testParseValue() throws JsonRpcInvalidParamsException { + long value = callArguments.parseValue(); + Assert.assertEquals(256L, value); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java new file mode 100644 index 00000000000..f10526e30a4 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionReceiptTest.java @@ -0,0 +1,66 @@ +package org.tron.core.services.jsonrpc; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.TransactionRetCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.services.jsonrpc.types.TransactionReceipt; +import org.tron.core.store.TransactionRetStore; +import org.tron.protos.Protocol; + +public class TransactionReceiptTest extends BaseTest { + + @Resource + private Wallet wallet; + + @Resource + private TransactionRetStore transactionRetStore; + + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testTransactionReceipt() { + Protocol.TransactionInfo transactionInfo = Protocol.TransactionInfo.newBuilder() + .setId(ByteString.copyFrom("1".getBytes())) + .setContractAddress(ByteString.copyFrom("address1".getBytes())) + .setReceipt(Protocol.ResourceReceipt.newBuilder() + .setEnergyUsageTotal(0L) + .setResult(Protocol.Transaction.Result.contractResult.DEFAULT) + .build()) + .addLog(Protocol.TransactionInfo.Log.newBuilder() + .setAddress(ByteString.copyFrom("address1".getBytes())) + .setData(ByteString.copyFrom("data".getBytes())) + .build()) + .build(); + TransactionRetCapsule transactionRetCapsule = new TransactionRetCapsule(); + transactionRetCapsule.addTransactionInfo(transactionInfo); + transactionRetStore.put(ByteArray.fromLong(1), transactionRetCapsule); + + Protocol.Transaction.raw.Builder raw = Protocol.Transaction.raw.newBuilder(); + Protocol.Transaction.Contract.Builder contract = Protocol.Transaction.Contract.newBuilder(); + contract.setType(Protocol.Transaction.Contract.ContractType.UpdateBrokerageContract); + raw.addContract(contract.build()); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData(raw).build(); + + TransactionReceipt transactionReceipt = new TransactionReceipt( + Protocol.Block.newBuilder().setBlockHeader( + Protocol.BlockHeader.newBuilder().setRawData( + Protocol.BlockHeader.raw.newBuilder().setNumber(1))).addTransactions( + transaction).build(), transactionInfo, wallet); + + Assert.assertEquals(transactionReceipt.getBlockNumber(),"0x1"); + Assert.assertEquals(transactionReceipt.getTransactionIndex(),"0x0"); + Assert.assertEquals(transactionReceipt.getLogs().length,1); + Assert.assertEquals(transactionReceipt.getBlockHash(), + "0x0000000000000001464f071c8a336fd22eb5145dff1b245bda013ec89add8497"); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionResultTest.java b/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionResultTest.java new file mode 100644 index 00000000000..a71441c73b4 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/jsonrpc/TransactionResultTest.java @@ -0,0 +1,59 @@ +package org.tron.core.services.jsonrpc; + +import com.google.protobuf.ByteString; +import javax.annotation.Resource; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.BaseTest; +import org.tron.common.utils.ByteArray; +import org.tron.core.Constant; +import org.tron.core.Wallet; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.config.args.Args; +import org.tron.core.services.jsonrpc.types.TransactionResult; +import org.tron.protos.Protocol; + +public class TransactionResultTest extends BaseTest { + + @Resource + private Wallet wallet; + + static { + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); + } + + @Test + public void testBuildTransactionResultWithBlock() { + Protocol.Transaction.raw.Builder raw = Protocol.Transaction.raw.newBuilder().addContract( + Protocol.Transaction.Contract.newBuilder().setType( + Protocol.Transaction.Contract.ContractType.TriggerSmartContract)); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData(raw).build(); + BlockCapsule blockCapsule = new BlockCapsule(Protocol.Block.newBuilder().setBlockHeader( + Protocol.BlockHeader.newBuilder().setRawData(Protocol.BlockHeader.raw.newBuilder() + .setParentHash(ByteString.copyFrom(ByteArray.fromHexString( + "0304f784e4e7bae517bcab94c3e0c9214fb4ac7ff9d7d5a937d1f40031f87b82"))) + .setNumber(9))).addTransactions(transaction).build()); + + TransactionResult transactionResult = new TransactionResult(blockCapsule,0, transaction, + 100,1, wallet); + Assert.assertEquals(transactionResult.getBlockNumber(), "0x9"); + Assert.assertEquals(transactionResult.getHash(), + "0xdebef90d0a8077620711b1b5af2b702665887ddcbf80868108026e1ab5e0bfb7"); + Assert.assertEquals(transactionResult.getGasPrice(), "0x1"); + Assert.assertEquals(transactionResult.getGas(), "0x64"); + } + + @Test + public void testBuildTransactionResult() { + Protocol.Transaction.raw.Builder raw = Protocol.Transaction.raw.newBuilder().addContract( + Protocol.Transaction.Contract.newBuilder().setType( + Protocol.Transaction.Contract.ContractType.TriggerSmartContract)); + Protocol.Transaction transaction = Protocol.Transaction.newBuilder().setRawData(raw).build(); + TransactionResult transactionResult = new TransactionResult(transaction, wallet); + Assert.assertEquals(transactionResult.getHash(), + "0xdebef90d0a8077620711b1b5af2b702665887ddcbf80868108026e1ab5e0bfb7"); + Assert.assertEquals(transactionResult.getGasPrice(), "0x"); + Assert.assertEquals(transactionResult.getNonce(), "0x0000000000000000"); + } + +} diff --git a/framework/src/test/java/org/tron/core/services/ratelimiter/GlobalRateLimiterTest.java b/framework/src/test/java/org/tron/core/services/ratelimiter/GlobalRateLimiterTest.java new file mode 100644 index 00000000000..b2f4915df1e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/ratelimiter/GlobalRateLimiterTest.java @@ -0,0 +1,28 @@ +package org.tron.core.services.ratelimiter; + +import java.lang.reflect.Field; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Test; +import org.tron.core.Constant; +import org.tron.core.config.args.Args; + +public class GlobalRateLimiterTest { + + @Test + public void testAcquire() throws Exception { + String[] a = new String[0]; + Args.setParam(a, Constant.TESTNET_CONF); + RuntimeData runtimeData = new RuntimeData(null); + Field field = runtimeData.getClass().getDeclaredField("address"); + field.setAccessible(true); + field.set(runtimeData, "127.0.0.1"); + Assert.assertEquals(runtimeData.getRemoteAddr(), "127.0.0.1"); + GlobalRateLimiter.acquire(runtimeData); + } + + @AfterClass + public static void destroy() { + Args.clearParam(); + } +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java index 844e3ff4ae0..72ac126e394 100644 --- a/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java +++ b/framework/src/test/java/org/tron/core/services/ratelimiter/adaptor/AdaptorTest.java @@ -5,7 +5,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.Semaphore; import org.junit.Assert; -import org.testng.annotations.Test; +import org.junit.Test; import org.tron.common.utils.ReflectUtils; import org.tron.core.services.ratelimiter.adapter.GlobalPreemptibleAdapter; import org.tron.core.services.ratelimiter.adapter.IPQPSRateLimiterAdapter; @@ -23,20 +23,19 @@ public void testStrategy() { IPQpsStrategy strategy1 = (IPQpsStrategy) ReflectUtils.getFieldObject(adapter1, "strategy"); - Assert.assertTrue(Double.valueOf( + Assert.assertEquals(5.0d, Double.parseDouble( ReflectUtils.getFieldValue(strategy1.getMapParams().get("qps"), - "value").toString()) - == 5.0d); - Assert.assertTrue(strategy1.getMapParams().get("notExist") == null); + "value").toString()), 0.0); + Assert.assertNull(strategy1.getMapParams().get("notExist")); String paramString2 = "qps=5xyz"; IPQPSRateLimiterAdapter adapter2 = new IPQPSRateLimiterAdapter(paramString2); IPQpsStrategy strategy2 = (IPQpsStrategy) ReflectUtils.getFieldObject(adapter2, "strategy"); - Assert.assertTrue(Double.valueOf( + Assert.assertEquals(IPQpsStrategy.DEFAULT_IPQPS, Double.valueOf( ReflectUtils.getFieldValue(strategy2.getMapParams().get("qps"), - "value").toString()).equals(IPQpsStrategy.DEFAULT_IPQPS)); + "value").toString())); } @Test @@ -46,9 +45,9 @@ public void testIPQPSRateLimiterAdapter() { IPQpsStrategy strategy = (IPQpsStrategy) ReflectUtils.getFieldObject(adapter, "strategy"); - Assert.assertTrue(Double - .valueOf(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), - "value").toString()) == 5.0d); + Assert.assertEquals(5.0d, Double + .parseDouble(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), + "value").toString()), 0.0); long t0 = System.currentTimeMillis(); for (int i = 0; i < 20; i++) { @@ -61,7 +60,7 @@ public void testIPQPSRateLimiterAdapter() { for (int i = 0; i < 20; i++) { if (i % 2 == 0) { strategy.acquire("1.2.3.4"); - } else if (i % 2 == 1) { + } else { strategy.acquire("4.3.2.1"); } } @@ -69,7 +68,7 @@ public void testIPQPSRateLimiterAdapter() { Assert.assertTrue(t1 - t0 > 1500); Cache ipLimiter = (Cache) ReflectUtils .getFieldObject(strategy, "ipLimiter"); - Assert.assertTrue(ipLimiter.size() == 2); + Assert.assertEquals(2, ipLimiter.size()); } @Test @@ -78,9 +77,9 @@ public void testGlobalPreemptibleAdapter() { GlobalPreemptibleAdapter adapter1 = new GlobalPreemptibleAdapter(paramString1); GlobalPreemptibleStrategy strategy1 = (GlobalPreemptibleStrategy) ReflectUtils .getFieldObject(adapter1, "strategy"); - Assert.assertTrue(Integer.valueOf( + Assert.assertEquals(1, Integer.parseInt( ReflectUtils.getFieldValue(strategy1.getMapParams().get("permit"), - "value").toString()) == 1); + "value").toString())); boolean first = strategy1.acquire(); Assert.assertTrue(first); @@ -95,9 +94,9 @@ public void testGlobalPreemptibleAdapter() { GlobalPreemptibleAdapter adapter2 = new GlobalPreemptibleAdapter(paramString2); GlobalPreemptibleStrategy strategy2 = (GlobalPreemptibleStrategy) ReflectUtils .getFieldObject(adapter2, "strategy"); - Assert.assertTrue(Integer.valueOf( + Assert.assertEquals(3, Integer.parseInt( ReflectUtils.getFieldValue(strategy2.getMapParams().get("permit"), - "value").toString()) == 3); + "value").toString())); first = strategy2.acquire(); Assert.assertTrue(first); @@ -114,11 +113,11 @@ public void testGlobalPreemptibleAdapter() { Assert.assertTrue(fourAfterOneRelease); Semaphore sp = (Semaphore) ReflectUtils.getFieldObject(strategy2, "sp"); - Assert.assertTrue(sp.availablePermits() == 0); + Assert.assertEquals(0, sp.availablePermits()); strategy2.release(); strategy2.release(); strategy2.release(); - Assert.assertTrue(sp.availablePermits() == 3); + Assert.assertEquals(3, sp.availablePermits()); } @@ -128,9 +127,9 @@ public void testQpsRateLimiterAdapter() { QpsRateLimiterAdapter adapter = new QpsRateLimiterAdapter(paramString); QpsStrategy strategy = (QpsStrategy) ReflectUtils.getFieldObject(adapter, "strategy"); - Assert.assertTrue(Double - .valueOf(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), - "value").toString()) == 5); + Assert.assertEquals(5, Double + .parseDouble(ReflectUtils.getFieldValue(strategy.getMapParams().get("qps"), + "value").toString()), 0.0); strategy.acquire(); long t0 = System.currentTimeMillis(); diff --git a/framework/src/test/java/org/tron/core/services/stop/BlockHeightStopTest.java b/framework/src/test/java/org/tron/core/services/stop/BlockHeightStopTest.java new file mode 100644 index 00000000000..66a827fc55e --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/stop/BlockHeightStopTest.java @@ -0,0 +1,21 @@ +package org.tron.core.services.stop; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.tron.common.parameter.CommonParameter; + +@Slf4j +public class BlockHeightStopTest extends ConditionallyStopTest { + + private static final long height = 64; + + protected void initParameter(CommonParameter parameter) { + parameter.setShutdownBlockHeight(height); + } + + @Override + protected void check() throws Exception { + Assert.assertEquals(height, dbManager.getDynamicPropertiesStore() + .getLatestBlockHeaderNumberFromDB()); + } +} diff --git a/framework/src/test/java/org/tron/core/services/stop/BlockSyncCountStopTest.java b/framework/src/test/java/org/tron/core/services/stop/BlockSyncCountStopTest.java new file mode 100644 index 00000000000..0ac9b93f2dc --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/stop/BlockSyncCountStopTest.java @@ -0,0 +1,22 @@ +package org.tron.core.services.stop; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.tron.common.parameter.CommonParameter; + +@Slf4j +public class BlockSyncCountStopTest extends ConditionallyStopTest { + + private static final long sync = 512; + + protected void initParameter(CommonParameter parameter) { + parameter.setShutdownBlockCount(sync); + } + + @Override + protected void check() throws Exception { + + Assert.assertEquals(sync + currentHeader, dbManager + .getDynamicPropertiesStore().getLatestBlockHeaderNumberFromDB()); + } +} diff --git a/framework/src/test/java/org/tron/core/services/stop/BlockTimeStopTest.java b/framework/src/test/java/org/tron/core/services/stop/BlockTimeStopTest.java new file mode 100644 index 00000000000..1e16ad6c3b0 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/stop/BlockTimeStopTest.java @@ -0,0 +1,40 @@ +package org.tron.core.services.stop; + +import java.text.ParseException; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.tron.common.cron.CronExpression; +import org.tron.common.parameter.CommonParameter; + +@Slf4j +public class BlockTimeStopTest extends ConditionallyStopTest { + private static final DateTimeFormatter pattern = DateTimeFormatter + .ofPattern("ss mm HH dd MM ? yyyy"); + private static final String time = localDateTime.plusSeconds(12 * 3).format(pattern); + + private static CronExpression cronExpression; + + + static { + try { + cronExpression = new CronExpression(time); + } catch (ParseException e) { + logger.error("{}", e.getMessage()); + } + } + + + protected void initParameter(CommonParameter parameter) { + parameter.setShutdownBlockTime(cronExpression); + } + + @Override + protected void check() throws Exception { + long height = dbManager + .getDynamicPropertiesStore().getLatestBlockHeaderNumberFromDB(); + Assert.assertTrue(cronExpression.isSatisfiedBy(new Date(chainManager + .getBlockById(chainManager.getBlockIdByNum(height)).getTimeStamp()))); + } +} diff --git a/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java b/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java new file mode 100644 index 00000000000..b417b27b380 --- /dev/null +++ b/framework/src/test/java/org/tron/core/services/stop/ConditionallyStopTest.java @@ -0,0 +1,187 @@ +package org.tron.core.services.stop; + +import com.google.common.collect.Maps; +import com.google.protobuf.ByteString; +import java.io.File; +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.crypto.ECKey; +import org.tron.common.parameter.CommonParameter; +import org.tron.common.utils.ByteArray; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.LocalWitnesses; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.Utils; +import org.tron.consensus.dpos.DposSlot; +import org.tron.core.ChainBaseManager; +import org.tron.core.Constant; +import org.tron.core.capsule.AccountCapsule; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.capsule.WitnessCapsule; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import org.tron.core.consensus.ConsensusService; +import org.tron.core.db.BlockGenerate; +import org.tron.core.db.Manager; +import org.tron.core.net.TronNetDelegate; +import org.tron.protos.Protocol; + +@Slf4j +public abstract class ConditionallyStopTest extends BlockGenerate { + + @ClassRule + public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + static ChainBaseManager chainManager; + private static DposSlot dposSlot; + + private final String key = PublicMethod.getRandomPrivateKey(); + private final byte[] privateKey = ByteArray.fromHexString(key); + + private final AtomicInteger port = new AtomicInteger(0); + protected String dbPath; + protected Manager dbManager; + long currentHeader = -1; + private TronNetDelegate tronNetDelegate; + private TronApplicationContext context; + + + static LocalDateTime localDateTime = LocalDateTime.now(); + private long time = ZonedDateTime.of(localDateTime, + ZoneId.systemDefault()).toInstant().toEpochMilli(); + + protected abstract void initParameter(CommonParameter parameter); + + protected abstract void check() throws Exception; + + protected void initDbPath() throws IOException { + dbPath = temporaryFolder.newFolder().toString(); + } + + + @Before + public void init() throws Exception { + + initDbPath(); + logger.info("Full node running."); + Args.setParam(new String[] {"-d", dbPath}, Constant.TEST_CONF); + Args.getInstance().setNodeListenPort(10000 + port.incrementAndGet()); + + initParameter(Args.getInstance()); + context = new TronApplicationContext(DefaultConfig.class); + + dbManager = context.getBean(Manager.class); + setManager(dbManager); + dposSlot = context.getBean(DposSlot.class); + ConsensusService consensusService = context.getBean(ConsensusService.class); + consensusService.start(); + chainManager = dbManager.getChainBaseManager(); + tronNetDelegate = context.getBean(TronNetDelegate.class); + tronNetDelegate.setExit(false); + currentHeader = dbManager.getDynamicPropertiesStore() + .getLatestBlockHeaderNumberFromDB(); + + byte[] address = PublicMethod.getAddressByteByPrivateKey(key); + ByteString addressByte = ByteString.copyFrom(address); + WitnessCapsule witnessCapsule = new WitnessCapsule(addressByte); + chainManager.getWitnessStore().put(addressByte.toByteArray(), witnessCapsule); + chainManager.addWitness(addressByte); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(addressByte).build()); + chainManager.getAccountStore().put(addressByte.toByteArray(), accountCapsule); + } + + @After + public void destroy() { + Args.clearParam(); + context.destroy(); + } + + private void generateBlock(Map witnessAndAccount) throws Exception { + + BlockCapsule block = + createTestBlockCapsule( + chainManager.getDynamicPropertiesStore().getLatestBlockHeaderTimestamp() + 3000, + chainManager.getDynamicPropertiesStore().getLatestBlockHeaderNumber() + 1, + chainManager.getDynamicPropertiesStore().getLatestBlockHeaderHash().getByteString(), + witnessAndAccount); + + tronNetDelegate.processBlock(block, false); + } + + @Test + public void testStop() throws Exception { + final ECKey ecKey = ECKey.fromPrivate(privateKey); + Assert.assertNotNull(ecKey); + byte[] address = ecKey.getAddress(); + WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(address)); + chainManager.getWitnessScheduleStore().saveActiveWitnesses(new ArrayList<>()); + chainManager.addWitness(ByteString.copyFrom(address)); + + Protocol.Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); + + tronNetDelegate.processBlock(new BlockCapsule(block), false); + + Map witnessAndAccount = addTestWitnessAndAccount(); + witnessAndAccount.put(ByteString.copyFrom(address), key); + while (!tronNetDelegate.isHitDown()) { + generateBlock(witnessAndAccount); + } + Assert.assertTrue(tronNetDelegate.isHitDown()); + check(); + } + + private Map addTestWitnessAndAccount() { + chainManager.getWitnesses().clear(); + return IntStream.range(0, 2) + .mapToObj( + i -> { + ECKey ecKey = new ECKey(Utils.getRandom()); + String privateKey = ByteArray.toHexString(ecKey.getPrivKey().toByteArray()); + ByteString address = ByteString.copyFrom(ecKey.getAddress()); + + WitnessCapsule witnessCapsule = new WitnessCapsule(address); + chainManager.getWitnessStore().put(address.toByteArray(), witnessCapsule); + chainManager.addWitness(address); + + AccountCapsule accountCapsule = + new AccountCapsule(Protocol.Account.newBuilder().setAddress(address).build()); + chainManager.getAccountStore().put(address.toByteArray(), accountCapsule); + + return Maps.immutableEntry(address, privateKey); + }) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + } + + private BlockCapsule createTestBlockCapsule(long time, + long number, ByteString hash, + Map witnessAddressMap) { + ByteString witnessAddress = dposSlot.getScheduledWitness(dposSlot.getSlot(time)); + BlockCapsule blockCapsule = new BlockCapsule(number, Sha256Hash.wrap(hash), time, + witnessAddress); + blockCapsule.generatedByMyself = true; + blockCapsule.setMerkleRoot(); + blockCapsule.sign(ByteArray.fromHexString(witnessAddressMap.get(witnessAddress))); + return blockCapsule; + } + +} diff --git a/framework/src/test/java/org/tron/core/tire/TrieTest.java b/framework/src/test/java/org/tron/core/tire/TrieTest.java index 103972b2e91..7005198ad8b 100644 --- a/framework/src/test/java/org/tron/core/tire/TrieTest.java +++ b/framework/src/test/java/org/tron/core/tire/TrieTest.java @@ -26,6 +26,7 @@ import org.bouncycastle.util.Arrays; import org.junit.Assert; import org.junit.Test; +import org.tron.core.capsule.utils.FastByteComparisons; import org.tron.core.capsule.utils.RLP; import org.tron.core.trie.TrieImpl; import org.tron.core.trie.TrieImpl.Node; @@ -136,7 +137,7 @@ public void testOrder() { trie2.put(RLP.encodeInt(i), String.valueOf(i).getBytes()); } byte[] rootHash2 = trie2.getRootHash(); - Assert.assertTrue(java.util.Arrays.equals(rootHash1, rootHash2)); + Assert.assertArrayEquals(rootHash1, rootHash2); } private void assertTrue(byte[] key, TrieImpl trieCopy) { @@ -151,4 +152,11 @@ private void assertFalse(byte[] key1, byte[] key2, TrieImpl trieCopy) { Assert.assertFalse(trieCopy.verifyProof(trieCopy.getRootHash(), key2, trieCopy.prove(key1))); } + @Test + public void testFastByteComparisons() { + byte[] test1 = new byte[] {0x00, 0x00, 0x01, 0x02, 0x03, 0x04}; + byte[] test2 = new byte[] {0x00, 0x01, 0x02, 0x03, 0x04}; + Assert.assertEquals(0, FastByteComparisons.compareTo(test1, 1, 5, test2, 0, 5)); + } + } diff --git a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java index 56e115aa325..c7b55ed4417 100644 --- a/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java +++ b/framework/src/test/java/org/tron/core/witness/ProposalControllerTest.java @@ -1,57 +1,45 @@ package org.tron.core.witness; +import com.google.common.collect.Lists; import com.google.protobuf.ByteString; -import java.io.File; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.ProposalCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; import org.tron.core.consensus.ProposalController; -import org.tron.core.db.Manager; import org.tron.core.store.DynamicPropertiesStore; import org.tron.protos.Protocol.Proposal; import org.tron.protos.Protocol.Proposal.State; -public class ProposalControllerTest { +public class ProposalControllerTest extends BaseTest { - private static Manager dbManager; - private static ConsensusService consensusService; - private static TronApplicationContext context; - private static String dbPath = "output_proposal_controller_test"; + @Resource + private ConsensusService consensusService; private static ProposalController proposalController; + private static boolean init; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - consensusService = context.getBean(ConsensusService.class); + @Before + public void init() { + if (init) { + return; + } consensusService.start(); - proposalController = ProposalController - .createInstance(dbManager); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + proposalController = ProposalController.createInstance(dbManager); + init = true; } @Test @@ -199,7 +187,7 @@ public void testHasMostApprovals() { proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); } - Assert.assertEquals(true, proposalCapsule.hasMostApprovals(activeWitnesses)); + Assert.assertTrue(proposalCapsule.hasMostApprovals(activeWitnesses)); proposalCapsule.clearApproval(); for (int i = 1; i < 18; i++) { @@ -214,10 +202,7 @@ public void testHasMostApprovals() { for (int i = 0; i < 3; i++) { proposalCapsule.addApproval(ByteString.copyFrom(new byte[]{(byte) i})); } - Assert.assertEquals(true, proposalCapsule.hasMostApprovals(activeWitnesses)); - - + Assert.assertTrue(proposalCapsule.hasMostApprovals(activeWitnesses)); } - } diff --git a/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java b/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java index 665b5049bfc..26e46ac138c 100644 --- a/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java +++ b/framework/src/test/java/org/tron/core/witness/WitnessControllerTest.java @@ -3,51 +3,24 @@ import static org.junit.Assert.assertEquals; import com.google.protobuf.ByteString; -import java.io.File; import java.util.ArrayList; import java.util.List; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import javax.annotation.Resource; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.consensus.dpos.DposSlot; -import org.tron.core.ChainBaseManager; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; -public class WitnessControllerTest { +public class WitnessControllerTest extends BaseTest { - private static Manager dbManager = new Manager(); - private static DposSlot dposSlot; - private static ChainBaseManager chainBaseManager; + @Resource + private DposSlot dposSlot; - private static TronApplicationContext context; - private static String dbPath = "output_witness_controller_test"; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - ByteString blank = ByteString.copyFrom(new byte[1]); - - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - - dposSlot = context.getBean(DposSlot.class); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } @Test diff --git a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java index 2556b1b3005..049fb2528b1 100644 --- a/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/LibrustzcashTest.java @@ -1,5 +1,11 @@ package org.tron.core.zksnark; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertTrue; +import static org.tron.common.math.Maths.random; +import static org.tron.common.math.Maths.round; import static org.tron.common.zksnark.JLibrustzcash.librustzcashCheckDiversifier; import static org.tron.common.zksnark.JLibrustzcash.librustzcashComputeCm; import static org.tron.common.zksnark.JLibrustzcash.librustzcashIvkToPkd; @@ -11,23 +17,20 @@ import static org.tron.common.zksnark.JLibsodium.CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES; import com.google.protobuf.ByteString; -import java.io.File; +import java.util.Arrays; import java.util.Optional; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; import java.util.stream.LongStream; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.Assert; import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; @@ -46,13 +49,12 @@ import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.PedersenHashCapsule; import org.tron.core.capsule.SpendDescriptionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.zen.ZenTransactionBuilder; import org.tron.core.zen.ZenTransactionBuilder.SpendDescriptionInfo; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; import org.tron.core.zen.address.FullViewingKey; @@ -65,44 +67,28 @@ import org.tron.protos.contract.ShieldContract.PedersenHash; @Slf4j -public class LibrustzcashTest { +public class LibrustzcashTest extends BaseTest { + private static final String dbDirectory = "db_Librustzcash_test"; + private static final String indexDirectory = "index_Librustzcash_test"; + @Resource + private Wallet wallet; - private static String dbPath = "output_Librustzcash_test"; - private static String dbDirectory = "db_Librustzcash_test"; - private static String indexDirectory = "index_Librustzcash_test"; - private static AnnotationConfigApplicationContext context; - private static Wallet wallet; - - static { + @BeforeClass + public static void init() { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w", "--debug" }, "config-test-mainnet.conf" ); - - context = new TronApplicationContext(DefaultConfig.class); - } - - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); Args.setFullNodeAllowShieldedTransaction(true); } - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random(true) * (maxInt - minInt) + minInt, true); } public static void test(byte[] K, byte[] ovk, byte[] cv, byte[] cm, byte[] epk) @@ -117,22 +103,20 @@ public static void test(byte[] K, byte[] ovk, byte[] cv, byte[] cm, byte[] epk) byte[] personalization = new byte[16]; byte[] aa = "Zcash_Derive_ock".getBytes(); System.arraycopy(aa, 0, personalization, 0, aa.length); - Assert.assertTrue( - JLibsodium.cryptoGenerichashBlack2bSaltPersonal( - new Black2bSaltPersonalParams(K, 32, block, 128, null, 0, // No key. - null, // No salt. - personalization)) == 0); + assertEquals(0, JLibsodium.cryptoGenerichashBlack2bSaltPersonal( + new Black2bSaltPersonalParams(K, 32, block, 128, null, 0, // No key. + null, // No salt. + personalization))); byte[] cipher_nonce = new byte[CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES]; - Assert.assertTrue(JLibsodium + assertNotEquals(0, JLibsodium .cryptoAeadChacha20poly1305IetfDecrypt(new Chacha20poly1305IetfDecryptParams( new byte[1024], null, null, new byte[1024], 1024, - null, 0, cipher_nonce, K)) != 0); + null, 0, cipher_nonce, K))); } public static void librustzcashInitZksnarkParams() { - - FullNodeHttpApiService.librustzcashInitZksnarkParams(); + ZksnarkInitService.librustzcashInitZksnarkParams(); } @Test @@ -148,8 +132,6 @@ public void testLibsodium() throws ZksnarkException { @Test public void testZcashParam() throws ZksnarkException { byte[] d = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - //byte[] d ={}; - //byte[] pkD = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15}; byte[] ivk = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; @@ -161,7 +143,7 @@ public void testZcashParam() throws ZksnarkException { (byte) 0xb4, 0x7d, 0x0e}; byte[] cm = new byte[32]; boolean check_d = librustzcashCheckDiversifier(d); - Assert.assertTrue(check_d); + assertTrue(check_d); //Most significant five bits of ivk must be 0. ivk[31] = (byte) 0x07; @@ -173,10 +155,10 @@ public void testZcashParam() throws ZksnarkException { System.out.printf("\n"); } } - Assert.assertTrue(check_pkd); + assertTrue(check_pkd); boolean res = librustzcashComputeCm(new ComputeCmParams(d, pkD, value, r, cm)); - Assert.assertFalse(res); + assertFalse(res); //check range of alpha byte[] ask = {(byte) 0xb7, 0x2c, (byte) 0xf7, (byte) 0xd6, 0x5e, 0x0e, (byte) 0x97, (byte) 0xd0, @@ -196,14 +178,14 @@ public void testZcashParam() throws ZksnarkException { boolean boolSigRes = librustzcashSaplingSpendSig( new SpendSigParams(ask, alpha, sighash, sigRes)); - Assert.assertFalse(boolSigRes); + assertFalse(boolSigRes); byte[] nsk = {(byte) 0xb6, 0x2c, (byte) 0xf7, (byte) 0xd6, 0x5e, 0x0e, (byte) 0x97, (byte) 0xd0, (byte) 0x82, 0x10, (byte) 0xc8, (byte) 0xcc, (byte) 0x93, 0x20, 0x68, (byte) 0xa6, 0x00, 0x3b, 0x34, 0x01, 0x01, 0x3b, 0x67, 0x06, (byte) 0xa9, (byte) 0xaf, 0x33, 0x65, (byte) 0xea, (byte) 0xb4, 0x7d, 0x0e}; - byte[] nk = new byte[32]; + byte[] nk; nk = librustzcashNskToNk(nsk); for (int j = 0; j < 32; j++) { @@ -217,7 +199,7 @@ public void testZcashParam() throws ZksnarkException { byte[] resbindSig = new byte[64]; boolean boolBindSig = librustzcashSaplingBindingSig( new BindingSigParams(ctx, value, sighash, resbindSig)); - Assert.assertFalse(boolBindSig); + assertFalse(boolBindSig); JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); } @@ -284,15 +266,14 @@ public long benchmarkCreateSpend() throws ZksnarkException { zkproof)); JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ret); - long time = (System.currentTimeMillis() - start); - System.out.println("--- time is: " + time + ", result is " + ret); + assertTrue(ret); return time; } - // @Test + @Ignore + @Test public void calBenchmarkSpendConcurrent() throws Exception { librustzcashInitZksnarkParams(); System.out.println("--- load ok ---"); @@ -307,24 +288,17 @@ public void calBenchmarkSpendConcurrent() throws Exception { ExecutorService generatePool = Executors.newFixedThreadPool( availableProcessors, - new ThreadFactory() { - @Override - public Thread newThread(Runnable r) { - return new Thread(r, "generate-transaction"); - } - }); + r -> new Thread(r, "generate-transaction")); long startGenerate = System.currentTimeMillis(); - LongStream.range(0L, count).forEach(l -> { - generatePool.execute(() -> { - try { - benchmarkCreateSpend(); - } catch (Exception ex) { - ex.printStackTrace(); - logger.error("", ex); - } - }); - }); + LongStream.range(0L, count).forEach(l -> generatePool.execute(() -> { + try { + benchmarkCreateSpend(); + } catch (Exception ex) { + ex.printStackTrace(); + logger.error("", ex); + } + })); countDownLatch.await(); @@ -466,7 +440,7 @@ public long benchmarkCreateSaplingOutput() throws BadItemException, ZksnarkExcep JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(result); + assertTrue(result); long endTime = System.currentTimeMillis(); long time = endTime - startTime; @@ -526,7 +500,7 @@ public void checkVerifyOutErr() throws ZksnarkException { JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertFalse(result); + assertFalse(result); } @Test @@ -550,19 +524,20 @@ public void testGenerateNote() throws Exception { try { Optional op = incomingViewingKey.address(diversifierT); // PaymentAddress op = spendingKey.defaultAddress(); - - Note note = new Note(op.get(), 100); - note.setRcm(ByteArray - .fromHexString( - "bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - - byte[] cm = note.cm(); - if (cm != null) { - success++; - } else { - fail++; + if (op.isPresent()) { + Note note = new Note(op.get(), 100); + note.setRcm(ByteArray + .fromHexString( + "bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); + + byte[] cm = note.cm(); + if (cm != null) { + success++; + } else { + fail++; + } + System.out.println("note is " + Arrays.toString(cm)); } - System.out.println("note is " + note.cm()); } catch (ZksnarkException e) { System.out.println("failed: " + e.getMessage()); fail++; @@ -573,7 +548,7 @@ public void testGenerateNote() throws Exception { System.out.println("success is: " + success); System.out.println("fail is: " + fail); - Assert.assertEquals(0, fail); + assertEquals(0, fail); } @Test @@ -615,7 +590,7 @@ public void testGenerateNoteWithDefault() throws Exception { System.out.println("success is: " + success); System.out.println("fail is: " + fail); - Assert.assertEquals(0, fail); + assertEquals(0, fail); } @Test @@ -635,13 +610,14 @@ public void testGenerateNoteWithConstant() throws Exception { try { Optional op = incomingViewingKey.address(diversifierT); // PaymentAddress op = spendingKey.defaultAddress(); + if (op.isPresent()) { + Note note = new Note(op.get(), randomInt(100, 100000)); + note.setRcm(ByteArray + .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - Note note = new Note(op.get(), randomInt(100, 100000)); - note.setRcm(ByteArray - .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - - byte[] cm = note.cm(); - System.out.println("note is " + note.cm()); + byte[] cm = note.cm(); + System.out.println("note is " + Arrays.toString(cm)); + } } catch (ZksnarkException e) { System.out.println("failed: " + e.getMessage()); } @@ -659,7 +635,7 @@ public void testPedersenHash() throws Exception { byte[] res = new byte[32]; JLibrustzcash.librustzcashMerkleHash(new MerkleHashParams(25, a, b, res)); - Assert.assertEquals("61a50a5540b4944da27cbd9b3d6ec39234ba229d2c461f4d719bc136573bf45b", + assertEquals("61a50a5540b4944da27cbd9b3d6ec39234ba229d2c461f4d719bc136573bf45b", ByteArray.toHexString(res)); } } diff --git a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java index 60c5dd43eac..183a504ee35 100644 --- a/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/MerkleContainerTest.java @@ -2,19 +2,14 @@ import com.google.protobuf.Any; import com.google.protobuf.ByteString; -import java.io.File; -import java.util.Arrays; -import org.junit.AfterClass; +import javax.annotation.Resource; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; -import org.tron.common.zksnark.MerkleContainer; import org.tron.core.Constant; import org.tron.core.Wallet; import org.tron.core.capsule.BlockCapsule; @@ -23,13 +18,12 @@ import org.tron.core.capsule.IncrementalMerkleVoucherCapsule; import org.tron.core.capsule.PedersenHashCapsule; import org.tron.core.capsule.TransactionCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ZksnarkException; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract.ContractType; +import org.tron.protos.contract.ShieldContract.IncrementalMerkleTree; import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; import org.tron.protos.contract.ShieldContract.OutputPoint; import org.tron.protos.contract.ShieldContract.OutputPointInfo; @@ -37,38 +31,28 @@ import org.tron.protos.contract.ShieldContract.ReceiveDescription; import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; -public class MerkleContainerTest { +public class MerkleContainerTest extends BaseTest { - private static Manager dbManager = new Manager(); - private static TronApplicationContext context; - private static String dbPath = "MerkleContainerTest"; - private static MerkleContainer merkleContainer; + @Resource + private Wallet wallet; + // private static MerkleContainer merkleContainer; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); + /*@Before + public void init() { merkleContainer = MerkleContainer .createInstance(dbManager.getMerkleTreeStore(), dbManager.getChainBaseManager() .getMerkleTreeIndexStore()); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } + }*/ - @Test + /*@Test public void test() { //add - /*IncrementalMerkleTreeContainer tree = new IncrementalMerkleTreeContainer( + IncrementalMerkleTreeContainer tree = new IncrementalMerkleTreeContainer( new IncrementalMerkleTreeCapsule()); String s1 = "2ec45f5ae2d1bc7a80df02abfb2814a1239f956c6fb3ac0e112c008ba2c1ab91"; PedersenHashCapsule compressCapsule1 = new PedersenHashCapsule(); @@ -164,9 +148,9 @@ public void test() { .putMerkleVoucherIntoStore(witness.getMerkleVoucherKey(), witness.getVoucherCapsule()); IncrementalMerkleTreeContainer bestMerkleRoot = merkleContainer.getBestMerkle(); - Assert.assertEquals(1, bestMerkleRoot.size());*/ + Assert.assertEquals(1, bestMerkleRoot.size()); - } + }*/ private Transaction createTransaction(String strCm1, String strCm2) { ByteString cm1 = ByteString.copyFrom(ByteArray.fromHexString(strCm1)); @@ -182,9 +166,8 @@ private Transaction createTransaction(String strCm1, String strCm2) { Transaction.Contract.newBuilder().setType(ContractType.ShieldedTransferContract) .setParameter( Any.pack(contract)).build()); - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) + return Transaction.newBuilder().setRawData(transactionBuilder.build()) .build(); - return transaction; } private void initMerkleTreeWitnessInfo() throws ZksnarkException { @@ -361,7 +344,6 @@ public void getMerkleTreeWitnessInfoTest() throws Exception { OutputPointInfo outputPointInfo = OutputPointInfo.newBuilder().addOutPoints(outputPoint1) .addOutPoints(outputPoint2).setBlockNum(number).build(); // Args.getInstance().setAllowShieldedTransaction(1); - Wallet wallet = context.getBean(Wallet.class); IncrementalMerkleVoucherInfo merkleTreeWitnessInfo = wallet .getMerkleTreeVoucherInfo(outputPointInfo); @@ -426,7 +408,7 @@ public void append() throws ZksnarkException { byte[] roota = witnessa.root().getContent().toByteArray(); byte[] rootb = witnessb.root().getContent().toByteArray(); - Assert.assertTrue(Arrays.equals(roota, rootb)); + Assert.assertArrayEquals(roota, rootb); } } diff --git a/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java b/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java index 155d5aee11a..faea3780135 100644 --- a/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/MerkleTreeTest.java @@ -2,76 +2,59 @@ import com.alibaba.fastjson.JSONArray; import com.google.common.base.Charsets; +import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.protobuf.ByteString; import java.io.File; import java.util.List; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; +import org.junit.Before; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.testng.collections.Lists; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleTreeContainer.EmptyMerkleRoots; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.MerklePath; -import org.tron.core.Wallet; import org.tron.core.capsule.IncrementalMerkleTreeCapsule; import org.tron.core.capsule.IncrementalMerkleVoucherCapsule; import org.tron.core.capsule.PedersenHashCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.contract.ShieldContract.PedersenHash; -public class MerkleTreeTest { +public class MerkleTreeTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; - private static String dbPath = "output_ShieldedTransaction_test"; - private static String dbDirectory = "db_ShieldedTransaction_test"; - private static String indexDirectory = "index_ShieldedTransaction_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; + private static final String dbDirectory = "db_ShieldedTransaction_test"; + private static final String indexDirectory = "index_ShieldedTransaction_test"; + private static boolean init; static { Args.setParam( new String[]{ - "--output-directory", dbPath, + "--output-directory", dbPath(), "--storage-db-directory", dbDirectory, "--storage-index-directory", indexDirectory, - "-w", "--debug" }, "config-test-mainnet.conf" ); - context = new TronApplicationContext(DefaultConfig.class); } /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(100_000L); - dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); + init = true; } private JSONArray readFile(String fileName) throws Exception { @@ -80,10 +63,8 @@ private JSONArray readFile(String fileName) throws Exception { List readLines = Files.readLines(new File(file1), Charsets.UTF_8); - JSONArray array = JSONArray + return JSONArray .parseArray(readLines.stream().reduce((s, s2) -> s + s2).get()); - - return array; } private String PedersenHash2String(PedersenHash hash) { diff --git a/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java b/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java index f77a85b5bc1..3c3fb14b2b1 100644 --- a/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/NoteEncDecryTest.java @@ -1,22 +1,17 @@ package org.tron.core.zksnark; import com.google.protobuf.ByteString; -import java.io.File; import java.util.Optional; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; import org.tron.core.Wallet; import org.tron.core.capsule.AssetIssueCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.ZksnarkException; import org.tron.core.zen.note.Note; import org.tron.core.zen.note.NoteEncryption.Encryption; @@ -25,11 +20,9 @@ import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; @Slf4j -public class NoteEncDecryTest { +public class NoteEncDecryTest extends BaseTest { - private static final String dbPath = "note_encdec_test"; private static final String FROM_ADDRESS; - private static final String ADDRESS_ONE_PRIVATE_KEY; private static final long OWNER_BALANCE = 100_000_000; private static final long FROM_AMOUNT = 110_000_000; private static final long tokenId = 1; @@ -41,42 +34,27 @@ public class NoteEncDecryTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static Manager dbManager; - private static TronApplicationContext context; - private static Wallet wallet; + private static boolean init; + @Resource + private Wallet wallet; static { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-localtest.conf"); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, "config-localtest.conf"); FROM_ADDRESS = Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; - ADDRESS_ONE_PRIVATE_KEY = "7f7f701e94d4f1dd60ee5205e7ea8ee31121427210417b608a6b2e96433549a7"; } /** * Init data. */ - @BeforeClass - public static void init() { - wallet = context.getBean(Wallet.class); - dbManager = context.getBean(Manager.class); + @Before + public void init() { + if (init) { + return; + } //give a big value for pool, avoid for dbManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(10_000_000_000L); // Args.getInstance().setAllowShieldedTransaction(1); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } /** diff --git a/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java b/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java index 155e0477d65..da4df70d9ac 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SaplingNoteTest.java @@ -1,14 +1,17 @@ package org.tron.core.zksnark; +import static org.tron.common.math.Maths.random; +import static org.tron.common.math.Maths.round; + import org.junit.AfterClass; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.testng.Assert; import org.tron.common.utils.ByteArray; import org.tron.core.config.args.Args; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.PaymentAddress; import org.tron.core.zen.address.SpendingKey; @@ -21,7 +24,7 @@ public class SaplingNoteTest { public static void init() { Args.setFullNodeAllowShieldedTransaction(true); // Args.getInstance().setAllowShieldedTransaction(1); - FullNodeHttpApiService.librustzcashInitZksnarkParams(); + ZksnarkInitService.librustzcashInitZksnarkParams(); } @AfterClass @@ -30,7 +33,7 @@ public static void removeDb() { } private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); + return (int) round(random(true) * (maxInt - minInt) + minInt, true); } @Test 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 1eb5becffb6..7746066abfa 100644 --- a/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/SendCoinShieldTest.java @@ -4,26 +4,26 @@ import com.alibaba.fastjson.JSONArray; import com.google.common.base.Charsets; +import com.google.common.collect.Lists; import com.google.common.io.Files; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.io.File; import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Optional; -import org.junit.AfterClass; +import javax.annotation.Resource; +import lombok.extern.slf4j.Slf4j; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; +import org.junit.Ignore; import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.testng.collections.Lists; import org.tron.api.GrpcAPI; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.FileUtil; import org.tron.common.utils.Sha256Hash; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleTreeContainer.EmptyMerkleRoots; @@ -50,9 +50,7 @@ import org.tron.core.capsule.SpendDescriptionCapsule; import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ContractExeException; @@ -66,9 +64,9 @@ import org.tron.core.exception.VMIllegalException; import org.tron.core.exception.ValidateSignatureException; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.zen.ZenTransactionBuilder; import org.tron.core.zen.ZenTransactionBuilder.SpendDescriptionInfo; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; import org.tron.core.zen.address.FullViewingKey; @@ -90,7 +88,8 @@ import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; import org.tron.protos.contract.ShieldContract.SpendDescription; -public class SendCoinShieldTest { +@Slf4j +public class SendCoinShieldTest extends BaseTest { public static final long totalBalance = 1000_0000_000_000L; private static final byte[] DEFAULT_OVK; @@ -105,16 +104,14 @@ public class SendCoinShieldTest { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static String dbPath = "output_ShieldedTransaction_test"; - private static String dbDirectory = "db_ShieldedTransaction_test"; - private static String indexDirectory = "index_ShieldedTransaction_test"; - private static AnnotationConfigApplicationContext context; - private static Manager dbManager; - private static Wallet wallet; + @Resource + private Wallet wallet; + + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-test-mainnet.conf"); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"--output-directory", dbPath()}, "config-test-mainnet.conf"); + Args.getInstance().setZenTokenId(String.valueOf(tokenId)); PUBLIC_ADDRESS_ONE = Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; DEFAULT_OVK = ByteArray @@ -124,49 +121,42 @@ public class SendCoinShieldTest { /** * Init data. */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - wallet = context.getBean(Wallet.class); + @Before + public void init() { + if (init) { + return; + } //init energy dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(1526647838000L); dbManager.getDynamicPropertiesStore().saveTotalEnergyWeight(100_000L); dbManager.getDynamicPropertiesStore().saveLatestBlockHeaderTimestamp(0); - } - - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - FileUtil.deleteDir(new File(dbPath)); - } - /** - * create temp Capsule test need. - */ - @Before - public void createCapsule() { - Args.getInstance().setZenTokenId(String.valueOf(tokenId)); dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(1); dbManager.getDynamicPropertiesStore().saveTokenIdNum(tokenId); AssetIssueContract assetIssueContract = AssetIssueContract.newBuilder() .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(PUBLIC_ADDRESS_ONE))) - .setName(ByteString.copyFrom(ByteArray.fromString(ASSET_NAME))) + .setName(ByteString.copyFrom(Objects.requireNonNull(ByteArray.fromString(ASSET_NAME)))) .setId(Long.toString(tokenId)).setTotalSupply(OWNER_BALANCE).setTrxNum(TRX_NUM).setNum(NUM) .setStartTime(START_TIME).setEndTime(END_TIME).setVoteScore(VOTE_SCORE) - .setDescription(ByteString.copyFrom(ByteArray.fromString(DESCRIPTION))) - .setUrl(ByteString.copyFrom(ByteArray.fromString(URL))).build(); + .setDescription(ByteString.copyFrom( + Objects.requireNonNull(ByteArray.fromString(DESCRIPTION)))) + .setUrl(ByteString.copyFrom(Objects.requireNonNull(ByteArray.fromString(URL)))).build(); AssetIssueCapsule assetIssueCapsule = new AssetIssueCapsule(assetIssueContract); dbManager.getAssetIssueV2Store().put(assetIssueCapsule.createDbV2Key(), assetIssueCapsule); + + init = true; } private void addZeroValueOutputNote(ZenTransactionBuilder builder) throws ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); - builder.addOutput(DEFAULT_OVK, paymentAddress, 0, "just for decode for ovk".getBytes()); + Optional optional = incomingViewingKey.address(DiversifierT.random()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(DEFAULT_OVK, paymentAddress, 0, "just for decode for ovk".getBytes()); + } } @Test @@ -180,7 +170,9 @@ public void testPathMock() throws ZksnarkException { List index = Lists.newArrayList(Arrays.asList(indexArray)); MerklePath path = new MerklePath(authenticationPath, index); byte[] encode = path.encode(); - System.out.print(ByteArray.toHexString(encode)); + String hexString = ByteArray.toHexString(encode); + System.out.print(hexString); + Assert.assertNotNull(hexString); } private PedersenHash String2PedersenHash(String str) { @@ -224,20 +216,21 @@ private IncrementalMerkleVoucherContainer createSimpleMerkleVoucherContainer(byt compressCapsule1.setContent(ByteString.copyFrom(cm)); PedersenHash a = compressCapsule1.getInstance(); tree.append(a); - IncrementalMerkleVoucherContainer voucher = tree.toVoucher(); - return voucher; + return tree.toVoucher(); } - private void librustzcashInitZksnarkParams() throws ZksnarkException { - FullNodeHttpApiService.librustzcashInitZksnarkParams(); + private void librustzcashInitZksnarkParams() { + ZksnarkInitService.librustzcashInitZksnarkParams(); } @Test - public void testStringRevert() throws Exception { + public void testStringRevert() { byte[] bytes = ByteArray .fromHexString("6c030e6d7460f91668cc842ceb78cdb54470469e78cd59cf903d3a6e1aa03e7c"); ByteUtil.reverse(bytes); - System.out.println("testStringRevert------" + ByteArray.toHexString(bytes)); + String hexString = ByteArray.toHexString(bytes); + System.out.println("testStringRevert------" + hexString); + Assert.assertNotNull(hexString); } @Test @@ -250,12 +243,9 @@ public void testGenerateSpendProof() throws Exception { DiversifierT diversifierT = new DiversifierT(); byte[] d; - while (true) { + do { d = org.tron.keystore.Wallet.generateRandomBytes(Constant.ZC_DIVERSIFIER_SIZE); - if (JLibrustzcash.librustzcashCheckDiversifier(d)) { - break; - } - } + } while (!JLibrustzcash.librustzcashCheckDiversifier(d)); diversifierT.setData(d); FullViewingKey fullViewingKey = expsk.fullViewingKey(); @@ -263,17 +253,19 @@ public void testGenerateSpendProof() throws Exception { IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); Optional op = incomingViewingKey.address(diversifierT); + if (op.isPresent()) { + Note note = new Note(op.get(), 100); + note.setRcm(ByteArray + .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - Note note = new Note(op.get(), 100); - note.setRcm(ByteArray - .fromHexString("bf4b2042e3e8c4a0b390e407a79a0b46e36eff4f7bb54b2349dbb0046ee21e02")); - - IncrementalMerkleVoucherContainer voucher = createComplexMerkleVoucherContainer(note.cm()); + IncrementalMerkleVoucherContainer voucher = createComplexMerkleVoucherContainer(note.cm()); - byte[] anchor = voucher.root().getContent().toByteArray(); - SpendDescriptionInfo spend = new SpendDescriptionInfo(expsk, note, anchor, voucher); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - SpendDescriptionCapsule sdesc = builder.generateSpendProof(spend, ctx); + byte[] anchor = voucher.root().getContent().toByteArray(); + SpendDescriptionInfo spend = new SpendDescriptionInfo(expsk, note, anchor, voucher); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + SpendDescriptionCapsule sdesc = builder.generateSpendProof(spend, ctx); + Assert.assertNotNull(sdesc); + } } @Test @@ -284,11 +276,15 @@ public void generateOutputProof() throws ZksnarkException { FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); - builder.generateOutputProof(builder.getReceives().get(0), ctx); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + Assert.assertNotNull(paymentAddress); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); + builder.generateOutputProof(builder.getReceives().get(0), ctx); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + } } @Test @@ -298,24 +294,27 @@ public void verifyOutputProof() throws ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); - ReceiveDescriptionCapsule capsule = builder - .generateOutputProof(builder.getReceives().get(0), ctx); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - ReceiveDescription receiveDescription = capsule.getInstance(); - ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); - if (!JLibrustzcash.librustzcashSaplingCheckOutput( - new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), - receiveDescription.getEpk().toByteArray(), - receiveDescription.getZkproof().toByteArray()))) { + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + Assert.assertNotNull(paymentAddress); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, new byte[512]); + ReceiveDescriptionCapsule capsule = builder + .generateOutputProof(builder.getReceives().get(0), ctx); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + ReceiveDescription receiveDescription = capsule.getInstance(); + ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); + if (!JLibrustzcash.librustzcashSaplingCheckOutput( + new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), + receiveDescription.getEpk().toByteArray(), + receiveDescription.getZkproof().toByteArray()))) { + JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); + throw new RuntimeException("librustzcashSaplingCheckOutput error"); + } JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); - throw new RuntimeException("librustzcashSaplingCheckOutput error"); } - JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); } @@ -329,49 +328,54 @@ public void testDecryptReceiveWithIvk() throws ZksnarkException { FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); - long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, memo); + long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000, memo); - ZenTransactionBuilder.ReceiveDescriptionInfo output = builder.getReceives().get(0); - ReceiveDescriptionCapsule receiveDescriptionCapsule = builder.generateOutputProof(output, ctx); - ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); + ZenTransactionBuilder.ReceiveDescriptionInfo output = builder.getReceives().get(0); + ReceiveDescriptionCapsule receiveDescriptionCapsule = builder + .generateOutputProof(output, ctx); + ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); - Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext - fullViewingKey.inViewingKey().getValue(), receiveDescription.getEpk().toByteArray(),//epk - receiveDescription.getNoteCommitment().toByteArray() //cm - ); + Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext + fullViewingKey.inViewingKey().getValue(), receiveDescription.getEpk().toByteArray(),//epk + receiveDescription.getNoteCommitment().toByteArray() //cm + ); - Assert.assertTrue(ret1.isPresent()); + Assert.assertTrue(ret1.isPresent()); - Note noteText = ret1.get(); - byte[] pkD = new byte[32]; - if (!JLibrustzcash.librustzcashIvkToPkd( - new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - return; - } + Note noteText = ret1.get(); + byte[] pkD = new byte[32]; + if (!JLibrustzcash.librustzcashIvkToPkd( + new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + return; + } - Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); - Assert.assertEquals(noteText.getValue(), 4000); - Assert.assertArrayEquals(noteText.getMemo(), memo); + Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); + Assert.assertEquals(4000, noteText.getValue()); + Assert.assertArrayEquals(noteText.getMemo(), memo); - String paymentAddressStr = KeyIo.encodePaymentAddress(new PaymentAddress(noteText.getD(), pkD)); + String paymentAddressStr = KeyIo.encodePaymentAddress( + new PaymentAddress(noteText.getD(), pkD)); - GrpcAPI.Note grpcAPINote = GrpcAPI.Note.newBuilder().setPaymentAddress(paymentAddressStr) - .setValue(noteText.getValue()).setRcm(ByteString.copyFrom(noteText.getRcm())) - .setMemo(ByteString.copyFrom(noteText.getMemo())).build(); + GrpcAPI.Note grpcAPINote = GrpcAPI.Note.newBuilder().setPaymentAddress(paymentAddressStr) + .setValue(noteText.getValue()).setRcm(ByteString.copyFrom(noteText.getRcm())) + .setMemo(ByteString.copyFrom(noteText.getMemo())).build(); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + } } public String byte2intstring(byte[] input) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < input.length; i++) { - sb.append(String.valueOf((int) input[i]) + ", "); + sb.append(String.valueOf(input[i])).append(", "); if (i % 16 == 15) { sb.append("\n"); } @@ -408,48 +412,50 @@ public void testDecryptReceiveWithOvk() throws Exception { byte[] cmuOpt = note.cm(); Assert.assertNotNull(cmuOpt); - NotePlaintextEncryptionResult enc = note.encrypt(pkd).get(); - NoteEncryption encryptor = enc.getNoteEncryption(); - OutgoingPlaintext outgoingPlaintext = new OutgoingPlaintext(note.getPkD(), encryptor.getEsk()); - - // encrypt with ovk - Encryption.OutCiphertext outCiphertext = outgoingPlaintext - .encrypt(fullViewingKey.getOvk(), receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), encryptor); - - // get pkD, esk from decryption of c_out with ovk - Optional ret2 = OutgoingPlaintext - .decrypt(outCiphertext, fullViewingKey.getOvk(), - receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), encryptor.getEpk()); - - if (ret2.isPresent()) { - OutgoingPlaintext decryptedOutgoingPlaintext = ret2.get(); - Assert.assertArrayEquals(decryptedOutgoingPlaintext.getPkD(), outgoingPlaintext.getPkD()); - Assert.assertArrayEquals(decryptedOutgoingPlaintext.getEsk(), outgoingPlaintext.getEsk()); - - //decrypt c_enc with pkd、esk - Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); - ciphertext.setData(enc.getEncCiphertext()); - Optional foo = Note - .decrypt(ciphertext, encryptor.getEpk(), decryptedOutgoingPlaintext.getEsk(), - decryptedOutgoingPlaintext.getPkD(), cmuOpt); - - if (foo.isPresent()) { - Note bar = foo.get(); - //verify result - Assert.assertEquals(4000, bar.getValue()); - Assert.assertArrayEquals(memo, bar.getMemo()); + Optional optional = note.encrypt(pkd); + if (optional.isPresent()) { + NotePlaintextEncryptionResult enc = optional.get(); + NoteEncryption encryptor = enc.getNoteEncryption(); + OutgoingPlaintext outgoingPlaintext = new OutgoingPlaintext( + note.getPkD(), encryptor.getEsk()); + // encrypt with ovk + Encryption.OutCiphertext outCiphertext = outgoingPlaintext + .encrypt(fullViewingKey.getOvk(), receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), encryptor); + + // get pkD, esk from decryption of c_out with ovk + Optional ret2 = OutgoingPlaintext + .decrypt(outCiphertext, fullViewingKey.getOvk(), + receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), encryptor.getEpk()); + + if (ret2.isPresent()) { + OutgoingPlaintext decryptedOutgoingPlaintext = ret2.get(); + Assert.assertArrayEquals(decryptedOutgoingPlaintext.getPkD(), outgoingPlaintext.getPkD()); + Assert.assertArrayEquals(decryptedOutgoingPlaintext.getEsk(), outgoingPlaintext.getEsk()); + + //decrypt c_enc with pkd、esk + Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); + ciphertext.setData(enc.getEncCiphertext()); + Optional foo = Note + .decrypt(ciphertext, encryptor.getEpk(), decryptedOutgoingPlaintext.getEsk(), + decryptedOutgoingPlaintext.getPkD(), cmuOpt); + + if (foo.isPresent()) { + Note bar = foo.get(); + //verify result + Assert.assertEquals(4000, bar.getValue()); + Assert.assertArrayEquals(memo, bar.getMemo()); + } else { + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.fail(); + } } else { JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertFalse(true); + Assert.fail(); } - } else { JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertFalse(true); } - - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); } @Test @@ -483,53 +489,55 @@ public void pushShieldedTransactionAndDecryptWithIvk() SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - builder - .addOutput(senderOvk, paymentAddress, 1000 * 1000000L - wallet.getShieldedTransactionFee(), - memo); - - TransactionCapsule transactionCap = builder.build(); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + builder.addOutput(senderOvk, paymentAddress, + 1000 * 1000000L - wallet.getShieldedTransactionFee(), memo); - boolean ok = dbManager.pushTransaction(transactionCap); - Assert.assertTrue(ok); + TransactionCapsule transactionCap = builder.build(); - // add here - byte[] ivk = incomingViewingKey.getValue(); - Protocol.Transaction t = transactionCap.getInstance(); + boolean ok = dbManager.pushTransaction(transactionCap); + Assert.assertTrue(ok); - for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { - if (c.getType() != ContractType.ShieldedTransferContract) { - continue; - } - ShieldedTransferContract stContract = c.getParameter() - .unpack(ShieldedTransferContract.class); - ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); + // add here + byte[] ivk = incomingViewingKey.getValue(); + Protocol.Transaction t = transactionCap.getInstance(); - Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext - ivk, receiveDescription.getEpk().toByteArray(),//epk - receiveDescription.getNoteCommitment().toByteArray() //cm - ); - - if (ret1.isPresent()) { - Note noteText = ret1.get(); - byte[] pkD = new byte[32]; - if (!JLibrustzcash.librustzcashIvkToPkd( - new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - return; + for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { + if (c.getType() != ContractType.ShieldedTransferContract) { + continue; + } + ShieldedTransferContract stContract = c.getParameter() + .unpack(ShieldedTransferContract.class); + ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); + + Optional ret1 = Note.decrypt(receiveDescription.getCEnc().toByteArray(),//ciphertext + ivk, receiveDescription.getEpk().toByteArray(),//epk + receiveDescription.getNoteCommitment().toByteArray() //cm + ); + + if (ret1.isPresent()) { + Note noteText = ret1.get(); + byte[] pkD = new byte[32]; + if (!JLibrustzcash.librustzcashIvkToPkd( + new IvkToPkdParams(incomingViewingKey.getValue(), noteText.getD().getData(), pkD))) { + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + return; + } + Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); + Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), + noteText.getValue()); + Assert.assertArrayEquals(memo, noteText.getMemo()); + } else { + Assert.fail(); } - Assert.assertArrayEquals(paymentAddress.getPkD(), pkD); - Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), - noteText.getValue()); - Assert.assertArrayEquals(memo, noteText.getMemo()); - } else { - Assert.assertFalse(true); } + // end here + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ok); } - // end here - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ok); } @Test @@ -570,59 +578,61 @@ public void pushShieldedTransactionAndDecryptWithOvk() SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); - builder - .addOutput(senderOvk, paymentAddress, 1000 * 1000000L - wallet.getShieldedTransactionFee(), - memo); - - TransactionCapsule transactionCap = builder.build(); - boolean ok = dbManager.pushTransaction(transactionCap); - Assert.assertTrue(ok); - - // add here - Protocol.Transaction t = transactionCap.getInstance(); - for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { - if (c.getType() != Protocol.Transaction.Contract.ContractType.ShieldedTransferContract) { - continue; - } - ShieldedTransferContract stContract = c.getParameter() - .unpack(ShieldedTransferContract.class); - ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); - - //first try to decrypt cOut with ovk, get pkd、esk - Encryption.OutCiphertext cOut = new Encryption.OutCiphertext(); - cOut.setData(receiveDescription.getCOut().toByteArray()); - Optional notePlaintext = OutgoingPlaintext.decrypt(cOut,//ciphertext - senderOvk, receiveDescription.getValueCommitment().toByteArray(), //cv - receiveDescription.getNoteCommitment().toByteArray(), //cmu - receiveDescription.getEpk().toByteArray() //epk - ); - - //then decrypt c_enc with pkd、esk, get decoded note == ciphertext - if (notePlaintext.isPresent()) { - OutgoingPlaintext decryptedOutgoingPlaintext = notePlaintext.get(); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + byte[] memo = org.tron.keystore.Wallet.generateRandomBytes(512); + builder.addOutput(senderOvk, paymentAddress, + 1000 * 1000000L - wallet.getShieldedTransactionFee(), memo); - Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); - ciphertext.setData(receiveDescription.getCEnc().toByteArray()); - Optional foo = Note.decrypt(ciphertext, receiveDescription.getEpk().toByteArray(), - decryptedOutgoingPlaintext.getEsk(), decryptedOutgoingPlaintext.getPkD(), - receiveDescription.getNoteCommitment().toByteArray()); - - if (foo.isPresent()) { - Note bar = foo.get(); - //verify result - Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), bar.getValue()); - Assert.assertArrayEquals(memo, bar.getMemo()); - } else { - Assert.assertFalse(true); + TransactionCapsule transactionCap = builder.build(); + boolean ok = dbManager.pushTransaction(transactionCap); + Assert.assertTrue(ok); + + // add here + Protocol.Transaction t = transactionCap.getInstance(); + for (org.tron.protos.Protocol.Transaction.Contract c : t.getRawData().getContractList()) { + if (c.getType() != Protocol.Transaction.Contract.ContractType.ShieldedTransferContract) { + continue; + } + ShieldedTransferContract stContract = c.getParameter() + .unpack(ShieldedTransferContract.class); + ReceiveDescription receiveDescription = stContract.getReceiveDescription(0); + + //first try to decrypt cOut with ovk, get pkd、esk + Encryption.OutCiphertext cOut = new Encryption.OutCiphertext(); + cOut.setData(receiveDescription.getCOut().toByteArray()); + Optional notePlaintext = OutgoingPlaintext.decrypt(cOut,//ciphertext + senderOvk, receiveDescription.getValueCommitment().toByteArray(), //cv + receiveDescription.getNoteCommitment().toByteArray(), //cmu + receiveDescription.getEpk().toByteArray() //epk + ); + + //then decrypt c_enc with pkd、esk, get decoded note == ciphertext + if (notePlaintext.isPresent()) { + OutgoingPlaintext decryptedOutgoingPlaintext = notePlaintext.get(); + + Encryption.EncCiphertext ciphertext = new Encryption.EncCiphertext(); + ciphertext.setData(receiveDescription.getCEnc().toByteArray()); + Optional foo = Note.decrypt(ciphertext, receiveDescription.getEpk().toByteArray(), + decryptedOutgoingPlaintext.getEsk(), decryptedOutgoingPlaintext.getPkD(), + receiveDescription.getNoteCommitment().toByteArray()); + + if (foo.isPresent()) { + Note bar = foo.get(); + //verify result + Assert.assertEquals(1000 * 1000000L - wallet.getShieldedTransactionFee(), + bar.getValue()); + Assert.assertArrayEquals(memo, bar.getMemo()); + } else { + Assert.fail(); + } } } + // end here + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ok); } - // end here - - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ok); } private byte[] getHash() { @@ -630,6 +640,8 @@ private byte[] getHash() { .getInstance().isECKeyCryptoEngine(), "this is a test".getBytes()).getBytes(); } + @Ignore + @Test public void checkZksnark() throws BadItemException, ZksnarkException { librustzcashInitZksnarkParams(); long ctx = JLibrustzcash.librustzcashSaplingProvingCtxInit(); @@ -652,14 +664,17 @@ public void checkZksnark() throws BadItemException, ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); - TransactionCapsule transactionCap = builder.build(); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - boolean ret = ZksnarkClient.getInstance().checkZksnarkProof(transactionCap.getInstance(), - getShieldTransactionHashIgnoreTypeException(transactionCap.getInstance()), - 10 * 1000000); - Assert.assertTrue(ret); + Optional optional = incomingViewingKey.address(DiversifierT.random()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); + TransactionCapsule transactionCap = builder.build(); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + boolean ret = ZksnarkClient.getInstance().checkZksnarkProof(transactionCap.getInstance(), + getShieldTransactionHashIgnoreTypeException(transactionCap.getInstance()), + 10 * 1000000); + Assert.assertTrue(ret); + } } @Test @@ -695,7 +710,7 @@ public void testVerifySpendProof() throws BadItemException, ZksnarkException { spendDescriptionCapsule.getRk().toByteArray(), spendDescriptionCapsule.getZkproof().toByteArray(), result, getHash())); JLibrustzcash.librustzcashSaplingVerificationCtxFree(verifyContext); - Assert.assertEquals(ok, true); + Assert.assertTrue(ok); } @Test @@ -717,16 +732,19 @@ public void saplingBindingSig() throws BadItemException, ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); - builder.generateOutputProof(builder.getReceives().get(0), ctx); - - // test create binding sig - byte[] bindingSig = new byte[64]; - boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( - new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ret); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); + builder.generateOutputProof(builder.getReceives().get(0), ctx); + + // test create binding sig + byte[] bindingSig = new byte[64]; + boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( + new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ret); + } } @Test @@ -756,13 +774,16 @@ public void pushShieldedTransaction() SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(DiversifierT.random()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, - 4010 * 1000000L - wallet.getShieldedTransactionFee(), new byte[512]); - TransactionCapsule transactionCap = builder.build(); - boolean ok = dbManager.pushTransaction(transactionCap); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ok); + Optional optional = incomingViewingKey.address(DiversifierT.random()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, + 4010 * 1000000L - wallet.getShieldedTransactionFee(), new byte[512]); + TransactionCapsule transactionCap = builder.build(); + boolean ok = dbManager.pushTransaction(transactionCap); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ok); + } } @Test @@ -785,46 +806,49 @@ public void finalCheck() throws BadItemException, ZksnarkException { SpendingKey spendingKey = SpendingKey.random(); FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(new DiversifierT()).get(); - builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); - ReceiveDescriptionCapsule receiveDescriptionCapsule = builder - .generateOutputProof(builder.getReceives().get(0), ctx); - - //create binding sig - byte[] bindingSig = new byte[64]; - boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( - new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); - JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); - Assert.assertTrue(ret); - // check spend - ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); - byte[] result = new byte[64]; - JLibrustzcash.librustzcashSaplingSpendSig( - new SpendSigParams(expsk.getAsk(), builder.getSpends().get(0).getAlpha(), getHash(), - result)); - - SpendDescription spendDescription = spendDescriptionCapsule.getInstance(); - boolean ok; - ok = JLibrustzcash.librustzcashSaplingCheckSpend( - new CheckSpendParams(ctx, spendDescription.getValueCommitment().toByteArray(), - spendDescription.getAnchor().toByteArray(), - spendDescription.getNullifier().toByteArray(), spendDescription.getRk().toByteArray(), - spendDescription.getZkproof().toByteArray(), result, getHash())); - Assert.assertTrue(ok); - - // check output - ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); - ok = JLibrustzcash.librustzcashSaplingCheckOutput( - new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), - receiveDescription.getNoteCommitment().toByteArray(), - receiveDescription.getEpk().toByteArray(), - receiveDescription.getZkproof().toByteArray())); - Assert.assertTrue(ok); - // final check - ok = JLibrustzcash.librustzcashSaplingFinalCheck( - new FinalCheckParams(ctx, builder.getValueBalance(), bindingSig, getHash())); - Assert.assertTrue(ok); - JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); + Optional optional = incomingViewingKey.address(new DiversifierT()); + if (optional.isPresent()) { + PaymentAddress paymentAddress = optional.get(); + builder.addOutput(fullViewingKey.getOvk(), paymentAddress, 4000 * 1000000L, new byte[512]); + ReceiveDescriptionCapsule receiveDescriptionCapsule = builder + .generateOutputProof(builder.getReceives().get(0), ctx); + + //create binding sig + byte[] bindingSig = new byte[64]; + boolean ret = JLibrustzcash.librustzcashSaplingBindingSig( + new BindingSigParams(ctx, builder.getValueBalance(), getHash(), bindingSig)); + JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); + Assert.assertTrue(ret); + // check spend + ctx = JLibrustzcash.librustzcashSaplingVerificationCtxInit(); + byte[] result = new byte[64]; + JLibrustzcash.librustzcashSaplingSpendSig( + new SpendSigParams(expsk.getAsk(), builder.getSpends().get(0).getAlpha(), getHash(), + result)); + + SpendDescription spendDescription = spendDescriptionCapsule.getInstance(); + boolean ok; + ok = JLibrustzcash.librustzcashSaplingCheckSpend( + new CheckSpendParams(ctx, spendDescription.getValueCommitment().toByteArray(), + spendDescription.getAnchor().toByteArray(), + spendDescription.getNullifier().toByteArray(), spendDescription.getRk().toByteArray(), + spendDescription.getZkproof().toByteArray(), result, getHash())); + Assert.assertTrue(ok); + + // check output + ReceiveDescription receiveDescription = receiveDescriptionCapsule.getInstance(); + ok = JLibrustzcash.librustzcashSaplingCheckOutput( + new CheckOutputParams(ctx, receiveDescription.getValueCommitment().toByteArray(), + receiveDescription.getNoteCommitment().toByteArray(), + receiveDescription.getEpk().toByteArray(), + receiveDescription.getZkproof().toByteArray())); + Assert.assertTrue(ok); + // final check + ok = JLibrustzcash.librustzcashSaplingFinalCheck( + new FinalCheckParams(ctx, builder.getValueBalance(), bindingSig, getHash())); + Assert.assertTrue(ok); + JLibrustzcash.librustzcashSaplingVerificationCtxFree(ctx); + } } @Test @@ -847,11 +871,11 @@ public void testEmptyRoots() throws Exception { } private JSONArray readFile(String fileName) throws Exception { - String file1 = SendCoinShieldTest.class.getClassLoader() - .getResource("json" + File.separator + fileName).getFile(); + String file1 = Objects.requireNonNull(SendCoinShieldTest.class.getClassLoader() + .getResource("json" + File.separator + fileName)).getFile(); List readLines = Files.readLines(new File(file1), Charsets.UTF_8); - JSONArray array = JSONArray.parseArray(readLines.stream().reduce((s, s2) -> s + s2).get()); - return array; + Optional optional = readLines.stream().reduce((s, s2) -> s + s2); + return optional.map(JSONArray::parseArray).orElse(null); } @@ -864,9 +888,9 @@ public void testComputeCm() throws Exception { 9990000000L, ByteArray .fromHexString("08e3a2ff1101b628147125b786c757b483f1cf7c309f8a647055bfb1ca819c02"), result))) { - System.out.println(" error"); + Assert.fail(); } else { - System.out.println(" ok"); + Assert.assertTrue(true); } } @@ -897,12 +921,9 @@ public void getSpendingKey() throws Exception { DiversifierT diversifierT = new DiversifierT(); byte[] d; - while (true) { + do { d = org.tron.keystore.Wallet.generateRandomBytes(Constant.ZC_DIVERSIFIER_SIZE); - if (JLibrustzcash.librustzcashCheckDiversifier(d)) { - break; - } - } + } while (!JLibrustzcash.librustzcashCheckDiversifier(d)); diversifierT.setData(d); System.out.println("d is: " + ByteArray.toHexString(d)); @@ -1336,7 +1357,7 @@ public void TestCreateMultipleTxAtTheSameTime() throws Exception { executeTx(transactionCapsule); System.out.println("Success execute tx,num:" + transactionCapsule.getBlockNum()); } catch (Exception ex) { - System.out.println(ex); + logger.error("error", ex); } }); } @@ -1531,7 +1552,7 @@ public void TestGeneratesProofWithWrongRcm() throws Exception { builder.addSpend(expsk, note, anchor, voucher); SpendDescriptionCapsule spendDescriptionCapsule = builder .generateSpendProof(builder.getSpends().get(0), ctx); - + Assert.assertNotNull(spendDescriptionCapsule); } @Test @@ -1641,9 +1662,7 @@ private TransactionCapsule generateDefaultBuilder(ZenTransactionBuilder builder) String TO_ADDRESS = generateDefaultToAccount(); builder.setTransparentOutput(ByteArray.fromHexString(TO_ADDRESS), 1000 * 1000000L - wallet.getShieldedTransactionFee()); - - TransactionCapsule transactionCap = builder.build(); - return transactionCap; + return builder.build(); } @Test @@ -1676,6 +1695,7 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println( "rk:" + ByteArray.toHexString(spendDescriptionCapsule.getRk().toByteArray())); spendDescriptionCapsule.setRk(fakeRk); + spendDescriptionCapsule.setRk(ByteString.copyFrom(fakeRk)); return spendDescriptionCapsule; } }; @@ -1718,6 +1738,9 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo .toHexString(spendDescriptionCapsule.getZkproof().toByteArray())); spendDescriptionCapsule.setZkproof(fakeProof); + spendDescriptionCapsule.setZkproof(ByteString.copyFrom(fakeProof)); + spendDescriptionCapsule.setSpendAuthoritySignature(spendDescriptionCapsule + .getSpendAuthoritySignature()); return spendDescriptionCapsule; } }; @@ -1756,6 +1779,7 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println( "nf:" + ByteArray.toHexString(spendDescriptionCapsule.getNullifier().toByteArray())); spendDescriptionCapsule.setNullifier(bytes); + spendDescriptionCapsule.setNullifier(ByteString.copyFrom(bytes)); return spendDescriptionCapsule; } }; @@ -1770,7 +1794,6 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo throw e; } System.out.println("Done"); - return; } } } @@ -1793,6 +1816,9 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo System.out.println( "bytes:" + ByteArray.toHexString(spendDescriptionCapsule.getAnchor().toByteArray())); spendDescriptionCapsule.setAnchor(bytes); + spendDescriptionCapsule.setAnchor(ByteString.copyFrom(bytes)); + spendDescriptionCapsule.setValueCommitment(new byte[32]); + spendDescriptionCapsule.setValueCommitment(ByteString.copyFrom(new byte[32])); return spendDescriptionCapsule; } }; @@ -1807,8 +1833,16 @@ public SpendDescriptionCapsule generateSpendProof(SpendDescriptionInfo spend, lo throw e; } System.out.println("Done"); - return; } } + + SpendDescriptionCapsule c = new SpendDescriptionCapsule(new byte[32]); + SpendDescriptionCapsule c1 = new SpendDescriptionCapsule(ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]),ByteString.copyFrom(new byte[32])); + Assert.assertNotNull(c); + Assert.assertNotNull(c1); } } 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 d3cbdb71e95..2a7545f7a9b 100755 --- a/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java +++ b/framework/src/test/java/org/tron/core/zksnark/ShieldedReceiveTest.java @@ -1,33 +1,36 @@ package org.tron.core.zksnark; +import static org.tron.common.utils.PublicMethod.getHexAddressByPrivateKey; +import static org.tron.common.utils.PublicMethod.getRandomPrivateKey; + import com.google.common.primitives.Bytes; import com.google.protobuf.Any; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; -import java.io.File; import java.security.SignatureException; import java.util.List; import java.util.Optional; +import javax.annotation.Resource; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; -import org.junit.BeforeClass; import org.junit.Test; import org.tron.api.GrpcAPI.BytesMessage; import org.tron.api.GrpcAPI.DecryptNotes; +import org.tron.api.GrpcAPI.DecryptNotesMarked; import org.tron.api.GrpcAPI.ReceiveNote; import org.tron.api.GrpcAPI.SpendAuthSigParameters; import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.common.crypto.ECKey; import org.tron.common.parameter.CommonParameter; import org.tron.common.utils.ByteArray; -import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; import org.tron.common.utils.Sha256Hash; +import org.tron.common.utils.client.utils.TransactionUtils; import org.tron.common.zksnark.IncrementalMerkleTreeContainer; import org.tron.common.zksnark.IncrementalMerkleVoucherContainer; import org.tron.common.zksnark.JLibrustzcash; @@ -37,7 +40,6 @@ import org.tron.common.zksnark.LibrustzcashParam.IvkToPkdParams; import org.tron.common.zksnark.LibrustzcashParam.OutputProofParams; import org.tron.common.zksnark.LibrustzcashParam.SpendSigParams; -import org.tron.core.ChainBaseManager; import org.tron.core.Wallet; import org.tron.core.actuator.Actuator; import org.tron.core.actuator.ActuatorCreator; @@ -52,11 +54,8 @@ import org.tron.core.capsule.TransactionCapsule; import org.tron.core.capsule.TransactionResultCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.consensus.ConsensusService; -import org.tron.core.db.BlockGenerate; -import org.tron.core.db.Manager; import org.tron.core.exception.AccountResourceInsufficientException; import org.tron.core.exception.BadItemException; import org.tron.core.exception.ContractExeException; @@ -72,11 +71,11 @@ import org.tron.core.exception.VMIllegalException; import org.tron.core.exception.ValidateSignatureException; import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.FullNodeHttpApiService; import org.tron.core.utils.TransactionUtil; import org.tron.core.zen.ZenTransactionBuilder; import org.tron.core.zen.ZenTransactionBuilder.ReceiveDescriptionInfo; import org.tron.core.zen.ZenTransactionBuilder.SpendDescriptionInfo; +import org.tron.core.zen.ZksnarkInitService; import org.tron.core.zen.address.DiversifierT; import org.tron.core.zen.address.ExpandedSpendingKey; import org.tron.core.zen.address.FullViewingKey; @@ -93,7 +92,6 @@ import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.Transaction; import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.TransactionSign; import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; import org.tron.protos.contract.ShieldContract.OutputPoint; @@ -104,9 +102,8 @@ import org.tron.protos.contract.ShieldContract.SpendDescription; @Slf4j -public class ShieldedReceiveTest extends BlockGenerate { +public class ShieldedReceiveTest extends BaseTest { - private static final String dbPath = "receive_description_test"; private static final String FROM_ADDRESS; private static final String ADDRESS_ONE_PRIVATE_KEY; private static final long OWNER_BALANCE = 100_000_000; @@ -120,56 +117,36 @@ public class ShieldedReceiveTest extends BlockGenerate { private static final int VOTE_SCORE = 2; private static final String DESCRIPTION = "TRX"; private static final String URL = "https://tron.network/"; - private static Manager dbManager; - private static ChainBaseManager chainBaseManager; - private static ConsensusService consensusService; - private static TronApplicationContext context; - private static Wallet wallet; - private static TransactionUtil transactionUtil; + @Resource + private ConsensusService consensusService; + @Resource + private Wallet wallet; + @Resource + private TransactionUtil transactionUtil; + + private static boolean init; static { - Args.setParam(new String[]{"--output-directory", dbPath}, "config-localtest.conf"); - context = new TronApplicationContext(DefaultConfig.class); - FROM_ADDRESS = Wallet.getAddressPreFixString() + "a7d8a35b260395c14aa456297662092ba3b76fc0"; - ADDRESS_ONE_PRIVATE_KEY = "7f7f701e94d4f1dd60ee5205e7ea8ee31121427210417b608a6b2e96433549a7"; + Args.setParam(new String[]{"--output-directory", dbPath()}, "config-localtest.conf"); + ADDRESS_ONE_PRIVATE_KEY = getRandomPrivateKey(); + FROM_ADDRESS = getHexAddressByPrivateKey(ADDRESS_ONE_PRIVATE_KEY);; } /** * Init data. */ - @BeforeClass - public static void init() { - FileUtil.deleteDir(new File(dbPath)); - - wallet = context.getBean(Wallet.class); - transactionUtil = context.getBean(TransactionUtil.class); - dbManager = context.getBean(Manager.class); - chainBaseManager = context.getBean(ChainBaseManager.class); - setManager(dbManager); - consensusService = context.getBean(ConsensusService.class); + @Before + public void init() { + if (init) { + return; + } consensusService.start(); - //give a big value for pool, avoid for chainBaseManager.getDynamicPropertiesStore().saveTotalShieldedPoolValue(10_000_000_000L); - // Args.getInstance().setAllowShieldedTransaction(1); - } - - /** - * Release resources. - */ - @AfterClass - public static void destroy() { - Args.clearParam(); - context.destroy(); - - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + init = true; } private static void librustzcashInitZksnarkParams() { - FullNodeHttpApiService.librustzcashInitZksnarkParams(); + ZksnarkInitService.librustzcashInitZksnarkParams(); } private static byte[] randomUint256() { @@ -329,13 +306,8 @@ public void testBroadcastBeforeAllowZksnark() TransactionCapsule transactionCap = builder.build(); //Add public address sign - TransactionSign.Builder transactionSignBuild = TransactionSign.newBuilder(); - transactionSignBuild.setTransaction(transactionCap.getInstance()); - transactionSignBuild.setPrivateKey(ByteString.copyFrom( - ByteArray.fromHexString(ADDRESS_ONE_PRIVATE_KEY))); - - transactionCap = transactionUtil.addSign(transactionSignBuild.build()); - + transactionCap = TransactionUtils.addTransactionSign(transactionCap.getInstance(), + ADDRESS_ONE_PRIVATE_KEY, chainBaseManager.getAccountStore()); try { dbManager.pushTransaction(transactionCap); Assert.assertFalse(true); @@ -348,7 +320,7 @@ public void testBroadcastBeforeAllowZksnark() } /* - * generate spendproof, dataToBeSigned, outputproof example dynamicly according to the params file + * generate spendproof, dataToBeSigned, outputproof example dynamically according to the params file */ public String[] generateSpendAndOutputParams() throws ZksnarkException, BadItemException { librustzcashInitZksnarkParams(); @@ -400,6 +372,8 @@ public String[] generateSpendAndOutputParams() throws ZksnarkException, BadItemE // generate checkSpendParams SpendDescription spendDescription = builder.getContractBuilder().getSpendDescription(0); + SpendDescriptionCapsule spendDescriptionCapsule = new SpendDescriptionCapsule(spendDescription); + Assert.assertNotNull(spendDescriptionCapsule); CheckSpendParams checkSpendParams = new CheckSpendParams(ctx, spendDescription.getValueCommitment().toByteArray(), spendDescription.getAnchor().toByteArray(), @@ -904,20 +878,43 @@ private ReceiveDescriptionCapsule changeGenerateOutputProof(ReceiveDescriptionIn JLibrustzcash.librustzcashSaplingProvingCtxFree(ctx); throw new ZksnarkException("Output proof failed"); } - + ReceiveDescriptionCapsule c = new ReceiveDescriptionCapsule(new byte[32]); + ReceiveDescriptionCapsule c1 = + new ReceiveDescriptionCapsule(ReceiveDescription.newBuilder().build()); + ReceiveDescriptionCapsule c2 = + new ReceiveDescriptionCapsule(ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32]), + ByteString.copyFrom(new byte[32])); + Assert.assertNotNull(c); + Assert.assertNotNull(c1); + Assert.assertNotNull(c2); ReceiveDescriptionCapsule receiveDescriptionCapsule = new ReceiveDescriptionCapsule(); receiveDescriptionCapsule.setValueCommitment(cv); + receiveDescriptionCapsule.setValueCommitment(ByteString.copyFrom(cv)); receiveDescriptionCapsule.setNoteCommitment(cm); + receiveDescriptionCapsule.setNoteCommitment(ByteString.copyFrom(cm)); receiveDescriptionCapsule.setEpk(encryptor.getEpk()); + receiveDescriptionCapsule.setEpk(ByteString.copyFrom(encryptor.getEpk())); receiveDescriptionCapsule.setCEnc(enc.getEncCiphertext()); + receiveDescriptionCapsule.setCEnc(ByteString.copyFrom(enc.getEncCiphertext())); receiveDescriptionCapsule.setZkproof(zkProof); + receiveDescriptionCapsule.setZkproof(ByteString.copyFrom(zkProof)); + receiveDescriptionCapsule.getEphemeralKey(); + receiveDescriptionCapsule.getData(); + receiveDescriptionCapsule.getZkproof(); + receiveDescriptionCapsule.getOutCiphertext(); OutgoingPlaintext outPlaintext = new OutgoingPlaintext(output.getNote().getPkD(), encryptor.getEsk()); - receiveDescriptionCapsule.setCOut(outPlaintext + byte[] bytes = outPlaintext .encrypt(output.getOvk(), receiveDescriptionCapsule.getValueCommitment().toByteArray(), receiveDescriptionCapsule.getCm().toByteArray(), - encryptor).getData()); + encryptor).getData(); + receiveDescriptionCapsule.setCOut(bytes); + receiveDescriptionCapsule.setCOut(ByteString.copyFrom(bytes)); Note newNote = output.getNote(); byte[] newCm; @@ -2401,17 +2398,17 @@ public void testMemoNotEnough() throws ContractValidateException, TooBigTransact */ @Test public void pushSameSkAndScanAndSpend() throws Exception { - - byte[] privateKey = ByteArray - .fromHexString("f4df789d3210ac881cb900464dd30409453044d2777060a0c391cbdf4c6a4f57"); + List localPrivateKeys = Args.getLocalWitnesses().getPrivateKeys(); + byte[] privateKey = ByteArray.fromHexString(localPrivateKeys.get(0)); final ECKey ecKey = ECKey.fromPrivate(privateKey); + assert ecKey != null; byte[] witnessAddress = ecKey.getAddress(); WitnessCapsule witnessCapsule = new WitnessCapsule(ByteString.copyFrom(witnessAddress)); chainBaseManager.addWitness(ByteString.copyFrom(witnessAddress)); //sometimes generate block failed, try several times. - - Block block = getSignedBlock(witnessCapsule.getAddress(), 0, privateKey); + long time = System.currentTimeMillis(); + Block block = getSignedBlock(witnessCapsule.getAddress(), time, privateKey); dbManager.pushBlock(new BlockCapsule(block)); //create transactions @@ -2459,17 +2456,25 @@ public void pushSameSkAndScanAndSpend() throws Exception { Thread.sleep(500); //package transaction to block - block = getSignedBlock(witnessCapsule.getAddress(), 0, privateKey); + block = getSignedBlock(witnessCapsule.getAddress(), time + 3000, privateKey); dbManager.pushBlock(new BlockCapsule(block)); BlockCapsule blockCapsule3 = new BlockCapsule(wallet.getNowBlock()); Assert.assertEquals("blocknum != 2", 2, blockCapsule3.getNum()); + block = getSignedBlock(witnessCapsule.getAddress(), time + 6000, 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()); @@ -2485,6 +2490,7 @@ public void pushSameSkAndScanAndSpend() throws Exception { outPointBuild.setIndex(i); request.addOutPoints(outPointBuild.build()); } + request.setBlockNum(1); IncrementalMerkleVoucherInfo merkleVoucherInfo = wallet .getMerkleTreeVoucherInfo(request.build()); diff --git a/framework/src/test/java/org/tron/keystore/CredentialsTest.java b/framework/src/test/java/org/tron/keystore/CredentialsTest.java new file mode 100644 index 00000000000..3fe2ce02b63 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/CredentialsTest.java @@ -0,0 +1,48 @@ +package org.tron.keystore; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import junit.framework.TestCase; +import lombok.extern.slf4j.Slf4j; +import org.junit.Test; +import org.springframework.util.Assert; +import org.tron.common.crypto.SignUtils; +import org.tron.common.crypto.sm2.SM2; +import org.tron.common.utils.ByteUtil; + +@Slf4j +public class CredentialsTest extends TestCase { + + @Test + public void testCreate() throws NoSuchAlgorithmException { + Credentials credentials = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.hasText(credentials.getAddress(),"Credentials address create failed!"); + Assert.notNull(credentials.getSignInterface(), + "Credentials cryptoEngine create failed"); + } + + @Test + public void testCreateFromSM2() { + try { + Credentials.create(SM2.fromNodeId(ByteUtil.hexToBytes("fffffffffff" + + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + + "fffffffffffffffffffffffffffffffffffffff"))); + } catch (Exception e) { + Assert.isInstanceOf(IllegalArgumentException.class, e); + } + } + + @Test + public void testEquals() throws NoSuchAlgorithmException { + Credentials credentials1 = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Credentials credentials2 = Credentials.create(SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + Assert.isTrue(!credentials1.equals(credentials2), + "Credentials instance should be not equal!"); + Assert.isTrue(!(credentials1.hashCode() == credentials2.hashCode()), + "Credentials instance hashcode should be not equal!"); + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/keystore/WalletFileTest.java b/framework/src/test/java/org/tron/keystore/WalletFileTest.java new file mode 100644 index 00000000000..c24647be322 --- /dev/null +++ b/framework/src/test/java/org/tron/keystore/WalletFileTest.java @@ -0,0 +1,75 @@ +package org.tron.keystore; + +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Test; +import org.tron.common.crypto.SignUtils; +import org.tron.core.exception.CipherException; + +@Slf4j +public class WalletFileTest { + + @Test + public void testGetAddress() throws NoSuchAlgorithmException, CipherException { + WalletFile walletFile1 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + WalletFile walletFile2 = Wallet.createStandard("", SignUtils.getGeneratedRandomSign( + SecureRandom.getInstance("NativePRNG"),true)); + WalletFile walletFile3 = (WalletFile) getSame(walletFile1); + Assert.assertNotEquals(walletFile1.getAddress(), walletFile2.getAddress()); + Assert.assertNotEquals(walletFile1.getCrypto(), walletFile2.getCrypto()); + Assert.assertNotEquals(walletFile1.getId(), walletFile2.getId()); + Assert.assertEquals(walletFile1.getVersion(), walletFile2.getVersion()); + Assert.assertNotEquals(walletFile1, walletFile2); + Assert.assertEquals(walletFile1, walletFile3); + Assert.assertNotEquals(walletFile1, null); + Assert.assertNotEquals(walletFile2, new Object()); + Assert.assertNotEquals(0, walletFile1.hashCode()); + + WalletFile.CipherParams cipherParams = new WalletFile.CipherParams(); + WalletFile.CipherParams cipherParams1 = new WalletFile.CipherParams(); + WalletFile.CipherParams cipherParams2 = (WalletFile.CipherParams) getSame(cipherParams); + Assert.assertEquals(cipherParams, cipherParams1); + Assert.assertEquals(cipherParams, cipherParams2); + Assert.assertNotEquals(cipherParams, null); + Assert.assertNotEquals(cipherParams, new Object()); + Assert.assertEquals(0, cipherParams.hashCode()); + + WalletFile.Aes128CtrKdfParams aes128CtrKdfParams = new WalletFile.Aes128CtrKdfParams(); + WalletFile.Aes128CtrKdfParams aes128CtrKdfParams1 = new WalletFile.Aes128CtrKdfParams(); + WalletFile.Aes128CtrKdfParams aes128CtrKdfParams2 = (WalletFile.Aes128CtrKdfParams) + getSame(aes128CtrKdfParams); + Assert.assertEquals(aes128CtrKdfParams, aes128CtrKdfParams1); + Assert.assertEquals(aes128CtrKdfParams, aes128CtrKdfParams2); + Assert.assertNotEquals(aes128CtrKdfParams, null); + Assert.assertNotEquals(aes128CtrKdfParams, new Object()); + Assert.assertEquals(0, aes128CtrKdfParams.hashCode()); + + WalletFile.ScryptKdfParams scryptKdfParams = new WalletFile.ScryptKdfParams(); + WalletFile.ScryptKdfParams scryptKdfParams1 = new WalletFile.ScryptKdfParams(); + WalletFile.ScryptKdfParams scryptKdfParams2 = (WalletFile.ScryptKdfParams) + getSame(scryptKdfParams); + Assert.assertEquals(scryptKdfParams, scryptKdfParams1); + Assert.assertEquals(scryptKdfParams, scryptKdfParams2); + Assert.assertNotEquals(scryptKdfParams, null); + Assert.assertNotEquals(scryptKdfParams, new Object()); + Assert.assertEquals(0, scryptKdfParams.hashCode()); + + WalletFile.Crypto crypto = new WalletFile.Crypto(); + WalletFile.Crypto crypto1 = new WalletFile.Crypto(); + WalletFile.Crypto crypto2 = (WalletFile.Crypto) getSame(crypto); + Assert.assertEquals(crypto, crypto1); + Assert.assertEquals(crypto, crypto2); + Assert.assertNotEquals(crypto, null); + Assert.assertNotEquals(crypto, new Object()); + Assert.assertEquals(0, crypto.hashCode()); + + } + + private Object getSame(Object obj) { + return obj; + } + +} \ No newline at end of file diff --git a/framework/src/test/java/org/tron/keystroe/CredentialsTest.java b/framework/src/test/java/org/tron/keystroe/CredentialsTest.java new file mode 100644 index 00000000000..ce992c3443f --- /dev/null +++ b/framework/src/test/java/org/tron/keystroe/CredentialsTest.java @@ -0,0 +1,34 @@ +package org.tron.keystroe; + +import lombok.var; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; +import org.tron.common.crypto.SignInterface; +import org.tron.keystore.Credentials; + +public class CredentialsTest { + + @Test + public void test_equality() { + var aObject = new Object(); + var si = Mockito.mock(SignInterface.class); + var si2 = Mockito.mock(SignInterface.class); + var si3 = Mockito.mock(SignInterface.class); + var address = "TQhZ7W1RudxFdzJMw6FvMnujPxrS6sFfmj".getBytes(); + var address2 = "TNCmcTdyrYKMtmE1KU2itzeCX76jGm5Not".getBytes(); + Mockito.when(si.getAddress()).thenReturn(address); + Mockito.when(si2.getAddress()).thenReturn(address); + Mockito.when(si3.getAddress()).thenReturn(address2); + var aCredential = Credentials.create(si); + Assert.assertFalse(aObject.equals(aCredential)); + Assert.assertFalse(aCredential.equals(aObject)); + Assert.assertFalse(aCredential.equals(null)); + var anotherCredential = Credentials.create(si); + Assert.assertTrue(aCredential.equals(anotherCredential)); + var aCredential2 = Credentials.create(si2); + Assert.assertTrue(aCredential.equals(anotherCredential)); + var aCredential3 = Credentials.create(si3); + Assert.assertFalse(aCredential.equals(aCredential3)); + } +} diff --git a/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java b/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java index f87b0f81730..decdbff5e25 100755 --- a/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java +++ b/framework/src/test/java/org/tron/program/AccountVoteWitnessTest.java @@ -4,59 +4,25 @@ import com.google.protobuf.ByteString; import java.io.File; import java.util.List; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.TronApplicationContext; +import org.tron.common.BaseTest; import org.tron.consensus.dpos.MaintenanceManager; import org.tron.core.Constant; import org.tron.core.capsule.AccountCapsule; import org.tron.core.capsule.WitnessCapsule; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; -import org.tron.core.db.Manager; import org.tron.protos.Protocol.AccountType; @Slf4j -public class AccountVoteWitnessTest { +public class AccountVoteWitnessTest extends BaseTest { - private static TronApplicationContext context; - - private static Manager dbManager; - private static MaintenanceManager maintenanceManager; - private static String dbPath = "output_witness_test"; + @Resource + private MaintenanceManager maintenanceManager; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); - } - - /** - * init db. - */ - @BeforeClass - public static void init() { - dbManager = context.getBean(Manager.class); - maintenanceManager = context.getBean(MaintenanceManager.class); - // Args.setParam(new String[]{}, Constant.TEST_CONF); - // dbManager = new Manager(); - // dbManager.init(); - } - - /** - * remo db when after test. - */ - @AfterClass - public static void removeDb() { - Args.clearParam(); - context.destroy(); - File dbFolder = new File(dbPath); - if (deleteFolder(dbFolder)) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); } private static Boolean deleteFolder(File index) { diff --git a/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java b/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java deleted file mode 100644 index 174c708a7c7..00000000000 --- a/framework/src/test/java/org/tron/program/LiteFullNodeToolTest.java +++ /dev/null @@ -1,292 +0,0 @@ -package org.tron.program; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.File; -import java.math.BigInteger; -import java.nio.file.Paths; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.DatabaseGrpc; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.config.DbBackupConfig; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.FileUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.DefaultConfig; -import org.tron.core.config.args.Args; -import org.tron.core.services.RpcApiService; -import org.tron.core.services.interfaceOnSolidity.RpcApiServiceOnSolidity; -import org.tron.protos.Protocol; -import org.tron.protos.contract.BalanceContract; -import org.tron.tool.litefullnode.LiteFullNodeTool; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -public class LiteFullNodeToolTest { - - private static final Logger logger = LoggerFactory.getLogger("Test"); - - private TronApplicationContext context; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private DatabaseGrpc.DatabaseBlockingStub databaseBlockingStub = null; - private RpcApiService rpcApiService; - private RpcApiServiceOnSolidity rpcApiServiceOnSolidity; - private Application appTest; - - private String databaseDir; - - @Rule - public ExpectedException thrown = ExpectedException.none(); - - /** - * init logic. - */ - public void startApp() { - context = new TronApplicationContext(DefaultConfig.class); - appTest = ApplicationFactory.create(context); - rpcApiService = context.getBean(RpcApiService.class); - rpcApiServiceOnSolidity = context.getBean(RpcApiServiceOnSolidity.class); - appTest.addService(rpcApiService); - appTest.addService(rpcApiServiceOnSolidity); - appTest.initServices(Args.getInstance()); - appTest.startServices(); - appTest.startup(); - - String fullnode = String.format("%s:%d", "127.0.0.1", - Args.getInstance().getRpcPort()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelFull); - databaseBlockingStub = DatabaseGrpc.newBlockingStub(channelFull); - } - - /** - * Delete the database when exit. - */ - public static void destory(String dbPath) { - if (FileUtil.deleteDir(new File(dbPath))) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - /** - * shutdown the fullnode. - */ - public void shutdown() { - appTest.shutdownServices(); - appTest.shutdown(); - context.destroy(); - } - - @Test - public void testToolsWithLevelDB() { - String dbPath = "output_lite_fn_leveldb_test"; - Args.setParam(new String[]{"-d", dbPath, "-w"}, "config-localtest.conf"); - // allow account root - Args.getInstance().setAllowAccountStateRoot(1); - databaseDir = Args.getInstance().getStorage().getDbDirectory(); - testTools("LEVELDB", dbPath); - destory(dbPath); - } - - @Test - public void testToolsWithRocksDB() { - String dbPath = "output_lite_fn_rocksdb_test"; - Args.setParam(new String[]{"-d", dbPath, "-w"}, "config-localtest.conf"); - // allow account root - Args.getInstance().setAllowAccountStateRoot(1); - databaseDir = Args.getInstance().getStorage().getDbDirectory(); - // init dbBackupConfig to avoid NPE - Args.getInstance().dbBackupConfig = DbBackupConfig.getInstance(); - testTools("ROCKSDB", dbPath); - destory(dbPath); - } - - private void testTools(String dbType, String dbPath) { - final String[] argsForSnapshot = - new String[]{"-o", "split", "-t", "snapshot", "--fn-data-path", - dbPath + File.separator + databaseDir, "--dataset-path", dbPath}; - final String[] argsForHistory = - new String[]{"-o", "split", "-t", "history", "--fn-data-path", - dbPath + File.separator + databaseDir, "--dataset-path", dbPath}; - final String[] argsForMerge = - new String[]{"-o", "merge", "--fn-data-path", dbPath + File.separator + databaseDir, - "--dataset-path", dbPath + File.separator + "history"}; - Args.getInstance().getStorage().setDbEngine(dbType); - // start fullnode - startApp(); - // produce transactions for 10 seconds - generateSomeTransactions(10); - // stop the node - shutdown(); - // delete tran-cache - FileUtil.deleteDir(Paths.get(dbPath, databaseDir, "trans-cache").toFile()); - // generate snapshot - LiteFullNodeTool.main(argsForSnapshot); - // start fullnode - startApp(); - // produce transactions for 10 seconds - generateSomeTransactions(4); - // stop the node - shutdown(); - // generate history - LiteFullNodeTool.main(argsForHistory); - // backup original database to database_bak - File database = new File(Paths.get(dbPath, databaseDir).toString()); - if (!database.renameTo(new File(Paths.get(dbPath, databaseDir + "_bak").toString()))) { - throw new RuntimeException( - String.format("rename %s to %s failed", database.getPath(), - Paths.get(dbPath, databaseDir).toString())); - } - // change snapshot to the new database - File snapshot = new File(Paths.get(dbPath, "snapshot").toString()); - if (!snapshot.renameTo(new File(Paths.get(dbPath, databaseDir).toString()))) { - throw new RuntimeException( - String.format("rename snapshot to %s failed", - Paths.get(dbPath, databaseDir).toString())); - } - // start and validate the snapshot - startApp(); - generateSomeTransactions(4); - // stop the node - shutdown(); - // merge history - LiteFullNodeTool.main(argsForMerge); - // start and validate - startApp(); - generateSomeTransactions(4); - shutdown(); - } - - private void generateSomeTransactions(int during) { - during *= 1000; // ms - int runTime = 0; - int sleepOnce = 100; - while (true) { - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] address = ecKey2.getAddress(); - - String sunPri = "cba92a516ea09f620a16ff7ee95ce0df1d56550a8babe9964981a7144c8a784a"; - byte[] sunAddress = getFinalAddress(sunPri); - sendcoin(address, 1L, - sunAddress, sunPri, blockingStubFull); - try { - Thread.sleep(sleepOnce); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if ((runTime += sleepOnce) > during) { - return; - } - } - } - - /** - * Set public for future use. - * @param priKey private key - * @return public addr - */ - public static byte[] getFinalAddress(String priKey) { - Wallet.setAddressPreFixByte((byte) 0x41); - ECKey key = ECKey.fromPrivate(new BigInteger(priKey, 16)); - return key.getAddress(); - } - - /** - * Set public for future use. - * @param to addr receives the asset - * @param amount asset amount - * @param owner sender - * @param priKey private key of the sender - * @param blockingStubFull Grpc interface - * @return true or false - */ - public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte((byte) 0x41); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - int times = 0; - while (times++ <= 2) { - - BalanceContract.TransferContract.Builder builder = - BalanceContract.TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - continue; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - return false; - } - - /** - * Set public for future use. - * @param ecKey ecKey of the private key - * @param transaction transaction object - */ - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * Set public for future use. - * @param transaction transaction object - * @param blockingStubFull Grpc interface - */ - public static GrpcAPI.Return broadcastTransaction( - Protocol.Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { - int i = 10; - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - while (!response.getResult() && response.getCode() == GrpcAPI.Return.response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - } - return response; - } - -} diff --git a/framework/src/test/java/org/tron/program/SolidityNodeTest.java b/framework/src/test/java/org/tron/program/SolidityNodeTest.java index 307b44d0b9c..a95d07c0c11 100755 --- a/framework/src/test/java/org/tron/program/SolidityNodeTest.java +++ b/framework/src/test/java/org/tron/program/SolidityNodeTest.java @@ -1,73 +1,29 @@ package org.tron.program; -import java.io.File; +import javax.annotation.Resource; import lombok.extern.slf4j.Slf4j; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.BeforeClass; import org.junit.Test; -import org.tron.common.application.Application; -import org.tron.common.application.ApplicationFactory; -import org.tron.common.application.TronApplicationContext; -import org.tron.common.overlay.client.DatabaseGrpcClient; +import org.tron.common.BaseTest; +import org.tron.common.client.DatabaseGrpcClient; import org.tron.core.Constant; -import org.tron.core.config.DefaultConfig; import org.tron.core.config.args.Args; import org.tron.core.services.RpcApiService; +import org.tron.core.services.http.solidity.SolidityNodeHttpApiService; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.DynamicProperties; @Slf4j -public class SolidityNodeTest { +public class SolidityNodeTest extends BaseTest { - private static TronApplicationContext context; - - private static RpcApiService rpcApiService; - private static Application appT; - private static String dbPath = "output_witness_test"; + @Resource + RpcApiService rpcApiService; + @Resource + SolidityNodeHttpApiService solidityNodeHttpApiService; static { - Args.setParam(new String[]{"-d", dbPath}, Constant.TEST_CONF); - context = new TronApplicationContext(DefaultConfig.class); + Args.setParam(new String[]{"-d", dbPath()}, Constant.TEST_CONF); Args.getInstance().setSolidityNode(true); - appT = ApplicationFactory.create(context); - rpcApiService = context.getBean(RpcApiService.class); - } - - /** - * init db. - */ - @BeforeClass - public static void init() { - rpcApiService.start(); - } - - /** - * remo db when after test. - */ - @AfterClass - public static void removeDb() { - Args.clearParam(); - rpcApiService.stop(); - context.destroy(); - File dbFolder = new File(dbPath); - if (deleteFolder(dbFolder)) { - logger.info("Release resources successful."); - } else { - logger.info("Release resources failure."); - } - } - - private static Boolean deleteFolder(File index) { - if (!index.isDirectory() || index.listFiles().length <= 0) { - return index.delete(); - } - for (File file : index.listFiles()) { - if (null != file && !deleteFolder(file)) { - return false; - } - } - return index.delete(); } @Test @@ -78,12 +34,13 @@ public void testSolidityArgs() { @Test public void testSolidityGrpcCall() { + rpcApiService.start(); DatabaseGrpcClient databaseGrpcClient = null; - String addr = Args.getInstance().getTrustNodeAddr(); + String address = Args.getInstance().getTrustNodeAddr(); try { - databaseGrpcClient = new DatabaseGrpcClient(addr); + databaseGrpcClient = new DatabaseGrpcClient(address); } catch (Exception e) { - logger.error("Failed to create database grpc client {}", addr); + logger.error("Failed to create database grpc client {}", address); } Assert.assertNotNull(databaseGrpcClient); @@ -93,6 +50,23 @@ public void testSolidityGrpcCall() { Block genesisBlock = databaseGrpcClient.getBlock(0); Assert.assertNotNull(genesisBlock); Assert.assertFalse(genesisBlock.getTransactionsList().isEmpty()); + Block invalidBlock = databaseGrpcClient.getBlock(-1); + Assert.assertNotNull(invalidBlock); + try { + databaseGrpcClient = new DatabaseGrpcClient(address, -1); + } catch (Exception e) { + logger.error("Failed to create database grpc client {}", address); + } + databaseGrpcClient.shutdown(); + rpcApiService.stop(); } + @Test + public void testSolidityNodeHttpApiService() { + solidityNodeHttpApiService.start(); + // start again + solidityNodeHttpApiService.start(); + solidityNodeHttpApiService.stop(); + Assert.assertTrue(true); + } } diff --git a/framework/src/test/java/org/tron/program/SupplementTest.java b/framework/src/test/java/org/tron/program/SupplementTest.java new file mode 100644 index 00000000000..3dfa23dfce4 --- /dev/null +++ b/framework/src/test/java/org/tron/program/SupplementTest.java @@ -0,0 +1,150 @@ +package org.tron.program; + +import static org.apache.commons.lang3.StringUtils.EMPTY; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.tron.keystore.WalletUtils.passwordValid; + +import java.io.File; +import java.io.IOException; +import java.math.BigInteger; +import javax.annotation.Resource; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.tron.common.BaseTest; +import org.tron.common.config.DbBackupConfig; +import org.tron.common.entity.PeerInfo; +import org.tron.common.utils.CompactEncoder; +import org.tron.common.utils.JsonUtil; +import org.tron.common.utils.Value; +import org.tron.core.Constant; +import org.tron.core.capsule.StorageRowCapsule; +import org.tron.core.capsule.utils.RLP; +import org.tron.core.config.TronLogShutdownHook; +import org.tron.core.config.args.Args; +import org.tron.core.services.http.HttpSelfFormatFieldName; +import org.tron.core.store.StorageRowStore; +import org.tron.keystore.WalletUtils; + +public class SupplementTest extends BaseTest { + + private static String dbPath; + + @Resource + private StorageRowStore storageRowStore; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @BeforeClass + public static void init() throws IOException { + dbPath = dbPath(); + Args.setParam(new String[]{"--output-directory", dbPath, "--debug"}, Constant.TEST_CONF); + } + + @Test + public void testGet() throws Exception { + StorageRowCapsule storageRowCapsule = storageRowStore.get(new byte[]{}); + assertNotNull(storageRowCapsule); + + DbBackupConfig dbBackupConfig = new DbBackupConfig(); + String p = dbPath + File.separator; + dbBackupConfig.initArgs(true, p + "propPath", p + "bak1path/", p + "bak2path/", 1); + + WalletUtils.generateFullNewWalletFile("123456", new File(dbPath)); + WalletUtils.generateLightNewWalletFile("123456", new File(dbPath)); + WalletUtils.getDefaultKeyDirectory(); + WalletUtils.getTestnetKeyDirectory(); + WalletUtils.getMainnetKeyDirectory(); + + Value value = new Value(new byte[]{1}); + value.asBytes(); + value = new Value(1); + value.asInt(); + value = new Value(100L); + value.asLong(); + value = new Value(new BigInteger("1000")); + value.asBigInt(); + value = new Value("1000"); + value.asString(); + value.isEmpty(); + value = new Value(new byte[]{1, 2, 3}); + value.isList(); + value.isReadableString(); + value.isHexString(); + value.isHashCode(); + value.isNull(); + value.length(); + assertNotNull(value.toString()); + value.countBranchNodes(); + + PeerInfo peerInfo = new PeerInfo(); + peerInfo.setAvgLatency(peerInfo.getAvgLatency()); + peerInfo.setBlockInPorcSize(peerInfo.getBlockInPorcSize()); + peerInfo.setConnectTime(peerInfo.getConnectTime()); + peerInfo.setDisconnectTimes(peerInfo.getDisconnectTimes()); + peerInfo.setHeadBlockTimeWeBothHave(peerInfo.getHeadBlockTimeWeBothHave()); + peerInfo.setHeadBlockWeBothHave(peerInfo.getHeadBlockWeBothHave()); + peerInfo.setHost(peerInfo.getHost()); + peerInfo.setInFlow(peerInfo.getInFlow()); + peerInfo.setLastBlockUpdateTime(peerInfo.getLastBlockUpdateTime()); + peerInfo.setLastSyncBlock(peerInfo.getLastSyncBlock()); + peerInfo.setLocalDisconnectReason(peerInfo.getLocalDisconnectReason()); + peerInfo.setNodeCount(peerInfo.getNodeCount()); + peerInfo.setNodeId(peerInfo.getNodeId()); + peerInfo.setRemainNum(peerInfo.getRemainNum()); + peerInfo.setRemoteDisconnectReason(peerInfo.getRemoteDisconnectReason()); + peerInfo.setScore(peerInfo.getScore()); + peerInfo.setPort(peerInfo.getPort()); + peerInfo.setSyncFlag(peerInfo.isSyncFlag()); + peerInfo.setNeedSyncFromPeer(peerInfo.isNeedSyncFromPeer()); + peerInfo.setNeedSyncFromUs(peerInfo.isNeedSyncFromUs()); + peerInfo.setSyncToFetchSize(peerInfo.getSyncToFetchSize()); + peerInfo.setSyncToFetchSizePeekNum(peerInfo.getSyncToFetchSizePeekNum()); + peerInfo.setSyncBlockRequestedSize(peerInfo.getSyncBlockRequestedSize()); + peerInfo.setUnFetchSynNum(peerInfo.getUnFetchSynNum()); + peerInfo.setActive(peerInfo.isActive()); + + assertNotNull(JsonUtil.json2Obj("{}", PeerInfo.class)); + assertNotNull(JsonUtil.obj2Json(peerInfo)); + + assertTrue(HttpSelfFormatFieldName.isAddressFormat( + "protocol.DelegatedResourceMessage.fromAddress")); + assertTrue(HttpSelfFormatFieldName.isNameStringFormat( + "protocol.MarketPriceList.buy_token_id")); + + CompactEncoder.packNibbles(new byte[] {1,2,3,4,5,6,7}); + assertFalse(CompactEncoder.hasTerminator(new byte[] {1,2,3,4,5,6,7})); + CompactEncoder.unpackToNibbles(new byte[] {1,2,3,4,5,6,7}); + CompactEncoder.binToNibblesNoTerminator(new byte[] {1,2,3,4,5,6,7}); + + assertNotNull(RLP.decodeIP4Bytes(new byte[] {1,2,3,4,5,6,7}, 0)); + RLP.decodeByteArray(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.nextItemLength(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decodeStringItem(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decodeInt(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decode2OneItem(new byte[] {1,2,3,4,5,6,7}, 0); + RLP.decode2(new byte[] {1,2,3,4,5,6,7}, 1); + RLP.decode2(new byte[] {1,2,3,4,5,6,7}); + thrown.expect(ClassCastException.class); + RLP.unwrapList(new byte[] {1,2,3,4,5,6,7}); + } + + @Test + public void testPasswordValid() { + assertFalse(passwordValid(EMPTY)); + assertFalse(passwordValid("12345")); + assertTrue(passwordValid("123456")); + } + + @Test + public void testRun() { + TronLogShutdownHook hook = new TronLogShutdownHook(); + hook.run(); + assertTrue(true); + } + +} diff --git a/framework/src/test/java/stest/tron/wallet/account/BrokerageTest001.java b/framework/src/test/java/stest/tron/wallet/account/BrokerageTest001.java deleted file mode 100644 index 636c2d361df..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/BrokerageTest001.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol; -import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class BrokerageTest001 { - - private String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - private String dev001Key = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private byte[] dev001Address = PublicMethed.getFinalAddress(dev001Key); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - PublicMethed.printAddress(dev001Key); - } - - @Test - public void updateBrokerageTest001() { - // witness updateBrokerage - Assert.assertTrue(updateBrokerage(witnessAddress001, 55, blockingStubFull)); - - Assert.assertTrue(updateBrokerage(witnessAddress001, 0, blockingStubFull)); - - Assert.assertTrue(updateBrokerage(witnessAddress001, 100, blockingStubFull)); - - Assert.assertFalse(updateBrokerage(witnessAddress001, -55, blockingStubFull)); - - // normal account updateBrokerage fail - Assert.assertFalse(updateBrokerage(dev001Address, 55, blockingStubFull)); - } - - @Test - public void getBrokerageTest001() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(witnessAddress001)) - .build(); - - Assert.assertEquals(20, blockingStubFull.getBrokerageInfo(bytesMessage).getNum()); - - // getBrokerageInfo from solidity node - Assert.assertEquals(20, blockingStubSolidity.getBrokerageInfo(bytesMessage).getNum()); - Assert.assertEquals(20, blockingStubSoliInFull.getBrokerageInfo(bytesMessage).getNum()); - Assert.assertEquals(20, blockingStubPbft.getBrokerageInfo(bytesMessage).getNum()); - } - - @Test - public void getRewardTest002() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(witnessAddress001)) - .build(); - Assert.assertTrue(blockingStubFull.getRewardInfo(bytesMessage) != null); - - // getRewardInfo from solidity node - Assert.assertTrue(blockingStubSolidity.getRewardInfo(bytesMessage) != null); - Assert.assertTrue(blockingStubPbft.getRewardInfo(bytesMessage) != null); - Assert.assertTrue(blockingStubSoliInFull.getRewardInfo(bytesMessage) != null); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - boolean updateBrokerage(byte[] owner, int brokerage, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - logger.info("transaction:" + transaction); - if (transactionExtention.getResult().getResult()) { - return true; - } - return true; - } - - public void getBrokerage() { - - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount001.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount001.java deleted file mode 100644 index 003518663d3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount001.java +++ /dev/null @@ -1,232 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestAccount001 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String invalidTestKey = - "592BB6C9BB255409A6A45EFD18E9A74FECDDCCE93A40D96B70FBE334E6361E36"; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test - public void testqueryaccountfromfullnode() { - //Query success, get the right balance,bandwidth and the account name. - Account queryResult = queryAccount(testKey002, blockingStubFull); - /* Account queryResult = PublicMethed.queryAccountByAddress(fromAddress,blockingStubFull); - logger.info(ByteArray.toStr(queryResult.getAccountName().toByteArray())); - logger.info(Long.toString(queryResult.getBalance())); - logger.info(ByteArray.toStr(queryResult.getAddress().toByteArray()));*/ - Assert.assertTrue(queryResult.getBalance() > 0); - //Assert.assertTrue(queryResult.getBandwidth() >= 0); - Assert.assertTrue(queryResult.getAccountName().toByteArray().length > 0); - Assert.assertFalse(queryResult.getAddress().isEmpty()); - - //Query failed - Account invalidQueryResult = queryAccount(invalidTestKey, blockingStubFull); - Assert.assertTrue(invalidQueryResult.getAccountName().isEmpty()); - Assert.assertTrue(invalidQueryResult.getAddress().isEmpty()); - - //Improve coverage. - queryResult.hashCode(); - queryResult.getSerializedSize(); - queryResult.equals(queryResult); - queryResult.equals(invalidQueryResult); - } - - @Test - public void testqueryaccountfromsoliditynode() { - //Query success, get the right balance,bandwidth and the account name. - Account queryResult = solidityqueryAccount(testKey002, blockingStubSolidity); - Assert.assertTrue(queryResult.getBalance() > 0); - //Assert.assertTrue(queryResult.getBandwidth() >= 0); - Assert.assertTrue(queryResult.getAccountName().toByteArray().length > 0); - Assert.assertFalse(queryResult.getAddress().isEmpty()); - - //Query failed - Account invalidQueryResult = solidityqueryAccount(invalidTestKey, blockingStubSolidity); - Assert.assertTrue(invalidQueryResult.getAccountName().isEmpty()); - Assert.assertTrue(invalidQueryResult.getAddress().isEmpty()); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - logger.info(Integer.toString(ecKey.getAddress().length)); - - //PublicMethed.AddPreFix(); - logger.info(Integer.toString(ecKey.getAddress().length)); - System.out.println("address ====== " + ByteArray.toHexString(ecKey.getAddress())); - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - //return grpcQueryAccount(address,blockingStubFull); - } - - /** - * constructor. - */ - - public Account solidityqueryAccount(String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - //byte[] address = PublicMethed.AddPreFix(ecKey.getAddress()); - return grpcQueryAccountSolidity(ecKey.getAddress(), blockingStubSolidity); - //return grpcQueryAccountSolidity(address,blockingStubSolidity); - } - - /** - * constructor. - */ - - public String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - //address = PublicMethed.AddPreFix(address); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Account grpcQueryAccountSolidity(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - //address = PublicMethed.AddPreFix(address); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubSolidity.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java deleted file mode 100644 index b2206b426f7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount003.java +++ /dev/null @@ -1,485 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestAccount003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue_" + Long.toString(now); - private static final long TotalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String mostLongNamePlusOneChar = "1abcdeabcdefabcdefg1abcdefg10o0og1abcdefg10o0oabcd" - + "efabcdefg1abcdefg10o0og1abcdefg10o0oabcdefabcdefg1abcdefg10o0og1abcdefg10o0oab" - + "cdefabcdefg1abcdefg10o0og1abcdefg10o0ofabcdefg1abcdefg10o0og1abcdefg10o0o"; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey1.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - public static String getRandomStr(int length) { - String base = "abcdefghijklmnopqrstuvwxyz0123456789"; - int randomNum; - char randomChar; - Random random = new Random(); - StringBuffer str = new StringBuffer(); - - for (int i = 0; i < length; i++) { - randomNum = random.nextInt(base.length()); - randomChar = base.charAt(randomNum); - str.append(randomChar); - } - return str.toString(); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - PublicMethed.printAddress(lowBalTest); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void test1CreateAccount() { - Account noCreateAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - while (noCreateAccount.getBalance() != 0) { - ecKey = new ECKey(Utils.getRandom()); - lowBalAddress = ecKey.getAddress(); - lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - noCreateAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - } - Assert.assertTrue(sendCoin(lowBalAddress, 1L, fromAddress, testKey002)); - noCreateAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - logger.info(Long.toString(noCreateAccount.getBalance())); - Assert.assertTrue(noCreateAccount.getBalance() == 1); - } - - @Test(enabled = true) - public void test2UpdateAccount() { - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, - mostLongNamePlusOneChar.getBytes(), lowBalTest, blockingStubFull)); - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, "".getBytes(), lowBalTest, - blockingStubFull)); - String mostLongName = getRandomStr(33); - Assert.assertTrue(PublicMethed.updateAccount(lowBalAddress, mostLongName.getBytes(), lowBalTest, - blockingStubFull)); - String firstUpdateName = getRandomStr(32); - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, firstUpdateName.getBytes(), - lowBalTest, blockingStubFull)); - String secondUpdateName = getRandomStr(15); - Assert.assertFalse(PublicMethed.updateAccount(lowBalAddress, secondUpdateName.getBytes(), - lowBalTest, blockingStubFull)); - } - - @Test(enabled = true) - public void test3NoBalanceCreateAssetIssue() { - Account lowaccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - if (lowaccount.getBalance() > 0) { - Assert.assertTrue(sendCoin(toAddress, lowaccount.getBalance(), lowBalAddress, lowBalTest)); - } - //Create AssetIssue failed when there is no enough balance. - Assert.assertFalse(PublicMethed.createAssetIssue(lowBalAddress, name, TotalSupply, 1, - 1, now + 100000000L, now + 10000000000L, 2, - description, url, 10000L, 10000L, 1L, - 1L, lowBalTest, blockingStubFull)); - logger.info("nobalancecreateassetissue"); - } - - @Test(enabled = true) - public void test4NoBalanceTransferTrx() { - //Send Coin failed when there is no enough balance. - Assert.assertFalse(sendCoin(toAddress, 100000000000000000L, lowBalAddress, lowBalTest)); - } - - @Test(enabled = true) - public void test5NoBalanceCreateWitness() { - //Apply to be super witness failed when no enough balance. - Assert.assertFalse(createWitness(lowBalAddress, fromAddress, lowBalTest)); - } - - @Test(enabled = true) - public void test6NoFreezeBalanceToUnfreezeBalance() { - //Unfreeze account failed when no freeze balance - Account noFreezeAccount = PublicMethed.queryAccount(lowBalTest, blockingStubFull); - if (noFreezeAccount.getFrozenCount() == 0) { - Assert.assertFalse(unFreezeBalance(lowBalAddress, lowBalTest)); - } else { - logger.info("This account has freeze balance, please test this case for manual"); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Boolean sendCoin(byte[] to, long amount, byte[] owner, String priKey) { - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder - = AssetIssueContractOuterClass.AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(TotalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] address, String priKey) { - //byte[] address = address; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - BalanceContract.UnfreezeBalanceContract.Builder builder - = BalanceContract.UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - BalanceContract.UnfreezeBalanceContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder - = WitnessContract.VoteWitnessContract.Vote.newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - return false; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(addRess)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info("response.getresult() == false"); - return false; - } - return true; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - return true; - - - } - - class AccountComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long.compare(((Account) o2).getBalance(), ((Account) o1).getBalance()); - } - } - -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount004.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount004.java deleted file mode 100644 index 80d84a96fa3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount004.java +++ /dev/null @@ -1,338 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAccount004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String noFrozenBalanceTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - - private final byte[] noFrozenAddress = PublicMethed.getFinalAddress(noFrozenBalanceTestKey); - Long freezeAmount = 2000000L; - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - - } - - @Test(enabled = true) - public void testFreezeBalance() { - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account004AddressForFreeze = ecKey2.getAddress(); - String account004KeyForFreeze = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(account004AddressForFreeze, 10000000, - fromAddress, testKey002, blockingStubFull)); - //Freeze failed when freeze amount is large than currently balance. - Assert.assertFalse(freezeBalance(account004AddressForFreeze, 9000000000000000000L, - 3L, account004KeyForFreeze)); - //Freeze failed when freeze amount less than 1Trx - Assert.assertFalse(freezeBalance(account004AddressForFreeze, 999999L, 3L, - account004KeyForFreeze)); - //Freeze failed when freeze duration isn't 3 days. - //Assert.assertFalse(freezeBalance(fromAddress, 1000000L, 2L, testKey002)); - //Unfreeze balance failed when 3 days hasn't come. - Assert.assertFalse(PublicMethed.unFreezeBalance(account004AddressForFreeze, - account004KeyForFreeze, 0, null, blockingStubFull)); - //Freeze failed when freeze amount is 0. - Assert.assertFalse(freezeBalance(account004AddressForFreeze, 0L, 3L, - account004KeyForFreeze)); - //Freeze failed when freeze amount is -1. - Assert.assertFalse(freezeBalance(account004AddressForFreeze, -1L, 3L, - account004KeyForFreeze)); - //Freeze failed when freeze duration is -1. - //Assert.assertFalse(freezeBalance(fromAddress, 1000000L, -1L, testKey002)); - //Freeze failed when freeze duration is 0. - //Assert.assertFalse(freezeBalance(fromAddress, 1000000L, 0L, testKey002)); - - } - - @Test(enabled = true) - public void testUnFreezeBalance() { - //Unfreeze failed when there is no freeze balance. - //Wait to be create account - - Assert.assertFalse(PublicMethed.unFreezeBalance(noFrozenAddress, noFrozenBalanceTestKey, 1, - null, blockingStubFull)); - logger.info("Test unfreezebalance"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account004Address = ecKey1.getAddress(); - String account004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert - .assertTrue(PublicMethed.sendcoin(account004Address, freezeAmount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(account004Address, freezeAmount, 0, - account004Key, blockingStubFull)); - Account account004; - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == 0); - Assert.assertTrue(PublicMethed.unFreezeBalance(account004Address, account004Key, 0, - null, blockingStubFull)); - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == freezeAmount); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account004Address, freezeAmount, 0, - 1, account004Key, blockingStubFull)); - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == 0); - - Assert.assertFalse(PublicMethed.unFreezeBalance(account004Address, account004Key, 0, - null, blockingStubFull)); - Assert.assertTrue(PublicMethed.unFreezeBalance(account004Address, account004Key, 1, - null, blockingStubFull)); - account004 = PublicMethed.queryAccount(account004Address, blockingStubFull); - Assert.assertTrue(account004.getBalance() == freezeAmount); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - PublicMethed.waitProduceNextBlock(searchBlockingStubFull); - /* while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - }*/ - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount005.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount005.java deleted file mode 100644 index da675842482..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount005.java +++ /dev/null @@ -1,267 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAccount005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String notWitnessTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - private final byte[] notWitness = PublicMethed.getFinalAddress(notWitnessTestKey); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = - Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - - } - - @Test - public void testWithdrawBalance() { - //Withdraw failed when you are not witness - Assert.assertFalse(withdrawBalance(notWitness, notWitnessTestKey)); - //Due to it's hard to automation, withdraw balance success case is not automation, - // please test by manual - //Assert.assertTrue(WithdrawBalance(fromAddress,testKey002)); - //Withdraw failed when the latest time to withdraw within 1 day. - - if (withdrawBalance(fromAddress, testKey002)) { - Assert.assertFalse(withdrawBalance(fromAddress, testKey002)); - } else { - logger.info("This account has withdraw within 1 day, please confirm"); - } - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - BalanceContract.WithdrawBalanceContract.Builder builder = - BalanceContract.WithdrawBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - BalanceContract.WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote.newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - if (key.equals(afterVote.getVotes(j).getVoteAddress())) { - Long afterVoteNum = Long.parseLong(witness.get(key)); - Assert.assertTrue(afterVoteNum == afterVote.getVotes(j).getVoteCount()); - logger.info("test equal vote"); - } - } - } - return true; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount006.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount006.java deleted file mode 100644 index d231ac80c60..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount006.java +++ /dev/null @@ -1,186 +0,0 @@ -package stest.tron.wallet.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount006 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 20000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] account006Address = ecKey.getAddress(); - String account006Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(account006Key); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void test1GetAccountNet() { - ecKey = new ECKey(Utils.getRandom()); - account006Address = ecKey.getAddress(); - account006Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - //Sendcoin to this account - ByteString addressBS1 = ByteString.copyFrom(account006Address); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 100000000, 3, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(account006Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - - //Get new account net information. - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - logger.info(Long.toString(accountNetMessage.getNetLimit())); - logger.info(Long.toString(accountNetMessage.getNetUsed())); - logger.info(Long.toString(accountNetMessage.getFreeNetLimit())); - logger.info(Long.toString(accountNetMessage.getFreeNetUsed())); - logger.info(Long.toString(accountNetMessage.getTotalNetLimit())); - logger.info(Long.toString(accountNetMessage.getTotalNetWeight())); - Assert.assertTrue(accountNetMessage.getNetLimit() == 0); - Assert.assertTrue(accountNetMessage.getNetUsed() == 0); - Assert.assertTrue(accountNetMessage.getFreeNetLimit() == FREENETLIMIT); - Assert.assertTrue(accountNetMessage.getFreeNetUsed() == 0); - Assert.assertTrue(accountNetMessage.getTotalNetLimit() > 0); - Assert.assertTrue(accountNetMessage.getTotalNetWeight() > 0); - logger.info("testGetAccountNet"); - - } - - @Test(enabled = true) - public void test2UseFreeNet() { - - //Transfer some TRX to other to test free net cost. - Assert.assertTrue(PublicMethed.sendcoin(fromAddress, 1L, account006Address, - account006Key, blockingStubFull)); - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - //Every transaction may cost 200 net. - Assert.assertTrue(accountNetMessage.getFreeNetUsed() > 0 && accountNetMessage - .getFreeNetUsed() < 300); - logger.info("testUseFreeNet"); - } - - @Test(enabled = true) - public void test3UseMoneyToDoTransaction() { - Assert.assertTrue(PublicMethed.sendcoin(account006Address, 1000000L, fromAddress, - testKey002, blockingStubFull)); - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - //Use out the free net - Integer times = 0; - while (accountNetMessage.getFreeNetUsed() < BASELINE && times++ < 30) { - PublicMethed.sendcoin(fromAddress, 1L, account006Address, account006Key, - blockingStubFull); - accountNetMessage = blockingStubFull.getAccountNet(request); - } - - Account queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long beforeSendBalance = queryAccount.getBalance(); - Assert.assertTrue(PublicMethed.sendcoin(fromAddress, 1L, account006Address, account006Key, - blockingStubFull)); - queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long afterSendBalance = queryAccount.getBalance(); - //when the free net is not enough and no balance freeze, use money to do the transaction. - Assert.assertTrue(beforeSendBalance - afterSendBalance > 1); - logger.info("testUseMoneyToDoTransaction"); - } - - @Test(enabled = true) - public void test4UseNet() { - //Freeze balance to own net. - Assert.assertTrue(PublicMethed.freezeBalance(account006Address, 10000000L, - 3, account006Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1L, account006Address, - account006Key, blockingStubFull)); - ByteString addressBs = ByteString.copyFrom(account006Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - Assert.assertTrue(accountNetMessage.getNetLimit() > 0); - Assert.assertTrue(accountNetMessage.getNetUsed() > 150); - - Account queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long beforeSendBalance = queryAccount.getBalance(); - Assert.assertTrue(PublicMethed.sendcoin(fromAddress, 1L, account006Address, - account006Key, blockingStubFull)); - queryAccount = PublicMethed.queryAccount(account006Key, blockingStubFull); - Long afterSendBalance = queryAccount.getBalance(); - //when you freeze balance and has net,you didn't cost money. - logger.info("before is " + Long.toString(beforeSendBalance) + " and after is " - + Long.toString(afterSendBalance)); - Assert.assertTrue(beforeSendBalance - afterSendBalance == 1); - addressBs = ByteString.copyFrom(account006Address); - request = Account.newBuilder().setAddress(addressBs).build(); - accountNetMessage = blockingStubFull.getAccountNet(request); - //when you freeze balance and has net,you cost net. - logger.info(Long.toString(accountNetMessage.getNetUsed())); - Assert.assertTrue(accountNetMessage.getNetUsed() > 350); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount007.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount007.java deleted file mode 100644 index 33a20804976..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount007.java +++ /dev/null @@ -1,126 +0,0 @@ -package stest.tron.wallet.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount007 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //owner account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account007Address = ecKey1.getAddress(); - String account007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - //Wait to be create account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey2.getAddress(); - String newAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(account007Key); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testCreateAccount() { - Assert.assertTrue(PublicMethed.sendcoin(account007Address, 10000000, - fromAddress, testKey002, blockingStubFull)); - Account accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - final Long beforeBalance = accountInfo.getBalance(); - - AccountNetMessage accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - final Long beforeFreeNet = accountNetInfo.getFreeNetUsed(); - - Assert.assertTrue(PublicMethed.createAccount(account007Address, newAccountAddress, - account007Key, blockingStubFull)); - - accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - Long afterBalance = accountInfo.getBalance(); - - accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - Long afterFreeNet = accountNetInfo.getFreeNetUsed(); - - logger.info(Long.toString(beforeBalance)); - logger.info(Long.toString(afterBalance)); - - //When creator has no bandwidth, he can't use the free net. - Assert.assertTrue(afterFreeNet == beforeFreeNet); - - //When the creator has no bandwidth, create a new account should spend 0.1TRX. - Assert.assertTrue(beforeBalance - afterBalance == 100000); - } - - @Test(enabled = true) - public void testExceptionCreateAccount() { - //Try to create an exist account - Assert - .assertFalse(PublicMethed.createAccount(account007Address, account007Address, account007Key, - blockingStubFull)); - - //Try to create an invalid account - byte[] wrongAddress = "wrongAddress".getBytes(); - Assert.assertFalse(PublicMethed.createAccount(account007Address, wrongAddress, account007Key, - blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount009.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount009.java deleted file mode 100644 index d60c9171507..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount009.java +++ /dev/null @@ -1,122 +0,0 @@ -package stest.tron.wallet.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount009 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account009Address = ecKey1.getAddress(); - String account009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account009SecondAddress = ecKey2.getAddress(); - String account009SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] account009InvalidAddress = ecKey3.getAddress(); - String account009InvalidKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(account009Key); - PublicMethed.printAddress(account009SecondKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testGetEnergy() { - Assert.assertTrue(PublicMethed.sendcoin(account009Address, 10000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account009SecondAddress, 10000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account009InvalidAddress, 10000000, - fromAddress, testKey002, blockingStubFull)); - - Account account009Info = PublicMethed.queryAccount(account009Key, blockingStubFull); - logger.info(Long.toString( - account009Info.getAccountResource().getFrozenBalanceForEnergy().getExpireTime())); - Assert.assertTrue(account009Info.getAccountResource().getEnergyUsage() == 0); - Assert.assertTrue(account009Info.getAccountResource().getFrozenBalanceForEnergy() - .getExpireTime() == 0); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account009Address, 1000000L, - 3, 1, account009Key, blockingStubFull)); - account009Info = PublicMethed.queryAccount(account009Key, blockingStubFull); - Assert.assertTrue(account009Info.getAccountResource().getEnergyUsage() == 0); - Assert.assertTrue(account009Info.getAccountResource().getFrozenBalanceForEnergy() - .getFrozenBalance() == 1000000L); - - AccountResourceMessage account009Resource = PublicMethed.getAccountResource(account009Address, - blockingStubFull); - Assert.assertTrue(account009Resource.getTotalEnergyLimit() >= 50000000000L); - Assert.assertTrue(account009Resource.getEnergyLimit() > 0); - Assert.assertTrue(account009Resource.getTotalEnergyWeight() >= 1); - } - - @Test(enabled = true) - public void testGetEnergyInvalid() { - //The resourceCode can only be 0 or 1 - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account009InvalidAddress, - 1000000L, 3, 0, account009InvalidKey, blockingStubFull)); - Assert.assertFalse(PublicMethed.freezeBalanceGetEnergy(account009InvalidAddress, 1000000L, - 3, -1, account009InvalidKey, blockingStubFull)); - Assert.assertFalse(PublicMethed.freezeBalanceGetEnergy(account009InvalidAddress, 1000000L, - 3, 3, account009InvalidKey, blockingStubFull)); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount011.java b/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount011.java deleted file mode 100644 index d50783f72c1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/account/WalletTestAccount011.java +++ /dev/null @@ -1,83 +0,0 @@ -package stest.tron.wallet.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account011Address = ecKey1.getAddress(); - String account011Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(account011Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = true) - public void testgenerateAddress() { - EmptyMessage.Builder builder = EmptyMessage.newBuilder(); - blockingStubFull.generateAddress(builder.build()); - blockingStubSolidity.generateAddress(builder.build()); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - - } - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock003.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock003.java deleted file mode 100644 index c226cef843f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock003.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.block; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestBlock003 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testGetNextMaintenanceTime() { - long now = System.currentTimeMillis(); - NumberMessage getNextMaintenanceTime = blockingStubFull - .getNextMaintenanceTime(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(getNextMaintenanceTime.getNum())); - logger.info(Long.toString(now)); - Assert.assertTrue(getNextMaintenanceTime.getNum() > now); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock004.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock004.java deleted file mode 100644 index 2a21a4bdc6d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock004.java +++ /dev/null @@ -1,203 +0,0 @@ -package stest.tron.wallet.block; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -//import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestBlock004 { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLimitNext() { - // - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(2); - builder.setEndNum(4); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.isPresent()); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 2); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(1).hasBlockHeader()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByExceptionLimitNext() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - //From -1 to 1 - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(-1); - builder.setEndNum(1); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - - //From 3 to 3 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(3); - builder.setEndNum(3); - blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - - //From 4 to 2 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(4); - builder.setEndNum(2); - blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - - //From 999999990 to 999999999 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(999999990); - builder.setEndNum(999999999); - blockList = blockingStubFull.getBlockByLimitNext(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock005.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock005.java deleted file mode 100644 index 4179fd4748a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock005.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.block; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -//import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestBlock005 { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLatestNum() { - // - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(3).build(); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.isPresent()); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 3); - Assert.assertTrue(getBlockByLatestNum.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue( - getBlockByLatestNum.get().getBlock(1).getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse( - getBlockByLatestNum.get().getBlock(2).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - logger.info("TestGetBlockByLatestNum ok!!!"); - - } - - @Test(enabled = true) - public void testGetBlockByExceptionNum() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(-1).build(); - GrpcAPI.BlockList blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - - numberMessage = NumberMessage.newBuilder().setNum(0).build(); - blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - - numberMessage = NumberMessage.newBuilder().setNum(100).build(); - blockList = blockingStubFull.getBlockByLatestNum(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock006.java b/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock006.java deleted file mode 100644 index 4fb4103a537..00000000000 --- a/framework/src/test/java/stest/tron/wallet/block/WalletTestBlock006.java +++ /dev/null @@ -1,111 +0,0 @@ -package stest.tron.wallet.block; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class WalletTestBlock006 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testGetTransactionCountByBlockNumFromFullnode() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - Long transactionNumInBlock = 0L; - transactionNumInBlock = blockingStubFull.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock >= 1); - - builder.setNum(-10); - transactionNumInBlock = blockingStubFull.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - builder.setNum(currentBlockNum + 10000L); - transactionNumInBlock = blockingStubFull.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - } - - @Test(enabled = true) - public void testGetTransactionCountByBlockNumFromSolidity() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - Long transactionNumInBlock = 0L; - transactionNumInBlock = blockingStubSolidity.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock >= 1); - - builder.setNum(-10); - transactionNumInBlock = blockingStubSolidity.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - builder.setNum(currentBlockNum + 10000L); - transactionNumInBlock = blockingStubSolidity.getTransactionCountByBlockNum(builder - .build()).getNum(); - Assert.assertTrue(transactionNumInBlock == -1); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee001.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee001.java deleted file mode 100644 index 3116598bc08..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee001.java +++ /dev/null @@ -1,131 +0,0 @@ -package stest.tron.wallet.committee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee001 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //Witness 47.93.9.236 - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test - public void testListProposals() { - //List proposals - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer beforeProposalCount = listProposals.get().getProposalsCount(); - - //CreateProposal - final long now = System.currentTimeMillis(); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 1000000L); - PublicMethed.createProposal(witness001Address, witnessKey001, proposalMap, blockingStubFull); - - //List proposals - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - Integer afterProposalCount = listProposals.get().getProposalsCount(); - Assert.assertTrue(beforeProposalCount + 1 == afterProposalCount); - logger.info(Long.toString(listProposals.get().getProposals(0).getCreateTime())); - logger.info(Long.toString(now)); - //Assert.assertTrue(listProposals.get().getProposals(0).getCreateTime() >= now); - Assert.assertTrue(listProposals.get().getProposals(0).getParametersMap().equals(proposalMap)); - - //getProposalListPaginated - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(0); - pageMessageBuilder.setLimit(1); - ProposalList paginatedProposalList = blockingStubFull - .getPaginatedProposalList(pageMessageBuilder.build()); - Assert.assertTrue(paginatedProposalList.getProposalsCount() >= 1); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee002.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee002.java deleted file mode 100644 index 4abd87f3937..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee002.java +++ /dev/null @@ -1,365 +0,0 @@ -package stest.tron.wallet.committee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee002 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - //Witness 47.93.9.236 - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - } - - - @Test(enabled = true) - public void testCreateProposalMaintenanceTimeInterval() { - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, 10000000L, - toAddress, testKey003, blockingStubFull)); - - //0:MAINTENANCE_TIME_INTERVAL,[3*27s,24h] - //Minimum interval - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum interval - proposalMap.put(0L, 86400000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum -1 interval, create failed. - proposalMap.put(0L, 80000L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 interval - proposalMap.put(0L, 86401000L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(0L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, proposalMap, - blockingStubFull)); - } - - @Test(enabled = true) - public void testCreateProposalAccountUpgradeCost() { - //1:ACCOUNT_UPGRADE_COST,[0,100 000 000 000 000 000]//drop - //Minimum AccountUpgradeCost - HashMap proposalMap = new HashMap(); - proposalMap.put(1L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum AccountUpgradeCost - proposalMap.put(1L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 AccountUpgradeCost - proposalMap.put(1L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 AccountUpgradeCost - proposalMap.put(1L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(1L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - } - - @Test(enabled = true) - public void testCreateProposalCreateAccountFee() { - //2:CREATE_ACCOUNT_FEE,[0,100 000 000 000 000 000]//drop - //Minimum CreateAccountFee - HashMap proposalMap = new HashMap(); - proposalMap.put(2L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum CreateAccountFee - proposalMap.put(2L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 CreateAccountFee - proposalMap.put(2L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 CreateAccountFee - proposalMap.put(2L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(2L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testTransactionFee() { - //3:TRANSACTION_FEE,[0,100 000 000 000 000 000]//drop - //Minimum TransactionFee - HashMap proposalMap = new HashMap(); - proposalMap.put(3L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum TransactionFee - proposalMap.put(3L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 TransactionFee - proposalMap.put(3L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 TransactionFee - proposalMap.put(3L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(3L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testAssetIssueFee() { - //4:ASSET_ISSUE_FEE,[0,100 000 000 000 000 000]//drop - //Minimum AssetIssueFee - HashMap proposalMap = new HashMap(); - proposalMap.put(4L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Duplicat proposals - proposalMap.put(4L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum AssetIssueFee - proposalMap.put(4L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 AssetIssueFee - proposalMap.put(4L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 AssetIssueFee - proposalMap.put(4L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(4L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testWitnessPayPerBlock() { - //5:WITNESS_PAY_PER_BLOCK,[0,100 000 000 000 000 000]//drop - //Minimum WitnessPayPerBlock - HashMap proposalMap = new HashMap(); - proposalMap.put(5L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum WitnessPayPerBlock - proposalMap.put(5L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 WitnessPayPerBlock - proposalMap.put(5L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 WitnessPayPerBlock - proposalMap.put(5L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(5L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testWitnessStandbyAllowance() { - //6:WITNESS_STANDBY_ALLOWANCE,[0,100 000 000 000 000 000]//drop - //Minimum WitnessStandbyAllowance - HashMap proposalMap = new HashMap(); - proposalMap.put(6L, 0L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum WitnessStandbyAllowance - proposalMap.put(6L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 WitnessStandbyAllowance - proposalMap.put(6L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 WitnessStandbyAllowance - proposalMap.put(6L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(6L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - @Test(enabled = true) - public void testCreateNewAccountFeeInSystemControl() { - //7:CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT,0 or 1 - HashMap proposalMap = new HashMap(); - proposalMap.put(7L, 1L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum WitnessStandbyAllowance - proposalMap.put(7L, 100000000000000000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Minimum - 1 WitnessStandbyAllowance - proposalMap.put(6L, -1L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Maximum + 1 WitnessStandbyAllowance - proposalMap.put(6L, 100000000000000001L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //Non witness account - proposalMap.put(6L, 86400000L); - Assert.assertFalse(PublicMethed.createProposal(toAddress, testKey003, - proposalMap, blockingStubFull)); - - } - - - @Test(enabled = true) - public void testInvalidProposals() { - // The index isn't from 0-9 - HashMap proposalMap = new HashMap(); - proposalMap.put(10L, 60L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - //The index is -1 - proposalMap.put(-1L, 6L); - Assert.assertFalse(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee003.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee003.java deleted file mode 100644 index 12b098f95fa..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee003.java +++ /dev/null @@ -1,166 +0,0 @@ -package stest.tron.wallet.committee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee003 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - //private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - //private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - //private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testApproveProposal() { - PublicMethed.sendcoin(witness001Address, 1000000L, - toAddress, testKey003, blockingStubFull); - PublicMethed.sendcoin(witness002Address, 1000000L, - toAddress, testKey003, blockingStubFull); - - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - true, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list after approve - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - logger.info(Integer.toString(listProposals.get().getProposals(0).getApprovalsCount())); - Assert.assertTrue(listProposals.get().getProposals(0).getApprovalsCount() == 1); - //logger.info(Base58.encode58Check(witness002Address)); - //logger.info(Base58.encode58Check(listProposals.get().getProposals(0). - // getApprovalsList().get(0).toByteArray())); - Assert.assertTrue(Base58.encode58Check(witness002Address).equals(Base58.encode58Check( - listProposals.get().getProposals(0).getApprovalsList().get(0).toByteArray()))); - - //Failed to approve proposal when you already approval this proposal - Assert.assertFalse(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - true, blockingStubFull)); - - //Success to change the option from true to false. - Assert.assertTrue(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - false, blockingStubFull)); - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - Assert.assertTrue(listProposals.get().getProposals(0).getApprovalsCount() == 0); - - //Failed to approvel proposal when you already approval this proposal - Assert.assertFalse(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - false, blockingStubFull)); - - //Non witness can't approval proposal - Assert.assertFalse(PublicMethed.approveProposal(toAddress, testKey003, proposalId, - true, blockingStubFull)); - - //Muti approval - Assert.assertTrue(PublicMethed.approveProposal(witness001Address, witnessKey001, proposalId, - true, blockingStubFull)); - Assert.assertTrue(PublicMethed.approveProposal(witness002Address, witnessKey002, proposalId, - true, blockingStubFull)); - //Assert.assertTrue(PublicMethed.approveProposal(witness003Address,witnessKey003,proposalId, - // true,blockingStubFull)); - //Assert.assertTrue(PublicMethed.approveProposal(witness004Address,witnessKey004,proposalId, - // true,blockingStubFull)); - //Assert.assertTrue(PublicMethed.approveProposal(witness005Address,witnessKey005,proposalId, - // true,blockingStubFull)); - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - Assert.assertTrue(listProposals.get().getProposals(0).getApprovalsCount() == 2); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee004.java b/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee004.java deleted file mode 100644 index 6112ab62c7c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/committee/WalletTestCommittee004.java +++ /dev/null @@ -1,219 +0,0 @@ -package stest.tron.wallet.committee; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.ChainParameters; -import org.tron.protos.Protocol.Proposal; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class WalletTestCommittee004 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - //private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - //private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - //private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void test1DeleteProposal() { - PublicMethed.sendcoin(witness001Address, 1000000L, - toAddress, testKey003, blockingStubFull); - PublicMethed.sendcoin(witness002Address, 1000000L, - toAddress, testKey003, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Create a proposal and approval it - HashMap proposalMap = new HashMap(); - proposalMap.put(1L, 99999L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - Assert.assertTrue(PublicMethed.approveProposal(witness001Address, witnessKey001, - proposalId, true, blockingStubFull)); - logger.info(Integer.toString(listProposals.get().getProposals(0).getStateValue())); - //The state is "pending", state value == 0 - Assert.assertTrue(listProposals.get().getProposals(0).getStateValue() == 0); - - //When the proposal isn't created by you, you can't delete it. - Assert.assertFalse(PublicMethed.deleteProposal(witness002Address, witnessKey002, - proposalId, blockingStubFull)); - //Cancel the proposal - Assert.assertTrue(PublicMethed.deleteProposal(witness001Address, witnessKey001, - proposalId, blockingStubFull)); - //When the state is cancel, you can't delete it again. - Assert.assertFalse(PublicMethed.deleteProposal(witness001Address, witnessKey001, - proposalId, blockingStubFull)); - //You can't delete an invalid proposal - Assert.assertFalse(PublicMethed.deleteProposal(witness001Address, witnessKey001, - proposalId + 100, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - logger.info(Integer.toString(listProposals.get().getProposals(0).getStateValue())); - //The state is "cancel", state value == 3 - Assert.assertTrue(listProposals.get().getProposals(0).getStateValue() == 3); - - //When the state is cancel, you can't approval proposal - Assert.assertFalse(PublicMethed.approveProposal(witness001Address, witnessKey001, - proposalId, true, blockingStubFull)); - Assert.assertFalse(PublicMethed.approveProposal(witness001Address, witnessKey001, - proposalId, false, blockingStubFull)); - } - - @Test(enabled = true) - public void test2GetProposal() { - //Create a proposal and approval it - HashMap proposalMap = new HashMap(); - proposalMap.put(1L, 999999999L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - - BytesMessage request = BytesMessage.newBuilder().setValue(ByteString.copyFrom( - ByteArray.fromLong(Long.parseLong(proposalId.toString())))) - .build(); - Proposal proposal = blockingStubFull.getProposalById(request); - Optional getProposal = Optional.ofNullable(proposal); - - Assert.assertTrue(getProposal.isPresent()); - Assert.assertTrue(getProposal.get().getStateValue() == 0); - - //Invalid get proposal - final Integer wrongProposalId = proposalId + 99; - request = BytesMessage.newBuilder().setValue(ByteString.copyFrom( - ByteArray.fromLong(Long.parseLong(wrongProposalId.toString())))) - .build(); - proposal = blockingStubFull.getProposalById(request); - getProposal = Optional.ofNullable(proposal); - logger.info(Long.toString(getProposal.get().getCreateTime())); - Assert.assertTrue(getProposal.get().getCreateTime() == 0); - } - - @Test(enabled = false) - public void testGetChainParameters() { - //Set the default map - HashMap defaultCommitteeMap = new HashMap(); - defaultCommitteeMap.put("MAINTENANCE_TIME_INTERVAL", 300000L); - defaultCommitteeMap.put("ACCOUNT_UPGRADE_COST", 9999000000L); - defaultCommitteeMap.put("CREATE_ACCOUNT_FEE", 100000L); - defaultCommitteeMap.put("TRANSACTION_FEE", 10L); - defaultCommitteeMap.put("ASSET_ISSUE_FEE", 1024000000L); - defaultCommitteeMap.put("WITNESS_PAY_PER_BLOCK", 32000000L); - defaultCommitteeMap.put("WITNESS_STANDBY_ALLOWANCE", 115200000000L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT", 0L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_BANDWIDTH_RATE", 1L); - - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - logger.info(getChainParameters.get().getChainParameter(i).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(i).getValue())); - } - Assert.assertTrue(getChainParameters.get().getChainParameterCount() >= 10); - Assert.assertTrue(getChainParameters.get() - .getChainParameter(1).getValue() == 9999000000L); - Assert.assertTrue(getChainParameters.get().getChainParameter(4) - .getValue() == 1024000000L); - Assert.assertTrue(getChainParameters.get().getChainParameter(7).getValue() == 0); - Assert.assertTrue(getChainParameters.get().getChainParameter(8).getValue() == 1); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/CipherException.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/CipherException.java deleted file mode 100644 index a0164c6bba6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/CipherException.java +++ /dev/null @@ -1,19 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -/** - * Cipher exception wrapper. - */ -public class CipherException extends Exception { - - public CipherException(String message) { - super(message); - } - - public CipherException(Throwable cause) { - super(cause); - } - - public CipherException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/DailyBuildReport.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/DailyBuildReport.java deleted file mode 100644 index ec4b061d1b7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/DailyBuildReport.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.nio.file.StandardOpenOption; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.testng.ITestContext; -import org.testng.ITestResult; -import org.testng.TestListenerAdapter; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; - -public class DailyBuildReport extends TestListenerAdapter { - - StringBuilder passedDescriptionList = new StringBuilder(""); - StringBuilder failedDescriptionList = new StringBuilder(""); - StringBuilder skippedDescriptionList = new StringBuilder(""); - private Integer passedNum = 0; - private Integer failedNum = 0; - private Integer skippedNum = 0; - private String reportPath; - public Map transactionType = new HashMap<>(); - public Long endBlockNum = 0L; - public static Long startBlockNum = 0L; - public Long totalTransactionNum = 0L; - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - @Override - public void onStart(ITestContext context) { - reportPath = "Daily_Build_Report"; - StringBuilder sb = new StringBuilder("3.Stest report: "); - String res = sb.toString(); - try { - Files.write((Paths.get(reportPath)), res.getBytes("utf-8")); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void onTestSuccess(ITestResult result) { - passedDescriptionList.append(result.getMethod().getRealClass() + ": " - + result.getMethod().getDescription() + "\n"); - passedNum++; - } - - @Override - public void onTestFailure(ITestResult result) { - failedDescriptionList.append(result.getMethod().getRealClass() + ": " - + result.getMethod().getDescription() + "\n"); - failedNum++; - } - - @Override - public void onTestSkipped(ITestResult result) { - skippedDescriptionList.append(result.getMethod().getRealClass() + ": " - + result.getMethod().getDescription() + "\n"); - skippedNum++; - } - - - @Override - public void onFinish(ITestContext testContext) { - StringBuilder sb = new StringBuilder(); - sb.append("Total: " + (passedNum + failedNum + skippedNum) + ", " + "Passed: " + passedNum - + ", " + "Failed: " + failedNum + ", " + "Skipped: " + skippedNum + "\n"); - sb.append("------------------------------------------------------------------------------\n"); - List> list = calculateAfterDailyBuild(); - sb.append("Total transaction number:" + totalTransactionNum + "\n"); - sb.append("Transaction type list:" + "\n"); - for (Map.Entry entry : list) { - sb.append(entry.getKey()); - for (int i = entry.getKey().length(); i < 40; i++) { - sb.append(" "); - } - sb.append(" : " + entry.getValue() + "\n"); - - } - sb.append("------------------------------------------------------------------------------\n"); - sb.append("Passed list " + "\n"); - //sb.append("Passed case List: " + "\n"); - sb.append(passedDescriptionList.toString()); - sb.append("------------------------------------------------------------------------------\n"); - sb.append("Failed list: " + "\n"); - //sb.append("Failed case List: " + "\n"); - sb.append(failedDescriptionList.toString()); - sb.append("------------------------------------------------------------------------------\n"); - sb.append("Skipped list: " + "\n"); - //sb.append("Skipped case List: " + "\n"); - sb.append(skippedDescriptionList.toString()); - sb.append("----------------------------------------------------------------\n"); - - String res = sb.toString(); - try { - Files.write((Paths.get(reportPath)), res.getBytes("utf-8"), StandardOpenOption.APPEND); - } catch (IOException e) { - e.printStackTrace(); - } - - } - - /** - * calculate transaction num and transaction type After DailyBuild. - */ - public List> calculateAfterDailyBuild() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - endBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - System.out.println("-----startnum :" + startBlockNum + "-----endnum:" + endBlockNum); - List listTrans; - List listContract; - Protocol.Block block; - int transNum; - int contractNum; - String contractType; - for (long i = startBlockNum; i < endBlockNum; i++) { - block = PublicMethed.getBlock(i, blockingStubFull); - listTrans = block.getTransactionsList(); - transNum = block.getTransactionsCount(); - totalTransactionNum += transNum; - for (int j = 0; j < transNum; j++) { - listContract = listTrans.get(j).getRawData().getContractList(); - contractNum = listContract.size(); - for (int k = 0; k < contractNum; k++) { - contractType = listContract.get(k).getType().toString(); - transactionType.put(contractType, transactionType.getOrDefault(contractType, 0) + 1); - } - } - } - try { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - - List> list = new ArrayList<>(transactionType.entrySet()); - Collections.sort(list, new Comparator>() { - @Override - public int compare(Map.Entry o1, Map.Entry o2) { - return (o2.getValue()).compareTo(o1.getValue()); - } - }); - return list; - } - -} - diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/FileUtil.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/FileUtil.java deleted file mode 100644 index 03268fa8b9e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/FileUtil.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.List; - -public class FileUtil { - - /** - * constructor. - */ - - public static List recursiveList(String path) throws IOException { - - final List files = new ArrayList<>(); - - Files.walkFileTree(Paths.get(path), new FileVisitor() { - @Override - public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { - files.add(file.toString()); - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult visitFileFailed(Path file, IOException exc) { - return FileVisitResult.CONTINUE; - } - - @Override - public FileVisitResult postVisitDirectory(Path dir, IOException exc) { - return FileVisitResult.CONTINUE; - } - }); - - return files; - } - - /** - * constructor. - */ - - public static boolean recursiveDelete(String fileName) { - File file = new File(fileName); - if (file.exists()) { - //check if the file is a directory - if (file.isDirectory()) { - if ((file.list()).length > 0) { - for (String s : file.list()) { - //call deletion of file individually - recursiveDelete(fileName + System.getProperty("file.separator") + s); - } - } - } - - file.setWritable(true); - boolean result = file.delete(); - return result; - } else { - return false; - } - } - - /** - * constructor. - */ - - public static void saveData(String filePath, byte[] data) { - FileOutputStream fos = null; - try { - File file = new File(filePath); - file.createNewFile(); - fos = new FileOutputStream(file); - fos.write(data); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fos != null) { - try { - fos.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - /** - * constructor. - */ - - public static byte[] readData(String filePath) { - FileInputStream fi = null; - try { - File file = new File(filePath); - long fileSize = file.length(); - if (fileSize > Integer.MAX_VALUE) { - System.out.println("file too big..."); - return null; - } - fi = new FileInputStream(file); - byte[] buffer = new byte[(int) fileSize]; - int offset = 0; - int numRead; - while (offset < buffer.length - && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { - offset += numRead; - } - if (offset != buffer.length) { - return null; - } - return buffer; - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (fi != null) { - try { - fi.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return null; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java deleted file mode 100644 index eec885184d4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/JsonRpcBase.java +++ /dev/null @@ -1,405 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; -import io.netty.util.internal.StringUtil; - -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -// import java.util.*; - -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.services.http.Util; -import org.tron.core.zen.address.DiversifierT; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.ShieldContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class JsonRpcBase { - - public final String foundationAccountKey = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - - public static final String jsonRpcOwnerKey = - Configuration.getByPath("testng.conf").getString("defaultParameter.jsonRpcOwnerKey"); - public static final byte[] jsonRpcOwnerAddress = PublicMethed.getFinalAddress(jsonRpcOwnerKey); - public static final String jsonRpcOwnerAddressString = - PublicMethed.getAddressString(jsonRpcOwnerKey); - public static String jsonRpcNode = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(0); - public static String jsonRpcNodeForSolidity = - Configuration.getByPath("testng.conf").getStringList("jsonRpcNode.ip.list").get(1); - public static String httpFullNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - public static String httpsolidityNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(3); - public static String ethHttpsNode = - Configuration.getByPath("testng.conf").getStringList("ethHttpsNode.host.list").get(0); - - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - public static String data = null; - public String paramString = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - public String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - public static String trc20AddressByteString; - public static String trc20AddressHex; - public static String contractAddressFrom58; - public static String contractTrc20AddressFrom58; - public static String contractAddressFromHex; - public static ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployTrc20Txid; - public static String deployShieldTxid; - public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public static String burn = - "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," - + "bytes32[3],bytes32[9][],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - static JSONObject responseContent; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - public static String name = "jsonrpc-test"; - public static String jsonRpcAssetId; - public static Integer blockNum; - public static Integer blockNumForTrc20; - public static String blockNumHex; - public static String blockId; - public static String txid; - public static String trc20Txid; - - /** constructor. */ - @BeforeSuite(enabled = true, description = "Deploy json rpc test case resource") - public void deployJsonRpcUseResource() throws Exception { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - if (PublicMethed.queryAccount(jsonRpcOwnerAddress, blockingStubFull).getAssetV2Count() == 0L) { - Assert.assertTrue( - PublicMethed.sendcoin( - jsonRpcOwnerAddress, - 2048000000L, - foundationAccountAddress, - foundationAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // Create a new Asset Issue - Assert.assertTrue( - PublicMethed.createAssetIssue( - jsonRpcOwnerAddress, - name, - totalSupply, - 1, - 1, - System.currentTimeMillis() + 5000, - System.currentTimeMillis() + 1000000000, - 1, - "description", - "urlurlurl", - 2000L, - 2000L, - 1L, - 1L, - jsonRpcOwnerKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - response = HttpMethed.getAccount(httpFullNode, jsonRpcOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - jsonRpcAssetId = responseContent.getString("asset_issued_ID"); - - deployContract(); - triggerContract(); - deployTrc20Contract(); - } - - /** constructor. */ - public void deployContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("name", "transferTokenContract"); - param.addProperty("gas", "0x245498"); - String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - System.out.println("CODE:" + code); - String abi = retMap.get("abI").toString(); - System.out.println("abi:" + abi); - - param.addProperty("abi", abi); - param.addProperty("data", code); - param.addProperty("consumeUserResourcePercent", 100); - param.addProperty("originEnergyLimit", 11111111111111L); - param.addProperty("value", "0x1f4"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - - responseContent = HttpMethed.parseStringContent(transactionString); - final String txid = responseContent.getString("txID"); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), jsonRpcOwnerKey, blockingStubFull); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, 1L); - - response = HttpMethed.getTransactionById(httpFullNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractAddressFrom58:" + contractAddressFrom58); - } - - /** constructor. */ - public void triggerContract() throws Exception { - final Long beforeTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - final Long beforeBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - - String tokenIdParam = - "00000000000000000000000000000000000000000000000000000000000" - + Integer.toHexString(Integer.valueOf(jsonRpcAssetId)); - - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - paramString = addressParam + tokenIdParam + tokenValueParam; - logger.info("paramString:" + paramString); - - String selector = "TransferTokenTo(address,trcToken,uint256)"; - // exit(1); - param.addProperty("data", "0x" + Util.parseMethod(selector, paramString)); - data = "0x" + Util.parseMethod(selector, paramString); - param.addProperty("gas", "0x245498"); - param.addProperty("value", "0x1389"); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionString = responseContent.getJSONObject("result").getString("transaction"); - logger.info("transactionString : " + transactionString); - String transactionSignString = - HttpMethed.gettransactionsign(httpFullNode, transactionString, jsonRpcOwnerKey); - logger.info("transactionSignString:" + transactionSignString); - responseContent = HttpMethed.parseStringContent(transactionString); - txid = responseContent.getString("txID"); - logger.info("triggerTxid:" + txid); - - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - logger.info("response:" + response); - HttpMethed.verificationResult(response); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = - PublicMethed.getAssetBalanceByAssetId( - ByteString.copyFromUtf8(jsonRpcAssetId), foundationAccountKey, blockingStubFull); - Long afterBalance = HttpMethed.getBalance(httpFullNode, jsonRpcOwnerAddress); - - org.junit.Assert.assertEquals(beforeTokenBalance - afterTokenBalance, -1L); - org.junit.Assert.assertTrue(beforeBalance - afterBalance >= 5000); - - blockNum = - (int) (PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getBlockNumber()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - blockId = responseContent.get("blockID").toString(); - } - - /** constructor. */ - public void deployTrc20Contract() throws InterruptedException { - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf").getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployTrc20Txid = - PublicMethed.deployContractWithConstantParame( - contractName, - abi, - code, - constructorStr, - data, - "", - maxFeeLimit, - 0L, - 100, - null, - jsonRpcOwnerKey, - jsonRpcOwnerAddress, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("deployTrc20Txid:" + deployTrc20Txid); - response = HttpMethed.getTransactionById(httpFullNode, deployTrc20Txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - org.junit.Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractTrc20AddressFrom58 = responseContent.getString("contract_address"); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - - // NewFilterId = createNewFilterId(); - - Optional infoById = - PublicMethed.getTransactionInfoById(deployTrc20Txid, blockingStubFull); - - trc20AddressHex = ByteArray.toHexString(infoById.get().getContractAddress().toByteArray()); - byte[] trc20Address = infoById.get().getContractAddress().toByteArray(); - - String selector = "transfer(address,uint256)"; - String addressParam = - "000000000000000000000000" - + ByteArray.toHexString(foundationAccountAddress).substring(2); // [0,3) - String transferValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String paramString = addressParam + transferValueParam; - trc20Txid = - PublicMethed.triggerContract( - trc20Address, - selector, - paramString, - true, - 0, - maxFeeLimit, - "0", - 0, - jsonRpcOwnerAddress, - jsonRpcOwnerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - blockNumForTrc20 = - (int) - (PublicMethed.getTransactionInfoById(trc20Txid, blockingStubFull) - .get() - .getBlockNumber()); - } - - /** constructor. */ - public static HttpResponse getEthHttps(String ethHttpsNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "https://" + ethHttpsNode + "/v3/dfb752dd45204b8daae74249f4653584"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { - try { - String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; - response = HttpMethed.createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method) { - return getJsonRpcBody(method, new JsonArray(), 1); - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method, JsonArray params) { - return getJsonRpcBody(method, params, 1); - } - - /** constructor. */ - public static JsonObject getJsonRpcBody(String method, JsonArray params, Integer id) { - JsonObject jsonObject = new JsonObject(); - jsonObject.addProperty("jsonrpc", "2.0"); - jsonObject.addProperty("method", method); - jsonObject.add("params", params); - jsonObject.addProperty("id", id); - - return jsonObject; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java deleted file mode 100644 index e528c647545..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethed.java +++ /dev/null @@ -1,7091 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import static org.tron.common.crypto.Hash.sha3; -import static org.tron.common.crypto.Hash.sha3omit12; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.common.primitives.Longs; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.netty.util.internal.StringUtil; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.testng.Assert; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DecryptNotes.NoteTx; -import org.tron.api.GrpcAPI.DecryptNotesMarked; -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.IvkDecryptAndMarkParameters; -import org.tron.api.GrpcAPI.IvkDecryptParameters; -import org.tron.api.GrpcAPI.NfParameters; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.OvkDecryptParameters; -import org.tron.api.GrpcAPI.PrivateParameters; -import org.tron.api.GrpcAPI.PrivateParametersWithoutAsk; -import org.tron.api.GrpcAPI.ReceiveNote; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.SpendAuthSigParameters; -import org.tron.api.GrpcAPI.SpendNote; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.GrpcAPI.TransactionApprovedList; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletGrpc.WalletBlockingStub; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.capsule.BlockCapsule.BlockId; -import org.tron.core.zen.address.DiversifierT; -import org.tron.core.zen.address.ExpandedSpendingKey; -import org.tron.core.zen.address.FullViewingKey; -import org.tron.core.zen.address.IncomingViewingKey; -import org.tron.core.zen.address.PaymentAddress; -import org.tron.core.zen.address.SpendingKey; -import org.tron.keystore.WalletFile; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.DelegatedResourceAccountIndex; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.Protocol.Key; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.Transaction.Result; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AccountContract.AccountCreateContract; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.AccountContract.SetAccountIdContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract; -import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract; -import org.tron.protos.contract.ExchangeContract.ExchangeTransactionContract; -import org.tron.protos.contract.ExchangeContract.ExchangeWithdrawContract; -import org.tron.protos.contract.MarketContract; -import org.tron.protos.contract.ProposalContract.ProposalApproveContract; -import org.tron.protos.contract.ProposalContract.ProposalCreateContract; -import org.tron.protos.contract.ProposalContract.ProposalDeleteContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.ShieldContract.ShieldedTransferContract; -import org.tron.protos.contract.ShieldContract.SpendDescription; -import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract.Builder; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract.ABI; -import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapper; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract; -import org.tron.protos.contract.StorageContract.BuyStorageContract; -import org.tron.protos.contract.StorageContract.SellStorageContract; -import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; - -public class PublicMethed { - - // Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - private static final String FilePath = "Wallet"; - private static final Logger logger = LoggerFactory.getLogger("TestLogger"); - // private WalletGrpc.WalletBlockingStub blockingStubFull = null; - // private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public static Map utxoMapNote = new ConcurrentHashMap(); - public static List spendUtxoList = new ArrayList<>(); - private static List walletFile = new ArrayList<>(); - private static ShieldWrapper shieldWrapper = new ShieldWrapper(); - Wallet wallet = new Wallet(); - public static volatile Integer witnessNum; - - /** constructor. */ - public static Integer getWitnessNum(WalletGrpc.WalletBlockingStub blockingStubFull) { - if (null == witnessNum) { - witnessNum = PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList().size(); - } - - return witnessNum; - } - - /** constructor. */ - public static String createAssetIssueGetTxid( - byte[] address, - String name, - String abbreviation, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - /** constructor. */ - public static Boolean createAssetIssue( - byte[] address, - String name, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** constructor. */ - public static Boolean createAssetIssue( - byte[] address, - String name, - String abbreviation, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setAbbr(ByteString.copyFrom(abbreviation.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** constructor. */ - public static Boolean createAssetIssue( - byte[] address, - String name, - Long totalSupply, - Integer trxNum, - Integer icoNum, - int precision, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setPrecision(precision); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** constructor. */ - public static Return createAssetIssue2( - byte[] address, - String name, - Long totalSupply, - Integer trxNum, - Integer icoNum, - Long startTime, - Long endTime, - Integer voteScore, - String description, - String url, - Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, - Long fronzenAmount, - Long frozenDay, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - // Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - // builder.setPublicFreeAssetNetUsage(); - // builder.setPublicLatestFreeNetTime(); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = - blockingStubFull.createAssetIssue2(builder.build()); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - return ret; - } catch (Exception ex) { - ex.printStackTrace(); - // return false; - return Return.getDefaultInstance(); - } - } - - /** constructor. */ - public static Account queryAccountByAddress( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Account queryAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Protocol.Account queryAccount( - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); // 04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - /** constructor. */ - public static Account queryAccount( - byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Account getAccountById( - String accountId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } - - /** constructor. */ - public static Account getAccountByIdFromSolidity( - String accountId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString bsAccountId = ByteString.copyFromUtf8(accountId); - Account request = Account.newBuilder().setAccountId(bsAccountId).build(); - return blockingStubFull.getAccountById(request); - } - - /** constructor. */ - public static String loadPubKey() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** constructor. */ - public static byte[] getAddress(ECKey ecKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - return ecKey.getAddress(); - } - - /** constructor. */ - public static Protocol.Account grpcQueryAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Protocol.Account request = Protocol.Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** constructor. */ - public static Protocol.Block getBlock( - long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - /** constructor. */ - public static BlockExtention getBlock2(long blockNum, WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum2(builder.build()); - } - - /** constructor. */ - public static Protocol.Transaction signTransaction( - ECKey ecKey, Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - // logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - logger.info( - "Txid in sign is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); - } - - /** constructor. */ - public static Protocol.Transaction signTransactionForShield( - ECKey ecKey, Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - // logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - logger.info( - "Txid in sign is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - return TransactionUtils.sign(transaction, ecKey); - } - - /** constructor. */ - public static boolean participateAssetIssue( - byte[] to, - byte[] assertName, - long amount, - byte[] from, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Return participateAssetIssue2( - byte[] to, - byte[] assertName, - long amount, - byte[] from, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.participateAssetIssue2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - // Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return response; - } else { - return ret; - } - } - - /** constructor. */ - public static Boolean freezeBalance( - byte[] addRess, - long freezeBalance, - long freezeDuration, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = - blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - // Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - // beforeBandwidth = beforeFronzen.getBandwidth(); - // logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - /* Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - - Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - logger.info("beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" - + afterFrozenBalance.toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance);*/ - } - - /** constructor. */ - public static Return freezeBalance2( - byte[] addRess, - long freezeBalance, - long freezeDuration, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = - blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Protocol.Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - // Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - // beforeBandwidth = beforeFronzen.getBandwidth(); - // logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - if (response.getResult() == false) { - return response; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = - blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - - Protocol.Account afterFronzen = queryAccount(priKey, blockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - logger.info( - "beforefronen" - + beforeFrozenBalance.toString() - + " afterfronzen" - + afterFrozenBalance.toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - return ret; - } - - /** constructor. */ - public static Boolean unFreezeBalance( - byte[] address, - String priKey, - int resourceCode, - byte[] receiverAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static Boolean sendcoin( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - while (times++ <= 2) { - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - continue; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - return false; - } - - /** constructor. */ - public static String sendcoinGetTransactionHex( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - Integer times = 0; - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info( - "HEX transaction is : " - + "transaction hex string is " - + ByteArray.toHexString(transaction.toByteArray())); - return ByteArray.toHexString(transaction.toByteArray()); - } - - /** constructor. */ - public static Boolean cancelDeferredTransactionById( - String txid, byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - /*Contract.CancelDeferredTransactionContract.Builder builder = Contract - .CancelDeferredTransactionContract.newBuilder(); - builder.setTransactionId(ByteString.copyFrom(ByteArray.fromHexString(txid))); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - Contract.CancelDeferredTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .createCancelDeferredTransactionContract(contract); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Cancel transaction before sign txid = " + ByteArray.toHexString( - transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - System.out.println( - "Cancel transaction txid = " + ByteArray.toHexString(transactionExtention - .getTxid().toByteArray())); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult();*/ - return null; - } - - - - /** constructor. */ - public static Boolean sendcoinDelayed( - byte[] to, - long amount, - long delaySeconds, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - - // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - logger.info( - "Txid is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - - /** constructor. */ - public static String sendcoinDelayedGetTxid( - byte[] to, - long amount, - long delaySeconds, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - - // transaction = TransactionUtils.setDelaySeconds(transaction, delaySeconds); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(ecKey, transaction); - logger.info( - "Txid is " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - - - - /** constructor. */ - public static Return sendcoin2( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** constructor. */ - public static String sendcoinGetTransactionId( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - // Test raw data - /* Protocol.Transaction.raw.Builder builder1 = transaction.getRawData().toBuilder(); - builder1.setData(ByteString.copyFromUtf8("12345678")); - Transaction.Builder builder2 = transaction.toBuilder(); - builder2.setRawData(builder1); - transaction = builder2.build();*/ - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static Optional getTransactionById( - String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - - return Optional.ofNullable(transaction); - } - - /** constructor. */ - public static Optional getTransactionById( - String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - return Optional.ofNullable(transaction); - } - - /** constructor. */ - public static Long getAssetBalanceByAssetId( - ByteString assetId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Account assetOwnerAccount = queryAccount(priKey, blockingStubFull); - Long assetOwnerAssetBalance = 0L; - for (String id : assetOwnerAccount.getAssetV2Map().keySet()) { - if (assetId.toStringUtf8().equalsIgnoreCase(id)) { - assetOwnerAssetBalance = assetOwnerAccount.getAssetV2Map().get(id); - } - } - logger.info("asset balance is " + assetOwnerAssetBalance); - return assetOwnerAssetBalance; - } - - /* - public static Optional getDeferredTransactionById(String txId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - DeferredTransaction transaction = blockingStubFull.getDeferredTransactionById(request); - if (Objects.isNull(transaction)) { - transaction = blockingStubFull.getDeferredTransactionById(request); - } - return Optional.ofNullable(transaction); - } - */ - - /** constructor. */ - public static Optional getTransactionByIdSolidity( - String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubSolidity.getTransactionById(request); - return Optional.ofNullable(transaction); - } - - /** constructor. */ - public static String printTransaction(Transaction transaction) { - String result = ""; - result += "hash: "; - result += "\n"; - result += - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), transaction.toByteArray())); - result += "\n"; - result += "txid: "; - result += "\n"; - result += - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - result += "\n"; - - if (transaction.getRawData() != null) { - result += "raw_data: "; - result += "\n"; - result += "{"; - result += "\n"; - result += printTransactionRow(transaction.getRawData()); - result += "}"; - result += "\n"; - } - - return result; - } - - /** constructor. */ - public static long printTransactionRow(Transaction.raw raw) { - long timestamp = raw.getTimestamp(); - - return timestamp; - } - - /** constructor. */ - public static boolean updateAsset( - byte[] address, - byte[] description, - byte[] url, - long newLimit, - long newPublicLimit, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Return updateAsset2( - byte[] address, - byte[] description, - byte[] url, - long newLimit, - long newPublicLimit, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.updateAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** constructor. */ - public static boolean transferAsset( - byte[] to, - byte[] assertName, - long amount, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean updateAccount( - byte[] addressBytes, - byte[] accountNameBytes, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean waitSolidityNodeSynFullNodeData( - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block solidityCurrentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Integer wait = 0; - logger.info("Fullnode block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - - while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 - && wait - < ((getWitnessNum(blockingStubFull) >= 27) - ? 27 - : getWitnessNum(blockingStubFull) + 1)) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info( - "Soliditynode num is " + solidityCurrentBlock.getBlockHeader().getRawData().getNumber()); - solidityCurrentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - if (wait == 24) { - logger.info("Didn't syn,skip to next case."); - return false; - } - wait++; - } - return true; - } - - /** constructor. */ - public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - Block nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - - Integer wait = 0; - logger.info("Block num is " + currentBlock.getBlockHeader().getRawData().getNumber()); - while (nextNum <= currentNum + 1 && wait <= 45) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // logger.info("Wait to produce next block"); - nextBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - if (wait == 45) { - logger.info("These 45 second didn't produce a block,please check."); - return false; - } - wait++; - } - logger.info("quit normally"); - return true; - } - - /** constructor. */ - public static AccountNetMessage getAccountNet( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountNet(request); - } - - /* public static byte[] addPreFix(byte[] address) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Config config = Configuration.getByPath("testng.conf"); - byte ADD_PRE_FIX_BYTE_MAINNET = (byte) 0x41; //41 + address - byte ADD_PRE_FIX_BYTE_TESTNET = (byte) 0xa0; //a0 + address - byte[] preFix = new byte[1]; - if (config.hasPath("net.type") && "mainnet".equalsIgnoreCase(config.getString("net.type"))) { - WalletClient.setAddressPreFixByte(ADD_PRE_FIX_BYTE_MAINNET); - preFix[0] = ADD_PRE_FIX_BYTE_MAINNET; - }else { - WalletClient.setAddressPreFixByte(ADD_PRE_FIX_BYTE_TESTNET); - preFix[0] = ADD_PRE_FIX_BYTE_TESTNET; - } - byte[] finalAddress = new byte[preFix.length+address.length]; - System.arraycopy(preFix, 0, finalAddress, 0, preFix.length); - System.arraycopy(address, 0, finalAddress, preFix.length, address.length); - return finalAddress; - - }*/ - - /** constructor. */ - public static byte[] getFinalAddress(String priKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - WalletClient walletClient; - walletClient = new WalletClient(priKey); - // walletClient.init(0); - return walletClient.getAddress(); - } - - /** constructor. */ - public static String createAccountGetTxid( - byte[] ownerAddress, - byte[] newAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static boolean createAccount( - byte[] ownerAddress, - byte[] newAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Return createAccount2( - byte[] ownerAddress, - byte[] newAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** constructor. */ - public static boolean voteWitness( - byte[] ownerAddress, - String priKey, - HashMap witnessMap, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - for (byte[] address : witnessMap.keySet()) { - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(witnessMap.get(address)); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static boolean createProposal( - byte[] ownerAddress, - String priKey, - HashMap parametersMap, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static boolean approveProposal( - byte[] ownerAddress, - String priKey, - long id, - boolean isAddApproval, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean deleteProposal( - byte[] ownerAddress, String priKey, long id, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean printAddress(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info(key); - logger.info(ByteArray.toHexString(getFinalAddress(key))); - logger.info(Base58.encode58Check(getFinalAddress(key))); - return true; - } - - /** constructor. */ - public static String getAddressString(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - return Base58.encode58Check(getFinalAddress(key)); - } - - /** constructor. */ - public static ArrayList getAddressInfo(String key) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ArrayList accountList = new ArrayList(); - accountList.add(key); - accountList.add(ByteArray.toHexString(getFinalAddress(key))); - accountList.add(Base58.encode58Check(getFinalAddress(key))); - return accountList; - } - - /** constructor. */ - public static boolean setAccountId( - byte[] accountIdBytes, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Boolean freezeBalanceGetTronPower( - byte[] addRess, - long freezeBalance, - long freezeDuration, - int resourceCode, - ByteString receiverAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return freezeBalanceForReceiver( - addRess, - freezeBalance, - freezeDuration, - resourceCode, - receiverAddress, - priKey, - blockingStubFull); - } - - /** constructor. */ - public static Boolean freezeBalanceGetEnergy( - byte[] addRess, - long freezeBalance, - long freezeDuration, - int resourceCode, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration) - .setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static AccountResourceMessage getAccountResource( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccountResource(request); - } - - /** constructor. */ - public static boolean buyStorage( - long quantity, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BuyStorageContract.Builder builder = BuyStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setQuant(quantity); - BuyStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.buyStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean sellStorage( - long quantity, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SellStorageContract.Builder builder = SellStorageContract.newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress).setStorageBytes(quantity); - SellStorageContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.sellStorage(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static byte[] deployContractFallbackReceive( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi2(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return contractAddress; - } - } - - /** constructor. */ - public static byte[] deployContract( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return contractAddress; - } - } - - /** constructor. */ - public static byte[] deployContract( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContract( - contractName, - abiString, - code, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static byte[] deployContractFallback( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractFallbackReceive( - contractName, - abiString, - code, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static byte[] deployContractForLibrary( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - String compilerVersion, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(1000L); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - if (compilerVersion.equals("v5") || compilerVersion.equals("V5")) { - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, "v5"); - } else { - // old version - byteCode = replaceLibraryAddresscompilerVersion(code, libraryAddress, null); - } - - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(0); - contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return contractAddress; - } - } - - /** constructor. */ - public static String deployContractAndGetTransactionInfoById( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractAndGetTransactionInfoById( - contractName, - abiString, - code, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static String deployContractAndGetTransactionInfoById( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static SmartContract.ABI jsonStr2Abi(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null - && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null - && abiItem.getAsJsonObject().get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null - ? abiItem.getAsJsonObject().get("name").getAsString() - : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null - ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() - : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null - ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() - : null; - String type = - abiItem.getAsJsonObject().get("type") != null - ? abiItem.getAsJsonObject().get("type").getAsString() - : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null - && abiItem.getAsJsonObject().get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null - ? abiItem.getAsJsonObject().get("stateMutability").getAsString() - : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = - SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - - entryBuilder.setType(getEntryType(type)); - entryBuilder.setPayable(payable); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); - } - - /** constructor. */ - public static SmartContract.ABI jsonStr2Abi2(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null - && abiItem.getAsJsonObject().get("anonymous").getAsBoolean(); - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null - && abiItem.getAsJsonObject().get("constant").getAsBoolean(); - final String name = - abiItem.getAsJsonObject().get("name") != null - ? abiItem.getAsJsonObject().get("name").getAsString() - : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null - ? abiItem.getAsJsonObject().get("inputs").getAsJsonArray() - : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null - ? abiItem.getAsJsonObject().get("outputs").getAsJsonArray() - : null; - String type = - abiItem.getAsJsonObject().get("type") != null - ? abiItem.getAsJsonObject().get("type").getAsString() - : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null - && abiItem.getAsJsonObject().get("payable").getAsBoolean(); - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null - ? abiItem.getAsJsonObject().get("stateMutability").getAsString() - : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") - && !type.equalsIgnoreCase("receive") - && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = inputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = - SmartContract.ABI.Entry.Param.newBuilder(); - JsonElement indexed = outputItem.getAsJsonObject().get("indexed"); - - paramBuilder.setIndexed((indexed != null) && indexed.getAsBoolean()); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - entryBuilder.setType(getEntryType2(type)); - - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); - } - - /** constructor. */ - public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "error": - return SmartContract.ABI.Entry.EntryType.Error; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } - } - - /** constructor. */ - public static SmartContract.ABI.Entry.EntryType getEntryType2(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - case "receive": - return SmartContract.ABI.Entry.EntryType.Receive; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } - } - - /** constructor. */ - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { - case "pure": - return SmartContract.ABI.Entry.StateMutabilityType.Pure; - case "view": - return SmartContract.ABI.Entry.StateMutabilityType.View; - case "nonpayable": - return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; - case "payable": - return SmartContract.ABI.Entry.StateMutabilityType.Payable; - default: - return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; - } - } - - /** constructor. */ - public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { - - // get owner address - // this address should be as same as the onweraddress in trx, DONNOT modify it - byte[] ownerAddress = owneraddress; - - // get tx hash - byte[] txRawDataHash = - Sha256Hash.of( - CommonParameter.getInstance().isECKeyCryptoEngine(), trx.getRawData().toByteArray()) - .getBytes(); - - // combine - byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; - System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); - System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - - return sha3omit12(combined); - } - - /** constructor. */ - public static SmartContract getContract( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContract(bytesMessage); - } - - /** constructor. */ - public static SmartContractDataWrapper getContractInfo( - byte[] address, WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - logger.info( - "contract name is " - + blockingStubFull.getContractInfo(bytesMessage).getSmartContract().getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContractInfo(bytesMessage); - } - - private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex = - ByteArray.toHexString(Commons.decodeFromBase58Check(addr)).substring(2); - - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - String beReplaced = "__" + libraryName + repeated; - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } - - - - private static byte[] replaceLibraryAddresscompilerVersion( - String code, String libraryAddressPair, String compilerVersion) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex; - libraryAddressHex = - (new String(Hex.encode(Commons.decodeFromBase58Check(addr)), StandardCharsets.US_ASCII)) - .substring(2); - - String beReplaced; - if (compilerVersion == null) { - // old version - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - beReplaced = "__" + libraryName + repeated; - } else if (compilerVersion.equalsIgnoreCase("v5")) { - // 0.5.4 version - String libraryNameKeccak256 = - ByteArray.toHexString(sha3(ByteArray.fromString(libraryName))).substring(0, 34); - beReplaced = "__\\$" + libraryNameKeccak256 + "\\$__"; - } else { - throw new RuntimeException("unknown compiler version."); - } - - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } - - /** constructor. */ - public static boolean updateSetting( - byte[] contractAddress, - long consumeUserResourcePercent, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - - /** 61 constructor. */ - public static Optional getTransactionInfoById( - String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - - /** 61 constructor. */ - public static Optional getTransactionInfoByIdFromSolidity( - String txId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - transactionInfo = blockingStubFull.getTransactionInfoById(request); - return Optional.ofNullable(transactionInfo); - } - - /** constructor. */ - public static Optional getTransactionInfoByBlockNum( - long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubFull.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } - - /** constructor. */ - public static Optional getTransactionInfoByBlockNumFromSolidity( - long blockNum, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - TransactionInfoList transactionInfoList; - transactionInfoList = blockingStubSolidity.getTransactionInfoByBlockNum(builder.build()); - return Optional.ofNullable(transactionInfoList); - } - - /** constructor. */ - public static String triggerContract( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return triggerContract( - contractAddress, - method, - argsStr, - isHex, - callValue, - feeLimit, - "0", - 0, - ownerAddress, - priKey, - blockingStubFull); - } - - /** constructor. */ - public static String triggerContract( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = new byte[0]; - if (!method.equalsIgnoreCase("#")) { - input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - } - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static String triggerContractBoth( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - return triggerContractBoth( - contractAddress, - method, - argsStr, - isHex, - callValue, - feeLimit, - "0", - 0, - ownerAddress, - priKey, - blockingStubFull, - blockingStubFull1); - } - - /** constructor. */ - public static String triggerContractBoth( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = - broadcastTransactionBoth(transaction, blockingStubFull, blockingStubFull1); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static String triggerParamListContract( - byte[] contractAddress, - String method, - List params, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, params)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static Boolean exchangeCreate( - byte[] firstTokenId, - long firstTokenBalance, - byte[] secondTokenId, - long secondTokenBalance, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)) - .setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static Boolean injectExchange( - long exchangeId, - byte[] tokenId, - long quant, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)) - .setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } - - /** constructor. */ - public static Optional getExchangeList( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ExchangeList exchangeList = - blockingStubSolidity.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } - - /** constructor. */ - public static Optional getExchange( - String id, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - BytesMessage request = - BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) - .build(); - Exchange exchange = blockingStubSolidity.getExchangeById(request); - return Optional.ofNullable(exchange); - } - - /** constructor. */ - public static Optional getExchange( - String id, WalletGrpc.WalletBlockingStub blockingStubFull) { - BytesMessage request = - BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromLong(Long.parseLong(id)))) - .build(); - Exchange exchange = blockingStubFull.getExchangeById(request); - return Optional.ofNullable(exchange); - } - - /** constructor. */ - public static boolean exchangeWithdraw( - long exchangeId, - byte[] tokenId, - long quant, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)) - .setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static boolean exchangeTransaction( - long exchangeId, - byte[] tokenId, - long quant, - long expected, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)) - .setQuant(quant) - .setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static String deployContractWithConstantParame( - String contractName, - String abiString, - String code, - String constructorStr, - String argsStr, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractWithConstantParame( - contractName, - abiString, - code, - constructorStr, - argsStr, - data, - feeLimit, - value, - consumeUserResourcePercent, - 1000L, - "0", - 0L, - libraryAddress, - priKey, - ownerAddress, - blockingStubFull); - } - - /** constructor. */ - public static String deployContractWithConstantParame( - String contractName, - String abiString, - String code, - String constructorStr, - String argsStr, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - - code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); - byte[] owner = ownerAddress; - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - // logger.info("brodacast succesfully"); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static Boolean freezeBalanceForReceiver( - byte[] addRess, - long freezeBalance, - long freezeDuration, - int resourceCode, - ByteString receiverAddressBytes, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder - .setOwnerAddress(byteAddreess) - .setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration) - .setResourceValue(resourceCode); - if (receiverAddressBytes != null) { - builder.setReceiverAddress(receiverAddressBytes); - } - FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static Optional getDelegatedResource( - byte[] fromAddress, byte[] toAddress, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = - DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs) - .setToAddress(toAddressBs) - .build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); - } - - /** constructor. */ - public static Optional getDelegatedResourceFromSolidity( - byte[] fromAddress, - byte[] toAddress, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString fromAddressBs = ByteString.copyFrom(fromAddress); - ByteString toAddressBs = ByteString.copyFrom(toAddress); - - DelegatedResourceMessage request = - DelegatedResourceMessage.newBuilder() - .setFromAddress(fromAddressBs) - .setToAddress(toAddressBs) - .build(); - DelegatedResourceList delegatedResource = blockingStubFull.getDelegatedResource(request); - return Optional.ofNullable(delegatedResource); - } - - /** constructor. */ - public static Optional getDelegatedResourceAccountIndex( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ByteString addressBs = ByteString.copyFrom(address); - - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - - DelegatedResourceAccountIndex accountIndex = - blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } - - /** constructor. */ - public static Optional - getDelegatedResourceAccountIndexFromSolidity( - byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ByteString addressBs = ByteString.copyFrom(address); - - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(addressBs).build(); - - DelegatedResourceAccountIndex accountIndex = - blockingStubFull.getDelegatedResourceAccountIndex(bytesMessage); - return Optional.ofNullable(accountIndex); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueByName( - String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueByNameFromSolidity( - String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - return blockingStubFull.getAssetIssueByName(request); - } - - /** constructor. */ - public static Optional getAssetIssueListByName( - String assetName, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional getAssetIssueListByNameFromSolidity( - String assetName, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetNameBs = ByteString.copyFrom(assetName.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional listAssetIssueFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.AssetIssueList assetIssueList = - blockingStubFull.getAssetIssueList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional listAssetIssuepaginatedFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull, Long offset, Long limit) { - GrpcAPI.PaginatedMessage.Builder pageMessageBuilder = GrpcAPI.PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = - blockingStubFull.getPaginatedAssetIssueList(pageMessageBuilder.build()); - return Optional.ofNullable(assetIssueList); - } - - /** constructor. */ - public static Optional listWitnesses( - WalletGrpc.WalletBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = - blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } - - /** constructor. */ - public static Optional listWitnessesFromSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - GrpcAPI.WitnessList witnessList = - blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(witnessList); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueById( - String assetId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } - - /** constructor. */ - public static AssetIssueContract getAssetIssueByIdFromSolidity( - String assetId, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString assetIdBs = ByteString.copyFrom(assetId.getBytes()); - BytesMessage request = BytesMessage.newBuilder().setValue(assetIdBs).build(); - return blockingStubFull.getAssetIssueById(request); - } - - /** constructor. */ - public static Optional getAssetIssueByAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueByAccount(request); - return Optional.ofNullable(assetIssueList); - } - - private static Permission json2Permission(JSONObject json) { - Permission.Builder permissionBuilder = Permission.newBuilder(); - if (json.containsKey("type")) { - int type = json.getInteger("type"); - permissionBuilder.setTypeValue(type); - } - if (json.containsKey("permission_name")) { - String permissionName = json.getString("permission_name"); - permissionBuilder.setPermissionName(permissionName); - } - if (json.containsKey("threshold")) { - // long threshold = json.getLong("threshold"); - long threshold = Long.parseLong(json.getString("threshold")); - permissionBuilder.setThreshold(threshold); - } - if (json.containsKey("parent_id")) { - int parentId = json.getInteger("parent_id"); - permissionBuilder.setParentId(parentId); - } - if (json.containsKey("operations")) { - byte[] operations = ByteArray.fromHexString(json.getString("operations")); - permissionBuilder.setOperations(ByteString.copyFrom(operations)); - } - if (json.containsKey("keys")) { - JSONArray keys = json.getJSONArray("keys"); - List keyList = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - Key.Builder keyBuilder = Key.newBuilder(); - JSONObject key = keys.getJSONObject(i); - String address = key.getString("address"); - long weight = Long.parseLong(key.getString("weight")); - // long weight = key.getLong("weight"); - // keyBuilder.setAddress(ByteString.copyFrom(address.getBytes())); - keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); - keyBuilder.setWeight(weight); - keyList.add(keyBuilder.build()); - } - permissionBuilder.addAllKeys(keyList); - } - return permissionBuilder.build(); - } - - /** constructor. */ - public static boolean accountPermissionUpdate( - String permissionJson, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static long getFreezeBalanceCount( - byte[] accountAddress, - String ecKey, - Long targetEnergy, - WalletGrpc.WalletBlockingStub blockingStubFull) { - // Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - - Account info = queryAccount(accountAddress, blockingStubFull); - - Account getAccount = queryAccount(ecKey, blockingStubFull); - - long balance = info.getBalance(); - long frozenBalance = info.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance(); - long totalEnergyLimit = resourceInfo.getTotalEnergyLimit(); - long totalEnergyWeight = resourceInfo.getTotalEnergyWeight(); - long energyUsed = resourceInfo.getEnergyUsed(); - long energyLimit = resourceInfo.getEnergyLimit(); - - if (energyUsed > energyLimit) { - targetEnergy = energyUsed - energyLimit + targetEnergy; - } - - if (totalEnergyWeight == 0) { - return 1000_000L; - } - - // totalEnergyLimit / (totalEnergyWeight + needBalance) = needEnergy / needBalance - final BigInteger totalEnergyWeightBi = BigInteger.valueOf(totalEnergyWeight); - long needBalance = - totalEnergyWeightBi - .multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetEnergy)) - .divide(BigInteger.valueOf(totalEnergyLimit - targetEnergy)) - .longValue(); - - logger.info("getFreezeBalanceCount, needBalance: " + needBalance); - - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger.info("getFreezeBalanceCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } - - /** constructor. */ - public static Long getAssetIssueValue( - byte[] accountAddress, - ByteString assetIssueId, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Long assetIssueCount = 0L; - Account contractAccount = queryAccount(accountAddress, blockingStubFull); - Map createAssetIssueMap = contractAccount.getAssetV2Map(); - for (Map.Entry entry : createAssetIssueMap.entrySet()) { - if (assetIssueId.toStringUtf8().equals(entry.getKey())) { - assetIssueCount = entry.getValue(); - } - } - return assetIssueCount; - } - - /** constructor. */ - public static List getStrings(byte[] data) { - int index = 0; - List ret = new ArrayList<>(); - while (index < data.length) { - ret.add(byte2HexStr(data, index, 32)); - index += 32; - } - return ret; - } - - /** constructor. */ - public static String byte2HexStr(byte[] b, int offset, int length) { - StringBuilder ssBuilder = new StringBuilder(); - for (int n = offset; n < offset + length && n < b.length; n++) { - String stmp = Integer.toHexString(b[n] & 0xFF); - ssBuilder.append((stmp.length() == 1) ? "0" + stmp : stmp); - } - return ssBuilder.toString().toUpperCase().trim(); - } - - /** constructor. */ - public static Transaction addTransactionSign( - Transaction transaction, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()); - - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** constructor. */ - public static GrpcAPI.Return deployContractAndGetResponse( - String contractName, - String abiString, - String code, - String data, - Long feeLimit, - long value, - long consumeUserResourcePercent, - long originEnergyLimit, - String tokenId, - long tokenValue, - String libraryAddress, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - // byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = - contractBuilder.setNewContract(builder.build()).build(); - - TransactionExtention transactionExtention = - blockingStubFull.deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - byte[] contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response; - } - - /** constructor. */ - public static GrpcAPI.Return triggerContractAndGetResponse( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response; - } - - /** constructor. */ - public static boolean updateEnergyLimit( - byte[] contractAddress, - long originEnergyLimit, - String priKey, - byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); - - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - /** constructor. */ - public static GrpcAPI.Return accountPermissionUpdateForResponse( - String permissionJson, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return ret; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response; - } - - public static TransactionApprovedList getTransactionApprovedList( - Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { - return blockingStubFull.getTransactionApprovedList(transaction); - } - - /** constructor. */ - public static long getFreezeBalanceNetCount( - byte[] accountAddress, - String ecKey, - Long targetNet, - WalletGrpc.WalletBlockingStub blockingStubFull) { - // Precision change as the entire network freezes - AccountResourceMessage resourceInfo = getAccountResource(accountAddress, blockingStubFull); - - Account info = queryAccount(accountAddress, blockingStubFull); - - Account getAccount = queryAccount(ecKey, blockingStubFull); - - long balance = info.getBalance(); - long totalNetLimit = resourceInfo.getTotalNetLimit(); - long totalNetWeight = resourceInfo.getTotalNetWeight(); - long netUsed = resourceInfo.getNetUsed(); - long netLimit = resourceInfo.getNetLimit(); - - if (netUsed > netLimit) { - targetNet = netUsed - netLimit + targetNet; - } - - if (totalNetWeight == 0) { - return 1000_000L; - } - - // totalNetLimit / (totalNetWeight + needBalance) = needNet / needBalance - final BigInteger totalNetWeightBi = BigInteger.valueOf(totalNetWeight); - long needBalance = - totalNetWeightBi - .multiply(BigInteger.valueOf(1_000_000)) - .multiply(BigInteger.valueOf(targetNet)) - .divide(BigInteger.valueOf(totalNetLimit - targetNet)) - .longValue(); - - logger.info("getFreezeBalanceNetCount, needBalance: " + needBalance); - - if (needBalance < 1000000L) { - needBalance = 1000000L; - logger.info( - "getFreezeBalanceNetCount, needBalance less than 1 TRX, modify to: " + needBalance); - } - return needBalance; - } - - /** constructor. */ - public static GrpcAPI.Return broadcastTransaction( - Transaction transaction, WalletGrpc.WalletBlockingStub blockingStubFull) { - int i = 10; - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - while (!response.getResult() && response.getCode() == response_code.SERVER_BUSY && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } - - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } - - /** constructor. */ - public static GrpcAPI.Return broadcastTransactionBoth( - Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletGrpc.WalletBlockingStub blockingStubFull1) { - int i = 10; - waitProduceNextBlock(blockingStubFull1); - GrpcAPI.Return response = blockingStubFull1.broadcastTransaction(transaction); - GrpcAPI.Return response1 = blockingStubFull.broadcastTransaction(transaction); - while (response.getResult() == false - && response.getCode() == response_code.SERVER_BUSY - && i > 0) { - try { - Thread.sleep(300); - } catch (InterruptedException e) { - e.printStackTrace(); - } - i--; - response = blockingStubFull.broadcastTransaction(transaction); - logger.info("repeate times = " + (10 - i)); - } - - if (response.getResult() == false) { - logger.info("Code = " + response.getCode()); - logger.info("Message = " + response.getMessage().toStringUtf8()); - } - return response; - } - - /** constructor. */ - public static String exec(String command) throws InterruptedException { - String returnString = ""; - Process pro = null; - Runtime runTime = Runtime.getRuntime(); - if (runTime == null) { - logger.error("Create runtime false!"); - } - try { - pro = runTime.exec(command); - BufferedReader input = new BufferedReader(new InputStreamReader(pro.getInputStream())); - PrintWriter output = new PrintWriter(new OutputStreamWriter(pro.getOutputStream())); - String line; - while ((line = input.readLine()) != null) { - returnString = returnString + line + "\n"; - } - input.close(); - output.close(); - pro.destroy(); - } catch (IOException ex) { - logger.error(null, ex); - } - return returnString; - } - - /** constructor. */ - public static HashMap getBycodeAbiNoOptimize( - String solFile, String contractName) { - final String compile = - Configuration.getByPath("testng.conf").getString("defaultParameter.solidityCompile"); - - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; - - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } - - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile - + " --bin --abi --overwrite " - + absolutePath - + "/" - + solFile - + " -o " - + absolutePath - + "/" - + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } - - /** constructor. */ - public static HashMap getBycodeAbi(String solFile, String contractName) { - final String compile = - Configuration.getByPath("testng.conf").getString("defaultParameter.solidityCompile"); - - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode//output" + dirPath; - - File binFile = new File(outputPath + "/" + contractName + ".bin"); - File abiFile = new File(outputPath + "/" + contractName + ".abi"); - if (binFile.exists()) { - binFile.delete(); - } - if (abiFile.exists()) { - abiFile.delete(); - } - - HashMap retMap = new HashMap<>(); - String absolutePath = System.getProperty("user.dir"); - logger.debug("absolutePath: " + absolutePath); - logger.debug("solFile: " + solFile); - logger.debug("outputPath: " + outputPath); - String cmd = - compile - + " --optimize --bin --abi --overwrite " - + absolutePath - + "/" - + solFile - + " -o " - + absolutePath - + "/" - + outputPath; - logger.info("cmd: " + cmd); - - String byteCode = null; - String abI = null; - - // compile solidity file - try { - exec(cmd); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // get byteCode and ABI - try { - byteCode = fileRead(outputPath + "/" + contractName + ".bin", false); - retMap.put("byteCode", byteCode); - logger.debug("byteCode: " + byteCode); - abI = fileRead(outputPath + "/" + contractName + ".abi", false); - retMap.put("abI", abI); - logger.debug("abI: " + abI); - } catch (Exception e) { - e.printStackTrace(); - } - return retMap; - } - - /** constructor. */ - public static String fileRead(String filePath, boolean isLibrary) throws Exception { - File file = new File(filePath); - FileReader reader = new FileReader(file); - BufferedReader breader = new BufferedReader(reader); - StringBuilder sb = new StringBuilder(); - String s = ""; - if (!isLibrary) { - if ((s = breader.readLine()) != null) { - sb.append(s); - } - breader.close(); - } else { - String fistLine = breader.readLine(); - breader.readLine(); - if ((s = breader.readLine()) != null && !s.equals("")) { - s = s.substring(s.indexOf("-> ") + 3); - sb.append(s + ":"); - } else { - s = fistLine.substring(fistLine.indexOf("__") + 2, fistLine.lastIndexOf("__")); - sb.append(s + ":"); - } - breader.close(); - } - return sb.toString(); - } - - /** constructor. */ - public static HashMap getBycodeAbiForLibrary( - String solFile, String contractName) { - HashMap retMap = null; - String dirPath = solFile.substring(solFile.lastIndexOf("/"), solFile.lastIndexOf(".")); - String outputPath = "src/test/resources/soliditycode/output" + dirPath; - try { - retMap = PublicMethed.getBycodeAbi(solFile, contractName); - String library = fileRead(outputPath + "/" + contractName + ".bin", true); - retMap.put("library", library); - logger.debug("library: " + library); - } catch (Exception e) { - e.printStackTrace(); - } - - return retMap; - } - - /** constructor. */ - public static String triggerConstantContract( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = - blockingStubFull.triggerConstantContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static TransactionExtention triggerConstantContractForExtentionOnSolidity( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = - blockingStubSolidity.triggerConstantContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static String clearContractAbi( - byte[] contractAddress, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearAbiContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 - && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = - transactionExtention.getTransaction().getRawData().toBuilder(); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - } - - /** constructor. */ - public static TransactionExtention clearContractAbiForExtention( - byte[] contractAddress, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearAbiContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearAbiContract); - return transactionExtention; - } - - /** constructor. */ - public static TransactionExtention triggerConstantContractForExtention( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - if (tokenId.equalsIgnoreCase("") || tokenId.equalsIgnoreCase("#")) { - logger.info("tokenid is 0"); - tokenId = "0"; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.triggerConstantContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static TransactionExtention triggerSolidityContractForExtention( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletSolidityGrpc.WalletSolidityBlockingStub solidityBlockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = - solidityBlockingStubFull.triggerConstantContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static TransactionExtention triggerContractForExtention( - byte[] contractAddress, - String method, - String argsStr, - Boolean isHex, - long callValue, - long feeLimit, - String tokenId, - long tokenValue, - byte[] ownerAddress, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - return transactionExtention; - } - - /** constructor. */ - public static String create2(String[] parameters) { - if (parameters == null || parameters.length != 3) { - logger.error("create2 needs 3 parameter:\ncreate2 address code salt"); - return null; - } - - byte[] address = WalletClient.decodeFromBase58Check(parameters[0]); - if (!WalletClient.addressValid(address)) { - logger.error("length of address must be 21 bytes."); - return null; - } - - byte[] code = Hex.decode(parameters[1]); - byte[] temp = Longs.toByteArray(Long.parseLong(parameters[2])); - if (temp.length != 8) { - logger.error("Invalid salt!"); - return null; - } - byte[] salt = new byte[32]; - System.arraycopy(temp, 0, salt, 24, 8); - - byte[] mergedData = ByteUtil.merge(address, salt, sha3(code)); - String create2Address = Base58.encode58Check(sha3omit12(mergedData)); - - logger.info("create2 Address: " + create2Address); - - return create2Address; - } - - /** constructor. */ - public static boolean sendShieldCoin( - byte[] publicZenTokenOwnerAddress, - long fromAmount, - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - List shieldOutputList, - byte[] publicZenTokenToAddress, - long toAmount, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - // String shieldAddress = noteInfo.getPaymentAddress(); - // ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - // System.out.println("address " + noteInfo.getPaymentAddress()); - // System.out.println("value " + noteInfo.getValue()); - // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - // System.out.println("trxId " + noteInfo.getTrxId()); - // System.out.println("index " + noteInfo.getIndex()); - // System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = - ByteArray.fromHexString( - "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder.addShieldedReceives( - ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = - blockingStubFull.createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = - any.unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - return broadcastTransaction(transaction, blockingStubFull).getResult(); - } - - /** constructor. */ - public static boolean sendShieldCoinWithoutAsk( - byte[] publicZenTokenOwnerAddress, - long fromAmount, - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - List shieldOutputList, - byte[] publicZenTokenToAddress, - long toAmount, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParametersWithoutAsk.Builder builder = PrivateParametersWithoutAsk.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - byte[] ask = new byte[32]; - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() != 1) { - System.out.println("Can't get all merkel tree, please check the notes."); - return false; - } - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - // String shieldAddress = noteInfo.getPaymentAddress(); - // ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - System.arraycopy(expandedSpendingKey.getAsk(), 0, ask, 0, 32); - builder.setAk( - ByteString.copyFrom(ExpandedSpendingKey.getAkFromAsk(expandedSpendingKey.getAsk()))); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - // System.out.println("address " + noteInfo.getPaymentAddress()); - // System.out.println("value " + noteInfo.getValue()); - // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - // System.out.println("trxId " + noteInfo.getTrxId()); - // System.out.println("index " + noteInfo.getIndex()); - // System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = - ByteArray.fromHexString( - "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder.addShieldedReceives( - ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = - blockingStubFull.createShieldedTransactionWithoutSpendAuthSig(builder.build()); - if (transactionExtention == null) { - System.out.println("sendShieldCoinWithoutAsk failure."); - return false; - } - BytesMessage trxHash = - blockingStubFull.getShieldTransactionHash(transactionExtention.getTransaction()); - if (trxHash == null || trxHash.getValue().toByteArray().length != 32) { - System.out.println("sendShieldCoinWithoutAsk get transaction hash failure."); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - System.out.println("This method only for ShieldedTransferContract, please check!"); - return false; - } - Any any = transaction.getRawData().getContract(0).getParameter(); - Transaction transaction1 = transactionExtention.getTransaction(); - try { - ShieldedTransferContract shieldContract = any.unpack(ShieldedTransferContract.class); - List spendDescList = shieldContract.getSpendDescriptionList(); - ShieldedTransferContract.Builder contractBuild = - shieldContract.toBuilder().clearSpendDescription(); - for (int i = 0; i < spendDescList.size(); i++) { - - SpendAuthSigParameters.Builder builder1 = SpendAuthSigParameters.newBuilder(); - builder1.setAsk(ByteString.copyFrom(ask)); - builder1.setTxHash(ByteString.copyFrom(trxHash.getValue().toByteArray())); - builder1.setAlpha(builder.getShieldedSpends(i).getAlpha()); - SpendDescription.Builder spendDescription = spendDescList.get(i).toBuilder(); - BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); - spendDescription.setSpendAuthoritySignature( - ByteString.copyFrom(authSig.getValue().toByteArray())); - - contractBuild.addSpendDescription(spendDescription.build()); - } - - Transaction.raw.Builder rawBuilder = - transaction.toBuilder() - .getRawDataBuilder() - .clearContract() - .addContract( - Transaction.Contract.newBuilder() - .setType(ContractType.ShieldedTransferContract) - .setParameter(Any.pack(contractBuild.build())) - .build()); - - transaction = transaction.toBuilder().clearRawData().setRawData(rawBuilder).build(); - - transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - transaction1 = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - if (transaction1.getRawData().getContract(0).getType() - != ContractType.ShieldedTransferContract) { - transaction1 = signTransaction(ecKey, transaction1); - } else { - Any any1 = transaction1.getRawData().getContract(0).getParameter(); - ShieldedTransferContract shieldedTransferContract = - any1.unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction1 = signTransactionForShield(ecKey, transaction1); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - } - } - } catch (Exception e) { - System.out.println(e); - } - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray()))); - return broadcastTransaction(transaction1, blockingStubFull).getResult(); - } - - /** constructor. */ - public static List addShieldOutputList( - List shieldOutList, String shieldToAddress, String toAmountString, String menoString) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - try { - noteBuild.setRcm(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - // logger.info(shieldOutList.toString()); - return shieldOutList; - } - - /** constructor. */ - public static Optional generateShieldAddress() { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - try { - DiversifierT diversifier = DiversifierT.random(); - SpendingKey spendingKey = SpendingKey.random(); - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - PaymentAddress paymentAddress = incomingViewingKey.address(diversifier).get(); - - addressInfo.setSk(spendingKey.getValue()); - addressInfo.setD(diversifier); - addressInfo.setIvk(incomingViewingKey.getValue()); - addressInfo.setOvk(fullViewingKey.getOvk()); - addressInfo.setPkD(paymentAddress.getPkD()); - - if (addressInfo.validateCheck()) { - return Optional.of(addressInfo); - } - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** constructor. */ - public static DecryptNotes listShieldNote( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info(ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - // startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - // startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubFull.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } - } - - /** constructor. */ - public static DecryptNotesMarked getShieldNotesAndMarkByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - // startBlockNum = 0L; - logger.info("ivk:" + ByteArray.toHexString(shieldAddressInfo.get().ivk)); - try { - IvkDecryptAndMarkParameters.Builder builder = IvkDecryptAndMarkParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - builder.setAk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.get().getFullViewingKey().getNk())); - DecryptNotesMarked decryptNotes = blockingStubSolidity.scanAndMarkNoteByIvk(builder.build()); - logger.info(decryptNotes.toString()); - return decryptNotes; - } catch (Exception e) { - logger.info(e.toString()); - return null; - } - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByIvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setIvk(ByteString.copyFrom(shieldAddressInfo.get().getIvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByIvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByOvk( - Optional shieldAddressInfo, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - logger.info("ovk:" + ByteArray.toHexString(shieldAddressInfo.get().ovk)); - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum + 1); - builder.setEndBlockIndex(currentBlockNum + 1); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubFull.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static DecryptNotes getShieldNotesByOvkOnSolidity( - Optional shieldAddressInfo, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Block currentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long startBlockNum = 0L; - if (currentBlockNum > 100) { - startBlockNum = currentBlockNum - 100; - } - OvkDecryptParameters.Builder builder = OvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(startBlockNum); - builder.setEndBlockIndex(currentBlockNum); - builder.setOvk(ByteString.copyFrom(shieldAddressInfo.get().getOvk())); - DecryptNotes notes = blockingStubSolidity.scanNoteByOvk(builder.build()); - logger.info(notes.toString()); - return notes; - } - - /** constructor. */ - public static String getMemo(Note note) { - return ZenUtils.getMemo(note.getMemo().toByteArray()); - } - - /** constructor. */ - public static SpendResult getSpendResult( - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = - Optional.of(blockingStubFull.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - logger.info("AK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getAk())); - logger.info("NK:" + ByteArray.toHexString(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubFull.isSpend(builder.build()); - return result; - } - return null; - } - - /** constructor. */ - public static SpendResult getSpendResultOnSolidity( - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - Optional merkleVoucherInfo = - Optional.of(blockingStubSolidity.getMerkleTreeVoucherInfo(request.build())); - - if (merkleVoucherInfo.isPresent() && merkleVoucherInfo.get().getVouchersCount() > 0) { - NoteParameters.Builder builder = NoteParameters.newBuilder(); - try { - builder.setAk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(shieldAddressInfo.getFullViewingKey().getNk())); - } catch (Exception e) { - Assert.assertTrue(1 == 1); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - builder.setNote(noteBuild.build()); - builder.setTxid(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - builder.setIndex(noteTx.getIndex()); - // builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubSolidity.isSpend(builder.build()); - return result; - } - return null; - } - - /** constructor. */ - public static String getShieldNullifier( - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - if (merkleVoucherInfo.getVouchersCount() < 1) { - System.out.println("get merkleVoucherInfo failure."); - return null; - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - String shieldAddress = noteTx.getNote().getPaymentAddress(); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - // TODO - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - NfParameters.Builder builder = NfParameters.newBuilder(); - builder.setNote(noteBuild.build()); - builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - builder.setAk(ByteString.copyFrom(fullViewingKey.getAk())); - builder.setNk(ByteString.copyFrom(fullViewingKey.getNk())); - - BytesMessage nullifier = blockingStubFull.createShieldNullifier(builder.build()); - return ByteArray.toHexString(nullifier.getValue().toByteArray()); - - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** constructor. */ - public static String sendShieldCoinGetTxid( - byte[] publicZenTokenOwnerAddress, - long fromAmount, - ShieldAddressInfo shieldAddressInfo, - NoteTx noteTx, - List shieldOutputList, - byte[] publicZenTokenToAddress, - long toAmount, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - // ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - // String shieldAddress = noteInfo.getPaymentAddress(); - // ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - // System.out.println("address " + noteInfo.getPaymentAddress()); - // System.out.println("value " + noteInfo.getValue()); - // System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - // System.out.println("trxId " + noteInfo.getTrxId()); - // System.out.println("index " + noteInfo.getIndex()); - // System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = - blockingStubFull.getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = - ByteArray.fromHexString( - "030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder.addShieldedReceives( - ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = - blockingStubFull.createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldedTransferContract shieldedTransferContract = - any.unpack(ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0) { - transaction = signTransactionForShield(ecKey, transaction); - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } else { - System.out.println( - "trigger txid = " - + ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - } - - /** constructor. */ - public static byte[] decode58Check(String input) { - byte[] decodeCheck = org.tron.common.utils.Base58.decode(input); - if (decodeCheck.length <= 4) { - return null; - } - byte[] decodeData = new byte[decodeCheck.length - 4]; - System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length); - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), decodeData); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance().isECKeyCryptoEngine(), hash0); - if (hash1[0] == decodeCheck[decodeData.length] - && hash1[1] == decodeCheck[decodeData.length + 1] - && hash1[2] == decodeCheck[decodeData.length + 2] - && hash1[3] == decodeCheck[decodeData.length + 3]) { - return decodeData; - } - return null; - } - - /** constructor. */ - public static void freedResource( - byte[] fromAddress, - String priKey, - byte[] toAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - long balance = PublicMethed.queryAccount(fromAddress, blockingStubFull).getBalance(); - sendcoin(toAddress, balance - 500000, fromAddress, priKey, blockingStubFull); - } - - /** constructor. */ - public static String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } - - /** constructor. */ - public static String bytes32ToString(byte[] bytes) { - if (bytes == null) { - return "null"; - } - int imax = bytes.length - 1; - if (imax == -1) { - return ""; - } - - StringBuilder b = new StringBuilder(); - for (int i = 0; ; i++) { - b.append(bytes[i]); - if (i == imax) { - return b.toString(); - } - } - } - - /** constructor. */ - public static Return transferAssetForReturn( - byte[] to, - byte[] assertName, - long amount, - byte[] address, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.transferAsset2(contract); - - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; - } - - /** constructor. */ - public static Return sendcoinForReturn( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transaction = blockingStubFull.createTransaction2(contract); - if (transaction == null) { - return transaction.getResult(); - } - Return ret = transaction.getResult(); - return ret; - } - - /** constructor. */ - public static Transaction sendcoinForTransaction( - byte[] to, - long amount, - byte[] owner, - String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - // String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention extention = blockingStubFull.createTransaction2(contract); - Protocol.Transaction transaction = extention.getTransaction(); - return transaction; - } - - /** constructor. */ - public static String marketSellAsset( - byte[] owner, - String priKey, - byte[] sellTokenId, - long sellTokenQuantity, - byte[] buyTokenId, - long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - MarketContract.MarketSellAssetContract.Builder builder = - MarketContract.MarketSellAssetContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; - } - - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); - - String txid = - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - - System.out.println("trigger txid = " + txid); - return txid; - } - - /** constructor. */ - public static Return marketSellAssetGetResposne( - byte[] owner, - String priKey, - byte[] sellTokenId, - long sellTokenQuantity, - byte[] buyTokenId, - long buyTokenQuantity, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - MarketContract.MarketSellAssetContract.Builder builder = - MarketContract.MarketSellAssetContract.newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - - return transactionExtention.getResult(); - } - - /** constructor. */ - public static String marketCancelOrder( - byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - MarketContract.MarketCancelOrderContract.Builder builder = - MarketContract.MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret.getMessage().toStringUtf8(); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - if (transaction.getRawData().getContract(0).getType() - == ContractType.ShieldedTransferContract) { - return null; - } - - transaction = signTransaction(ecKey, transaction); - broadcastTransaction(transaction, blockingStubFull); - - String txid = - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - - System.out.println("trigger txid = " + txid); - - return txid; - } - - /** constructor. */ - public static Return marketCancelOrderGetResposne( - byte[] owner, String priKey, byte[] orderId, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - MarketContract.MarketCancelOrderContract.Builder builder = - MarketContract.MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - - if (transactionExtention == null) { - return null; - } - return transactionExtention.getResult(); - } - - /** constructor. */ - public static Optional getMarketOrderByAccount( - byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubFull.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketOrderByAccountSolidity( - byte[] address, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString addressBs = ByteString.copyFrom(address); - BytesMessage request = BytesMessage.newBuilder().setValue(addressBs).build(); - - Protocol.MarketOrderList marketOrderList; - marketOrderList = blockingStubSolidity.getMarketOrderByAccount(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketOrderById( - byte[] order, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubFull.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } - - /** constructor. */ - public static Optional getMarketOrderByIdSolidity( - byte[] order, WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - ByteString orderBytes = ByteString.copyFrom(order); - BytesMessage request = BytesMessage.newBuilder().setValue(orderBytes).build(); - Protocol.MarketOrder orderPair = blockingStubSolidity.getMarketOrderById(request); - return Optional.ofNullable(orderPair); - } - - /** constructor. */ - public static Optional getMarketPriceByPair( - byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketPriceList marketPriceList = blockingStubFull.getMarketPriceByPair(request); - return Optional.ofNullable(marketPriceList); - } - - /** constructor. */ - public static Optional getMarketOrderListByPair( - byte[] sellTokenId, byte[] buyTokenId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = blockingStubFull.getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketOrderListByPairSolidity( - byte[] sellTokenId, - byte[] buyTokenId, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPair request = - Protocol.MarketOrderPair.newBuilder() - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .build(); - - Protocol.MarketOrderList marketOrderList = - blockingStubSolidity.getMarketOrderListByPair(request); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketPairList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - Protocol.MarketOrderPairList marketOrderList = - blockingStubFull.getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static Optional getMarketPairListSolidity( - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - Protocol.MarketOrderPairList marketOrderList = - blockingStubSolidity.getMarketPairList(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(marketOrderList); - } - - /** constructor. */ - public static String stringToHexString(String s) { - String str = ""; - for (int i = 0; i < s.length(); i++) { - int ch = s.charAt(i); - String s4 = Integer.toHexString(ch); - str = str + s4; - } - return str; - } - - /** constructor. */ - public static String hexStringToString(String s) { - if (s == null || s.equals("")) { - return null; - } - s = s.replace(" ", ""); - byte[] baKeyword = new byte[s.length() / 2]; - for (int i = 0; i < baKeyword.length; i++) { - try { - baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16)); - } catch (Exception e) { - e.printStackTrace(); - } - } - try { - s = new String(baKeyword, "gbk"); - new String(); - } catch (Exception e1) { - e1.printStackTrace(); - } - return s; - } - - /** constructor. */ - public static String removeAll0sAtTheEndOfHexStr(String s) { - return s.replaceAll("(00)+$", ""); - } - - /** constructor. */ - public static String replaceCode(String code, String address) { - if (code.indexOf("__$") == -1) { - return code; - } else { - int index = code.indexOf("_"); - String oldStr = code.substring(index - 1, index + 39); - Pattern p = Pattern.compile(oldStr); - Matcher m = p.matcher(code); - String result = m.replaceAll(address); - return result; - } - } - - /** constructor. */ - public static Map getAllowance2( - Long startNum, Long endNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - final String blackHole = - Configuration.getByPath("testng.conf").getString("defaultParameter.blackHoleAddress"); - Long totalCount = 0L; - Map witnessBlockCount = new HashMap<>(); - Map witnessBrokerage = new HashMap<>(); - Map witnessVoteCount = new HashMap<>(); - Map witnessAllowance = new HashMap<>(); - List witnessList = - PublicMethed.listWitnesses(blockingStubFull).get().getWitnessesList(); - for (Protocol.Witness witness : witnessList) { - witnessVoteCount.put( - ByteArray.toHexString(witness.getAddress().toByteArray()), witness.getVoteCount()); - GrpcAPI.BytesMessage bytesMessage = - GrpcAPI.BytesMessage.newBuilder().setValue(witness.getAddress()).build(); - Long brokerager = blockingStubFull.getBrokerageInfo(bytesMessage).getNum(); - witnessBrokerage.put(ByteArray.toHexString(witness.getAddress().toByteArray()), brokerager); - totalCount += witness.getVoteCount(); - } - Optional infoById = null; - for (Long k = startNum; k < endNum; k++) { - String witnessAdd = - ByteArray.toHexString( - PublicMethed.getBlock(k, blockingStubFull) - .getBlockHeader() - .getRawData() - .getWitnessAddress() - .toByteArray()); - witnessBlockCount.put(witnessAdd, witnessBlockCount.getOrDefault(witnessAdd, 0) + 1); - List transList = - PublicMethed.getBlock(k, blockingStubFull).getTransactionsList(); - for (Transaction tem : transList) { - String txid = - ByteArray.toHexString( - Sha256Hash.hash( - CommonParameter.getInstance().isECKeyCryptoEngine(), - tem.getRawData().toByteArray())); - logger.info("----ss txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long packingFee = infoById.get().getPackingFee(); - - witnessAllowance.put( - witnessAdd, witnessAllowance.getOrDefault(witnessAdd, 0L) + packingFee); - } - } - - logger.info("========totalCount:" + totalCount); - List chainParaList = - blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()) - .getChainParameterList(); - Long witness127PayPerBlock = 0L; - Long witnessPayPerBlock = 0L; - for (Protocol.ChainParameters.ChainParameter para : chainParaList) { - if ("getWitness127PayPerBlock".equals(para.getKey())) { - witness127PayPerBlock = para.getValue(); - } - if ("getWitnessPayPerBlock".equals(para.getKey())) { - witnessPayPerBlock = para.getValue(); - } - } - logger.info( - "witness127PayPerBlock:" - + witness127PayPerBlock - + "\n witnessPayPerBlock:" - + witnessPayPerBlock); - - for (Map.Entry entry : witnessBrokerage.entrySet()) { - logger.info("-----witnessBrokerage " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessVoteCount.entrySet()) { - logger.info("-----witnessVoteCount " + entry.getKey() + " : " + entry.getValue()); - } - for (Map.Entry entry : witnessBlockCount.entrySet()) { - logger.info("-----witnessBlockCount " + entry.getKey() + " : " + entry.getValue()); - } - - for (Map.Entry entry : witnessVoteCount.entrySet()) { - String witnessAdd = entry.getKey(); - logger.info( - "----witnessAdd:" - + witnessAdd - + " block count:" - + witnessBlockCount.get(witnessAdd) - + " all: " - + witnessAllowance.getOrDefault(witnessAdd, 0L)); - Long pay = - (witnessBlockCount.get(witnessAdd) * witnessPayPerBlock - + (endNum - startNum) * witness127PayPerBlock * entry.getValue() / totalCount - + witnessAllowance.getOrDefault(witnessAdd, 0L)) - * witnessBrokerage.get(witnessAdd) - / 100; - - witnessAllowance.put(witnessAdd, pay); - logger.info("****** " + witnessAdd + " : " + pay); - } - return witnessAllowance; - } - - public static String getContractStringMsg(byte[] contractMsgArray) { - int resultLenth = ByteArray.toInt(ByteArray.subArray(contractMsgArray, 32, 64)); - return ByteArray.toStr(ByteArray.subArray(contractMsgArray, 64, 64 + resultLenth)); - } - - /** constructor. */ - public boolean updateBrokerage( - byte[] owner, int brokerage, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = - blockingStubFull.updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println( - "Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = broadcastTransaction(transaction, blockingStubFull); - - return response.getResult(); - } - - /** constructor. */ - public static Long getAccountBalance( - Protocol.Block block, byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = - new BlockId( - org.tron.common.utils.Sha256Hash.of( - CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - - BalanceContract.AccountIdentifier accountIdentifier = - BalanceContract.AccountIdentifier.newBuilder() - .setAddress(ByteString.copyFrom(address)) - .build(); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = - BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()) - .setNumber(blockNum) - .build(); - - BalanceContract.AccountBalanceRequest accountBalanceRequest = - BalanceContract.AccountBalanceRequest.newBuilder() - .setAccountIdentifier(accountIdentifier) - .setBlockIdentifier(blockIdentifier) - .build(); - return blockingStubFull.getAccountBalance(accountBalanceRequest).getBalance(); - } - - /** constructor. */ - public static BalanceContract.BlockBalanceTrace getBlockBalance( - Protocol.Block block, WalletGrpc.WalletBlockingStub blockingStubFull) { - final Long blockNum = block.getBlockHeader().getRawData().getNumber(); - BlockId blockId = - new BlockId( - org.tron.common.utils.Sha256Hash.of( - CommonParameter.getInstance().isECKeyCryptoEngine(), - block.getBlockHeader().getRawData().toByteArray()), - block.getBlockHeader().getRawData().getNumber()); - BalanceContract.BlockBalanceTrace.BlockIdentifier blockIdentifier = - BalanceContract.BlockBalanceTrace.BlockIdentifier.newBuilder() - .setHash(blockId.getByteString()) - .setNumber(blockNum) - .build(); - - return blockingStubFull.getBlockBalanceTrace(blockIdentifier); - } - - /** 61 constructor. */ - public static Optional getTransactionFromPending( - String txId, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction; - transaction = blockingStubFull.getTransactionFromPending(request); - return Optional.ofNullable(transaction); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethedForMutiSign.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethedForMutiSign.java deleted file mode 100644 index 87256d07453..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/PublicMethedForMutiSign.java +++ /dev/null @@ -1,5335 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import static org.tron.common.crypto.Hash.sha3omit12; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonParser; -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes.NoteTx; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.PrivateParameters; -import org.tron.api.GrpcAPI.ReceiveNote; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.SpendNote; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletGrpc.WalletBlockingStub; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.Base58; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.exception.CancelException; -import org.tron.core.zen.address.ExpandedSpendingKey; -import org.tron.core.zen.address.SpendingKey; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Key; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.Transaction.Result; -import org.tron.protos.Protocol.Transaction.raw; -import org.tron.protos.contract.AccountContract.AccountCreateContract; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.AccountContract.SetAccountIdContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UpdateAssetContract; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; -import org.tron.protos.contract.ExchangeContract.ExchangeCreateContract; -import org.tron.protos.contract.ExchangeContract.ExchangeInjectContract; -import org.tron.protos.contract.ExchangeContract.ExchangeTransactionContract; -import org.tron.protos.contract.ExchangeContract.ExchangeWithdrawContract; -import org.tron.protos.contract.MarketContract; -import org.tron.protos.contract.ProposalContract.ProposalApproveContract; -import org.tron.protos.contract.ProposalContract.ProposalCreateContract; -import org.tron.protos.contract.ProposalContract.ProposalDeleteContract; -import org.tron.protos.contract.ShieldContract; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import org.tron.protos.contract.SmartContractOuterClass.ClearABIContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract.Builder; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateEnergyLimitContract; -import org.tron.protos.contract.SmartContractOuterClass.UpdateSettingContract; -import org.tron.protos.contract.StorageContract.UpdateBrokerageContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import org.tron.protos.contract.WitnessContract.WitnessCreateContract; -import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; - - -public class PublicMethedForMutiSign { - - private static final Logger logger = LoggerFactory.getLogger("TestLogger"); - Wallet wallet = new Wallet(); - - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - - /** - * constructor. - */ - - public static Boolean createAssetIssueWithpermissionId(byte[] address, String name, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - TransactionExtention transactionExtention = blockingStubFull - .createAssetIssue2(builder.build()); - Return ret = transactionExtention.getResult(); - if (transactionExtention == null) { - return false; - } - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public static String createAssetIssueForTransactionId(byte[] address, String name, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - public static boolean broadcastTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - Return response = PublicMethed.broadcastTransaction(transaction, blockingStubFull); - return response.getResult(); - } - - - /** - * constructor. - */ - public static Account queryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public static Account queryAccount(byte[] address, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - - /** - * constructor. - */ - - public static Account queryAccount(String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - /** - * constructor. - */ - - public static String loadPubKey() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - public static byte[] getAddress(ECKey ecKey) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public static Account grpcQueryAccount(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public static Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - /** - * constructor. - */ - - public static Transaction signTransaction(ECKey ecKey, Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - private static Transaction signTransaction(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - if (transaction.getRawData().getTimestamp() == 0) { - transaction = TransactionUtils.setTimestamp(transaction); - } - - long currentTime = System.currentTimeMillis();//*1000000 + System.nanoTime()%1000000; - Transaction.Builder builder = transaction.toBuilder(); - org.tron.protos.Protocol.Transaction.raw.Builder rowBuilder = transaction.getRawData() - .toBuilder(); - rowBuilder.setTimestamp(currentTime); - builder.setRawData(rowBuilder.build()); - transaction = builder.build(); - - for (int i = 0; i < priKeys.length; i += 1) { - String priKey = priKeys[i]; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - transaction = TransactionUtils.sign(transaction, ecKey); - TransactionSignWeight weight = blockingStubFull.getTransactionSignWeight(transaction); - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION) { - break; - } - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.NOT_ENOUGH_PERMISSION) { - continue; - } - } - return transaction; - } - - - /** - * constructor. - */ - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean participateAssetIssueWithPermissionId(byte[] to, byte[] assertName, - long amount, byte[] from, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static String participateAssetIssueForTransactionId(byte[] to, byte[] assertName, - long amount, byte[] from, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return null; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceWithPermissionId(byte[] addRess, long freezeBalance, - long freezeDuration, int permissionId, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(priKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static Boolean unFreezeBalanceWithPermissionId(byte[] address, String priKey, - int resourceCode, byte[] receiverAddress, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean unFreezeBalance(byte[] address, String priKey, int resourceCode, - byte[] receiverAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess).setResourceValue(resourceCode); - if (receiverAddress != null) { - ByteString receiverAddressBytes = ByteString.copyFrom(receiverAddress); - builder.setReceiverAddress(receiverAddressBytes); - } - - UnfreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static String sendcoinGetTransactionHex(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - logger.info("HEX transaction is : " + "transaction hex string is " + ByteArray - .toHexString(transaction.toByteArray())); - return ByteArray.toHexString(transaction.toByteArray()); - - } - - - /** - * constructor. - */ - public static boolean updateAsset(byte[] address, byte[] description, byte[] url, long newLimit, - long newPublicLimit, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean updateAssetWithPermissionId(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static String updateAssetForTransactionId(byte[] address, byte[] description, byte[] url, - long newLimit, long newPublicLimit, String priKey, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UpdateAssetContract.Builder builder = UpdateAssetContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(address); - builder.setDescription(ByteString.copyFrom(description)); - builder.setUrl(ByteString.copyFrom(url)); - builder.setNewLimit(newLimit); - builder.setNewPublicLimit(newPublicLimit); - builder.setOwnerAddress(basAddreess); - - UpdateAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean transferAssetWithpermissionId(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.transferAsset2(contract); - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static String transferAssetForTransactionId(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (!result) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean waitProduceNextBlock(WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - - Block nextBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - Long nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - - Integer wait = 0; - logger.info( - "Block num is " + Long.toString(currentBlock.getBlockHeader().getRawData().getNumber())); - while (nextNum <= currentNum + 1 && wait <= 15) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Wait to produce next block"); - nextBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - nextNum = nextBlock.getBlockHeader().getRawData().getNumber(); - if (wait == 15) { - logger.info("These 45 second didn't produce a block,please check."); - return false; - } - wait++; - } - logger.info("quit normally"); - return true; - } - - /** - * constructor. - */ - - public static boolean createAccount(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static boolean createAccountWhtiPermissionId(byte[] ownerAddress, byte[] newAddress, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createAccount2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static boolean createProposal(byte[] ownerAddress, String priKey, - HashMap parametersMap, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean createProposalWithPermissionId(byte[] ownerAddress, String priKey, - HashMap parametersMap, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalCreateContract.Builder builder = ProposalCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.putAllParameters(parametersMap); - - ProposalCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean approveProposal(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean approveProposalWithPermission(byte[] ownerAddress, String priKey, long id, - boolean isAddApproval, int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalApproveContract.Builder builder = ProposalApproveContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - builder.setIsAddApproval(isAddApproval); - ProposalApproveContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalApprove(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean deleteProposal(byte[] ownerAddress, String priKey, long id, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean deleteProposalWithPermissionId(byte[] ownerAddress, String priKey, long id, - int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - ProposalDeleteContract.Builder builder = ProposalDeleteContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setProposalId(id); - - ProposalDeleteContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.proposalDelete(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean setAccountId(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - transaction = signTransaction(ecKey, transaction); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceGetEnergy(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - return deployContract(contractName, abiString, code, data, feeLimit, value, - consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull, permissionKeyString); - } - - /** - * constructor. - */ - - public static byte[] deployContract(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = PublicMethed - .generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - broadcastTransaction(transaction, blockingStubFull); - return contractAddress; - } - - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractAndGetTransactionInfoById(contractName, abiString, code, data, feeLimit, - value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, ownerAddress, - blockingStubFull); - } - - /** - * constructor. - */ - - public static String deployContractAndGetTransactionInfoById(String contractName, - String abiString, String code, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - byte[] contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static SmartContract.ABI jsonStr2Abi(String jsonStr) { - if (jsonStr == null) { - return null; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jsonElementRoot = jsonParser.parse(jsonStr); - JsonArray jsonRoot = jsonElementRoot.getAsJsonArray(); - SmartContract.ABI.Builder abiBuilder = SmartContract.ABI.newBuilder(); - for (int index = 0; index < jsonRoot.size(); index++) { - JsonElement abiItem = jsonRoot.get(index); - boolean anonymous = - abiItem.getAsJsonObject().get("anonymous") != null ? abiItem.getAsJsonObject() - .get("anonymous").getAsBoolean() : false; - final boolean constant = - abiItem.getAsJsonObject().get("constant") != null ? abiItem.getAsJsonObject() - .get("constant").getAsBoolean() : false; - final String name = - abiItem.getAsJsonObject().get("name") != null ? abiItem.getAsJsonObject().get("name") - .getAsString() : null; - JsonArray inputs = - abiItem.getAsJsonObject().get("inputs") != null ? abiItem.getAsJsonObject().get("inputs") - .getAsJsonArray() : null; - final JsonArray outputs = - abiItem.getAsJsonObject().get("outputs") != null ? abiItem.getAsJsonObject() - .get("outputs").getAsJsonArray() : null; - String type = - abiItem.getAsJsonObject().get("type") != null ? abiItem.getAsJsonObject().get("type") - .getAsString() : null; - final boolean payable = - abiItem.getAsJsonObject().get("payable") != null ? abiItem.getAsJsonObject() - .get("payable").getAsBoolean() : false; - final String stateMutability = - abiItem.getAsJsonObject().get("stateMutability") != null ? abiItem.getAsJsonObject() - .get("stateMutability").getAsString() : null; - if (type == null) { - logger.error("No type!"); - return null; - } - if (!type.equalsIgnoreCase("fallback") && null == inputs) { - logger.error("No inputs!"); - return null; - } - - SmartContract.ABI.Entry.Builder entryBuilder = SmartContract.ABI.Entry.newBuilder(); - entryBuilder.setAnonymous(anonymous); - entryBuilder.setConstant(constant); - if (name != null) { - entryBuilder.setName(name); - } - - /* { inputs : optional } since fallback function not requires inputs*/ - if (inputs != null) { - for (int j = 0; j < inputs.size(); j++) { - JsonElement inputItem = inputs.get(j); - if (inputItem.getAsJsonObject().get("name") == null - || inputItem.getAsJsonObject().get("type") == null) { - logger.error("Input argument invalid due to no name or no type!"); - return null; - } - String inputName = inputItem.getAsJsonObject().get("name").getAsString(); - String inputType = inputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - paramBuilder.setIndexed(false); - paramBuilder.setName(inputName); - paramBuilder.setType(inputType); - entryBuilder.addInputs(paramBuilder.build()); - } - } - - /* { outputs : optional } */ - if (outputs != null) { - for (int k = 0; k < outputs.size(); k++) { - JsonElement outputItem = outputs.get(k); - if (outputItem.getAsJsonObject().get("name") == null - || outputItem.getAsJsonObject().get("type") == null) { - logger.error("Output argument invalid due to no name or no type!"); - return null; - } - String outputName = outputItem.getAsJsonObject().get("name").getAsString(); - String outputType = outputItem.getAsJsonObject().get("type").getAsString(); - SmartContract.ABI.Entry.Param.Builder paramBuilder = SmartContract.ABI.Entry.Param - .newBuilder(); - paramBuilder.setIndexed(false); - paramBuilder.setName(outputName); - paramBuilder.setType(outputType); - entryBuilder.addOutputs(paramBuilder.build()); - } - } - - entryBuilder.setType(getEntryType(type)); - entryBuilder.setPayable(payable); - if (stateMutability != null) { - entryBuilder.setStateMutability(getStateMutability(stateMutability)); - } - - abiBuilder.addEntrys(entryBuilder.build()); - } - - return abiBuilder.build(); - } - - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.EntryType getEntryType(String type) { - switch (type) { - case "constructor": - return SmartContract.ABI.Entry.EntryType.Constructor; - case "function": - return SmartContract.ABI.Entry.EntryType.Function; - case "event": - return SmartContract.ABI.Entry.EntryType.Event; - case "fallback": - return SmartContract.ABI.Entry.EntryType.Fallback; - default: - return SmartContract.ABI.Entry.EntryType.UNRECOGNIZED; - } - } - - /** - * constructor. - */ - - public static SmartContract.ABI.Entry.StateMutabilityType getStateMutability( - String stateMutability) { - switch (stateMutability) { - case "pure": - return SmartContract.ABI.Entry.StateMutabilityType.Pure; - case "view": - return SmartContract.ABI.Entry.StateMutabilityType.View; - case "nonpayable": - return SmartContract.ABI.Entry.StateMutabilityType.Nonpayable; - case "payable": - return SmartContract.ABI.Entry.StateMutabilityType.Payable; - default: - return SmartContract.ABI.Entry.StateMutabilityType.UNRECOGNIZED; - } - } - - /** - * constructor. - */ - - public static SmartContract getContract(byte[] address, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ByteString byteString = ByteString.copyFrom(address); - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(byteString).build(); - Integer i = 0; - while (blockingStubFull.getContract(bytesMessage).getName().isEmpty() && i++ < 4) { - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - logger.info("contract name is " + blockingStubFull.getContract(bytesMessage).getName()); - logger.info("contract address is " + WalletClient.encode58Check(address)); - return blockingStubFull.getContract(bytesMessage); - } - - private static byte[] replaceLibraryAddress(String code, String libraryAddressPair) { - - String[] libraryAddressList = libraryAddressPair.split("[,]"); - - for (int i = 0; i < libraryAddressList.length; i++) { - String cur = libraryAddressList[i]; - - int lastPosition = cur.lastIndexOf(":"); - if (-1 == lastPosition) { - throw new RuntimeException("libraryAddress delimit by ':'"); - } - String libraryName = cur.substring(0, lastPosition); - String addr = cur.substring(lastPosition + 1); - String libraryAddressHex = ByteArray.toHexString(Commons.decodeFromBase58Check(addr)) - .substring(2); - - String repeated = new String(new char[40 - libraryName.length() - 2]).replace("\0", "_"); - String beReplaced = "__" + libraryName + repeated; - Matcher m = Pattern.compile(beReplaced).matcher(code); - code = m.replaceAll(libraryAddressHex); - } - - return Hex.decode(code); - } - - private static byte[] replaceLibraryAddress_1(String code, byte[] libraryAddress) { - - String libraryAddressHex = ByteArray.toHexString(libraryAddress).substring(2); - - Matcher m = Pattern.compile("__.*__").matcher(code); - code = m.replaceAll(libraryAddressHex); - return Hex.decode(code); - } - - /** - * constructor. - */ - - public static boolean updateSetting(byte[] contractAddress, long consumeUserResourcePercent, - String priKey, byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean updateSettingWithPermissionId(byte[] contractAddress, - long consumeUserResourcePercent, String priKey, byte[] ownerAddress, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateSettingContract.Builder builder = UpdateSettingContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - - UpdateSettingContract updateSettingContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateSetting(updateSettingContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean updateEnergyLimitWithPermissionId(byte[] contractAddress, - long originEnergyLimit, String priKey, byte[] ownerAddress, int permissionId, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - UpdateEnergyLimitContract.Builder builder = UpdateEnergyLimitContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setOriginEnergyLimit(originEnergyLimit); - - UpdateEnergyLimitContract updateEnergyLimitContract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull - .updateEnergyLimit(updateEnergyLimitContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - return triggerContract(contractAddress, method, argsStr, isHex, callValue, feeLimit, "0", 0, - ownerAddress, priKey, blockingStubFull, permissionKeyString); - } - - /** - * constructor. - */ - - public static String triggerContract(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static Boolean exchangeCreate(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean injectExchange(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - public static Optional getExchangeList( - WalletGrpc.WalletBlockingStub blockingStubFull) { - ExchangeList exchangeList = blockingStubFull.listExchanges(EmptyMessage.newBuilder().build()); - return Optional.ofNullable(exchangeList); - } - - /** - * constructor. - */ - - public static boolean exchangeWithdraw(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean exchangeTransaction(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return deployContractWithConstantParame(contractName, abiString, code, constructorStr, argsStr, - data, feeLimit, value, consumeUserResourcePercent, 1000L, "0", 0L, libraryAddress, priKey, - ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - - public static String deployContractWithConstantParame(String contractName, String abiString, - String code, String constructorStr, String argsStr, String data, Long feeLimit, long value, - long consumeUserResourcePercent, long originEnergyLimit, String tokenId, long tokenValue, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - - code += Hex.toHexString(AbiUtil.encodeInput(constructorStr, argsStr)); - byte[] owner = ownerAddress; - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - transaction = signTransaction(ecKey, transaction); - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - byte[] contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - - public static Boolean freezeBalanceForReceiver(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - builder.setReceiverAddress(receiverAddressBytes); - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - private static Permission json2Permission(JSONObject json) { - Permission.Builder permissionBuilder = Permission.newBuilder(); - if (json.containsKey("type")) { - int type = json.getInteger("type"); - permissionBuilder.setTypeValue(type); - } - if (json.containsKey("permission_name")) { - String permissionName = json.getString("permission_name"); - permissionBuilder.setPermissionName(permissionName); - } - if (json.containsKey("threshold")) { - // long threshold = json.getLong("threshold"); - long threshold = Long.parseLong(json.getString("threshold")); - permissionBuilder.setThreshold(threshold); - } - if (json.containsKey("parent_id")) { - int parentId = json.getInteger("parent_id"); - permissionBuilder.setParentId(parentId); - } - if (json.containsKey("operations")) { - byte[] operations = ByteArray.fromHexString(json.getString("operations")); - permissionBuilder.setOperations(ByteString.copyFrom(operations)); - } - if (json.containsKey("keys")) { - JSONArray keys = json.getJSONArray("keys"); - List keyList = new ArrayList<>(); - for (int i = 0; i < keys.size(); i++) { - Key.Builder keyBuilder = Key.newBuilder(); - JSONObject key = keys.getJSONObject(i); - String address = key.getString("address"); - // long weight = key.getLong("weight"); - long weight = Long.parseLong(key.getString("weight")); - keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); - keyBuilder.setWeight(weight); - keyList.add(keyBuilder.build()); - } - permissionBuilder.addAllKeys(keyList); - } - return permissionBuilder.build(); - } - - /** - * constructor. - */ - - public static boolean accountPermissionUpdate(String permissionJson, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static String accountPermissionUpdateForTransactionId(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - - /** - * constructor. - */ - public static String accountPermissionUpdateForTransactionId1(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownerpermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesspermission = permissions.getJSONObject("witness_permission"); - JSONArray activepermissions = permissions.getJSONArray("active_permissions"); - - if (ownerpermission != null) { - Permission ownerPermission = json2Permission(ownerpermission); - builder.setOwner(ownerPermission); - } - if (witnesspermission != null) { - Permission witnessPermission = json2Permission(witnesspermission); - builder.setWitness(witnessPermission); - } - if (activepermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activepermissions.size(); j++) { - JSONObject permission = activepermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - /** - * constructor. - */ - public static Transaction addTransactionSign(Transaction transaction, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()); - - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** - * constructor. - */ - public static Boolean voteWitness(HashMap witness, byte[] addRess, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static void printPermissionList(List permissionList) { - String result = "\n"; - result += "["; - result += "\n"; - int i = 0; - for (Permission permission : permissionList) { - result += "permission " + i + " :::"; - result += "\n"; - result += "{"; - result += "\n"; - result += printPermission(permission); - result += "\n"; - result += "}"; - result += "\n"; - i++; - } - result += "]"; - System.out.println(result); - } - - /** - * constructor. - */ - public static String printPermission(Permission permission) { - StringBuffer result = new StringBuffer(); - result.append("permission_type: "); - result.append(permission.getType()); - result.append("\n"); - result.append("permission_id: "); - result.append(permission.getId()); - result.append("\n"); - result.append("permission_name: "); - result.append(permission.getPermissionName()); - result.append("\n"); - result.append("threshold: "); - result.append(permission.getThreshold()); - result.append("\n"); - result.append("parent_id: "); - result.append(permission.getParentId()); - result.append("\n"); - result.append("operations: "); - result.append(ByteArray.toHexString(permission.getOperations().toByteArray())); - result.append("\n"); - if (permission.getKeysCount() > 0) { - result.append("keys:"); - result.append("\n"); - result.append("["); - result.append("\n"); - for (Key key : permission.getKeysList()) { - result.append(printKey(key)); - } - result.append("]"); - result.append("\n"); - } - return result.toString(); - } - - /** - * constructor. - */ - public static String printKey(Key key) { - StringBuffer result = new StringBuffer(); - result.append("address: "); - result.append(encode58Check(key.getAddress().toByteArray())); - result.append("\n"); - result.append("weight: "); - result.append(key.getWeight()); - result.append("\n"); - return result.toString(); - } - - /** - * constructor. - */ - public static String encode58Check(byte[] input) { - byte[] hash0 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), input); - byte[] hash1 = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), hash0); - byte[] inputCheck = new byte[input.length + 4]; - System.arraycopy(input, 0, inputCheck, 0, input.length); - System.arraycopy(hash1, 0, inputCheck, input.length, 4); - return Base58.encode(inputCheck); - } - - /** - * constructor. - */ - public static Transaction sendcoinWithPermissionIdNotSign(byte[] to, long amount, byte[] owner, - int permissionId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - - Transaction transaction = transactionExtention.getTransaction(); - raw rawData = transaction.getRawData(); - Transaction.Contract contract1 = transactionExtention.getTransaction().getRawData() - .getContractList().get(0); - contract1 = contract1.toBuilder().setPermissionId(permissionId).build(); - rawData = rawData.toBuilder().clearContract().addContract(contract1).build(); - transaction = transaction.toBuilder().setRawData(rawData).build(); - - return transaction; - - } - - /** - * constructor. - */ - public static TransactionSignWeight getTransactionSignWeight(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - return blockingStubFull.getTransactionSignWeight(transaction); - } - - /** - * constructor. - */ - public static Return broadcastTransaction1(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - return PublicMethed.broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean accountPermissionUpdateWithPermissionId(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - - Transaction transaction = transactionExtention.getTransaction(); - raw rawData = transaction.getRawData(); - Transaction.Contract contract1 = transactionExtention.getTransaction().getRawData() - .getContractList().get(0); - contract1 = contract1.toBuilder().setPermissionId(permissionId).build(); - rawData = rawData.toBuilder().clearContract().addContract(contract1).build(); - transaction = transaction.toBuilder().setRawData(rawData).build(); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response.getResult(); - } - - /** - * constructor. - */ - public static Transaction accountPermissionUpdateWithoutSign(String permissionJson, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transaction; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - return transaction; - } - - /** - * constructor. - */ - public static Transaction addTransactionSignWithPermissionId(Transaction transaction, - String priKey, int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - - //transaction = setPermissionId(transaction, permissionId); - Transaction.raw.Builder raw = transaction.getRawData().toBuilder(); - Transaction.Contract.Builder contract = raw.getContract(0).toBuilder() - .setPermissionId(permissionId); - raw.clearContract(); - raw.addContract(contract); - transaction = transaction.toBuilder().setRawData(raw).build(); - - Transaction.Builder transactionBuilderSigned = transaction.toBuilder(); - byte[] hash = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()); - ECKey ecKey = temKey; - ECDSASignature signature = ecKey.sign(hash); - ByteString bsSign = ByteString.copyFrom(signature.toByteArray()); - transactionBuilderSigned.addSignature(bsSign); - transaction = transactionBuilderSigned.build(); - return transaction; - } - - /** - * constructor. - */ - public static Transaction setPermissionId(Transaction transaction, int permissionId) - throws CancelException { - if (transaction.getSignatureCount() != 0 - || transaction.getRawData().getContract(0).getPermissionId() != 0) { - return transaction; - } - if (permissionId < 0) { - throw new CancelException("User cancelled"); - } - if (permissionId != 0) { - Transaction.raw.Builder raw = transaction.getRawData().toBuilder(); - Transaction.Contract.Builder contract = raw.getContract(0).toBuilder() - .setPermissionId(permissionId); - raw.clearContract(); - raw.addContract(contract); - transaction = transaction.toBuilder().setRawData(raw).build(); - } - return transaction; - } - - /** - * constructor. - */ - public static int getActivePermissionKeyCount(List permissionList) { - int permissionCount = 0; - for (Permission permission : permissionList) { - permissionCount += permission.getKeysCount(); - } - return permissionCount; - } - - /** - * constructor. - */ - public static Boolean sendcoinWithPermissionId(byte[] to, long amount, byte[] owner, - int permissionId, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.createTransaction2(contract); - - Transaction transaction = transactionExtention.getTransaction(); - raw rawData = transaction.getRawData(); - Transaction.Contract contract1 = transactionExtention.getTransaction().getRawData() - .getContractList().get(0); - contract1 = contract1.toBuilder().setPermissionId(permissionId).build(); - rawData = rawData.toBuilder().clearContract().addContract(contract1).build(); - transaction = transaction.toBuilder().setRawData(rawData).build(); - transactionExtention = transactionExtention.toBuilder().setTransaction(transaction).build(); - - if (transactionExtention == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - public static void recoverWitnessPermission(String ownerKey, List ownerPermissionKeys, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - PublicMethed.printAddress(ownerKey); - byte[] ownerAddress = new WalletClient(ownerKey).getAddress(); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue( - accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - } - - /** - * constructor. - */ - public static String getOperations(Integer[] ints) { - List list = new ArrayList<>(Arrays.asList(ints)); - byte[] operations = new byte[32]; - list.forEach(e -> { - operations[e / 8] |= (1 << e % 8); - }); - - System.out.println(ByteArray.toHexString(operations)); - return ByteArray.toHexString(operations); - } - - /** - * constructor. - */ - public static GrpcAPI.Return accountPermissionUpdateForResponse(String permissionJson, - byte[] owner, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] priKeys) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - AccountPermissionUpdateContract.Builder builder = AccountPermissionUpdateContract.newBuilder(); - - JSONObject permissions = JSONObject.parseObject(permissionJson); - JSONObject ownersPermission = permissions.getJSONObject("owner_permission"); - JSONObject witnesssPermission = permissions.getJSONObject("witness_permission"); - JSONArray activesPermissions = permissions.getJSONArray("active_permissions"); - - if (ownersPermission != null) { - Permission ownerPermission = json2Permission(ownersPermission); - builder.setOwner(ownerPermission); - } - if (witnesssPermission != null) { - Permission witnessPermission = json2Permission(witnesssPermission); - builder.setWitness(witnessPermission); - } - if (activesPermissions != null) { - List activePermissionList = new ArrayList<>(); - for (int j = 0; j < activesPermissions.size(); j++) { - JSONObject permission = activesPermissions.getJSONObject(j); - activePermissionList.add(json2Permission(permission)); - } - builder.addAllActives(activePermissionList); - } - builder.setOwnerAddress(ByteString.copyFrom(owner)); - - AccountPermissionUpdateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.accountPermissionUpdate(contract); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return ret; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, priKeys); - Return response = broadcastTransaction1(transaction, blockingStubFull); - return response; - } - - /** - * constructor. - */ - public static void recoverAccountPermission(String ownerKey, List ownerPermissionKeys, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - PublicMethed.printAddress(ownerKey); - byte[] ownerAddress = new WalletClient(ownerKey).getAddress(); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue( - accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - } - - /** - * constructor. - */ - public static Transaction sendcoin2(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - return transaction; - - } - - /** - * constructor. - */ - public static Protocol.Transaction createFakeTransaction(byte[] toAddrss, Long amount, - byte[] fromAddress) { - - TransferContract contract = TransferContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(fromAddress)) - .setToAddress(ByteString.copyFrom(toAddrss)).setAmount(amount).build(); - Protocol.Transaction transaction = createTransaction(contract, ContractType.TransferContract); - - return transaction; - } - - /** - * constructor. - */ - private static Transaction setReference(Transaction transaction, long blockNum, - byte[] blockHash) { - byte[] refBlockNum = ByteArray.fromLong(blockNum); - Transaction.raw rawData = transaction.getRawData().toBuilder() - .setRefBlockHash(ByteString.copyFrom(blockHash)) - .setRefBlockBytes(ByteString.copyFrom(refBlockNum)).build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - /** - * constructor. - */ - public static Transaction setExpiration(Transaction transaction, long expiration) { - Transaction.raw rawData = transaction.getRawData().toBuilder().setExpiration(expiration) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - /** - * constructor. - */ - public static Transaction createTransaction(com.google.protobuf.Message message, - ContractType contractType) { - Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( - Transaction.Contract.newBuilder().setType(contractType).setParameter(Any.pack(message)) - .build()); - - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) - .build(); - - long time = System.currentTimeMillis(); - AtomicLong count = new AtomicLong(); - long geTime = count.incrementAndGet() + time; - String ref = "" + geTime; - - transaction = setReference(transaction, geTime, ByteArray.fromString(ref)); - - transaction = setExpiration(transaction, geTime); - - return transaction; - } - - /** - * constructor. - */ - - public static String triggerContractWithPermissionId(byte[] contractAddress, String method, - String argsStr, Boolean isHex, long callValue, long feeLimit, String tokenId, long tokenValue, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString, int permissionId) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong(tokenId)); - builder.setCallTokenValue(tokenValue); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static byte[] generateContractAddress(Transaction trx, byte[] owneraddress) { - - // get owner address - // this address should be as same as the onweraddress in trx, DONNOT modify it - byte[] ownerAddress = owneraddress; - - // get tx hash - byte[] txRawDataHash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), trx.getRawData().toByteArray()).getBytes(); - - // combine - byte[] combined = new byte[txRawDataHash.length + ownerAddress.length]; - System.arraycopy(txRawDataHash, 0, combined, 0, txRawDataHash.length); - System.arraycopy(ownerAddress, 0, combined, txRawDataHash.length, ownerAddress.length); - - return sha3omit12(combined); - - } - - /** - * constructor. - */ - - public static byte[] deployContractWithPermissionId(String contractName, String abiString, - String code, String data, Long feeLimit, long value, long consumeUserResourcePercent, - long originEnergyLimit, String tokenId, long tokenValue, String libraryAddress, String priKey, - byte[] ownerAddress, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString, int permissionId) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(originEnergyLimit); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(tokenValue); - contractBuilder.setTokenId(Long.parseLong(tokenId)); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - contractAddress = generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - - GrpcAPI.Return response = broadcastTransaction1(transaction, blockingStubFull); - if (response.getResult() == false) { - return null; - } else { - //logger.info("brodacast succesfully"); - return contractAddress; - } - } - - - /** - * constructor. - */ - public static byte[] deployContract1(String contractName, String abiString, String code, - String data, Long feeLimit, long value, long consumeUserResourcePercent, - String libraryAddress, String priKey, byte[] ownerAddress, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SmartContract.ABI abi = jsonStr2Abi(abiString); - if (abi == null) { - logger.error("abi is null"); - return null; - } - //byte[] codeBytes = Hex.decode(code); - SmartContract.Builder builder = SmartContract.newBuilder(); - builder.setName(contractName); - builder.setOriginAddress(ByteString.copyFrom(owner)); - builder.setAbi(abi); - builder.setConsumeUserResourcePercent(consumeUserResourcePercent); - builder.setOriginEnergyLimit(1000L); - - if (value != 0) { - - builder.setCallValue(value); - } - - byte[] byteCode; - if (null != libraryAddress) { - byteCode = replaceLibraryAddress(code, libraryAddress); - } else { - byteCode = Hex.decode(code); - } - builder.setBytecode(ByteString.copyFrom(byteCode)); - - Builder contractBuilder = CreateSmartContract.newBuilder(); - contractBuilder.setOwnerAddress(ByteString.copyFrom(owner)); - contractBuilder.setCallTokenValue(0L); - contractBuilder.setTokenId(Long.parseLong("0")); - CreateSmartContract contractDeployContract = contractBuilder.setNewContract(builder.build()) - .build(); - - TransactionExtention transactionExtention = blockingStubFull - .deployContract(contractDeployContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - - byte[] contractAddress = PublicMethed - .generateContractAddress(transactionExtention.getTransaction(), owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - System.out.println( - "txid = " + ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - contractAddress = PublicMethed.generateContractAddress(transaction, owner); - System.out.println( - "Your smart contract address will be: " + WalletClient.encode58Check(contractAddress)); - broadcastTransaction(transaction, blockingStubFull); - return contractAddress; - } - - /** - * constructor. - */ - public static String triggerContract1(byte[] contractAddress, String method, String argsStr, - Boolean isHex, long callValue, long feeLimit, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - if (argsStr.equalsIgnoreCase("#")) { - logger.info("argsstr is #"); - argsStr = ""; - } - - byte[] owner = ownerAddress; - byte[] input = Hex.decode(AbiUtil.parseMethod(method, argsStr, isHex)); - - TriggerSmartContract.Builder builder = TriggerSmartContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - builder.setData(ByteString.copyFrom(input)); - builder.setCallValue(callValue); - builder.setTokenId(Long.parseLong("0")); - builder.setCallTokenValue(0L); - TriggerSmartContract triggerContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.triggerContract(triggerContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return null; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return null; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - rawBuilder.setFeeLimit(feeLimit); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return null; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return null; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - broadcastTransaction(transaction, blockingStubFull); - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - - /** - * constructor. - */ - - public static boolean updateAccountWithPermissionId(byte[] addressBytes, byte[] accountNameBytes, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static String transferAssetForTransactionId1(byte[] to, byte[] assertName, long amount, - byte[] address, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - logger.info("transaction == null"); - } else { - logger.info("transaction.getRawData().getContractCount() == 0"); - } - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (result == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } - - - /** - * constructor. - */ - - public static Boolean freezeBalanceGetEnergyWithPermissionId(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = TransactionUtils.setTimestamp(transaction); - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static Boolean freezeBalanceForReceiverWithPermissionId(byte[] addRess, long freezeBalance, - long freezeDuration, int resourceCode, ByteString receiverAddressBytes, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration).setResourceValue(resourceCode); - builder.setReceiverAddress(receiverAddressBytes); - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static boolean createAccount1(byte[] ownerAddress, byte[] newAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - AccountCreateContract.Builder builder = AccountCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setAccountAddress(ByteString.copyFrom(newAddress)); - AccountCreateContract contract = builder.build(); - Transaction transaction = blockingStubFull.createAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - - public static boolean setAccountId1(byte[] accountIdBytes, byte[] ownerAddress, String priKey, - int permissionId, WalletGrpc.WalletBlockingStub blockingStubFull, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - SetAccountIdContract.Builder builder = SetAccountIdContract.newBuilder(); - ByteString bsAddress = ByteString.copyFrom(owner); - ByteString bsAccountId = ByteString.copyFrom(accountIdBytes); - builder.setAccountId(bsAccountId); - builder.setOwnerAddress(bsAddress); - SetAccountIdContract contract = builder.build(); - Transaction transaction = blockingStubFull.setAccountId(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return broadcastTransaction(transaction, blockingStubFull); - //Return response = broadcastTransaction1(transaction, blockingStubFull); - //if (response.getResult() == false) { - // logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - // return false; - //} else { - // return true; - //} - //return response.getResult(); - } - - - /** - * constructor. - */ - public static Boolean voteWitnessWithPermissionId(HashMap witness, byte[] addRess, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote.newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.voteWitnessAccount2(contract); - Transaction transaction = transactionExtention.getTransaction(); - - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static String createAssetIssueForTransactionId1(byte[] address, String name, - Long totalSupply, Integer trxNum, Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long freeAssetNetLimit, - Long publicFreeAssetNetLimit, Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return null; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - boolean result = broadcastTransaction(transaction, blockingStubFull); - if (result == false) { - return null; - } else { - return ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray())); - } - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } - - /** - * constructor. - */ - - public static Boolean injectExchange1(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeInjectContract.Builder builder = ExchangeInjectContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeInjectContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeInject(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static boolean exchangeWithdraw1(long exchangeId, byte[] tokenId, long quant, - byte[] ownerAddress, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, - int permissionId, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeWithdrawContract.Builder builder = ExchangeWithdrawContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant); - ExchangeWithdrawContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeWithdraw(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - - public static boolean exchangeTransaction1(long exchangeId, byte[] tokenId, long quant, - long expected, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - byte[] owner = ownerAddress; - - ExchangeTransactionContract.Builder builder = ExchangeTransactionContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setExchangeId(exchangeId) - .setTokenId(ByteString.copyFrom(tokenId)).setQuant(quant).setExpected(expected); - ExchangeTransactionContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeTransaction(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static Boolean exchangeCreate1(byte[] firstTokenId, long firstTokenBalance, - byte[] secondTokenId, long secondTokenBalance, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ExchangeCreateContract.Builder builder = ExchangeCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)) - .setFirstTokenId(ByteString.copyFrom(firstTokenId)).setFirstTokenBalance(firstTokenBalance) - .setSecondTokenId(ByteString.copyFrom(secondTokenId)) - .setSecondTokenBalance(secondTokenBalance); - ExchangeCreateContract contract = builder.build(); - TransactionExtention transactionExtention = blockingStubFull.exchangeCreate(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean clearContractAbi(byte[] contractAddress, byte[] ownerAddress, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, int permissionId, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] owner = ownerAddress; - - ClearABIContract.Builder builder = ClearABIContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setContractAddress(ByteString.copyFrom(contractAddress)); - - ClearABIContract clearABIContract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.clearContractABI(clearABIContract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create call trx failed!"); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction.getRetCount() != 0 && transactionExtention.getConstantResult(0) != null - && transactionExtention.getResult() != null) { - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - return false; - } - - final TransactionExtention.Builder texBuilder = TransactionExtention.newBuilder(); - Transaction.Builder transBuilder = Transaction.newBuilder(); - Transaction.raw.Builder rawBuilder = transactionExtention.getTransaction().getRawData() - .toBuilder(); - transBuilder.setRawData(rawBuilder); - for (int i = 0; i < transactionExtention.getTransaction().getSignatureCount(); i++) { - ByteString s = transactionExtention.getTransaction().getSignature(i); - transBuilder.setSignature(i, s); - } - for (int i = 0; i < transactionExtention.getTransaction().getRetCount(); i++) { - Result r = transactionExtention.getTransaction().getRet(i); - transBuilder.setRet(i, r); - } - texBuilder.setTransaction(transBuilder); - texBuilder.setResult(transactionExtention.getResult()); - texBuilder.setTxid(transactionExtention.getTxid()); - transactionExtention = texBuilder.build(); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean sendShieldCoin(byte[] publicZenTokenOwnerAddress, long fromAmount, - ShieldAddressInfo shieldAddressInfo, NoteTx noteTx, List shieldOutputList, - byte[] publicZenTokenToAddress, long toAmount, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull, Integer permission_id, - String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - PrivateParameters.Builder builder = PrivateParameters.newBuilder(); - if (!ByteUtil.isNullOrZeroArray(publicZenTokenOwnerAddress)) { - builder.setTransparentFromAddress(ByteString.copyFrom(publicZenTokenOwnerAddress)); - builder.setFromAmount(fromAmount); - } - if (!ByteUtil.isNullOrZeroArray(publicZenTokenToAddress)) { - builder.setTransparentToAddress(ByteString.copyFrom(publicZenTokenToAddress)); - builder.setToAmount(toAmount); - } - - if (shieldAddressInfo != null) { - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(noteTx.getTxid().toByteArray())); - outPointBuild.setIndex(noteTx.getIndex()); - request.addOutPoints(outPointBuild.build()); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - - //String shieldAddress = noteInfo.getPaymentAddress(); - //ShieldAddressInfo addressInfo = - // shieldWrapper.getShieldAddressInfoMap().get(shieldAddress); - SpendingKey spendingKey = new SpendingKey(shieldAddressInfo.getSk()); - try { - ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(ByteString.copyFrom(expandedSpendingKey.getAsk())); - builder.setNsk(ByteString.copyFrom(expandedSpendingKey.getNsk())); - builder.setOvk(ByteString.copyFrom(expandedSpendingKey.getOvk())); - } catch (Exception e) { - System.out.println(e); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteTx.getNote().getRcm().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(noteTx.getNote().getMemo().toByteArray())); - - //System.out.println("address " + noteInfo.getPaymentAddress()); - //System.out.println("value " + noteInfo.getValue()); - //System.out.println("rcm " + ByteArray.toHexString(noteInfo.getR())); - //System.out.println("trxId " + noteInfo.getTrxId()); - //System.out.println("index " + noteInfo.getIndex()); - //System.out.println("meno " + new String(noteInfo.getMemo())); - - SpendNote.Builder spendNoteBuilder = SpendNote.newBuilder(); - spendNoteBuilder.setNote(noteBuild.build()); - try { - spendNoteBuilder.setAlpha(ByteString.copyFrom(org.tron.core.zen.note.Note.generateR())); - } catch (Exception e) { - System.out.println(e); - } - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - spendNoteBuilder.setVoucher(merkleVoucherInfo.getVouchers(0)); - spendNoteBuilder.setPath(merkleVoucherInfo.getPaths(0)); - - builder.addShieldedSpends(spendNoteBuilder.build()); - - } else { - byte[] ovk = ByteArray - .fromHexString("030c8c2bc59fb3eb8afb047a8ea4b028743d23e7d38c6fa30908358431e2314d"); - builder.setOvk(ByteString.copyFrom(ovk)); - } - - if (shieldOutputList.size() > 0) { - for (int i = 0; i < shieldOutputList.size(); ++i) { - builder - .addShieldedReceives(ReceiveNote.newBuilder().setNote(shieldOutputList.get(i)).build()); - } - } - - TransactionExtention transactionExtention = blockingStubFull - .createShieldedTransaction(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - Any any = transaction.getRawData().getContract(0).getParameter(); - - try { - ShieldContract.ShieldedTransferContract shieldedTransferContract = any - .unpack(ShieldContract.ShieldedTransferContract.class); - if (shieldedTransferContract.getFromAmount() > 0 || fromAmount == 321321) { - Transaction.raw.Builder raw = transaction.getRawData().toBuilder(); - Transaction.Contract.Builder contract = raw.getContract(0).toBuilder() - .setPermissionId(permission_id); - raw.clearContract(); - raw.addContract(contract); - transaction = transaction.toBuilder().setRawData(raw).build(); - - transaction = signTransactionForShield(transaction, blockingStubFull, permissionKeyString); - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - } else { - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - } - } catch (Exception e) { - System.out.println(e); - } - return broadcastTransaction(transaction, blockingStubFull); - } - - - /** - * constructor. - */ - private static Transaction signTransactionForShield(Transaction transaction, - WalletGrpc.WalletBlockingStub blockingStubFull, String[] priKeys) { - /* if (transaction.getRawData().getTimestamp() == 0) { - transaction = TransactionUtils.setTimestamp(transaction); - } - - long currentTime = System.currentTimeMillis();//*1000000 + System.nanoTime()%1000000; - Transaction.Builder builder = transaction.toBuilder(); - org.tron.protos.Protocol.Transaction.raw.Builder rowBuilder = transaction.getRawData() - .toBuilder(); - rowBuilder.setTimestamp(currentTime); - builder.setRawData(rowBuilder.build()); - transaction = builder.build();*/ - - for (int i = 0; i < priKeys.length; i += 1) { - String priKey = priKeys[i]; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - transaction = TransactionUtils.sign(transaction, ecKey); - TransactionSignWeight weight = blockingStubFull.getTransactionSignWeight(transaction); - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION) { - break; - } - if (weight.getResult().getCode() - == TransactionSignWeight.Result.response_code.NOT_ENOUGH_PERMISSION) { - continue; - } - } - logger.info("Sign transaction:" + transaction.toString()); - return transaction; - } - - /** - * constructor. - */ - public static boolean createWitness(String url, byte[] owner, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - byte[] byteurl = url.getBytes(); - WitnessCreateContract.Builder builder = WitnessCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(byteurl)); - WitnessCreateContract contract = builder.build(); - - TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - System.out.println("RPC create trx failed!"); - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - - public static boolean updateWitness2(byte[] owner, byte[] url, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessUpdateContract.Builder builder = WitnessUpdateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessUpdateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.updateWitness2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult().getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } - return true; - } - - /** - * constructor. - */ - public static boolean withdrawBalance(byte[] address, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - WithdrawBalanceContract.Builder builder = WithdrawBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return true; - } - - /** - * constructor. - */ - public static boolean unFreezeAsset(byte[] addRess, String priKey, int permissionId, - String[] permissionKeyString, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address = addRess; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - UnfreezeAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - } catch (CancelException e) { - e.printStackTrace(); - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - return true; - } - - /** - * constructor. - */ - - public static Transaction sendcoinGetTransaction(byte[] to, long amount, byte[] owner, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull, String[] permissionKeyString) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - return null; - } - transaction = signTransaction(transaction, blockingStubFull, permissionKeyString); - - return transaction; - - } - - /** - * constructor. - */ - public static boolean updateBrokerage(byte[] owner, int brokerage, String priKey, - int permissionId, String[] priKeys, WalletGrpc.WalletBlockingStub blockingStubFull) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - UpdateBrokerageContract.Builder updateBrokerageContract = UpdateBrokerageContract.newBuilder(); - updateBrokerageContract.setOwnerAddress(ByteString.copyFrom(owner)).setBrokerage(brokerage); - TransactionExtention transactionExtention = blockingStubFull - .updateBrokerage(updateBrokerageContract.build()); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transactionExtention == null || !transactionExtention.getResult().getResult()) { - if (transactionExtention != null) { - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - } - return false; - } - try { - transaction = setPermissionId(transaction, permissionId); - transaction = signTransaction(transaction, blockingStubFull, priKeys); - } catch (Exception e) { - e.printStackTrace(); - } - - System.out.println("trigger txid = " + ByteArray - .toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()))); - - return broadcastTransaction(transaction, blockingStubFull); - } - - /** - * constructor. - */ - public static boolean marketSellAsset(byte[] owner, byte[] sellTokenId, - long sellTokenQuantity, byte[] buyTokenId, long buyTokenQuantity, - int permissionId, String[] priKeys, WalletBlockingStub blockingStubFull) { - - MarketContract.MarketSellAssetContract.Builder builder = MarketContract.MarketSellAssetContract - .newBuilder(); - builder - .setOwnerAddress(ByteString.copyFrom(owner)) - .setSellTokenId(ByteString.copyFrom(sellTokenId)) - .setSellTokenQuantity(sellTokenQuantity) - .setBuyTokenId(ByteString.copyFrom(buyTokenId)) - .setBuyTokenQuantity(buyTokenQuantity); - - TransactionExtention transactionExtention = blockingStubFull.marketSellAsset(builder.build()); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - - if (transaction.getRawData().getContract(0).getType() - != ContractType.MarketSellAssetContract) { - return false; - } - - try { - transaction = setPermissionId(transaction, permissionId); - transaction = signTransaction(transaction, blockingStubFull, priKeys); - } catch (CancelException e) { - e.printStackTrace(); - } - return broadcastTransaction(transaction, blockingStubFull); - - } - - /** - * constructor. - */ - public static boolean marketCancelOrder(byte[] owner, byte[] orderId, - int permissionId, String[] priKeys, - WalletBlockingStub blockingStubFull) { - - MarketContract.MarketCancelOrderContract.Builder builder = MarketContract - .MarketCancelOrderContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)).setOrderId(ByteString.copyFrom(orderId)); - - TransactionExtention transactionExtention = blockingStubFull.marketCancelOrder(builder.build()); - - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - - if (transaction.getRawData().getContract(0).getType() - != ContractType.MarketCancelOrderContract) { - System.out.println("Wrong ContractType :" - + transaction.getRawData().getContract(0).getType()); - return false; - } - - try { - transaction = setPermissionId(transaction, permissionId); - transaction = signTransaction(transaction,blockingStubFull,priKeys); - } catch (CancelException e) { - e.printStackTrace(); - } - return broadcastTransaction(transaction, blockingStubFull); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Retry.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/Retry.java deleted file mode 100644 index 8c9779504f9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Retry.java +++ /dev/null @@ -1,50 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import org.testng.IRetryAnalyzer; -import org.testng.ITestResult; - -public class Retry implements IRetryAnalyzer { - - private int retryCount = 0; - private int maxRetryCount = 2; - - // Below method returns 'true' if the test method has to be retried else 'false' - //and it takes the 'Result' as parameter of the test method that just ran - - /** - * constructor. - */ - - public boolean retry(ITestResult result) { - if (retryCount < maxRetryCount) { - System.out.println("Retrying test " + result.getName() + " with status " - + getResultStatusName(result.getStatus()) + " for the " + (retryCount + 1) + " time(s)."); - retryCount++; - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return true; - } - return false; - } - - /** - * constructor. - */ - - public String getResultStatusName(int status) { - String resultName = null; - if (status == 1) { - resultName = "SUCCESS"; - } - if (status == 2) { - resultName = "FAILURE"; - } - if (status == 3) { - resultName = "SKIP"; - } - return resultName; - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/RetryListener.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/RetryListener.java deleted file mode 100644 index 1e2ac832377..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/RetryListener.java +++ /dev/null @@ -1,20 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import org.testng.IAnnotationTransformer; -import org.testng.IRetryAnalyzer; -import org.testng.annotations.ITestAnnotation; - -public class RetryListener implements IAnnotationTransformer { - - @Override - public void transform(ITestAnnotation testannotation, Class testClass, - Constructor testConstructor, Method testMethod) { - IRetryAnalyzer retry = testannotation.getRetryAnalyzer(); - - if (retry == null) { - testannotation.setRetryAnalyzer(Retry.class); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Hash.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Hash.java deleted file mode 100644 index 6dd758a1501..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/Sha256Hash.java +++ /dev/null @@ -1,346 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -/* - * Copyright 2011 Google Inc. - * Copyright 2014 Andreas Schildbach - * - * 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. - */ - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.common.io.ByteStreams; -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; -import com.google.protobuf.ByteString; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.Serializable; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import org.bouncycastle.crypto.digests.SM3Digest; -import org.tron.common.utils.ByteArray; - - -/** - * A Sha256Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be - * used as keys in a map. It also checks that the length is correct and provides a bit more type - * safety. - */ -public class Sha256Hash implements Serializable, Comparable { - - public static final int LENGTH = 32; // bytes - public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]); - - private final byte[] bytes; - - private long blockNum; - - - /** - * constructor. - */ - - public Sha256Hash(long num, byte[] hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - this.blockNum = num; - } - - /** - * constructor. - */ - - public Sha256Hash(long num, Sha256Hash hash) { - byte[] rawHashBytes = this.generateBlockId(num, hash); - checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - this.blockNum = num; - } - - /** - * Use {@link #wrap(byte[])} instead. - */ - @Deprecated - public Sha256Hash(byte[] rawHashBytes) { - checkArgument(rawHashBytes.length == LENGTH); - this.bytes = rawHashBytes; - } - - /** - * Creates a new instance that wraps the given hash value. - * - * @param rawHashBytes the raw hash bytes to wrap - * @return a new instance - * @throws IllegalArgumentException if the given array length is not exactly 32 - */ - @SuppressWarnings("deprecation") // the constructor will be made private in the future - public static Sha256Hash wrap(byte[] rawHashBytes) { - return new Sha256Hash(rawHashBytes); - } - - public static Sha256Hash wrap(ByteString rawHashByteString) { - return wrap(rawHashByteString.toByteArray()); - } - - /** - * Use {@link #of(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Hash create(boolean isSha256, byte[] contents) { - return of(isSha256, contents); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - */ - public static Sha256Hash of(boolean isSha256, byte[] contents) { - return wrap(hash(isSha256, contents)); - } - - /** - * Creates a new instance containing the calculated (one-time) hash of the given file's contents. - * The file contents are read fully into memory, so this method should only be used with small - * files. - * - * @param file the file on which the hash value is calculated - * @return a new instance containing the calculated (one-time) hash - * @throws IOException if an error occurs while reading the file - */ - public static Sha256Hash of(boolean isSha256, File file) throws IOException { - - try (FileInputStream in = new FileInputStream(file)) { - return of(isSha256, ByteStreams.toByteArray(in)); - } - } - - /** - * Use {@link #twiceOf(byte[])} instead: this old name is ambiguous. - */ - @Deprecated - public static Sha256Hash createDouble(boolean isSha256, byte[] contents) { - return twiceOf(isSha256, contents); - } - - /** - * Creates a new instance containing the hash of the calculated hash of the given bytes. - * - * @param contents the bytes on which the hash value is calculated - * @return a new instance containing the calculated (two-time) hash - */ - public static Sha256Hash twiceOf(boolean isSha256, byte[] contents) { - return wrap(hashTwice(isSha256, contents)); - } - - /** - * Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the - * checked exception that can never occur with a RuntimeException. - * - * @return a new SHA-256 MessageDigest instance - */ - public static MessageDigest newDigest() { - try { - return MessageDigest.getInstance("SHA-256"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); // Can't happen. - } - } - - /** - * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked - * exception that can never occur with a RuntimeException. - * - * @return a new SM3 MessageDigest instance - */ - public static SM3Digest newSM3Digest() { - return new SM3Digest(); - } - - /** - * Calculates the SHA-256 hash of the given bytes. - * - * @param input the bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(boolean isSha256, byte[] input) { - return hash(isSha256, input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the hash (in big-endian order) - */ - public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - } - - /** - * Calculates the SHA-256 hash of the given bytes, and then hashes the resulting hash again. - * - * @param input the bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(boolean isSha256, byte[] input) { - return hashTwice(isSha256, input, 0, input.length); - } - - /** - * Calculates the SHA-256 hash of the given byte range, and then hashes the resulting hash again. - * - * @param input the array containing the bytes to hash - * @param offset the offset within the array of the bytes to hash - * @param length the number of bytes to hash - * @return the double-hash (in big-endian order) - */ - public static byte[] hashTwice(boolean isSha256, byte[] input, int offset, int length) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input, offset, length); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input, offset, length); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - digest.reset(); - digest.update(eHash, 0, eHash.length); - digest.doFinal(eHash, 0); - return eHash; - } - } - - /** - * Calculates the hash of hash on the given byte ranges. This is equivalent to concatenating the - * two ranges and then passing the result to {@link #hashTwice(byte[])}. - */ - public static byte[] hashTwice(boolean isSha256, byte[] input1, int offset1, int length1, - byte[] input2, int offset2, int length2) { - if (isSha256) { - MessageDigest digest = newDigest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - return digest.digest(digest.digest()); - } else { - SM3Digest digest = newSM3Digest(); - digest.update(input1, offset1, length1); - digest.update(input2, offset2, length2); - byte[] eHash = new byte[digest.getDigestSize()]; - digest.doFinal(eHash, 0); - return eHash; - } - } - - private byte[] generateBlockId(long blockNum, Sha256Hash blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = blockHash.getBytes(); - System.arraycopy(numBytes, 0, hash, 0, 8); - return hash; - } - - private byte[] generateBlockId(long blockNum, byte[] blockHash) { - byte[] numBytes = Longs.toByteArray(blockNum); - byte[] hash = blockHash; - System.arraycopy(numBytes, 0, hash, 0, 8); - return hash; - } - - public long getBlockNum() { - return blockNum; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || !(o instanceof Sha256Hash)) { - return false; - } - return Arrays.equals(bytes, ((Sha256Hash) o).bytes); - } - - @Override - public String toString() { - return ByteArray.toHexString(bytes); - } - - /** - * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable - * hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e. - * the value as a big integer lower than the target value). - */ - @Override - public int hashCode() { - // Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin. - return Ints - .fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]); - } - - /** - * Returns the bytes interpreted as a positive integer. - */ - public BigInteger toBigInteger() { - return new BigInteger(1, bytes); - } - - /** - * Returns the internal byte array, without defensively copying. Therefore do NOT modify the - * returned array. - */ - public byte[] getBytes() { - return bytes; - } - - /** - * For pb return ByteString. - */ - public ByteString getByteString() { - return ByteString.copyFrom(bytes); - } - - @Override - public int compareTo(final Sha256Hash other) { - for (int i = LENGTH - 1; i >= 0; i--) { - final int thisByte = this.bytes[i] & 0xff; - final int otherByte = other.bytes[i] & 0xff; - if (thisByte > otherByte) { - return 1; - } - if (thisByte < otherByte) { - return -1; - } - } - return 0; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldWrapper.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldWrapper.java deleted file mode 100644 index 52290587fc7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldWrapper.java +++ /dev/null @@ -1,427 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.netty.util.internal.StringUtil; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; -import lombok.Getter; -import lombok.Setter; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DecryptNotes.NoteTx; -import org.tron.api.GrpcAPI.IvkDecryptParameters; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.NoteParameters; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import stest.tron.wallet.common.client.Configuration; - -//import org.tron.walletserver.WalletApi; -//import stest.tron.wallet.common.client.Parameter.CommonConstant; - -public class ShieldWrapper { - - private static final String PREFIX_FOLDER = "WalletShield"; - private static final String IVK_AND_NUM_FILE_NAME = PREFIX_FOLDER + "/scanblocknumber"; - private static final String UNSPEND_NOTE_FILE_NAME = PREFIX_FOLDER + "/unspendnote"; - private static final String SPEND_NOTE_FILE_NAME = PREFIX_FOLDER + "/spendnote"; - private static final String SHIELD_ADDRESS_FILE_NAME = PREFIX_FOLDER + "/shieldaddress"; - //private WalletApi wallet; - private static AtomicLong nodeIndex = new AtomicLong(0L); - @Getter - @Setter - public Map ivkMapScanBlockNum = new ConcurrentHashMap(); - @Getter - @Setter - public Map utxoMapNote = new ConcurrentHashMap(); - - //Wallet wallet = new Wallet(); - @Getter - @Setter - public List spendUtxoList = new ArrayList<>(); - @Setter - @Getter - Map shieldAddressInfoMap = new ConcurrentHashMap(); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - private WalletGrpc.WalletBlockingStub blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - private Thread thread; - @Setter - private boolean resetNote = false; - - /* public void setWallet(WalletApi walletApi) { - wallet = walletApi; - if (!thread.isAlive()) { - thread.start(); - } - }*/ - - private void resetShieldNote() { - ivkMapScanBlockNum.clear(); - for (Entry entry : getShieldAddressInfoMap().entrySet()) { - ivkMapScanBlockNum.put(ByteArray.toHexString(entry.getValue().getIvk()), 0L); - } - - utxoMapNote.clear(); - spendUtxoList.clear(); - - ZenUtils.clearFile(IVK_AND_NUM_FILE_NAME); - ZenUtils.clearFile(UNSPEND_NOTE_FILE_NAME); - ZenUtils.clearFile(SPEND_NOTE_FILE_NAME); - nodeIndex.set(0L); - - updateIvkAndBlockNumFile(); - } - - private void scanBlockByIvk() { - try { - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(-1); - Block block = blockingStubFull.getBlockByNum(builder1.build()); - if (block != null) { - long blockNum = block.getBlockHeader().toBuilder().getRawData().getNumber(); - for (Entry entry : ivkMapScanBlockNum.entrySet()) { - - long start = entry.getValue(); - long end = start; - while (end < blockNum) { - if (blockNum - start > 1000) { - end = start + 1000; - } else { - end = blockNum; - } - - IvkDecryptParameters.Builder builder = IvkDecryptParameters.newBuilder(); - builder.setStartBlockIndex(start); - builder.setEndBlockIndex(end); - builder.setIvk(ByteString.copyFrom(ByteArray.fromHexString(entry.getKey()))); - DecryptNotes notes = blockingStubFull.scanNoteByIvk(builder.build()); - if (notes != null) { - for (int i = 0; i < notes.getNoteTxsList().size(); ++i) { - NoteTx noteTx = notes.getNoteTxsList().get(i); - ShieldNoteInfo noteInfo = new ShieldNoteInfo(); - noteInfo.setPaymentAddress(noteTx.getNote().getPaymentAddress()); - noteInfo.setR(noteTx.getNote().getRcm().toByteArray()); - noteInfo.setValue(noteTx.getNote().getValue()); - noteInfo.setTrxId(ByteArray.toHexString(noteTx.getTxid().toByteArray())); - noteInfo.setIndex(noteTx.getIndex()); - noteInfo.setNoteIndex(nodeIndex.getAndIncrement()); - noteInfo.setMemo(noteTx.getNote().getMemo().toByteArray()); - - utxoMapNote.put(noteInfo.getNoteIndex(), noteInfo); - } - saveUnspendNoteToFile(); - } - start = end; - } - - ivkMapScanBlockNum.put(entry.getKey(), blockNum); - } - updateIvkAndBlockNumFile(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void updateNoteWhetherSpend() { - try { - for (Entry entry : utxoMapNote.entrySet()) { - ShieldNoteInfo noteInfo = entry.getValue(); - - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(ByteArray.fromHexString(noteInfo.getTrxId()))); - outPointBuild.setIndex(noteInfo.getIndex()); - request.addOutPoints(outPointBuild.build()); - - IncrementalMerkleVoucherInfo merkleVoucherInfo = blockingStubFull.getMerkleTreeVoucherInfo( - request.build()); - if (merkleVoucherInfo.getVouchersCount() > 0) { - ShieldAddressInfo addressInfo = getShieldAddressInfoMap().get( - noteInfo.getPaymentAddress()); - NoteParameters.Builder builder = NoteParameters.newBuilder(); - builder.setAk(ByteString.copyFrom(addressInfo.getFullViewingKey().getAk())); - builder.setNk(ByteString.copyFrom(addressInfo.getFullViewingKey().getNk())); - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(noteInfo.getPaymentAddress()); - noteBuild.setValue(noteInfo.getValue()); - noteBuild.setRcm(ByteString.copyFrom(noteInfo.getR())); - noteBuild.setMemo(ByteString.copyFrom(noteInfo.getMemo())); - builder.setNote(noteBuild.build()); - //builder.setVoucher(merkleVoucherInfo.getVouchers(0)); - - SpendResult result = blockingStubFull.isSpend(builder.build()); - - if (result.getResult()) { - spendNote(entry.getKey()); - } - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public boolean init() { - ZenUtils.checkFolderExist(PREFIX_FOLDER); - - loadAddressFromFile(); - loadIvkFromFile(); - loadUnSpendNoteFromFile(); - loadSpendNoteFromFile(); - - thread = new Thread(new scanIvkRunable()); - return true; - } - - /** - * constructor. - */ - public boolean spendNote(long noteIndex) { - ShieldNoteInfo noteInfo = utxoMapNote.get(noteIndex); - if (noteInfo != null) { - utxoMapNote.remove(noteIndex); - spendUtxoList.add(noteInfo); - - saveUnspendNoteToFile(); - saveSpendNoteToFile(noteInfo); - } else { - System.err.println("Find note failure. index:" + noteIndex); - } - return true; - } - - /** - * constructor. - */ - public boolean addNewShieldAddress(final ShieldAddressInfo addressInfo) { - appendAddressInfoToFile(addressInfo); - long blockNum = 0; - try { - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(-1); - Block block = blockingStubFull.getBlockByNum(builder1.build()); - if (block != null) { - blockNum = block.getBlockHeader().toBuilder().getRawData().getNumber(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - ivkMapScanBlockNum.put(ByteArray.toHexString(addressInfo.getIvk()), blockNum); - updateIvkAndBlockNum(ByteArray.toHexString(addressInfo.getIvk()), blockNum); - - return true; - } - - /** - * constructor. - */ - private boolean updateIvkAndBlockNum(final String ivk, long blockNum) { - synchronized (IVK_AND_NUM_FILE_NAME) { - String date = ivk + ";" + blockNum; - ZenUtils.appendToFileTail(IVK_AND_NUM_FILE_NAME, date); - } - return true; - } - - /** - * constructor. - */ - private boolean updateIvkAndBlockNumFile() { - synchronized (IVK_AND_NUM_FILE_NAME) { - ZenUtils.clearFile(IVK_AND_NUM_FILE_NAME); - for (Entry entry : ivkMapScanBlockNum.entrySet()) { - String date = entry.getKey() + ";" + entry.getValue(); - ZenUtils.appendToFileTail(IVK_AND_NUM_FILE_NAME, date); - } - } - return true; - } - - /** - * constructor. - */ - private boolean loadIvkFromFile() { - ivkMapScanBlockNum.clear(); - List list = ZenUtils.getListFromFile(IVK_AND_NUM_FILE_NAME); - for (int i = 0; i < list.size(); ++i) { - String[] sourceStrArray = list.get(i).split(";"); - if (sourceStrArray.length != 2) { - System.err.println("len is not right."); - return false; - } - ivkMapScanBlockNum.put(sourceStrArray[0], Long.valueOf(sourceStrArray[1])); - } - return true; - } - - /** - * get shield address list. - */ - public List getShieldAddressList() { - List addressList = new ArrayList<>(); - for (Entry entry : shieldAddressInfoMap.entrySet()) { - addressList.add(entry.getKey()); - } - return addressList; - } - - /** - * update unspend note. - */ - private boolean saveUnspendNoteToFile() { - ZenUtils.clearFile(UNSPEND_NOTE_FILE_NAME); - for (Entry entry : utxoMapNote.entrySet()) { - String date = entry.getValue().encode(); - ZenUtils.appendToFileTail(UNSPEND_NOTE_FILE_NAME, date); - } - return true; - } - - /** - * load unspend note from file. - */ - private boolean loadUnSpendNoteFromFile() { - utxoMapNote.clear(); - - List list = ZenUtils.getListFromFile(UNSPEND_NOTE_FILE_NAME); - for (int i = 0; i < list.size(); ++i) { - ShieldNoteInfo noteInfo = new ShieldNoteInfo(); - noteInfo.decode(list.get(i)); - utxoMapNote.put(noteInfo.getNoteIndex(), noteInfo); - - if (noteInfo.getNoteIndex() > nodeIndex.get()) { - nodeIndex.set(noteInfo.getNoteIndex()); - } - } - return true; - } - - /** - * append spend note to file tail. - */ - private boolean saveSpendNoteToFile(ShieldNoteInfo noteInfo) { - String date = noteInfo.encode(); - ZenUtils.appendToFileTail(SPEND_NOTE_FILE_NAME, date); - return true; - } - - /** - * load spend note from file. - */ - private boolean loadSpendNoteFromFile() { - spendUtxoList.clear(); - List list = ZenUtils.getListFromFile(SPEND_NOTE_FILE_NAME); - for (int i = 0; i < list.size(); ++i) { - ShieldNoteInfo noteInfo = new ShieldNoteInfo(); - noteInfo.decode(list.get(i)); - spendUtxoList.add(noteInfo); - } - return true; - } - - /** - * load shield address from file. - */ - public boolean loadAddressFromFile() { - List addressList = ZenUtils.getListFromFile(SHIELD_ADDRESS_FILE_NAME); - - shieldAddressInfoMap.clear(); - for (String addressString : addressList) { - ShieldAddressInfo addressInfo = new ShieldAddressInfo(); - if (addressInfo.decode(addressString)) { - shieldAddressInfoMap.put(addressInfo.getAddress(), addressInfo); - } else { - System.out.println("*******************"); - } - } - return true; - } - - /** - * constructor. - */ - public boolean appendAddressInfoToFile(final ShieldAddressInfo addressInfo) { - String shieldAddress = addressInfo.getAddress(); - if (!StringUtil.isNullOrEmpty(shieldAddress)) { - String addressString = addressInfo.encode(); - ZenUtils.appendToFileTail(SHIELD_ADDRESS_FILE_NAME, addressString); - - shieldAddressInfoMap.put(shieldAddress, addressInfo); - } - return true; - } - - /** - * sort by value of UTXO. - */ - public List getvalidateSortUtxoList() { - List> list = new ArrayList<>(utxoMapNote.entrySet()); - Collections.sort(list, (Entry o1, Entry o2) -> { - if (o1.getValue().getValue() < o2.getValue().getValue()) { - return 1; - } else { - return -1; - } - }); - - List utxoList = new ArrayList<>(); - for (Map.Entry entry : list) { - String string = entry.getKey() + " " + entry.getValue().getPaymentAddress() + " "; - string += entry.getValue().getValue(); - string += " "; - string += entry.getValue().getTrxId(); - string += " "; - string += entry.getValue().getIndex(); - string += " "; - string += "UnSpend"; - string += " "; - string += ZenUtils.getMemo(entry.getValue().getMemo()); - utxoList.add(string); - } - return utxoList; - } - - public class scanIvkRunable implements Runnable { - - public void run() { - for (; ; ) { - try { - scanBlockByIvk(); - updateNoteWhetherSpend(); - //wait for 2.5 seconds - for (int i = 0; i < 5; ++i) { - Thread.sleep(500); - if (resetNote) { - resetShieldNote(); - resetNote = false; - System.out.println("Reset shield note success!"); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedAddressInfo.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedAddressInfo.java deleted file mode 100644 index b1bbf70cc80..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedAddressInfo.java +++ /dev/null @@ -1,122 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.util.Arrays; -import java.util.Optional; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.Setter; -import org.tron.common.utils.Base58; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.zen.address.DiversifierT; -import org.tron.core.zen.address.FullViewingKey; -import org.tron.core.zen.address.IncomingViewingKey; -import org.tron.core.zen.address.KeyIo; -import org.tron.core.zen.address.PaymentAddress; -import org.tron.core.zen.address.SpendingKey; - -@AllArgsConstructor -public class ShieldedAddressInfo { - - @Setter - @Getter - public byte[] sk; - @Setter - @Getter - public byte[] ivk; // 256 - @Setter - @Getter - public byte[] ovk; // 256 - @Setter - @Getter - DiversifierT d; - @Setter - @Getter - byte[] pkD; // 256 - - public ShieldedAddressInfo() { - } - - public FullViewingKey getFullViewingKey() throws ZksnarkException { - SpendingKey spendingKey = new SpendingKey(sk); - return spendingKey.fullViewingKey(); - } - - /** - * check parameters - */ - public boolean validateCheck() { - try { - SpendingKey spendingKey = new SpendingKey(sk); - FullViewingKey fullViewingKey = spendingKey.fullViewingKey(); - if (!Arrays.equals(fullViewingKey.getOvk(), ovk)) { - System.out.println("ovk check failure!"); - return false; - } - IncomingViewingKey incomingViewingKey = fullViewingKey.inViewingKey(); - if (!Arrays.equals(incomingViewingKey.getValue(), ivk)) { - System.out.println("ivk check failure!"); - return false; - } - Optional optionalPaymentAddress = incomingViewingKey.address(d); - if (!optionalPaymentAddress.isPresent() - || !Arrays.equals(optionalPaymentAddress.get().getPkD(), pkD)) { - System.out.println("pkd check failure!"); - return false; - } - return true; - } catch (Exception e) { - e.printStackTrace(); - } - return false; - } - - public String getAddress() { - return getShieldedAddress(d, pkD); - } - - public static String getShieldedAddress(DiversifierT d, byte[] pkD) { - try { - PaymentAddress paymentAddress = new PaymentAddress(d, pkD); - return KeyIo.encodePaymentAddress(paymentAddress); - } catch (Exception e) { - e.printStackTrace(); - } - return ""; - } - - /** - * format shielded address info to a string - */ - public String encode(byte[] encryptKey) throws CipherException { - byte[] text = new byte[sk.length + ivk.length + ovk.length + d.getData().length + pkD.length]; - System.arraycopy(sk, 0, text, 0, sk.length); - System.arraycopy(ivk, 0, text, sk.length, ivk.length); - System.arraycopy(ovk, 0, text, sk.length + ivk.length, ovk.length); - System.arraycopy(d.getData(), 0, text, sk.length + ivk.length + ovk.length, d.getData().length); - System.arraycopy(pkD, 0, text, sk.length + ivk.length + ovk.length + d.getData().length, - pkD.length); - - byte[] cipherText = ZenUtils.aesCtrEncrypt(text, encryptKey); - return Base58.encode(cipherText); - } - - /** - * parse string to get a shielded address info - */ - public boolean decode(final String data, byte[] encryptKey) throws CipherException { - byte[] cipherText = Base58.decode(data); - byte[] text = ZenUtils.aesCtrDecrypt(cipherText, encryptKey); - - sk = Arrays.copyOfRange(text, 0, 32); - ivk = Arrays.copyOfRange(text, 32, 64); - ovk = Arrays.copyOfRange(text, 64, 96); - d = new DiversifierT(Arrays.copyOfRange(text, 96, 107)); - pkD = Arrays.copyOfRange(text, 107, 139); - - if (validateCheck()) { - return true; - } else { - return false; - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedTRC20NoteInfo.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedTRC20NoteInfo.java deleted file mode 100644 index 96b38ce06c0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ShieldedTRC20NoteInfo.java +++ /dev/null @@ -1,96 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import io.netty.util.internal.StringUtil; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.Setter; -import org.tron.common.utils.Base58; -import org.tron.common.utils.ByteArray; - -@AllArgsConstructor -public class ShieldedTRC20NoteInfo { - - @Setter - @Getter - public long value = 0; - @Setter - @Getter - public String paymentAddress; - @Setter - @Getter - public byte[] r; // 256 - @Setter - @Getter - public String trxId; - @Setter - @Getter - public int index; - @Setter - @Getter - public long noteIndex; - @Setter - @Getter - public long position; - @Setter - @Getter - public byte[] memo; - - public ShieldedTRC20NoteInfo() { - } - - /** - * format shieldedTRC20 note to a string - */ - public String encode(byte[] encryptKey) throws CipherException { - String encodeString = noteIndex + ";"; - encodeString += paymentAddress; - encodeString += ";"; - encodeString += ByteArray.toHexString(r); - encodeString += ";"; - encodeString += trxId; - encodeString += ";"; - encodeString += String.valueOf(value); - encodeString += ";"; - encodeString += String.valueOf(index); - encodeString += ";"; - encodeString += String.valueOf(position); - encodeString += ";"; - String stringMemo = ByteArray.toHexString(memo); - if (StringUtil.isNullOrEmpty(stringMemo)) { - encodeString += "null"; - } else { - encodeString += stringMemo; - } - byte[] chipherText = ZenUtils.aesCtrEncrypt(encodeString.getBytes(), encryptKey); - encodeString = Base58.encode(chipherText); - return encodeString; - } - - /** - * parse string to get shieldedTRC20 note - */ - public boolean decode(String data, byte[] encryptKey) throws CipherException { - byte[] chipherText = Base58.decode(data); - byte[] text = ZenUtils.aesCtrDecrypt(chipherText, encryptKey); - data = new String(text); - - String[] sourceStrArray = data.split(";"); - if (sourceStrArray.length != 8) { - System.out.println("len is not right."); - return false; - } - noteIndex = Long.valueOf(sourceStrArray[0]); - paymentAddress = sourceStrArray[1]; - r = ByteArray.fromHexString(sourceStrArray[2]); - trxId = sourceStrArray[3]; - value = Long.valueOf(sourceStrArray[4]); - index = Integer.valueOf(sourceStrArray[5]); - position = Long.valueOf(sourceStrArray[6]); - if (sourceStrArray[7].equals("null")) { - memo = ByteArray.fromHexString(""); - } else { - memo = ByteArray.fromHexString(sourceStrArray[7]); - } - return true; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java deleted file mode 100644 index ac77484cc2f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenTrc20Base.java +++ /dev/null @@ -1,1724 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; -import io.netty.util.internal.StringUtil; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.ShieldedTRC20Parameters; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.core.Wallet; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.zen.address.DiversifierT; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.ShieldContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class ZenTrc20Base { - - public final String foundationAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - public static final String zenTrc20TokenOwnerKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTrc20TokenOwnerKey"); - public static final byte[] zenTrc20TokenOwnerAddress = PublicMethed - .getFinalAddress(zenTrc20TokenOwnerKey); - public static final String zenTrc20TokenOwnerAddressString = PublicMethed - .getAddressString(zenTrc20TokenOwnerKey); - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - public com.google.protobuf.ByteString contractAddressByteString; - public static byte[] contractAddressByte; - public static String contractAddress; - public static com.google.protobuf.ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployShieldTrc20Txid; - public static String deployShieldTxid; - public static String mint = "mint(uint256,bytes32[9],bytes32[2],bytes32[21])"; - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public static String burn = "burn(bytes32[10],bytes32[2],uint256,bytes32[2],address," - + "bytes32[3],bytes32[9][],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - static JSONObject responseContent; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - - - /** - * constructor. - */ - @BeforeSuite(enabled = true, description = "Deploy shield trc20 depend contract") - public void deployShieldTrc20DependContract() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - getDailyBuildStartNum(); - Assert.assertTrue(PublicMethed.sendcoin(zenTrc20TokenOwnerAddress, 10000000000000L, - foundationAccountAddress, foundationAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployShieldTrc20Txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - zenTrc20TokenOwnerKey, zenTrc20TokenOwnerAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTrc20Txid); - Optional infoById = PublicMethed - .getTransactionInfoById(deployShieldTrc20Txid, blockingStubFull); - contractAddressByteString = infoById.get().getContractAddress(); - contractAddressByte = infoById.get().getContractAddress().toByteArray(); - contractAddress = Base58.encode58Check(contractAddressByte); - logger.info(contractAddress); - - contractName = "shield"; - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_shield"); - code = Configuration.getByPath("testng.conf") - .getString("code.code_shield"); - data = "\"" + contractAddress + "\"" + "," + scalingFactorLogarithm; - constructorStr = "constructor(address,uint256)"; - deployShieldTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - zenTrc20TokenOwnerKey, zenTrc20TokenOwnerAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTxid); - infoById = PublicMethed - .getTransactionInfoById(deployShieldTxid, blockingStubFull); - shieldAddressByteString = infoById.get().getContractAddress(); - shieldAddressByte = infoById.get().getContractAddress().toByteArray(); - shieldAddress = Base58.encode58Check(shieldAddressByte); - logger.info(shieldAddress); - - data = "\"" + shieldAddress + "\"" + "," + totalSupply.toString(); - String txid = PublicMethed.triggerContract(contractAddressByte, - "approve(address,uint256)", data, false, - 0, maxFeeLimit, zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("approve:" + txid); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - - } - - /** - * constructor. - */ - public void getDailyBuildStartNum() { - DailyBuildReport.startBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder() - .build()).getBlockHeader().getRawData().getNumber(); - System.out.println("!!!!!!! 222222222startnum:" + DailyBuildReport.startBlockNum); - } - - - /** - * constructor. - */ - public GrpcAPI.ShieldedTRC20Parameters createShieldedTrc20Parameters(BigInteger publicFromAmount, - GrpcAPI.DecryptNotesTRC20 inputNoteList, List shieldedAddressInfoList, - List outputNoteList, String publicToAddress, Long pubicToAmount, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws ZksnarkException { - - GrpcAPI.PrivateShieldedTRC20Parameters.Builder builder - = GrpcAPI.PrivateShieldedTRC20Parameters.newBuilder(); - - //Mint type should set public from amount to parameter - if (publicFromAmount.compareTo(BigInteger.ZERO) > 0) { - builder.setFromAmount(publicFromAmount.toString()); - } - - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - long valueBalance = 0; - - if (inputNoteList != null) { - logger.info("Enter transfer type code"); - List rootAndPath = new ArrayList<>(); - for (int i = 0; i < inputNoteList.getNoteTxsCount(); i++) { - long position = inputNoteList.getNoteTxs(i).getPosition(); - rootAndPath.add(getRootAndPath(position, blockingStubSolidity)); - } - if (rootAndPath.isEmpty() || rootAndPath.size() != inputNoteList.getNoteTxsCount()) { - System.out.println("Can't get all merkle tree, please check the notes."); - return null; - } - for (int i = 0; i < rootAndPath.size(); i++) { - if (rootAndPath.get(i) == null) { - System.out.println("Can't get merkle path, please check the note " + i + "."); - return null; - } - } - - for (int i = 0; i < inputNoteList.getNoteTxsCount(); ++i) { - if (i == 0) { - String shieldedAddress = inputNoteList.getNoteTxs(i).getNote().getPaymentAddress(); - - String spendingKey = ByteArray.toHexString(shieldedAddressInfoList.get(0).getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - //ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(esk.get().getAsk()); - builder.setNsk(esk.get().getNsk()); - builder.setOvk(esk.get().getOvk()); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldedAddressInfoList.get(0).getAddress()); - noteBuild.setValue(inputNoteList.getNoteTxs(i).getNote().getValue()); - noteBuild.setRcm(inputNoteList.getNoteTxs(i).getNote().getRcm()); - noteBuild.setMemo(inputNoteList.getNoteTxs(i).getNote().getMemo()); - - System.out.println("address " + shieldedAddressInfoList.get(0).getAddress()); - System.out.println("value " + inputNoteList.getNoteTxs(i).getNote().getValue()); - System.out.println("trxId " + inputNoteList.getNoteTxs(i).getTxid()); - System.out.println("index " + inputNoteList.getNoteTxs(i).getIndex()); - System.out.println("position " + inputNoteList.getNoteTxs(i).getPosition()); - - byte[] eachRootAndPath = ByteArray.fromHexString(rootAndPath.get(i)); - byte[] root = Arrays.copyOfRange(eachRootAndPath, 0, 32); - byte[] path = Arrays.copyOfRange(eachRootAndPath, 32, 1056); - GrpcAPI.SpendNoteTRC20.Builder spendTrc20NoteBuilder = GrpcAPI.SpendNoteTRC20.newBuilder(); - spendTrc20NoteBuilder.setNote(noteBuild.build()); - spendTrc20NoteBuilder.setAlpha(ByteString.copyFrom(blockingStubFull.getRcm( - EmptyMessage.newBuilder().build()).getValue().toByteArray())); - spendTrc20NoteBuilder.setRoot(ByteString.copyFrom(root)); - spendTrc20NoteBuilder.setPath(ByteString.copyFrom(path)); - spendTrc20NoteBuilder.setPos(inputNoteList.getNoteTxs(i).getPosition()); - - valueBalance = Math.addExact(valueBalance, inputNoteList.getNoteTxs(i).getNote() - .getValue()); - builder.addShieldedSpends(spendTrc20NoteBuilder.build()); - } - } else { - //@TODO remove randomOvk by sha256.of(privateKey) - byte[] ovk = getRandomOvk(); - if (ovk != null) { - builder.setOvk(ByteString.copyFrom(ovk)); - } else { - System.out.println("Get random ovk from Rpc failure,please check config"); - return null; - } - } - - if (outputNoteList != null) { - for (int i = 0; i < outputNoteList.size(); i++) { - GrpcAPI.Note note = outputNoteList.get(i); - valueBalance = Math.subtractExact(valueBalance, note.getValue()); - builder.addShieldedReceives( - GrpcAPI.ReceiveNote.newBuilder().setNote(note).build()); - } - } - - if (!StringUtil.isNullOrEmpty(publicToAddress)) { - byte[] to = Commons.decodeFromBase58Check(publicToAddress); - if (to == null) { - return null; - } - builder.setTransparentToAddress(ByteString.copyFrom(to)); - builder.setToAmount(pubicToAmount.toString()); - } - - try { - return blockingStubFull.createShieldedContractParameters(builder.build()); - } catch (Exception e) { - Status status = Status.fromThrowable(e); - System.out.println("createShieldedContractParameters failed,error " - + status.getDescription()); - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.ShieldedTRC20Parameters createShieldedTrc20ParametersWithoutAsk( - BigInteger publicFromAmount, - GrpcAPI.DecryptNotesTRC20 inputNoteList, List shieldedAddressInfoList, - List outputNoteList, String publicToAddress, byte[] receiverAddressbyte, - Long pubicToAmount, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws ZksnarkException { - - GrpcAPI.PrivateShieldedTRC20ParametersWithoutAsk.Builder builder - = GrpcAPI.PrivateShieldedTRC20ParametersWithoutAsk.newBuilder(); - - //Mint type should set public from amount to parameter - if (publicFromAmount.compareTo(BigInteger.ZERO) > 0) { - builder.setFromAmount(publicFromAmount.toString()); - } - - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - - long valueBalance = 0; - byte[] ask = new byte[32]; - if (inputNoteList != null) { - List rootAndPath = new ArrayList<>(); - for (int i = 0; i < inputNoteList.getNoteTxsCount(); i++) { - long position = inputNoteList.getNoteTxs(i).getPosition(); - rootAndPath.add(getRootAndPath(position, blockingStubSolidity)); - } - if (rootAndPath.isEmpty() || rootAndPath.size() != inputNoteList.getNoteTxsCount()) { - System.out.println("Can't get all merkle tree, please check the notes."); - return null; - } - for (int i = 0; i < rootAndPath.size(); i++) { - if (rootAndPath.get(i) == null) { - System.out.println("Can't get merkle path, please check the note " + i + "."); - return null; - } - } - - for (int i = 0; i < inputNoteList.getNoteTxsCount(); ++i) { - if (i == 0) { - String spendingKey = ByteArray.toHexString(shieldedAddressInfoList.get(i).getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - System.arraycopy(esk.get().getAsk().toByteArray(), 0, ask, 0, 32); - - String ask1 = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask2 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask1))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask2)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - - builder.setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))); - builder.setOvk(esk.get().getOvk()); - builder.setNsk(esk.get().getNsk()); - - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldedAddressInfoList.get(i).getAddress()); - noteBuild.setValue(inputNoteList.getNoteTxs(i).getNote().getValue()); - noteBuild.setRcm(inputNoteList.getNoteTxs(i).getNote().getRcm()); - noteBuild.setMemo(inputNoteList.getNoteTxs(i).getNote().getMemo()); - - System.out.println("address " + shieldedAddressInfoList.get(i).getAddress()); - System.out.println("value " + inputNoteList.getNoteTxs(i).getNote().getValue()); - System.out.println("trxId " + ByteArray.toHexString(inputNoteList.getNoteTxs(i) - .getTxid().toByteArray())); - System.out.println("index " + inputNoteList.getNoteTxs(i).getIndex()); - System.out.println("position " + inputNoteList.getNoteTxs(i).getPosition()); - - byte[] eachRootAndPath = ByteArray.fromHexString(rootAndPath.get(i)); - byte[] root = Arrays.copyOfRange(eachRootAndPath, 0, 32); - byte[] path = Arrays.copyOfRange(eachRootAndPath, 32, 1056); - GrpcAPI.SpendNoteTRC20.Builder spendTrc20NoteBuilder = GrpcAPI.SpendNoteTRC20.newBuilder(); - spendTrc20NoteBuilder.setNote(noteBuild.build()); - spendTrc20NoteBuilder.setAlpha(ByteString.copyFrom(blockingStubFull.getRcm( - EmptyMessage.newBuilder().build()).getValue().toByteArray())); - spendTrc20NoteBuilder.setRoot(ByteString.copyFrom(root)); - spendTrc20NoteBuilder.setPath(ByteString.copyFrom(path)); - spendTrc20NoteBuilder.setPos(inputNoteList.getNoteTxs(i).getPosition()); - - builder.addShieldedSpends(spendTrc20NoteBuilder.build()); - valueBalance = Math.addExact(valueBalance, inputNoteList.getNoteTxs(i) - .getNote().getValue()); - } - } else { - //@TODO remove randomOvk by sha256.of(privateKey) - byte[] ovk = getRandomOvk(); - if (ovk != null) { - builder.setOvk(ByteString.copyFrom(ovk)); - } else { - System.out.println("Get random ovk from Rpc failure,please check config"); - return null; - } - } - - if (outputNoteList != null) { - for (int i = 0; i < outputNoteList.size(); i++) { - GrpcAPI.Note note = outputNoteList.get(i); - valueBalance = Math.subtractExact(valueBalance, note.getValue()); - builder.addShieldedReceives( - GrpcAPI.ReceiveNote.newBuilder().setNote(note).build()); - } - } - - if (!StringUtil.isNullOrEmpty(publicToAddress)) { - byte[] to = Commons.decodeFromBase58Check(publicToAddress); - if (to == null) { - return null; - } - builder.setTransparentToAddress(ByteString.copyFrom(to)); - builder.setToAmount(pubicToAmount.toString()); - } - - ShieldedTRC20Parameters parameters = blockingStubFull - .createShieldedContractParametersWithoutAsk(builder.build()); - if (parameters == null) { - System.out.println("createShieldedContractParametersWithoutAsk failed!"); - return null; - } - - GrpcAPI.ShieldedTRC20TriggerContractParameters.Builder stBuilder = - GrpcAPI.ShieldedTRC20TriggerContractParameters.newBuilder(); - stBuilder.setShieldedTRC20Parameters(parameters); - - if (parameters.getParameterType().equals("burn")) { - stBuilder.setAmount(pubicToAmount.toString()); - stBuilder.setTransparentToAddress(ByteString.copyFrom(receiverAddressbyte)); - } - - ByteString messageHash = parameters.getMessageHash(); - List spendDescList = parameters.getSpendDescriptionList(); - ShieldedTRC20Parameters.Builder newBuilder = - ShieldedTRC20Parameters.newBuilder().mergeFrom(parameters); - for (int i = 0; i < spendDescList.size(); i++) { - GrpcAPI.SpendAuthSigParameters.Builder builder1 = GrpcAPI.SpendAuthSigParameters.newBuilder(); - builder1.setAsk(ByteString.copyFrom(ask)); - builder1.setTxHash(messageHash); - builder1.setAlpha(builder.build().getShieldedSpends(i).getAlpha()); - - BytesMessage authSig = blockingStubFull.createSpendAuthSig(builder1.build()); - newBuilder.getSpendDescriptionBuilder(i) - .setSpendAuthoritySignature( - ByteString.copyFrom(authSig.getValue().toByteArray())); - - stBuilder.addSpendAuthoritySignature(authSig); - BytesMessage triggerInputData; - try { - triggerInputData = blockingStubFull.getTriggerInputForShieldedTRC20Contract(stBuilder - .build()); - } catch (Exception e) { - triggerInputData = null; - System.out.println("getTriggerInputForShieldedTRC20Contract error, please retry!"); - } - if (triggerInputData == null) { - return null; - } - newBuilder.setTriggerContractInput(ByteArray.toHexString(triggerInputData.getValue() - .toByteArray())); - - - } - return newBuilder.build(); - } - - - /** - * constructor. - */ - public String getRootAndPath(long position, WalletSolidityGrpc.WalletSolidityBlockingStub - blockingStubSolidity) { - String methodStr = "getPath(uint256)"; - byte[] indexBytes = ByteArray.fromLong(position); - String argsStr = ByteArray.toHexString(indexBytes); - argsStr = "000000000000000000000000000000000000000000000000" + argsStr; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(shieldAddressByte, methodStr, argsStr, - true, 0, 1000000000L, "0", 0, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubSolidity); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - return ByteArray.toHexString(result); - } - - - /** - * constructor. - */ - public String encodeMintParamsToHexString(GrpcAPI.ShieldedTRC20Parameters parameters, - BigInteger value) { - byte[] mergedBytes; - ShieldContract.ReceiveDescription revDesc = parameters.getReceiveDescription(0); - mergedBytes = ByteUtil.merge( - ByteUtil.bigIntegerToBytes(value, 32), - revDesc.getNoteCommitment().toByteArray(), - revDesc.getValueCommitment().toByteArray(), - revDesc.getEpk().toByteArray(), - revDesc.getZkproof().toByteArray(), - parameters.getBindingSignature().toByteArray(), - revDesc.getCEnc().toByteArray(), - revDesc.getCOut().toByteArray(), - new byte[12] - ); - return ByteArray.toHexString(mergedBytes); - } - - /** - * constructor. - */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public Optional getNewShieldedAddress(WalletGrpc.WalletBlockingStub - blockingStubFull) { - ShieldedAddressInfo addressInfo = new ShieldedAddressInfo(); - - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - final Optional d = Optional.of(blockingStubFull.getDiversifier( - EmptyMessage.newBuilder().build())); - - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.get().getAsk()); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(askBuilder.build())); - - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.get().getNsk()); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nskBuilder.build())); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - Optional ivk = Optional.of(blockingStubFull - .getIncomingViewingKey(viewBuilder.build())); - - GrpcAPI.IncomingViewingKeyDiversifierMessage.Builder builder - = GrpcAPI.IncomingViewingKeyDiversifierMessage - .newBuilder(); - builder.setD(d.get()); - builder.setIvk(ivk.get()); - Optional addressMessage = Optional.of(blockingStubFull - .getZenPaymentAddress(builder.build())); - addressInfo.setSk(sk.get().getValue().toByteArray()); - addressInfo.setD(new DiversifierT(d.get().getD().toByteArray())); - addressInfo.setIvk(ivk.get().getIvk().toByteArray()); - addressInfo.setOvk(expandedSpendingKeyMessage.get().getOvk().toByteArray()); - addressInfo.setPkD(addressMessage.get().getPkD().toByteArray()); - - System.out.println("ivk " + ByteArray.toHexString(ivk.get().getIvk().toByteArray())); - System.out.println("ovk " + ByteArray.toHexString(expandedSpendingKeyMessage.get() - .getOvk().toByteArray())); - - return Optional.of(addressInfo); - - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - - /** - * constructor. - */ - public static List addShieldTrc20OutputList(List shieldOutList, - String shieldToAddress, String toAmountString, String menoString, - WalletGrpc.WalletBlockingStub blockingStubFull) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - //noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - noteBuild.setRcm(ByteString.copyFrom(blockingStubFull.getRcm(EmptyMessage.newBuilder().build()) - .getValue().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } - - - /** - * constructor. - */ - public Long getBalanceOfShieldTrc20(String queryAddress, byte[] ownerAddress, - String ownerKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - String paramStr = "\"" + queryAddress + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressByte, "balanceOf(address)", - paramStr, false, 0, 0, "0", 0, - ownerAddress, ownerKey, blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - for (int i = 0; i < hexBalance.length(); i++) { - if (hexBalance.charAt(i) != '0') { - hexBalance = hexBalance.substring(i); - break; - } - } - logger.info(hexBalance); - return Long.parseLong(hexBalance, 16); - } - - - /** - * constructor. - */ - public String getBalanceOfShieldTrc20String(String queryAddress, byte[] ownerAddress, - String ownerKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - String paramStr = "\"" + queryAddress + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressByte, "balanceOf(address)", - paramStr, false, 0, 0, "0", 0, - ownerAddress, ownerKey, blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - for (int i = 0; i < hexBalance.length(); i++) { - if (hexBalance.charAt(i) != '0') { - hexBalance = hexBalance.substring(i); - break; - } - } - logger.info(hexBalance); - return hexBalance; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - Long startNum = currentBlockNum - 90L; - final Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String spendingKey = ByteArray.toHexString(shieldedAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - //System.out.println("ak:" + ByteArray.toHexString(ak.get().getValue().toByteArray())); - - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - //System.out.println("nk:" + ByteArray.toHexString(nk.get().getValue().toByteArray())); - String nkString = ByteArray.toHexString(nk.get().getValue().toByteArray()); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - GrpcAPI.IncomingViewingKeyMessage ivk = blockingStubFull - .getIncomingViewingKey(viewBuilder.build()); - - //ivk.getIvk() - String ivkString = ByteArray.toHexString(ivk.getIvk().toByteArray()); - String ivkStringOld = ByteArray.toHexString(shieldedAddressInfo.getIvk()); - GrpcAPI.IvkDecryptTRC20Parameters parameters = GrpcAPI.IvkDecryptTRC20Parameters - .newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) - .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) - .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) - .build(); - try { - return blockingStubSolidity.scanShieldedTRC20NotesByIvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByIvk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - Long startNum = currentBlockNum - 90L; - final Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String spendingKey = ByteArray.toHexString(shieldedAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - String nkString = ByteArray.toHexString(nk.get().getValue().toByteArray()); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - GrpcAPI.IncomingViewingKeyMessage ivk = blockingStubFull - .getIncomingViewingKey(viewBuilder.build()); - - String ivkString = ByteArray.toHexString(ivk.getIvk().toByteArray()); - GrpcAPI.IvkDecryptTRC20Parameters parameters = GrpcAPI.IvkDecryptTRC20Parameters - .newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) - .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) - .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) - //.setEvents() - .build(); - try { - return blockingStubFull.scanShieldedTRC20NotesByIvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByIvk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByIvkWithRange(ShieldedAddressInfo - shieldedAddressInfo, Long startNum, Long endNum, - WalletGrpc.WalletBlockingStub blockingStubFull) throws Exception { - - String spendingKey = ByteArray.toHexString(shieldedAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String akString = ByteArray.toHexString(ak.get().getValue().toByteArray()); - - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - String nkString = ByteArray.toHexString(nk.get().getValue().toByteArray()); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - GrpcAPI.IncomingViewingKeyMessage ivk = blockingStubFull - .getIncomingViewingKey(viewBuilder.build()); - - String ivkString = ByteArray.toHexString(ivk.getIvk().toByteArray()); - GrpcAPI.DecryptNotesTRC20 result = GrpcAPI.DecryptNotesTRC20.newBuilder().build(); - GrpcAPI.DecryptNotesTRC20 tempNoteTxs; - while (startNum < endNum) { - GrpcAPI.IvkDecryptTRC20Parameters parameters = GrpcAPI.IvkDecryptTRC20Parameters - .newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(startNum + 99) - .setShieldedTRC20ContractAddress(ByteString - .copyFrom(Commons.decode58Check(shieldAddress))) - .setIvk(ByteString.copyFrom(ByteArray.fromHexString(ivkString))) - .setAk(ByteString.copyFrom(ByteArray.fromHexString(akString))) - .setNk(ByteString.copyFrom(ByteArray.fromHexString(nkString))) - .build(); - tempNoteTxs = blockingStubFull.scanShieldedTRC20NotesByIvk(parameters); - logger.info("tempNoteTxs size:" + tempNoteTxs.getNoteTxsCount()); - - result = result.toBuilder().addAllNoteTxs(tempNoteTxs.getNoteTxsList()).build(); - - startNum = startNum + 99; - } - try { - return result; - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByIvk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByOvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - Long startNum = currentBlockNum - 90L; - Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String ovkString = ByteArray.toHexString(shieldedAddressInfo.getOvk()); - GrpcAPI.OvkDecryptTRC20Parameters parameters = GrpcAPI.OvkDecryptTRC20Parameters.newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setOvk(ByteString.copyFrom(ByteArray.fromHexString(ovkString))) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .build(); - - try { - return blockingStubFull.scanShieldedTRC20NotesByOvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByovk failed,error " + status.getDescription()); - - } - return null; - } - - - /** - * constructor. - */ - public GrpcAPI.DecryptNotesTRC20 scanShieldedTrc20NoteByOvk(ShieldedAddressInfo - shieldedAddressInfo, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws Exception { - long currentBlockNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - Long startNum = currentBlockNum - 90L; - Long endNum = currentBlockNum; - if (currentBlockNum < 100) { - startNum = 1L; - } - - String ovkString = ByteArray.toHexString(shieldedAddressInfo.getOvk()); - GrpcAPI.OvkDecryptTRC20Parameters parameters = GrpcAPI.OvkDecryptTRC20Parameters.newBuilder() - .setStartBlockIndex(startNum) - .setEndBlockIndex(endNum) - .setOvk(ByteString.copyFrom(ByteArray.fromHexString(ovkString))) - .setShieldedTRC20ContractAddress(ByteString.copyFrom(Commons.decode58Check(shieldAddress))) - .build(); - - try { - return blockingStubSolidity.scanShieldedTRC20NotesByOvk(parameters); - } catch (Exception e) { - System.out.println(e); - Status status = Status.fromThrowable(e); - System.out.println("ScanShieldedTRC20NoteByovk failed,error " + status.getDescription()); - - } - return null; - } - - /** - * constructor. - */ - public static Boolean getTrc20SpendResult( - ShieldedAddressInfo shieldAddressInfo, GrpcAPI.DecryptNotesTRC20.NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - GrpcAPI.NfTRC20Parameters.Builder builder = GrpcAPI.NfTRC20Parameters.newBuilder(); - - String spendingKey = ByteArray.toHexString(shieldAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - builder.setAk(ak.get().getValue()); - builder.setNk(nk.get().getValue()); - builder.setPosition(noteTx.getPosition()); - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(noteTx.getNote().getRcm()); - noteBuild.setMemo(noteTx.getNote().getMemo()); - builder.setNote(noteBuild.build()); - - Optional result = Optional.of(blockingStubFull - .isShieldedTRC20ContractNoteSpent(builder.build())); - return result.get().getIsSpent(); - } - - - /** - * constructor. - */ - public static Boolean getTrc20SpendResult( - ShieldedAddressInfo shieldAddressInfo, GrpcAPI.DecryptNotesTRC20.NoteTx noteTx, - WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) { - - GrpcAPI.NfTRC20Parameters.Builder builder = GrpcAPI.NfTRC20Parameters.newBuilder(); - - String spendingKey = ByteArray.toHexString(shieldAddressInfo.getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - String ask = ByteArray.toHexString(esk.get().getAsk().toByteArray()); - BytesMessage ask1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(ask))).build(); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(ask1)); - String nsk = ByteArray.toHexString(esk.get().getNsk().toByteArray()); - BytesMessage nsk1 = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(nsk))).build(); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nsk1)); - builder.setAk(ak.get().getValue()); - builder.setNk(nk.get().getValue()); - builder.setPosition(noteTx.getPosition()); - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddressInfo.getAddress()); - noteBuild.setValue(noteTx.getNote().getValue()); - noteBuild.setRcm(noteTx.getNote().getRcm()); - noteBuild.setMemo(noteTx.getNote().getMemo()); - builder.setNote(noteBuild.build()); - - Optional result = Optional.of(blockingStubSolidity - .isShieldedTRC20ContractNoteSpent(builder.build())); - return result.get().getIsSpent(); - } - - - /** - * constructor. - */ - public byte[] getRandomOvk() { - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - return expandedSpendingKeyMessage.get().getOvk().toByteArray(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * constructor. - */ - public BigInteger getRandomAmount() { - Random random = new Random(); - int x = random.nextInt(100000) + 100; - return BigInteger.valueOf(x); - } - - /** - * constructor. - */ - public Long getRandomLongAmount() { - Random random = new Random(); - int x = random.nextInt(100000) + 100; - return Long.valueOf(x); - } - - /** - * constructor. - */ - public String encodeTransferParamsToHexString(GrpcAPI.ShieldedTRC20Parameters parameters) { - byte[] input = new byte[0]; - byte[] spendAuthSig = new byte[0]; - byte[] output = new byte[0]; - byte[] c = new byte[0]; - byte[] bindingSig; - final byte[] mergedBytes; - List spendDescs = parameters.getSpendDescriptionList(); - for (ShieldContract.SpendDescription spendDesc : spendDescs) { - input = ByteUtil.merge(input, - spendDesc.getNullifier().toByteArray(), - spendDesc.getAnchor().toByteArray(), - spendDesc.getValueCommitment().toByteArray(), - spendDesc.getRk().toByteArray(), - spendDesc.getZkproof().toByteArray() - ); - spendAuthSig = ByteUtil.merge( - spendAuthSig, spendDesc.getSpendAuthoritySignature().toByteArray()); - } - byte[] inputOffsetbytes = longTo32Bytes(192); - long spendCount = spendDescs.size(); - byte[] spendCountBytes = longTo32Bytes(spendCount); - byte[] authOffsetBytes = longTo32Bytes(192 + 32 + 320 * spendCount); - List recvDescs = parameters.getReceiveDescriptionList(); - for (ShieldContract.ReceiveDescription recvDesc : recvDescs) { - output = ByteUtil.merge(output, - recvDesc.getNoteCommitment().toByteArray(), - recvDesc.getValueCommitment().toByteArray(), - recvDesc.getEpk().toByteArray(), - recvDesc.getZkproof().toByteArray() - ); - c = ByteUtil.merge(c, - recvDesc.getCEnc().toByteArray(), - recvDesc.getCOut().toByteArray(), - new byte[12] - ); - } - long recvCount = recvDescs.size(); - byte[] recvCountBytes = longTo32Bytes(recvCount); - byte[] outputOffsetbytes = longTo32Bytes(192 + 32 + 320 * spendCount + 32 + 64 * spendCount); - byte[] coffsetBytes = longTo32Bytes(192 + 32 + 320 * spendCount + 32 + 64 * spendCount + 32 - + 288 * recvCount); - bindingSig = parameters.getBindingSignature().toByteArray(); - mergedBytes = ByteUtil.merge(inputOffsetbytes, - authOffsetBytes, - outputOffsetbytes, - bindingSig, - coffsetBytes, - spendCountBytes, - input, - spendCountBytes, - spendAuthSig, - recvCountBytes, - output, - recvCountBytes, - c - ); - return ByteArray.toHexString(mergedBytes); - } - - /** - * constructor. - */ - public String encodeBurnParamsToHexString(GrpcAPI.ShieldedTRC20Parameters parameters, - BigInteger value, - String transparentToAddress) { - byte[] mergedBytes; - byte[] payTo = new byte[32]; - byte[] transparentToAddressBytes = Commons.decodeFromBase58Check(transparentToAddress); - System.arraycopy(transparentToAddressBytes, 0, payTo, 11, 21); - ShieldContract.SpendDescription spendDesc = parameters.getSpendDescription(0); - mergedBytes = ByteUtil.merge( - spendDesc.getNullifier().toByteArray(), - spendDesc.getAnchor().toByteArray(), - spendDesc.getValueCommitment().toByteArray(), - spendDesc.getRk().toByteArray(), - spendDesc.getZkproof().toByteArray(), - spendDesc.getSpendAuthoritySignature().toByteArray(), - ByteUtil.bigIntegerToBytes(value, 32), - parameters.getBindingSignature().toByteArray(), - payTo - ); - return ByteArray.toHexString(mergedBytes); - } - - - /** - * constructor. - */ - public byte[] longTo32Bytes(long value) { - byte[] longBytes = ByteArray.fromLong(value); - byte[] zeroBytes = new byte[24]; - return ByteUtil.merge(zeroBytes, longBytes); - } - - /** - * constructor. - */ - public JSONArray getHttpShieldedReceivesJsonArray(JSONArray shieldReceives, Long value, - String paymentAddress, String rcm) { - JSONObject note = new JSONObject(); - note.put("value", value); - note.put("payment_address", paymentAddress); - note.put("rcm", rcm); - JSONObject noteIndex = new JSONObject(); - noteIndex.put("note", note); - shieldReceives.add(noteIndex); - return shieldReceives; - - } - - - /** - * constructor. - */ - public static HttpResponse createShieldContractParameters(String httpNode, Long fromAmount, - JSONObject shieldAccountInfo, JSONArray shiledReceives) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedcontractparameters"; - - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", "4364c875deeb663781a2f1530f9e4f87ea81cc3c757ca2a30fa4768940de2f98"); - rawBody.put("from_amount", fromAmount.toString()); - rawBody.put("shielded_receives", shiledReceives); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("visible", true); - - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount) { - return createShieldContractParametersForBurn(httpNode, shieldAccountInfo, shieldedSpends, - toAddress, toAmount, null); - - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount, - JSONArray shieldedReceiver) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedcontractparameters"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ask", shieldAccountInfo.getString("ask")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - if (shieldedReceiver != null) { - rawBody.put("shielded_receives", shieldedReceiver); - } - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("transparent_to_address", toAddress); - rawBody.put("to_amount", toAmount.toString()); - rawBody.put("visible", true); - - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersWithoutAskForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount) { - return createShieldContractParametersWithoutAskForBurn(httpNode, shieldAccountInfo, - shieldedSpends, toAddress, toAmount, null); - } - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersWithoutAskForBurn(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, String toAddress, Long toAmount, - JSONArray shieldedReceiver) { - try { - final String requestUrl - = "http://" + httpNode + "/wallet/createshieldedcontractparameterswithoutask"; - - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ak", shieldAccountInfo.getString("ak")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("transparent_to_address", toAddress); - rawBody.put("to_amount", toAmount.toString()); - rawBody.put("visible", true); - if (shieldedReceiver != null) { - rawBody.put("shielded_receives", shieldedReceiver); - } - - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersForTransfer(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, JSONArray shieldedReceives) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createshieldedcontractparameters"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ask", shieldAccountInfo.getString("ask")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("shielded_receives", shieldedReceives); - rawBody.put("visible", true); - logger.info(rawBody.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - - /** - * constructor. - */ - public static HttpResponse createShieldContractParametersWithoutAskForTransfer(String httpNode, - JSONObject shieldAccountInfo, JSONArray shieldedSpends, JSONArray shieldedReceives) { - try { - final String requestUrl = "http://" + httpNode - + "/wallet/createshieldedcontractparameterswithoutask"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ovk", shieldAccountInfo.getString("ovk")); - rawBody.put("ak", shieldAccountInfo.getString("ak")); - rawBody.put("nsk", shieldAccountInfo.getString("nsk")); - rawBody.put("shielded_spends", shieldedSpends); - rawBody.put("shielded_TRC20_contract_address", shieldAddress); - rawBody.put("shielded_receives", shieldedReceives); - rawBody.put("visible", true); - logger.info(rawBody.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static JSONObject createSpendAuthSig(String httpNode, - JSONObject shieldAccountInfo, String messageHash, String alpha) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/createspendauthsig"; - JSONObject rawBody = new JSONObject(); - rawBody.put("ask", shieldAccountInfo.getString("ask")); - rawBody.put("tx_hash", messageHash); - rawBody.put("alpha", alpha); - logger.info("createSpendAuthSig:" + rawBody.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, rawBody); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response); - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByIvk(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNum(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = "http://" + httpNode + "/wallet/scanshieldedtrc20notesbyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ivk", shieldAddressInfo.getString("ivk")); - userBaseObj2.addProperty("ak", shieldAddressInfo.getString("ak")); - userBaseObj2.addProperty("nk", shieldAddressInfo.getString("nk")); - userBaseObj2.addProperty("visible", true); - logger.info("scanShieldTrc20NoteByIvk:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByIvkOnSolidity(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNumOnSolidity(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpNode + "/walletsolidity/scanshieldedtrc20notesbyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ivk", shieldAddressInfo.getString("ivk")); - userBaseObj2.addProperty("ak", shieldAddressInfo.getString("ak")); - userBaseObj2.addProperty("nk", shieldAddressInfo.getString("nk")); - userBaseObj2.addProperty("visible", true); - logger.info("scanShieldTrc20NoteByIvk:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByIvkOnPbft(String httpPbftNode, - JSONObject shieldAddressInfo) { - try { - - response = HttpMethed.getNowBlockFromPbft(httpPbftNode); - Long endScanNumber = HttpMethed.parseResponseContent(response).getJSONObject("block_header") - .getJSONObject("raw_data").getLong("number"); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpPbftNode + "/walletpbft/scanshieldedtrc20notesbyivk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ivk", shieldAddressInfo.getString("ivk")); - userBaseObj2.addProperty("ak", shieldAddressInfo.getString("ak")); - userBaseObj2.addProperty("nk", shieldAddressInfo.getString("nk")); - userBaseObj2.addProperty("visible", true); - logger.info("scanShieldTrc20NoteByIvk:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByOvk(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNum(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = "http://" + httpNode + "/wallet/scanshieldedtrc20notesbyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ovk", shieldAddressInfo.getString("ovk")); - userBaseObj2.addProperty("visible", true); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByOvkOnSolidity(String httpNode, - JSONObject shieldAddressInfo) { - try { - Long endScanNumber = HttpMethed.getNowBlockNumOnSolidity(httpNode); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpNode + "/walletsolidity/scanshieldedtrc20notesbyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ovk", shieldAddressInfo.getString("ovk")); - userBaseObj2.addProperty("visible", true); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static JSONArray scanShieldTrc20NoteByOvkOnPbft(String httpPbftNode, - JSONObject shieldAddressInfo) { - try { - response = HttpMethed.getNowBlockFromPbft(httpPbftNode); - Long endScanNumber = HttpMethed.parseResponseContent(response).getJSONObject("block_header") - .getJSONObject("raw_data").getLong("number"); - Long startScanNumer = endScanNumber > 99 ? endScanNumber - 90 : 1; - - final String requestUrl = - "http://" + httpPbftNode + "/walletpbft/scanshieldedtrc20notesbyovk"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("start_block_index", startScanNumer); - userBaseObj2.addProperty("end_block_index", endScanNumber); - userBaseObj2.addProperty("shielded_TRC20_contract_address", shieldAddress); - userBaseObj2.addProperty("ovk", shieldAddressInfo.getString("ovk")); - userBaseObj2.addProperty("visible", true); - logger.info("userBaseObj2:" + userBaseObj2.toString()); - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = responseContent.getJSONArray("noteTxs"); - - return jsonArray; - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - } - - /** - * constructor. - */ - public static String getRootAndPathByHttp(String httpNode, Integer position) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/triggerconstantcontract"; - JsonObject userBaseObj2 = new JsonObject(); - - userBaseObj2.addProperty("owner_address", zenTrc20TokenOwnerAddressString); - userBaseObj2.addProperty("contract_address", shieldAddress); - userBaseObj2.addProperty("function_selector", "getPath(uint256)"); - byte[] indexBytes = ByteArray.fromLong(position); - String argsStr = ByteArray.toHexString(indexBytes); - String parameter = "000000000000000000000000000000000000000000000000" + argsStr; - userBaseObj2.addProperty("parameter", parameter); - userBaseObj2.addProperty("fee_limit", maxFeeLimit); - userBaseObj2.addProperty("visible", true); - - response = HttpMethed.createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response).getJSONArray("constant_result").getString(0); - } - - /** - * constructor. - */ - public static JSONArray createAndSetShieldedSpends(String httpNode, - JSONArray shieldedSpends, JSONObject noteTxs) { - JSONObject shieldedSpend = new JSONObject(); - shieldedSpend.put("note", noteTxs.getJSONObject("note")); - shieldedSpend.put("alpha", noteTxs.getJSONObject("note").getString("rcm")); - Integer position = noteTxs.containsKey("position") ? noteTxs.getInteger("position") : 0; - String rootAndPath = getRootAndPathByHttp(httpNode, position); - String root = rootAndPath.substring(0, 64); - String path = rootAndPath.substring(64); - shieldedSpend.put("root", root); - shieldedSpend.put("path", path); - shieldedSpend.put("pos", position); - shieldedSpends.add(shieldedSpend); - return shieldedSpends; - } - - - /** - * constructor. - */ - public static String getRcm(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getrcm"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response).getString("value"); - } - - - /** - * constructor. - */ - public static Boolean isShieldedTrc20ContractNoteSpent(String httpNode, - JSONObject accountInfo, JSONObject noteTxs) { - try { - final String requestUrl = "http://" + httpNode + "/wallet/isshieldedtrc20contractnotespent"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("note", noteTxs.getJSONObject("note")); - userBaseObj2.put("ak", accountInfo.getString("ak")); - userBaseObj2.put("nk", accountInfo.getString("nk")); - userBaseObj2.put("position", noteTxs.containsKey("position") - ? noteTxs.getInteger("position") : 0); - userBaseObj2.put("visible", true); - userBaseObj2.put("shielded_TRC20_contract_address", shieldAddress); - logger.info(userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - return responseContent.containsKey("is_spent") - ? responseContent.getBoolean("is_spent") : false; - } - - /** - * constructor. - */ - public static Boolean isShieldedTrc20ContractNoteSpentOnSolidity(String httpNode, - JSONObject accountInfo, JSONObject noteTxs) { - try { - final String requestUrl - = "http://" + httpNode + "/walletsolidity/isshieldedtrc20contractnotespent"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("note", noteTxs.getJSONObject("note")); - userBaseObj2.put("ak", accountInfo.getString("ak")); - userBaseObj2.put("nk", accountInfo.getString("nk")); - userBaseObj2.put("position", noteTxs.containsKey("position") - ? noteTxs.getInteger("position") : 0); - userBaseObj2.put("visible", true); - userBaseObj2.put("shielded_TRC20_contract_address", shieldAddress); - logger.info(userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - return responseContent.containsKey("is_spent") ? responseContent.getBoolean("is_spent") : false; - } - - /** - * constructor. - */ - public static Boolean isShieldedTrc20ContractNoteSpentOnPbft(String httpPbftNode, - JSONObject accountInfo, JSONObject noteTxs) { - try { - final String requestUrl - = "http://" + httpPbftNode + "/walletpbft/isshieldedtrc20contractnotespent"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("note", noteTxs.getJSONObject("note")); - userBaseObj2.put("ak", accountInfo.getString("ak")); - userBaseObj2.put("nk", accountInfo.getString("nk")); - userBaseObj2.put("position", noteTxs.containsKey("position") - ? noteTxs.getInteger("position") : 0); - userBaseObj2.put("visible", true); - userBaseObj2.put("shielded_TRC20_contract_address", shieldAddress); - logger.info(userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - return responseContent.containsKey("is_spent") ? responseContent.getBoolean("is_spent") : false; - } - - /** - * constructor. - */ - public static HttpResponse getTriggerInputForShieldedTrc20Contract(String httpNode, - JSONObject shieldedTrc20Parameters, JSONArray spendAuthoritySignature) { - try { - final String requestUrl = "http://" + httpNode - + "/wallet/gettriggerinputforshieldedtrc20contract"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("shielded_TRC20_Parameters", shieldedTrc20Parameters); - userBaseObj2.put("spend_authority_signature", spendAuthoritySignature); - - logger.info("gettriggerinputforshieldedtrc20contract:" + userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public static HttpResponse getTriggerInputForShieldedTrc20BurnContract(String httpNode, - JSONObject shieldedTrc20Parameters, JSONArray spendAuthoritySignature, Long amount, - String toAddress) { - try { - final String requestUrl = "http://" - + httpNode + "/wallet/gettriggerinputforshieldedtrc20contract"; - JSONObject userBaseObj2 = new JSONObject(); - userBaseObj2.put("shielded_TRC20_Parameters", shieldedTrc20Parameters); - userBaseObj2.put("spend_authority_signature", spendAuthoritySignature); - userBaseObj2.put("amount", amount.toString()); - userBaseObj2.put("transparent_to_address", toAddress); - userBaseObj2.put("visible", true); - - logger.info("gettriggerinputforshieldedtrc20contract:" + userBaseObj2.toString()); - response = HttpMethed.createConnectForShieldTrc20(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenUtils.java b/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenUtils.java deleted file mode 100644 index f14b91670b7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/common/client/utils/ZenUtils.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.common.client.utils; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import javax.crypto.spec.IvParameterSpec; -import javax.crypto.spec.SecretKeySpec; - -public class ZenUtils { - - public static List getListFromFile(final String fileName) { - List list = new ArrayList<>(); - try { - FileInputStream inputStream = new FileInputStream(fileName); - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - - String str = null; - while ((str = bufferedReader.readLine()) != null) { - System.out.println(str); - list.add(str); - } - inputStream.close(); - bufferedReader.close(); - } catch (Exception e) { - if (e.getMessage() != null) { - System.out.println(e.getMessage()); - } else { - System.out.println(e.getClass()); - } - } - return list; - } - - public static boolean appendToFileTail(final String fileName, final String content) { - BufferedWriter out = null; - try { - out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, true))); - out.write(content + "\n"); - out.flush(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return true; - } - - public static void clearFile(String fileName) { - File file = new File(fileName); - try { - if (file.exists()) { - FileWriter fileWriter = new FileWriter(file); - fileWriter.write(""); - fileWriter.flush(); - fileWriter.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static void checkFolderExist(final String filePath) { - try { - File file = new File(filePath); - if (file.exists()) { - if (file.isDirectory()) { - return; - } else { - file.delete(); - } - } - file.mkdir(); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public static String getMemo(byte[] memo) { - int index = memo.length; - for (; index > 0; --index) { - if (memo[index - 1] != 0) { - break; - } - } - - byte[] inputCheck = new byte[index]; - System.arraycopy(memo, 0, inputCheck, 0, index); - return new String(inputCheck, Charset.forName("UTF-8")); - } - - - public static byte[] aesCtrEncrypt(byte[] text, byte[] encryptKey) throws CipherException { - try { - byte[] iv = new byte[16]; - new SecureRandom().nextBytes(iv); - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); - - SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES"); - cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); - byte[] cipherText = cipher.doFinal(text); - byte[] result = new byte[cipherText.length + iv.length]; - System.arraycopy(iv, 0, result, 0, iv.length); - System.arraycopy(cipherText, 0, result, iv.length, cipherText.length); - return result; - } catch (NoSuchPaddingException | NoSuchAlgorithmException - | InvalidAlgorithmParameterException | InvalidKeyException - | BadPaddingException | IllegalBlockSizeException e) { - throw new CipherException("Error performing cipher operation", e); - } - } - - public static byte[] aesCtrDecrypt(byte[] cipherText, byte[] encryptKey) throws CipherException { - try { - byte[] iv = Arrays.copyOfRange(cipherText, 0, 16); - cipherText = Arrays.copyOfRange(cipherText, iv.length, cipherText.length); - - IvParameterSpec ivParameterSpec = new IvParameterSpec(iv); - Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding"); - - SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES"); - cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec); - return cipher.doFinal(cipherText); - } catch (NoSuchPaddingException | NoSuchAlgorithmException - | InvalidAlgorithmParameterException | InvalidKeyException - | BadPaddingException | IllegalBlockSizeException e) { - throw new CipherException("Error performing cipher operation", e); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage002.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage002.java deleted file mode 100644 index a4db9515248..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage002.java +++ /dev/null @@ -1,271 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage002Address = ecKey1.getAddress(); - String linkage002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage002Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void updateSetting() { - String sendcoin = PublicMethed - .sendcoinGetTransactionId(linkage002Address, 200000000000L, fromAddress, - testKey002, blockingStubFull); - Account info; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById0 = null; - infoById0 = PublicMethed.getTransactionInfoById(sendcoin, blockingStubFull); - logger.info("infoById0 " + infoById0.get()); - Assert.assertEquals(ByteArray.toHexString(infoById0.get().getContractResult(0).toByteArray()), - ""); - Assert.assertEquals(infoById0.get().getResult().getNumber(), 0); - Optional ById = PublicMethed.getTransactionById(sendcoin, blockingStubFull); - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage002Address, 50000000L, - 3, 1, linkage002Key, blockingStubFull)); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage002Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage002.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - //Set the consumeUserResourcePercent is -1,Nothing change. - byte[] contractAddress; - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, -1, null, linkage002Key, linkage002Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter = PublicMethed.queryAccount(linkage002Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertTrue(afterNetUsed == 0); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterFreeNetUsed > 0); - - //Set the consumeUserResourcePercent is 101,Nothing change. - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull); - Account info3 = PublicMethed.queryAccount(linkage002Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyLimit3 = resourceInfo3.getEnergyLimit(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeFreeNetLimit3 = resourceInfo3.getFreeNetLimit(); - Long beforeNetLimit3 = resourceInfo3.getNetLimit(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - logger.info("beforeBalance3:" + beforeBalance3); - logger.info("beforeEnergyLimit3:" + beforeEnergyLimit3); - logger.info("beforeEnergyUsed3:" + beforeEnergyUsed3); - logger.info("beforeFreeNetLimit3:" + beforeFreeNetLimit3); - logger.info("beforeNetLimit3:" + beforeNetLimit3); - logger.info("beforeNetUsed3:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed3:" + beforeFreeNetUsed3); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 101, null, linkage002Key, linkage002Address, blockingStubFull); - Account infoafter3 = PublicMethed.queryAccount(linkage002Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull1); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyLimit3 = resourceInfoafter3.getEnergyLimit(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterFreeNetLimit3 = resourceInfoafter3.getFreeNetLimit(); - Long afterNetLimit3 = resourceInfoafter3.getNetLimit(); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - logger.info("afterBalance3:" + afterBalance3); - logger.info("afterEnergyLimit3:" + afterEnergyLimit3); - logger.info("afterEnergyUsed3:" + afterEnergyUsed3); - logger.info("afterFreeNetLimit3:" + afterFreeNetLimit3); - logger.info("afterNetLimit3:" + afterNetLimit3); - logger.info("afterNetUsed3:" + afterNetUsed3); - logger.info("afterFreeNetUsed3:" + afterFreeNetUsed3); - - Assert.assertEquals(beforeBalance3, afterBalance3); - Assert.assertTrue(afterNetUsed3 == 0); - Assert.assertTrue(afterEnergyUsed3 == 0); - Assert.assertTrue(afterFreeNetUsed3 > 0); - - //Set consumeUserResourcePercent is 100,balance not change,use FreeNet freezeBalanceGetEnergy. - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, linkage002Key, linkage002Address, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getConsumeUserResourcePercent() == 100); - - //Set the consumeUserResourcePercent is 0,balance not change,use FreeNet freezeBalanceGetEnergy. - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage002Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, null, linkage002Key, linkage002Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter2 = PublicMethed.queryAccount(linkage002Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage002Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - - Assert.assertEquals(beforeBalance2, afterBalance2); - Assert.assertTrue(afterNetUsed2 == 0); - Assert.assertTrue(afterEnergyUsed2 > 0); - Assert.assertTrue(afterFreeNetUsed2 > 0); - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getConsumeUserResourcePercent() == 0); - - //Update the consumeUserResourcePercent setting. - Assert.assertTrue(PublicMethed.updateSetting(contractAddress, 66L, - linkage002Key, linkage002Address, blockingStubFull)); - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getConsumeUserResourcePercent() == 66); - - //Updaate the consumeUserResourcePercent setting with -1 and 101 - Assert.assertFalse(PublicMethed.updateSetting(contractAddress, -1L, - linkage002Key, linkage002Address, blockingStubFull)); - Assert.assertFalse(PublicMethed.updateSetting(contractAddress, 101L, - linkage002Key, linkage002Address, blockingStubFull)); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage003.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage003.java deleted file mode 100644 index 1b4d8ad3c65..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage003.java +++ /dev/null @@ -1,157 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage003 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage003Address = ecKey1.getAddress(); - String linkage002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage002Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void deployWhenNoEnergy() { - Assert.assertTrue(PublicMethed.sendcoin(linkage003Address, 200000000L, fromAddress, - testKey003, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage003Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage003Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "src/test/resources/soliditycode//contractLinkage003.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - //use FreeNet and balance,EnergyUsed==0. - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 0, null, linkage002Key, linkage003Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - byte[] contractAddress = infoById.get().getContractAddress().toByteArray(); - Long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long fee = infoById.get().getFee(); - Long energyFee = infoById.get().getReceipt().getEnergyFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(linkage003Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage003Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getName().isEmpty()); - Assert.assertTrue((beforeBalance - fee) == afterBalance); - Assert.assertTrue(afterEnergyUsed == 0L); - Assert.assertTrue(afterFreeNetUsed > 0L); - Assert.assertTrue(afterNetUsed == 0L); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage004.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage004.java deleted file mode 100644 index 5cc614e08bc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage004.java +++ /dev/null @@ -1,320 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage004 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - String contractName; - String code; - String abi; - Long currentFee; - Account info; - Long beforeBalance; - Long beforeNetLimit; - Long beforeFreeNetLimit; - Long beforeFreeNetUsed; - Long beforeNetUsed; - Long beforeEnergyLimit; - Long beforeEnergyUsed; - Long afterBalance; - Long afterNetLimit; - Long afterFreeNetLimit; - Long afterFreeNetUsed; - Long afterNetUsed; - Long afterEnergyLimit; - Long afterEnergyUsed; - Long energyUsed; - Long netUsed; - Long energyFee; - Long fee; - Long energyUsageTotal; - Long netFee; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage004Address = ecKey1.getAddress(); - String linkage004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage004Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void test1GetTransactionInfoById() { - ecKey1 = new ECKey(Utils.getRandom()); - linkage004Address = ecKey1.getAddress(); - linkage004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(linkage004Address, 2000000000000L, fromAddress, - testKey003, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(linkage004Address, 10000000L, - 3, linkage004Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage004Address, blockingStubFull); - beforeBalance = info.getBalance(); - beforeEnergyLimit = resourceInfo.getEnergyLimit(); - beforeEnergyUsed = resourceInfo.getEnergyUsed(); - beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - beforeNetLimit = resourceInfo.getNetLimit(); - beforeNetUsed = resourceInfo.getNetUsed(); - beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage004.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - //use freezeBalanceGetNet,Balance .No freezeBalanceGetenergy - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 50, null, linkage004Key, linkage004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - fee = infoById.get().getFee(); - currentFee = fee; - energyFee = infoById.get().getReceipt().getEnergyFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(linkage004Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - afterNetLimit = resourceInfoafter.getNetLimit(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("---------------:"); - Assert.assertTrue(infoById.isPresent()); - Assert.assertTrue((beforeBalance - fee) == afterBalance); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterFreeNetUsed > 0); - } - - @Test(enabled = true) - public void test2FeeLimitIsTooSmall() { - //When the fee limit is only short with 1 sun,failed.use freezeBalanceGetNet. - maxFeeLimit = currentFee - 1L; - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage004Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - - String filePath = "./src/test/resources/soliditycode/contractLinkage004.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 50, null, linkage004Key, linkage004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - Long fee1 = infoById1.get().getFee(); - Long energyFee1 = infoById1.get().getReceipt().getEnergyFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - logger.info("fee1:" + fee1); - logger.info("energyFee1:" + energyFee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - - Account infoafter1 = PublicMethed.queryAccount(linkage004Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - - Assert.assertTrue((beforeBalance1 - fee1) == afterBalance1); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - Assert.assertTrue(energyUsageTotal1 > 0); - Assert.assertTrue(afterEnergyUsed1 == 0); - Assert.assertTrue(beforeNetUsed1 < afterNetUsed1); - - //When the fee limit is just ok.use energyFee,freezeBalanceGetNet,balance change. - maxFeeLimit = currentFee; - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage004Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 50, null, linkage004Key, linkage004Address, blockingStubFull); - //logger.info("testFeeLimitIsTooSmall, the txid is " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - Long fee2 = infoById2.get().getFee(); - Long energyFee2 = infoById2.get().getReceipt().getEnergyFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - logger.info("fee2:" + fee2); - logger.info("energyFee2:" + energyFee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - Account infoafter2 = PublicMethed.queryAccount(linkage004Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage004Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Assert.assertTrue(infoById2.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue((beforeBalance2 - fee2) == afterBalance2); - Assert.assertTrue((beforeNetUsed2 + netUsed2) >= afterNetUsed2); - - currentFee = fee2; - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage007.java b/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage007.java deleted file mode 100644 index 7fabf396aaf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/linkage/ContractLinkage007.java +++ /dev/null @@ -1,350 +0,0 @@ -package stest.tron.wallet.contract.linkage; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String contractName; - String code; - String abi; - byte[] contractAddress; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage007Address = ecKey1.getAddress(); - String linkage007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage007Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = true) - public void testRangeOfFeeLimit() { - - //Now the feelimit range is 0-1000000000,including 0 and 1000000000 - Assert.assertTrue(PublicMethed.sendcoin(linkage007Address, 2000000000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - //When the feelimit is large, the deploy will be failed,No used everything. - - String filePath = "./src/test/resources/soliditycode/contractLinkage002.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid; - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit + 1, 0L, 100, null, linkage007Key, - linkage007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterNetUsed == 0); - Assert.assertTrue(afterFreeNetUsed == 0); - - Assert.assertTrue(txid == null); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - //When the feelimit is 0, the deploy will be failed.Only use FreeNet,balance not change. - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", 0L, 0L, 100, null, linkage007Key, - linkage007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account infoafter1 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("---------------:"); - Assert.assertEquals(beforeBalance1, afterBalance1); - Assert.assertTrue(afterFreeNetUsed1 > 0); - Assert.assertTrue(afterNetUsed1 == 0); - Assert.assertTrue(afterEnergyUsed1 == 0); - Optional infoById; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - //Deploy the contract.success.use FreeNet,EnergyFee.balcne change - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 100, null, linkage007Key, - linkage007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - Long fee2 = infoById2.get().getFee(); - Long energyFee2 = infoById2.get().getReceipt().getEnergyFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - logger.info("fee2:" + fee2); - logger.info("energyFee2:" + energyFee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - Account infoafter2 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - logger.info("---------------:"); - Assert.assertTrue((beforeBalance2 - fee2) == afterBalance2); - Assert.assertTrue(afterEnergyUsed2 == 0); - Assert.assertTrue(afterFreeNetUsed2 > beforeFreeNetUsed2); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - contractAddress = infoById2.get().getContractAddress().toByteArray(); - - //When the feelimit is large, the trigger will be failed.Only use FreeNetUsed,Balance not change - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info3 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyLimit3 = resourceInfo3.getEnergyLimit(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeFreeNetLimit3 = resourceInfo3.getFreeNetLimit(); - Long beforeNetLimit3 = resourceInfo3.getNetLimit(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - logger.info("beforeBalance3:" + beforeBalance3); - logger.info("beforeEnergyLimit3:" + beforeEnergyLimit3); - logger.info("beforeEnergyUsed3:" + beforeEnergyUsed3); - logger.info("beforeFreeNetLimit3:" + beforeFreeNetLimit3); - logger.info("beforeNetLimit3:" + beforeNetLimit3); - logger.info("beforeNetUsed3:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed3:" + beforeFreeNetUsed3); - //String initParmes = "\"" + Base58.encode58Check(fromAddress) + "\",\"63\""; - String num = "4" + "," + "2"; - txid = PublicMethed.triggerContract(contractAddress, - "divideIHaveArgsReturn(int256,int256)", num, false, - 1000, maxFeeLimit + 1, linkage007Address, linkage007Key, blockingStubFull); - Account infoafter3 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyLimit3 = resourceInfoafter3.getEnergyLimit(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterFreeNetLimit3 = resourceInfoafter3.getFreeNetLimit(); - Long afterNetLimit3 = resourceInfoafter3.getNetLimit(); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - logger.info("afterBalance3:" + afterBalance3); - logger.info("afterEnergyLimit3:" + afterEnergyLimit3); - logger.info("afterEnergyUsed3:" + afterEnergyUsed3); - logger.info("afterFreeNetLimit3:" + afterFreeNetLimit3); - logger.info("afterNetLimit3:" + afterNetLimit3); - logger.info("afterNetUsed3:" + afterNetUsed3); - logger.info("afterFreeNetUsed3:" + afterFreeNetUsed3); - logger.info("---------------:"); - Assert.assertTrue(txid == null); - Assert.assertEquals(beforeBalance3, afterBalance3); - Assert.assertTrue(afterFreeNetUsed3 > beforeNetUsed3); - Assert.assertTrue(afterNetUsed3 == 0); - Assert.assertTrue(afterEnergyUsed3 == 0); - //When the feelimit is 0, the trigger will be failed.Only use FreeNetUsed,Balance not change - AccountResourceMessage resourceInfo4 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull); - Account info4 = PublicMethed.queryAccount(linkage007Address, blockingStubFull); - Long beforeBalance4 = info4.getBalance(); - Long beforeEnergyLimit4 = resourceInfo4.getEnergyLimit(); - Long beforeEnergyUsed4 = resourceInfo4.getEnergyUsed(); - Long beforeFreeNetLimit4 = resourceInfo4.getFreeNetLimit(); - Long beforeNetLimit4 = resourceInfo4.getNetLimit(); - Long beforeNetUsed4 = resourceInfo4.getNetUsed(); - Long beforeFreeNetUsed4 = resourceInfo4.getFreeNetUsed(); - logger.info("beforeBalance4:" + beforeBalance4); - logger.info("beforeEnergyLimit4:" + beforeEnergyLimit4); - logger.info("beforeEnergyUsed4:" + beforeEnergyUsed4); - logger.info("beforeFreeNetLimit4:" + beforeFreeNetLimit4); - logger.info("beforeNetLimit4:" + beforeNetLimit4); - logger.info("beforeNetUsed4:" + beforeNetUsed4); - logger.info("beforeFreeNetUsed4:" + beforeFreeNetUsed4); - txid = PublicMethed.triggerContract(contractAddress, - "divideIHaveArgsReturn(int256,int256)", num, false, - 1000, maxFeeLimit + 1, linkage007Address, linkage007Key, blockingStubFull); - Account infoafter4 = PublicMethed.queryAccount(linkage007Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter4 = PublicMethed.getAccountResource(linkage007Address, - blockingStubFull1); - Long afterBalance4 = infoafter4.getBalance(); - Long afterEnergyLimit4 = resourceInfoafter4.getEnergyLimit(); - Long afterEnergyUsed4 = resourceInfoafter4.getEnergyUsed(); - Long afterFreeNetLimit4 = resourceInfoafter4.getFreeNetLimit(); - Long afterNetLimit4 = resourceInfoafter4.getNetLimit(); - Long afterNetUsed4 = resourceInfoafter4.getNetUsed(); - Long afterFreeNetUsed4 = resourceInfoafter4.getFreeNetUsed(); - logger.info("afterBalance4:" + afterBalance4); - logger.info("afterEnergyLimit4:" + afterEnergyLimit4); - logger.info("afterEnergyUsed4:" + afterEnergyUsed4); - logger.info("afterFreeNetLimit4:" + afterFreeNetLimit4); - logger.info("afterNetLimit4:" + afterNetLimit4); - logger.info("afterNetUsed4:" + afterNetUsed4); - logger.info("afterFreeNetUsed4:" + afterFreeNetUsed4); - logger.info("---------------:"); - Assert.assertEquals(beforeBalance4, afterBalance4); - Assert.assertTrue(afterFreeNetUsed4 > beforeNetUsed4); - Assert.assertTrue(afterNetUsed4 == 0); - Assert.assertTrue(afterEnergyUsed4 == 0); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(Integer.toString(infoById.get().getResultValue())); - Assert.assertTrue(infoById.get().getFee() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario001.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario001.java deleted file mode 100644 index 04d305fd384..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario001.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract001Address = ecKey1.getAddress(); - String contract001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void deployAddressDemo() { - ecKey1 = new ECKey(Utils.getRandom()); - contract001Address = ecKey1.getAddress(); - contract001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(contract001Key); - - Assert.assertTrue(PublicMethed.sendcoin(contract001Address, 20000000L, toAddress, - testKey003, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract001Address, 15000000L, - 3, 1, contract001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract001Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(contract001Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/contractScenario001.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract001Key, contract001Address, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - accountResource = PublicMethed.getAccountResource(contract001Address, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Long balanceAfter = PublicMethed.queryAccount(contract001Key, blockingStubFull1).getBalance(); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after balance is " + Long.toString(balanceAfter)); - - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario003.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario003.java deleted file mode 100644 index ae22985e8eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario003.java +++ /dev/null @@ -1,135 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract003Address = ecKey1.getAddress(); - String contract003Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract003Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(contract003Key, blockingStubFull) - .getBalance())); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void deployErc223() { - ecKey1 = new ECKey(Utils.getRandom()); - contract003Address = ecKey1.getAddress(); - contract003Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(contract003Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract003Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(contract003Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/contractScenario003.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract003Key, contract003Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - logger.info(txid); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress.toByteArray(), blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - PublicMethed.waitProduceNextBlock(blockingStubFull1); - accountResource = PublicMethed.getAccountResource(contract003Address, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Long balanceAfter = PublicMethed.queryAccount(contract003Address, blockingStubFull1) - .getBalance(); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after balance is " + Long.toString(balanceAfter)); - logger.info("transaction fee is " + Long.toString(infoById.get().getFee())); - - Assert.assertTrue(energyLimit == 0); - Assert.assertTrue(energyUsage == 0); - Assert.assertTrue(balanceBefore == balanceAfter + infoById.get().getFee()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario004.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario004.java deleted file mode 100644 index 050f4a13a1d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario004.java +++ /dev/null @@ -1,131 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract004Address = ecKey1.getAddress(); - String contract004Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract004Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployErc20TronTokenWithoutData() { - Assert.assertTrue(PublicMethed.sendcoin(contract004Address, 200000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract004Address, 100000000L, - 3, 1, contract004Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract004Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode//contractScenario004.sol"; - String contractName = "TronToken"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract004Key, contract004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - System.out.println(info); - Assert.assertTrue(info.get().getResultValue() == 1); - } - - @Test(enabled = true) - public void deployErc20TronTokenWithData() { - Assert.assertTrue(PublicMethed - .sendcoin(contract004Address, 200000000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract004Address, 100000000L, - 3, 1, contract004Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract004Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode//contractScenario004.sol"; - String contractName = "TronToken"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(address)"; - String data = "\"" + Base58.encode58Check(contract004Address) + "\""; - String txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, contract004Key, contract004Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - System.out.println(info); - Assert.assertTrue(info.get().getResultValue() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario005.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario005.java deleted file mode 100644 index 69821298387..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario005.java +++ /dev/null @@ -1,110 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract005Address = ecKey1.getAddress(); - String contract005Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract005Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = false) - public void deployIcoContract() { - Assert.assertTrue(PublicMethed.sendcoin(contract005Address, 200000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract005Address, 10000000L, - 3, 1, contract005Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract005Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario005.sol"; - String contractName = "Crowdsale"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract005Key, contract005Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertEquals(1, infoById.get().getResultValue()); - accountResource = PublicMethed.getAccountResource(contract005Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario006.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario006.java deleted file mode 100644 index 78071cc7611..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario006.java +++ /dev/null @@ -1,123 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario006 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract006Address = ecKey1.getAddress(); - String contract006Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployFomo3D() { - ecKey1 = new ECKey(Utils.getRandom()); - contract006Address = ecKey1.getAddress(); - contract006Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(contract006Key); - - PublicMethed.sendcoin(contract006Address, 2000000000L, toAddress, - testKey003, blockingStubFull); - logger.info(Long.toString(PublicMethed.queryAccount(contract006Key, blockingStubFull) - .getBalance())); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract006Address, 100000000L, - 3, 1, contract006Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract006Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario006.sol"; - String contractName = "FoMo3Dlong"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress; - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract006Key, contract006Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - accountResource = PublicMethed.getAccountResource(contract006Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario007.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario007.java deleted file mode 100644 index 5b85d9e441c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario007.java +++ /dev/null @@ -1,111 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract007Address = ecKey1.getAddress(); - String contract007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract007Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployErc721CardMigration() { - ecKey1 = new ECKey(Utils.getRandom()); - contract007Address = ecKey1.getAddress(); - contract007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(contract007Address, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract007Address, 100000000L, - 3, 1, contract007Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract007Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(contract007Key, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - String contractName = "ERC721Token"; - - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractScenario007_deployErc721CardMigration"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractScenario007_deployErc721CardMigration"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract007Key, contract007Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - accountResource = PublicMethed.getAccountResource(contract007Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(contract007Key, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario008.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario008.java deleted file mode 100644 index 6fb52760440..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario008.java +++ /dev/null @@ -1,114 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario008 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract008Address = ecKey1.getAddress(); - String contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployErc721CryptoKitties() { - ecKey1 = new ECKey(Utils.getRandom()); - contract008Address = ecKey1.getAddress(); - contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(contract008Key); - Assert.assertTrue(PublicMethed.sendcoin(contract008Address, 5000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract008Address, 1000000L, - 3, 1, contract008Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract008Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - Long shortFeeLimit = 900L; - - String filePath = "./src/test/resources/soliditycode/contractScenario008.sol"; - String contractName = "KittyCore"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", shortFeeLimit, - 0L, 100, null, contract008Key, contract008Address, blockingStubFull); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract008Key, contract008Address, blockingStubFull); - - final SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario009.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario009.java deleted file mode 100644 index 4b902d5b404..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario009.java +++ /dev/null @@ -1,126 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract009Address = ecKey1.getAddress(); - String contract009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract009Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployContainLibraryContract() { - Assert.assertTrue(PublicMethed.sendcoin(contract009Address, 20000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract009Address, 1000000L, - 3, 1, contract009Key, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract009Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - String filePath = "./src/test/resources/soliditycode/contractScenario009.sol"; - String contractName = "Set"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] libraryContractAddress; - libraryContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract009Key, contract009Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - contractName = "C"; - retMap = PublicMethed.getBycodeAbiForLibrary(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - String library = retMap.get("library").toString(); - - //String libraryAddress = - // "browser/TvmTest_p1_Grammar_002.sol:Set:" + Base58.encode58Check(libraryContractAddress); - String libraryAddress; - libraryAddress = library - + Base58.encode58Check(libraryContractAddress); - - byte[] contractAddress = PublicMethed - .deployContractForLibrary(contractName, abi, code, "", maxFeeLimit, 0L, 100, libraryAddress, - contract009Key, contract009Address, compilerVersion, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - logger.info(ByteArray.toHexString(smartContract.getContractAddress().toByteArray())); - accountResource = PublicMethed.getAccountResource(contract009Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario010.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario010.java deleted file mode 100644 index 58bbc6869bb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario010.java +++ /dev/null @@ -1,114 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario010 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract009Address = ecKey1.getAddress(); - String contract009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract009Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployContainLibraryContract() { - ecKey1 = new ECKey(Utils.getRandom()); - contract009Address = ecKey1.getAddress(); - contract009Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(contract009Address, 600000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract009Address, 10000000L, - 3, 1, contract009Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract009Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long netUsage = accountResource.getNetUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before Net usage is " + Long.toString(netUsage)); - String filePath = "./src/test/resources/soliditycode/contractScenario010.sol"; - String contractName = "TRON_ERC721"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] libraryAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract009Key, contract009Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(libraryAddress, blockingStubFull); - - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - logger.info(ByteArray.toHexString(smartContract.getContractAddress().toByteArray())); - accountResource = PublicMethed.getAccountResource(contract009Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - netUsage = accountResource.getNetUsed(); - Assert.assertTrue(energyLimit > 0); - Assert.assertTrue(energyUsage > 0); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after Net usage is " + Long.toString(netUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario012.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario012.java deleted file mode 100644 index caa9bb1b3b3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario012.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario012 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - byte[] contractAddress = null; - String txid = ""; - Optional infoById = null; - String receiveAddressParam; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract012Address = ecKey1.getAddress(); - String contract012Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey2.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract012Key); - PublicMethed.printAddress(receiverKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void test1DeployTransactionCoin() { - ecKey1 = new ECKey(Utils.getRandom()); - contract012Address = ecKey1.getAddress(); - contract012Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(contract012Address, 2000000000L, fromAddress, - testKey002, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract012Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - String filePath = "./src/test/resources/soliditycode/contractScenario012.sol"; - String contractName = "PayTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100, - null, contract012Key, contract012Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - } - - - @Test(enabled = true) - public void test2TriggerTransactionCoin() { - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("contract Balance : -- " + account.getBalance()); - receiveAddressParam = "\"" + Base58.encode58Check(fromAddress) - + "\""; - //When the contract has no money,transaction coin failed. - txid = PublicMethed.triggerContract(contractAddress, - "sendToAddress2(address)", receiveAddressParam, false, - 0, 100000000L, contract012Address, contract012Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - } - - - @Test(enabled = true) - public void test3TriggerTransactionCanNotCreateAccount() { - ecKey2 = new ECKey(Utils.getRandom()); - receiverAddress = ecKey2.getAddress(); - receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - //Send some trx to the contract account. - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("contract Balance : -- " + account.getBalance()); - receiveAddressParam = "\"" + Base58.encode58Check(receiverAddress) - + "\""; - //In smart contract, you can create account - txid = PublicMethed.triggerContract(contractAddress, - "sendToAddress2(address)", receiveAddressParam, false, - 1000000000L, 100000000L, contract012Address, contract012Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - logger.info("result is " + infoById.get().getResultValue()); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - - Account account2 = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - Assert.assertEquals(5L, account2.getBalance()); - - } - - - @Test(enabled = true) - public void test4TriggerTransactionCoin() { - receiveAddressParam = "\"" + Base58.encode58Check(receiverAddress) - + "\""; - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("contract Balance : -- " + account.getBalance()); - //This time, trigger the methed sendToAddress2 is OK. - Assert.assertTrue(PublicMethed.sendcoin(receiverAddress, 10000000L, toAddress, - testKey003, blockingStubFull)); - txid = PublicMethed.triggerContract(contractAddress, - "sendToAddress2(address)", receiveAddressParam, false, - 0, 100000000L, contract012Address, contract012Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - logger.info("result is " + infoById.get().getResultValue()); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario013.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario013.java deleted file mode 100644 index d6adab1e7f8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario013.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario013 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress = null; - String txid = ""; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract013Address = ecKey1.getAddress(); - String contract013Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract013Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void deployTronTrxAndSunContract() { - Assert.assertTrue(PublicMethed.sendcoin(contract013Address, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract013Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario013.sol"; - String contractName = "timetest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract013Key, contract013Address, blockingStubFull); - logger.info(txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - } - - @Test(enabled = true) - public void triggerTronTrxAndSunContract() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract013Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - - String filePath = "./src/test/resources/soliditycode/contractScenario013.sol"; - String contractName = "timetest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contract013Key, contract013Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - - txid = PublicMethed.triggerContract(contractAddress, - "time()", "#", false, - 0, 100000000L, contract013Address, contract013Key, blockingStubFull); - logger.info(txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("result is " + infoById.get().getResultValue()); - logger.info("energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 0); - Assert.assertTrue(infoById.get().getFee() == infoById.get().getReceipt().getEnergyFee()); - Assert.assertFalse(infoById.get().getContractAddress().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario014.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario014.java deleted file mode 100644 index 90733f6989e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario014.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario014 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract with ABI created by itself") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("", - ByteArray.toHexString(infoById.get().getResMessage().toByteArray())); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), - SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario015.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario015.java deleted file mode 100644 index 2ef1504c833..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario015.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario015 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function ") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - logger.info("message:" + transaction.getRet(0).getRet()); - logger.info(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - logger.info("Result:" + Hex.toHexString(result)); - logger.info("getCode" + transactionExtention.getResult().getCode().getNumber()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario016.java b/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario016.java deleted file mode 100644 index d5784b78778..00000000000 --- a/framework/src/test/java/stest/tron/wallet/contract/scenario/ContractScenario016.java +++ /dev/null @@ -1,193 +0,0 @@ -package stest.tron.wallet.contract.scenario; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.BAD_JUMP_DESTINATION_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario016 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "ContractResult is BAD_JUMP_DESTINATION") - public void test1Grammar001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "Test"; - - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600" - + "080fd5b5061011f8061003a6000396000f30060806040526004361060485763ffffffff7c01000000000000" - + "000000000000000000000000000000000000000000006000350416634ef5a0088114604d5780639093b95b1" - + "4608c575b600080fd5b348015605857600080fd5b50d38015606457600080fd5b50d28015607057600080fd" - + "5b50607a60043560b8565b60408051918252519081900360200190f35b348015609757600080fd5b50d3801" - + "560a357600080fd5b50d2801560af57600080fd5b5060b660ee565b005b6000606082604051908082528060" - + "20026020018201604052801560e5578160200160208202803883390190505b50905050919050565b6001805" - + "600a165627a7a7230582092ba162087e13f41c6d6c00ba493edc5a5a6250a3840ece5f99aa38b66366a7000" - + "29"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\"" - + ":\"testOutOfMem\",\"outputs\":[{\"name\":\"r\",\"type\":\"bytes32\"}],\"payable\":false" - + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs" - + "\":[],\"name\":\"testBadJumpDestination\",\"outputs\":[],\"payable\":false,\"stateMutab" - + "ility\":\"nonpayable\",\"type\":\"function\"}]"; - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - txid = PublicMethed.triggerContract(contractAddress, - "testBadJumpDestination()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), BAD_JUMP_DESTINATION_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.BAD_JUMP_DESTINATION); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert - .assertEquals(contractResult.BAD_JUMP_DESTINATION, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is OUT_OF_ENERGY") - public void test2Grammar002() { - - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000001"); - Assert - .assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java deleted file mode 100644 index 6cbcc9b016f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/account/GetAccountBalance001.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.dailybuild.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.BalanceContract.BlockBalanceTrace; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j - -public class GetAccountBalance001 { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress = ecKey1.getAddress(); - final String testKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Integer sendAmount = 1234; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - Long beforeFromBalance; - Long beforeToBalance; - Long afterFromBalance; - Long afterToBalance; - private final String blackHoleAdd = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Test get account balance") - public void test01GetAccountBalance() { - Protocol.Block currentBlock = blockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - - beforeFromBalance = PublicMethed.getAccountBalance(currentBlock,fromAddress,blockingStubFull); - beforeToBalance = PublicMethed.getAccountBalance(currentBlock,testAddress,blockingStubFull); - - - } - - @Test(enabled = true, description = "Test get block balance") - public void test02GetBlockBalance() { - String txid = PublicMethed.sendcoinGetTransactionId(testAddress, sendAmount, fromAddress, - testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long blockNum = infoById.get().getBlockNumber(); - - Protocol.Block currentBlock = PublicMethed.getBlock(blockNum,blockingStubFull); - - BlockBalanceTrace blockBalanceTrace - = PublicMethed.getBlockBalance(currentBlock,blockingStubFull); - - - Assert.assertEquals(ByteString.copyFrom(fromAddress),blockBalanceTrace - .getTransactionBalanceTrace(0).getOperation(0).getAddress()); - Assert.assertEquals(-100000L,blockBalanceTrace.getTransactionBalanceTrace(0) - .getOperation(0).getAmount()); - - - Assert.assertEquals(ByteString.copyFrom(fromAddress),blockBalanceTrace - .getTransactionBalanceTrace(0).getOperation(1).getAddress()); - Assert.assertEquals(-sendAmount,blockBalanceTrace.getTransactionBalanceTrace(0) - .getOperation(1).getAmount()); - - - - Assert.assertEquals(ByteString.copyFrom(testAddress),blockBalanceTrace - .getTransactionBalanceTrace(0).getOperation(2).getAddress()); - Assert.assertEquals(-sendAmount,-blockBalanceTrace.getTransactionBalanceTrace(0) - .getOperation(2).getAmount()); - - - afterFromBalance = PublicMethed.getAccountBalance(currentBlock,fromAddress,blockingStubFull); - afterToBalance = PublicMethed.getAccountBalance(currentBlock,testAddress,blockingStubFull); - - Assert.assertTrue(afterToBalance - beforeToBalance == sendAmount); - Assert.assertTrue(beforeFromBalance - afterFromBalance >= sendAmount + 100000L); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(testAddress, testKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java deleted file mode 100644 index 24843f19716..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/account/TransactionFee001.java +++ /dev/null @@ -1,662 +0,0 @@ -package stest.tron.wallet.dailybuild.account; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Commons; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.Retry; -import stest.tron.wallet.common.client.utils.Sha256Hash; - - - -@Slf4j - -public class TransactionFee001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey01 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress01 = PublicMethed.getFinalAddress(witnessKey01); - private final String witnessKey02 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessAddress02 = PublicMethed.getFinalAddress(witnessKey02); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private final String blackHoleAdd = Configuration.getByPath("testng.conf") - .getString("defaultParameter.blackHoleAddress"); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private ManagedChannel channelPbft = null; - - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] deployAddress = ecKey1.getAddress(); - final String deployKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - Long startNum = 0L; - Long endNum = 0L; - Long witness01Allowance1 = 0L; - Long witness02Allowance1 = 0L; - Long blackHoleBalance1 = 0L; - Long witness01Allowance2 = 0L; - Long witness02Allowance2 = 0L; - Long blackHoleBalance2 = 0L; - Long witness01Increase = 0L; - Long witness02Increase = 0L; - Long beforeBurnTrxAmount = 0L; - Long afterBurnTrxAmount = 0L; - String txid = null; - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Test deploy contract with energy fee to sr") - public void test01DeployContractEnergyFeeToSr() { - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode//contractLinkage003.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = null; - String code = null; - String abi = null; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = PublicMethed.queryAccount(witnessAddress01, blockingStubFull) - .getAllowance(); - witness02Allowance1 = PublicMethed.queryAccount(witnessAddress02, blockingStubFull) - .getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 0, null, - deployKey, deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = PublicMethed.queryAccount(witnessAddress01, blockingStubFull) - .getAllowance(); - witness02Allowance2 = PublicMethed.queryAccount(witnessAddress02, blockingStubFull) - .getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - //blackHoleIncrease = blackHoleBalance2 - blackHoleBalance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - - Map witnessAllowance = PublicMethed.getAllowance2(startNum, endNum, - blockingStubFull); - - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1, blackHoleBalance2); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(infoById.get().getFee(),infoById.get().getPackingFee()); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertEquals(beforeBurnTrxAmount,afterBurnTrxAmount); - } - - @Test(enabled = true, retryAnalyzer = Retry.class, - description = "Test update account permission fee to black hole," - + "trans with multi sign and fee to sr") - public void test02UpdateAccountPermissionAndMultiSiginTrans() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - byte[] tmpAddr02 = tmpEcKey02.getAddress(); - final String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey01); - activePermissionKeys.add(tmpKey02); - - logger.info("** update owner and active permission to two address"); - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"" - + ",\"threshold\":2," - + "\"operations\"" - + ":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey01) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" - + "]}]}"; - - txid = PublicMethedForMutiSign.accountPermissionUpdateForTransactionId(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(infoById.get().getPackingFee(),0); - Assert.assertEquals(infoById.get().getFee(),100000000L); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - //blackHoleIncrease = blackHoleBalance2 - blackHoleBalance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance2, blackHoleBalance1); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - logger.info(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000000L); - - - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - - Protocol.Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())); - logger.info("-----transaction: " + txid); - - Protocol.Transaction transaction1 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction, tmpKey02, 2, blockingStubFull); - txid = ByteArray.toHexString(Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction1.getRawData().toByteArray())); - logger.info("-----transaction1: " + txid); - - Protocol.Transaction transaction2 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction1, witnessKey01, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - - GrpcAPI.TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - - witnessAllowance = PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance2, blackHoleBalance1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(infoById.get().getPackingFee(),0); - Assert.assertEquals(infoById.get().getFee(),1000000L); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 1000000L); - } - - @Test(enabled = true, description = "Test trigger result is \"OUT_OF_TIME\"" - + " with energy fee to sr") - public void test03OutOfTimeEnergyFeeToBlackHole() { - Random rand = new Random(); - Integer randNum = rand.nextInt(4000); - - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, maxFeeLimit * 10, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = null; - contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, deployKey, deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "90100", false, - 0, maxFeeLimit, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - logger.info("InfoById:" + infoById); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance2, blackHoleBalance1); - Long packingFee = infoById.get().getPackingFee(); - logger.info("receipt:" + infoById.get().getReceipt()); - Assert.assertTrue(packingFee == 0L); - Assert.assertTrue(infoById.get().getFee() >= maxFeeLimit); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == maxFeeLimit); - } - - @Test(enabled = true, description = "Test create account with netFee to sr") - public void test04AccountCreate() { - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - txid = PublicMethed.createAccountGetTxid(fromAddress, lowBalAddress, - testKey002, blockingStubFull); - - - PublicMethed.waitProduceNextBlock(blockingStubFull); - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + " increase :" + witness02Increase); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1,blackHoleBalance2); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getPackingFee() == 0L); - Assert.assertTrue(infoById.get().getFee() == 100000L); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000L); - } - - @Test(enabled = true, description = "Test trigger contract with netFee and energyFee to sr") - public void test05NetFeeAndEnergyFee2Sr() { - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, maxFeeLimit * 10, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = null; - contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, deployKey, deployAddress, blockingStubFull); - for (int i = 0; i < 15; i++) { - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "700", false, - 0, maxFeeLimit, deployAddress, deployKey, blockingStubFull); - } - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "700", false, - 0, maxFeeLimit, deployAddress, deployKey, blockingStubFull); - // PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + "increase :" + witness02Increase); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("InfoById:" + infoById); - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1,blackHoleBalance2); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertEquals(beforeBurnTrxAmount,afterBurnTrxAmount); - } - - /** - * constructor. - */ - - @Test(enabled = true, description = "Test create trc10 token with fee not to sr") - public void test06CreateAssetIssue() { - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] tokenAccountAddress = ecKey1.getAddress(); - final String tokenAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - PublicMethed.printAddress(tokenAccountKey); - - Assert.assertTrue(PublicMethed - .sendcoin(tokenAccountAddress, 1028000000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - startNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance1 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance1 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance1 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - beforeBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - long now = System.currentTimeMillis(); - long totalSupply = now; - String description = "for case assetissue016"; - String url = "https://stest.assetissue016.url/"; - String name = "AssetIssue016_" + Long.toString(now); - txid = PublicMethed.createAssetIssueGetTxid(tokenAccountAddress, name, name,totalSupply, - 1, 1, start, end, 1, description, url, 0L, - 0L, 1L, 1L, tokenAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - endNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - witness01Allowance2 = - PublicMethed.queryAccount(witnessAddress01, blockingStubFull).getAllowance(); - witness02Allowance2 = - PublicMethed.queryAccount(witnessAddress02, blockingStubFull).getAllowance(); - blackHoleBalance2 = PublicMethed.queryAccount(Commons.decode58Check(blackHoleAdd), - blockingStubFull).getBalance(); - - witness02Increase = witness02Allowance2 - witness02Allowance1; - witness01Increase = witness01Allowance2 - witness01Allowance1; - logger.info("----startNum:" + startNum + " endNum:" + endNum); - logger.info("====== witness01Allowance1 :" + witness01Allowance1 + " witness01Allowance2 :" - + witness01Allowance2 + " increase :" + witness01Increase); - logger.info("====== witness02Allowance1 :" + witness02Allowance1 + " witness02Allowance2 :" - + witness02Allowance2 + " increase :" + witness02Increase); - - Map witnessAllowance = - PublicMethed.getAllowance2(startNum, endNum, blockingStubFull); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress01)) - - witness01Increase)) <= 2); - Assert.assertTrue((Math.abs(witnessAllowance.get(ByteArray.toHexString(witnessAddress02)) - - witness02Increase)) <= 2); - Assert.assertEquals(blackHoleBalance1,blackHoleBalance2); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getPackingFee() == 0L); - Assert.assertTrue(infoById.get().getFee() == 1024000000L); - afterBurnTrxAmount = blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()).getNum(); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 1024000000L); - - - } - - /** - * constructor. - */ - - @Test(enabled = true, description = "Test getburntrx api from solidity or pbft") - public void test07GetBurnTrxFromSolidityOrPbft() { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - Assert.assertEquals(blockingStubFull - .getBurnTrx(EmptyMessage.newBuilder().build()),blockingStubSolidity.getBurnTrx( - EmptyMessage.newBuilder().build())); - Assert.assertEquals(blockingStubFull.getBurnTrx(EmptyMessage.newBuilder().build()), - blockingStubPbft.getBurnTrx( - EmptyMessage.newBuilder().build())); - } - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(deployAddress, deployKey, 1, deployAddress, - blockingStubFull); - PublicMethed.freedResource(deployAddress, deployKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/account/WalletTestAccount012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/account/WalletTestAccount012.java deleted file mode 100644 index c85fdca800b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/account/WalletTestAccount012.java +++ /dev/null @@ -1,204 +0,0 @@ -package stest.tron.wallet.dailybuild.account; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount012 { - private static final long sendAmount = 10000000000L; - private static final long frozenAmountForTronPower = 3456789L; - private static final long frozenAmountForNet = 7000000L; - private final String foundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress = PublicMethed.getFinalAddress(foundationKey); - - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] frozenAddress = ecKey1.getAddress(); - String frozenKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(frozenKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Freeze balance to get tron power") - public void test01FreezeBalanceGetTronPower() { - - - final Long beforeFrozenTime = System.currentTimeMillis(); - Assert.assertTrue(PublicMethed.sendcoin(frozenAddress, sendAmount, - foundationAddress, foundationKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - final Long beforeTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - final Long beforeTronPowerLimit = accountResource.getTronPowerLimit(); - - - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(frozenAddress,frozenAmountForTronPower, - 0,2,null,frozenKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(frozenAddress,frozenAmountForNet, - 0,0,null,frozenKey,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterFrozenTime = System.currentTimeMillis(); - Account account = PublicMethed.queryAccount(frozenAddress,blockingStubFull); - Assert.assertEquals(account.getTronPower().getFrozenBalance(),frozenAmountForTronPower); - Assert.assertTrue(account.getTronPower().getExpireTime() > beforeFrozenTime - && account.getTronPower().getExpireTime() < afterFrozenTime); - - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - Long afterTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - Long afterTronPowerLimit = accountResource.getTronPowerLimit(); - Long afterTronPowerUsed = accountResource.getTronPowerUsed(); - Assert.assertEquals(afterTotalTronPowerWeight - beforeTotalTronPowerWeight, - frozenAmountForTronPower / 1000000L); - - Assert.assertEquals(afterTronPowerLimit - beforeTronPowerLimit, - frozenAmountForTronPower / 1000000L); - - - - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(frozenAddress, - 6000000 - frozenAmountForTronPower, - 0,2,null,frozenKey,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - afterTronPowerLimit = accountResource.getTronPowerLimit(); - - Assert.assertEquals(afterTronPowerLimit - beforeTronPowerLimit, - 6); - - - } - - - @Test(enabled = true,description = "Vote witness by tron power") - public void test02VotePowerOnlyComeFromTronPower() { - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - final Long beforeTronPowerUsed = accountResource.getTronPowerUsed(); - - - HashMap witnessMap = new HashMap<>(); - witnessMap.put(witnessAddress,frozenAmountForNet / 1000000L); - Assert.assertFalse(PublicMethed.voteWitness(frozenAddress,frozenKey,witnessMap, - blockingStubFull)); - witnessMap.put(witnessAddress,frozenAmountForTronPower / 1000000L); - Assert.assertTrue(PublicMethed.voteWitness(frozenAddress,frozenKey,witnessMap, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - Long afterTronPowerUsed = accountResource.getTronPowerUsed(); - Assert.assertEquals(afterTronPowerUsed - beforeTronPowerUsed, - frozenAmountForTronPower / 1000000L); - - final Long secondBeforeTronPowerUsed = afterTronPowerUsed; - witnessMap.put(witnessAddress,(frozenAmountForTronPower / 1000000L) - 1); - Assert.assertTrue(PublicMethed.voteWitness(frozenAddress,frozenKey,witnessMap, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - afterTronPowerUsed = accountResource.getTronPowerUsed(); - Assert.assertEquals(secondBeforeTronPowerUsed - afterTronPowerUsed, - 1); - - - } - - @Test(enabled = true,description = "Tron power is not allow to others") - public void test03TronPowerIsNotAllowToOthers() { - Assert.assertFalse(PublicMethed.freezeBalanceGetTronPower(frozenAddress, - frozenAmountForTronPower, 0,2, - ByteString.copyFrom(foundationAddress),frozenKey,blockingStubFull)); - } - - - @Test(enabled = true,description = "Unfreeze balance for tron power") - public void test04UnfreezeBalanceForTronPower() { - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(foundationAddress, blockingStubFull); - final Long beforeTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - - - Assert.assertTrue(PublicMethed.unFreezeBalance(frozenAddress,frozenKey,2, - null,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed - .getAccountResource(frozenAddress, blockingStubFull); - Long afterTotalTronPowerWeight = accountResource.getTotalTronPowerWeight(); - Assert.assertEquals(beforeTotalTronPowerWeight - afterTotalTronPowerWeight, - 6); - - Assert.assertEquals(accountResource.getTronPowerLimit(),0L); - Assert.assertEquals(accountResource.getTronPowerUsed(),0L); - - Account account = PublicMethed.queryAccount(frozenAddress,blockingStubFull); - Assert.assertEquals(account.getTronPower().getFrozenBalance(),0); - - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(frozenAddress, frozenKey, 2, null, - blockingStubFull); - PublicMethed.unFreezeBalance(frozenAddress, frozenKey, 0, null, - blockingStubFull); - PublicMethed.freedResource(frozenAddress, frozenKey, foundationAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java deleted file mode 100644 index 03a20ac4aa5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletExchange001.java +++ /dev/null @@ -1,394 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletExchange001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true,description = "Create two asset issue to create exchange") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, toAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true,description = "Test create exchange") - public void test2CreateExchange() { - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethed.exchangeCreate(assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - Integer afterCreateExchangeNum = listExchange.get().getExchangesCount(); - Assert.assertTrue(afterCreateExchangeNum - beforeCreateExchangeNum == 1); - exchangeId = listExchange.get().getExchangesCount(); - - } - - @Test(enabled = true,description = "Test list exchange api") - public void test3ListExchange() { - listExchange = PublicMethed.getExchangeList(blockingStubFull); - for (Integer i = 0; i < listExchange.get().getExchangesCount(); i++) { - Assert.assertFalse(ByteArray.toHexString(listExchange.get().getExchanges(i) - .getCreatorAddress().toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getExchangeId() > 0); - Assert.assertFalse(ByteArray.toStr(listExchange.get().getExchanges(i).getFirstTokenId() - .toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getFirstTokenBalance() > 0); - } - } - - @Test(enabled = true,description = "Test inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethed.injectExchange(exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - } - - @Test(enabled = true,description = "Test withdraw exchange") - public void test5WithdrawExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethed.exchangeWithdraw(exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - - - } - - @Test(enabled = true,description = "Test exchange transaction") - public void test6TransactionExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethed - .exchangeTransaction(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - } - - @Test(enabled = true,description = "Test GetExchangeListPaginated api") - public void test7GetExchangeListPaginated() { - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(0); - pageMessageBuilder.setLimit(100); - ExchangeList exchangeList = blockingStubFull - .getPaginatedExchangeList(pageMessageBuilder.build()); - Assert.assertTrue(exchangeList.getExchangesCount() >= 1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Solidity support getExchangeId - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubSolidity); - logger.info("createtime is" + exchangeIdInfo.get().getCreateTime()); - Assert.assertTrue(exchangeIdInfo.get().getCreateTime() > 0); - - //Solidity support listexchange - listExchange = PublicMethed.getExchangeList(blockingStubSolidity); - Assert.assertTrue(listExchange.get().getExchangesCount() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true,description = "Test get exchange list from pbft") - public void test8GetExchangeListFromPbft() { - //Pbft support listexchange - listExchange = PublicMethed.getExchangeList(blockingStubPbft); - Assert.assertTrue(listExchange.get().getExchangesCount() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true,description = "Test get exchange by id from pbft") - public void test9GetExchangeByIdFromPbft() { - Assert.assertEquals(PublicMethed.getExchange(exchangeId.toString(), blockingStubPbft), - PublicMethed.getExchange(exchangeId.toString(), blockingStubSolidity)); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue001.java deleted file mode 100644 index e11c73c11f8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue001.java +++ /dev/null @@ -1,333 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Transfer asset use Bandwitch") - public void testTransferAssetBandwitchDecreaseWithin10Second() { - //get account - ecKey = new ECKey(Utils.getRandom()); - noBandwitchAddress = ecKey.getAddress(); - noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - PublicMethed.printAddress(noBandwitch); - - Assert.assertTrue(PublicMethed.sendcoin(noBandwitchAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(noBandwitchAddress, name, totalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, noBandwitch, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(noBandwitch, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - Assert.assertTrue(transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - noBandwitchAddress, noBandwitch)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Transfer Asset failed when transfer to yourself - Assert.assertFalse(transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - toAddress, testKey003)); - //Transfer Asset failed when the transfer amount is large than the asset balance you have. - Assert.assertFalse( - transferAsset(fromAddress, assetAccountId.toByteArray(), 9100000000000000000L, - toAddress, testKey003)); - //Transfer Asset failed when the transfer amount is 0 - Assert.assertFalse(transferAsset(fromAddress, assetAccountId.toByteArray(), 0L, - toAddress, testKey003)); - //Transfer Asset failed when the transfer amount is -1 - Assert.assertFalse(transferAsset(fromAddress, assetAccountId.toByteArray(), -1L, - toAddress, testKey003)); - - //Transfer success. - Assert.assertTrue(transferAsset(fromAddress, assetAccountId.toByteArray(), 1L, - toAddress, testKey003)); - - //No freeze asset, try to unfreeze asset failed. - Assert.assertFalse(unFreezeAsset(noBandwitchAddress, noBandwitch)); - - //Not create asset, try to unfreeze asset failed.No exception. - Assert.assertFalse(unFreezeAsset(toAddress, testKey003)); - - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(noBandwitchAddress, noBandwitch, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return response.getResult(); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue002.java deleted file mode 100644 index 5dc6e50fd69..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue002.java +++ /dev/null @@ -1,346 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = "Participate token") - public void testParticipateAssetissue() { - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] participateAccountAddress = ecKey1.getAddress(); - final String participateAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] toAddress = ecKey2.getAddress(); - final String testKey003 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - //send coin to the new account - Assert.assertTrue(PublicMethed.sendcoin(participateAccountAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Create a new Asset Issue - Assert.assertTrue(PublicMethed.createAssetIssue(participateAccountAddress, - name, totalSupply, 1, 1, System.currentTimeMillis() + 5000, - System.currentTimeMillis() + 1000000000, 1, description, url, - 2000L, 2000L, 1L, 1L, - participateAccountKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(participateAccountKey, blockingStubFull); - final ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Participate AssetIssue success - logger.info(name); - //Freeze amount to get bandwitch. - logger.info("toaddress balance is " - + PublicMethed.queryAccount(toAddress, blockingStubFull).getBalance()); - Assert.assertTrue(PublicMethed.freezeBalance(toAddress, 10000000, 3, testKey003, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), - 100L, toAddress, testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //The amount is large than the total supply, participate failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), 9100000000000000000L, toAddress, testKey003, - blockingStubFull)); - - //The amount is 0, participate asset issue failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), 0L, toAddress, testKey003, blockingStubFull)); - - //The amount is -1, participate asset issue failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(participateAccountAddress, - assetAccountId.toByteArray(), -1L, toAddress, testKey003, blockingStubFull)); - - //The asset issue owner address is not correct, participate asset issue failed. - Assert.assertFalse(PublicMethed.participateAssetIssue(fromAddress, - assetAccountId.toByteArray(), 100L, - toAddress, testKey003, blockingStubFull)); - - PublicMethed.freedResource(participateAccountAddress, participateAccountKey, fromAddress, - blockingStubFull); - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(name); - } - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue003.java deleted file mode 100644 index d27ab4ab55c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue003.java +++ /dev/null @@ -1,416 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private static final String tooLongName = "qazxswedcvfrtgbnhyujmkiolpoiuytre"; - private static final String chineseAssetIssuename = "中文都名字"; - private static final String tooLongAbbreviation = "wazxswedcvfrtgbnhyujmkiolpoiuytre"; - private static final String chineseAbbreviation = "中文的简称"; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqa" - + "zxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvq" - + "azxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = - "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqasw1qazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqaz" - + "xswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] asset003Address = ecKey.getAddress(); - String asset003Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Create token with exception condition") - public void testExceptionOfAssetIssuew() { - PublicMethed.sendcoin(asset003Address, 2048000000L, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 100000; - Long end = System.currentTimeMillis() + 1000000000; - //Freeze amount is large than total supply, create asset issue failed. - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 9000000000000000000L, 1L, asset003Key, blockingStubFull)); - //Freeze day is 0, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 100L, 0L, asset003Key, blockingStubFull)); - //Freeze amount is 0, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 0L, 1L, asset003Key, blockingStubFull)); - //Freeze day is -1, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 1000L, 1000L, - 1000L, -1L, asset003Key, blockingStubFull)); - //Freeze amount is -1, create failed - Assert.assertFalse(PublicMethed.createAssetIssue(asset003Address, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - -1L, 1L, asset003Key, blockingStubFull)); - //Freeze day is 3653(10 years + 1 day), create failed - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3653L, asset003Key, blockingStubFull)); - //Start time is late than end time. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - end, start, 2, description, url, 10000L, 10000L, - 1L, 2L, asset003Key, blockingStubFull)); - //Start time is early than currently time. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start - 1000000L, end, 2, description, url, 10000L, - 10000L, 1L, 2L, asset003Key, blockingStubFull)); - //totalSupply is zero. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, 0L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //Total supply is -1. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, -1L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //TrxNum is zero. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 0, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //TrxNum is -1. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, -1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //IcoNum is 0. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 0, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //IcoNum is -1. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, -1, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The asset issue name is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, "", totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The asset issue name is large than 33 char. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, tooLongName, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The asset issue name is chinese name. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, chineseAssetIssuename, - totalSupply, 1, 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The abbreviation is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, "", totalSupply, - 1, 10, start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The abbreviation is large than 33 char. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, tooLongAbbreviation, - totalSupply, 1, 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The abbreviation is chinese name. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, chineseAbbreviation, - totalSupply, 1, 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The URL is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start, end, 2, description, "", 10000L, 10000L, - 1L, 3652L, asset003Key, blockingStubFull)); - //The URL is too long. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, - 1, 10, start, end, 2, description, tooLongUrl, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The description is null. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, - 1, 10, start, end, 2, "", url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - //The description is too long, create failed. - Assert.assertFalse(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 10, - start, end, 2, tooLongDescription, url, 10000L, - 10000L, 1L, 3652L, asset003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Get asset issue list") - public void testGetAllAssetIssue() { - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(assetIssueList.getAssetIssueCount() >= 1); - Integer times = assetIssueList.getAssetIssueCount(); - if (assetIssueList.getAssetIssueCount() >= 10) { - times = 10; - } - for (Integer j = 0; j < times; j++) { - Assert.assertFalse(assetIssueList.getAssetIssue(j).getOwnerAddress().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getName().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getUrl().isEmpty()); - Assert.assertTrue(assetIssueList.getAssetIssue(j).getTotalSupply() > 0); - logger.info("test get all assetissue"); - } - - //Improve coverage. - assetIssueList.equals(assetIssueList); - assetIssueList.equals(null); - GrpcAPI.AssetIssueList newAssetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - assetIssueList.equals(newAssetIssueList); - assetIssueList.hashCode(); - assetIssueList.getSerializedSize(); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(asset003Address, asset003Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue004.java deleted file mode 100644 index 2b05a13861a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue004.java +++ /dev/null @@ -1,294 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue004 { - - //testng001、testng002、testng003、testng004 - /* private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7");*/ - private static final byte[] NO_ASSET_ADDRESS = Base58 - .decodeFromBase58Check("27XeWZUtufGk8jdjF3m1tuPnnRqqKgzS3pT"); - private static final byte[] INVALID_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue004_" + Long.toString(now); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ByteString addressBs1 = ByteString.copyFrom(fromAddress); - Account request1 = Account.newBuilder().setAddress(addressBs1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new asset issue - Assert.assertTrue(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 6, 1000, - start, end, 2, description, url, 10000L, 10000L, - 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } else { - logger.info("This account already create an assetisue"); - } - - } - - @Test(enabled = true, description = "Get asset issue by account") - public void testGetAssetIssueByAccount() { - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account request = Account.newBuilder().setAddress(addressBs).build(); - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueByAccount(request); - Optional queryAssetIssueByAccount = Optional.ofNullable(assetIssueList); - logger.info(Integer.toString(queryAssetIssueByAccount.get().getAssetIssueCount())); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssueCount() == 1); - for (Integer j = 0; j < queryAssetIssueByAccount.get().getAssetIssueCount(); j++) { - if (queryAssetIssueByAccount.get().getAssetIssue(j).getTotalSupply() == totalSupply) { - Assert.assertTrue(queryAssetIssueByAccount.isPresent()); - //Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getDecayRatio() > 0); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getTrxNum() > 0); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getVoteScore() > 0); - Assert.assertFalse(queryAssetIssueByAccount.get().getAssetIssue(j).getUrl().isEmpty()); - logger.info("TestGetAssetIssueByAccount ok!"); - } - } - - //No exception when the address didn't create asset issue. - ByteString addressBS1 = ByteString.copyFrom(NO_ASSET_ADDRESS); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryNoAssetByAccount = Optional.ofNullable(assetIssueList1); - Assert.assertTrue(queryNoAssetByAccount.get().getAssetIssueCount() == 0); - logger.info("No asset account queryed nothing"); - - //No exception when the address is invalid. - addressBS1 = ByteString.copyFrom(INVALID_ADDRESS); - request1 = Account.newBuilder().setAddress(addressBS1).build(); - assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - queryNoAssetByAccount = Optional.ofNullable(assetIssueList1); - Assert.assertTrue(queryNoAssetByAccount.get().getAssetIssueCount() == 0); - logger.info("No asset account queryed nothing"); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder - frozenBuilder = AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult()) { - logger.info(name); - } - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult()) { - Account search = queryAccount(ecKey, blockingStubFull); - } - return response.getResult(); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue005.java deleted file mode 100644 index 8b7fa37c5c6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue005.java +++ /dev/null @@ -1,297 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue005 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue005_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Get asset issue by name") - public void testGetAssetIssueByName() { - ByteString addressBS1 = ByteString.copyFrom(fromAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new asset issue - Assert.assertTrue(PublicMethed.createAssetIssue(fromAddress, name, totalSupply, 1, 100, - start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - } - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Get asset issue by name success. - - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(assetAccountId) - .build(); - AssetIssueContract assetIssueByName = - blockingStubFull.getAssetIssueByName(request); - - Assert.assertFalse(assetIssueByName.getUrl().isEmpty()); - Assert.assertFalse(assetIssueByName.getDescription().isEmpty()); - Assert.assertTrue(assetIssueByName.getTotalSupply() > 0); - Assert.assertTrue(assetIssueByName.getTrxNum() > 0); - - //Get asset issue by name failed when the name is not correct.There is no exception. - String wrongName = name + "_wrong"; - ByteString assetNameBs = ByteString.copyFrom(name.getBytes()); - assetNameBs = ByteString.copyFrom(wrongName.getBytes()); - request = GrpcAPI.BytesMessage.newBuilder().setValue(assetNameBs).build(); - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertFalse(assetIssueByName.getTotalSupply() > 0); - Assert.assertFalse(assetIssueByName.getTrxNum() > 0); - Assert.assertTrue(assetIssueByName.getUrl().isEmpty()); - Assert.assertTrue(assetIssueByName.getDescription().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult()) { - logger.info(name); - } - return response.getResult(); - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue006.java deleted file mode 100644 index 181dac3eddb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue006.java +++ /dev/null @@ -1,213 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue006 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "assetissue006" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "test query assetissue by timestamp from soliditynode"; - String url = "https://testqueryassetissue.com/bytimestamp/from/soliditynode/"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] queryAssetIssueFromSoliAddress = ecKey.getAddress(); - String queryAssetIssueKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - /* @Test(enabled = true) - public void testGetAssetIssueListByTimestamp() { - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress,10000000,3,testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(queryAssetIssueFromSoliAddress,2048000000,fromAddress, - testKey002,blockingStubFull)); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(queryAssetIssueFromSoliAddress, name, - totalSupply, 1, 100, start, end, 1, description, url, 1000L, - 1000L,1L,1L,queryAssetIssueKey,blockingStubFull)); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block solidityCurrentBlock = blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage - .newBuilder().build()); - Integer wait = 0; - while (solidityCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 10) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Solidity didn't synchronize the fullnode block,please wait"); - solidityCurrentBlock = blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder() - .build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - - long time = now; - NumberMessage.Builder timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueListByTimestamp(timeStamp.build()); - Optional getAssetIssueListByTimestamp = Optional - .ofNullable(assetIssueList); - - Assert.assertTrue(getAssetIssueListByTimestamp.isPresent()); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssueCount() > 0); - logger.info(Integer.toString(getAssetIssueListByTimestamp.get().getAssetIssueCount())); - for (Integer j = 0; j < getAssetIssueListByTimestamp.get().getAssetIssueCount(); j++) { - Assert.assertFalse(getAssetIssueListByTimestamp.get().getAssetIssue(j).getName().isEmpty()); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssue(j).getTotalSupply() > 0); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssue(j).getNum() > 0); - logger.info( - Long.toString(getAssetIssueListByTimestamp.get().getAssetIssue(j).getTotalSupply())); - } - - } - - @Test(enabled = true) - public void testExceptionGetAssetIssueListByTimestamp() { - //Time stamp is below zero. - long time = -1000000000; - NumberMessage.Builder timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueListByTimestamp(timeStamp.build()); - Optional getAssetIssueListByTimestamp = Optional - .ofNullable(assetIssueList); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssueCount() == 0); - - //No asset issue was create - time = 1000000000; - timeStamp = NumberMessage.newBuilder(); - timeStamp.setNum(time); - assetIssueList = blockingStubSolidity.getAssetIssueListByTimestamp(timeStamp.build()); - getAssetIssueListByTimestamp = Optional.ofNullable(assetIssueList); - Assert.assertTrue(getAssetIssueListByTimestamp.get().getAssetIssueCount() == 0); - - }*/ - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue007.java deleted file mode 100644 index aaac0b4ff29..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue007.java +++ /dev/null @@ -1,173 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue007 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static final Integer trxNum = 1; - private static final Integer icoNum = 1; - private static String name = "AssetIssue007_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 10000L; - Long publicFreeAssetNetLimit = 10000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset007Address = ecKey1.getAddress(); - String testKeyForAssetIssue007 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAssetAddress = ecKey2.getAddress(); - String participateAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForAssetIssue007); - PublicMethed.printAddress(participateAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Participate asset issue use participate bandwidth") - public void testParticipateAssetIssueUseParticipateBandwidth() { - Assert.assertTrue(PublicMethed - .sendcoin(asset007Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset007Address, name, totalSupply, trxNum, icoNum, start, end, 1, - description, url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, - testKeyForAssetIssue007, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(name); - //Assert.assertTrue(PublicMethed.waitProduceNextBlock(blockingStubFull)); - //When no balance, participate an asset issue - Assert.assertFalse(PublicMethed - .participateAssetIssue(asset007Address, name.getBytes(), 1L, participateAssetAddress, - participateAssetCreateKey, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(asset007Address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage asset007NetMessage = blockingStubFull.getAccountNet(request); - final Long asset007BeforeFreeNetUsed = asset007NetMessage.getFreeNetUsed(); - - //SendCoin to participate account. - Assert.assertTrue(PublicMethed - .sendcoin(participateAssetAddress, 10000000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - addressBs = ByteString.copyFrom(participateAssetAddress); - request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage participateAccountNetMessage = blockingStubFull.getAccountNet(request); - final Long participateAccountBeforeNetUsed = participateAccountNetMessage.getFreeNetUsed(); - Assert.assertTrue(participateAccountBeforeNetUsed == 0); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset007Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info(assetAccountId.toString()); - - //Participate an assetIssue, then query the net information. - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - addressBs = ByteString.copyFrom(asset007Address); - request = Account.newBuilder().setAddress(addressBs).build(); - asset007NetMessage = blockingStubFull.getAccountNet(request); - final Long asset007AfterFreeNetUsed = asset007NetMessage.getFreeNetUsed(); - - addressBs = ByteString.copyFrom(participateAssetAddress); - request = Account.newBuilder().setAddress(addressBs).build(); - participateAccountNetMessage = blockingStubFull.getAccountNet(request); - final Long participateAccountAfterNetUsed = participateAccountNetMessage.getFreeNetUsed(); - - logger.info(Long.toString(asset007BeforeFreeNetUsed)); - logger.info(Long.toString(asset007AfterFreeNetUsed)); - logger.info(Long.toString(participateAccountBeforeNetUsed)); - logger.info(Long.toString(participateAccountAfterNetUsed)); - Assert.assertTrue(asset007AfterFreeNetUsed <= asset007BeforeFreeNetUsed); - Assert.assertTrue(participateAccountAfterNetUsed - participateAccountBeforeNetUsed > 150); - - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account participateInfo = PublicMethed - .queryAccount(participateAssetCreateKey, blockingStubFull); - final Long beforeBalance = participateInfo.getBalance(); - Assert.assertTrue(PublicMethed - .participateAssetIssue(asset007Address, assetAccountId.toByteArray(), 1L, - participateAssetAddress, participateAssetCreateKey, blockingStubFull)); - participateInfo = PublicMethed.queryAccount(participateAssetCreateKey, blockingStubFull); - final Long afterBalance = participateInfo.getBalance(); - - Assert.assertTrue(beforeBalance - trxNum * 1 * icoNum >= afterBalance); - } - - @AfterMethod - public void aftertest() { - PublicMethed - .freedResource(asset007Address, testKeyForAssetIssue007, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue008.java deleted file mode 100644 index 97ff64d5ca6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue008.java +++ /dev/null @@ -1,282 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue008 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "assetissue008" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "test query assetissue from soliditynode"; - String url = "https://testqueryassetissue.com/from/soliditynode/"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] queryAssetIssueFromSoliAddress = ecKey.getAddress(); - String queryAssetIssueKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(ByteArray.toHexString(ecKey.getPrivKeyBytes())); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Get asset issue list from Solidity") - public void testGetAllAssetIssueFromSolidity() { - Assert.assertTrue(PublicMethed.sendcoin(queryAssetIssueFromSoliAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(queryAssetIssueFromSoliAddress, name, - totalSupply, 1, 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, queryAssetIssueKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(assetIssueList.getAssetIssueCount())); - - if (assetIssueList.getAssetIssueCount() == 0) { - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 10000000L, 3, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 999999L, fromAddress, - testKey002, blockingStubFull)); - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info("fullnode block num is " + Long.toString(currentBlock.getBlockHeader() - .getRawData().getNumber())); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - } - - assetIssueList = blockingStubSolidity - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(assetIssueList.getAssetIssueCount() >= 1); - for (Integer j = 0; j < assetIssueList.getAssetIssueCount(); j++) { - Assert.assertFalse(assetIssueList.getAssetIssue(j).getOwnerAddress().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getName().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getUrl().isEmpty()); - Assert.assertTrue(assetIssueList.getAssetIssue(j).getTotalSupply() > 0); - logger.info("test get all assetissue from solidity"); - } - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(queryAssetIssueFromSoliAddress, queryAssetIssueKey, fromAddress, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return response.getResult(); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue009.java deleted file mode 100644 index 924698b417b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue009.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - - /* @Test(enabled = true) - public void testGetAssetIssueByAccountOrNameFromSolidity() { - //By name - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account request = Account.newBuilder().setAddress(addressBs).build(); - GrpcAPI.AssetIssueList assetIssueList = blockingStubSolidity - .getAssetIssueByAccount(request); - Optional queryAssetIssueByAccount = Optional.ofNullable(assetIssueList); - logger.info(Integer.toString(queryAssetIssueByAccount.get().getAssetIssueCount())); - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssueCount() >= 1); - for (Integer j = 0; j < queryAssetIssueByAccount.get().getAssetIssueCount(); j++) { - Assert.assertTrue(queryAssetIssueByAccount.get().getAssetIssue(j).getTotalSupply() > 0); - Assert.assertFalse(queryAssetIssueByAccount.get().getAssetIssue(j).getName().isEmpty()); - logger.info("TestGetAssetIssueByAccount in soliditynode ok!!!"); - - } - - //By ID - ByteString assetName = queryAssetIssueByAccount.get().getAssetIssue(0).getName(); - GrpcAPI.BytesMessage requestAsset = GrpcAPI.BytesMessage.newBuilder().setValue(assetName) - .build(); - Contract.AssetIssueContract assetIssueByName = blockingStubSolidity - .getAssetIssueByName(requestAsset); - - Assert.assertFalse(assetIssueByName.getUrl().isEmpty()); - Assert.assertFalse(assetIssueByName.getDescription().isEmpty()); - Assert.assertTrue(assetIssueByName.getTotalSupply() > 0); - Assert.assertTrue(assetIssueByName.getTrxNum() > 0); - - logger.info("TestGetAssetIssueByNameFromSolidity"); - }*/ - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue010.java deleted file mode 100644 index f60dfa834eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue010.java +++ /dev/null @@ -1,443 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue010 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswe" - + "dcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqas" - + "wqaswqasw1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazx" - + "swedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static String name = "testAssetIssue010_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - String updateDescription = "This is test for update asset issue, case AssetIssue_010"; - String updateUrl = "www.updateassetissue.010.cn"; - Long freeAssetNetLimit = 1000L; - Long publicFreeAssetNetLimit = 1000L; - Long updateFreeAssetNetLimit = 10001L; - Long updatePublicFreeAssetNetLimit = 10001L; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] asset010Address = ecKey.getAddress(); - String testKeyForAssetIssue010 = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Update asset issue") - public void testUpdateAssetIssue() { - ecKey = new ECKey(Utils.getRandom()); - asset010Address = ecKey.getAddress(); - testKeyForAssetIssue010 = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - PublicMethed.printAddress(testKeyForAssetIssue010); - - Assert.assertTrue(PublicMethed - .sendcoin(asset010Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset010Address, 200000000L, 0, testKeyForAssetIssue010, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(asset010Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 1L, 1L, testKeyForAssetIssue010, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed - .queryAccount(testKeyForAssetIssue010, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Query the description and url,freeAssetNetLimit and publicFreeAssetNetLimit - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder() - .setValue(assetAccountId).build(); - AssetIssueContract assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(description)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(url)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == freeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == publicFreeAssetNetLimit); - - //Test update asset issue - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - updatePublicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //After update asset issue ,query the description and url, - // freeAssetNetLimit and publicFreeAssetNetLimit - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(updateDescription)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(updateUrl)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == updateFreeAssetNetLimit); - Assert - .assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == updatePublicFreeAssetNetLimit); - } - - @Test(enabled = true, description = "Update asset issue with exception condition") - public void testUpdateAssetIssueException() { - //Test update asset issue for wrong parameter - //publicFreeAssetNetLimit is -1 - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - -1L, testKeyForAssetIssue010, blockingStubFull)); - //publicFreeAssetNetLimit is 0 - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - 0, testKeyForAssetIssue010, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //FreeAssetNetLimit is -1 - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), -1, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //FreeAssetNetLimit is 0 - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), 0, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Description is null - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, "".getBytes(), updateUrl.getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //Url is null - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, description.getBytes(), "".getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //Too long discription - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, tooLongDescription.getBytes(), url.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - //Too long URL - Assert.assertFalse(PublicMethed - .updateAsset(asset010Address, description.getBytes(), tooLongUrl.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - } - - @AfterMethod - public void aftertest() { - PublicMethed - .freedResource(asset010Address, testKeyForAssetIssue010, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset010Address, testKeyForAssetIssue010, 0, asset010Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = PublicMethed.queryAccount(priKey, blockingStubFull); - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue011.java deleted file mode 100644 index c44485f98f9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue011.java +++ /dev/null @@ -1,133 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue011 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final String updateMostLongName = Long.toString(now) + "w234567890123456789"; - private static String name = "testAssetIssue011_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 10000L; - Long publicFreeAssetNetLimit = 10000L; - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset011Address = ecKey1.getAddress(); - String testKeyForAssetIssue011 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetCreateAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForAssetIssue011); - PublicMethed.printAddress(transferAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Transfer asset to create account") - public void testTransferAssetCreateAccount() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset011Address = ecKey1.getAddress(); - testKeyForAssetIssue011 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetCreateAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset011Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset011Address, 100000000L, 3, testKeyForAssetIssue011, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset011Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue011, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset011Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to create an account. - Assert.assertTrue(PublicMethed - .transferAsset(transferAssetCreateAddress, assetAccountId.toByteArray(), 1L, - asset011Address, testKeyForAssetIssue011, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account queryTransferAssetAccount = PublicMethed - .queryAccount(transferAssetCreateKey, blockingStubFull); - Assert.assertTrue(queryTransferAssetAccount.getAssetV2Count() == 1); - Assert.assertTrue(PublicMethed.updateAccount(asset011Address, Long.toString(now) - .getBytes(), testKeyForAssetIssue011, blockingStubFull)); - Assert.assertTrue(PublicMethed.updateAccount(transferAssetCreateAddress, updateMostLongName - .getBytes(), transferAssetCreateKey, blockingStubFull)); - queryTransferAssetAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - Assert.assertFalse(queryTransferAssetAccount.getAccountName().isEmpty()); - PublicMethed - .freedResource(asset011Address, testKeyForAssetIssue011, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset011Address, testKeyForAssetIssue011, 0, asset011Address, - blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue012.java deleted file mode 100644 index 8ad9b6cbe40..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue012.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue012 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 10000L; - Long publicFreeAssetNetLimit = 10000L; - String description = "for case assetissue012"; - String url = "https://stest.assetissue012.url/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset012Address = ecKey1.getAddress(); - String testKeyForAssetIssue012 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue012); - logger.info(transferAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Transfer asset use token owner net") - public void testTransferAssetUseCreatorNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset012Address = ecKey1.getAddress(); - testKeyForAssetIssue012 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(testKeyForAssetIssue012); - PublicMethed.printAddress(transferAssetCreateKey); - - Assert.assertTrue(PublicMethed - .sendcoin(asset012Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset012Address, 100000000L, 3, testKeyForAssetIssue012, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset012Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue012, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset012Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - Assert.assertTrue(PublicMethed.transferAsset( - transferAssetAddress, assetAccountId.toByteArray(), 10000000L, asset012Address, - testKeyForAssetIssue012, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Before transfer asset issue, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset012Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeNetUsed = assetCreatorNet.getNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the creator net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetCreatorNet = PublicMethed - .getAccountNet(asset012Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterNetUsed = assetCreatorNet.getNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterNetUsed - creatorBeforeNetUsed > netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed < netCostMeasure); - - PublicMethed - .freedResource(asset012Address, testKeyForAssetIssue012, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset012Address, testKeyForAssetIssue012, 0, asset012Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue013.java deleted file mode 100644 index 58795fda9e7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue013.java +++ /dev/null @@ -1,157 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue013 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue013_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 300L; - Long publicFreeAssetNetLimit = 3000L; - String description = "for case assetissue013"; - String url = "https://stest.assetissue013.url/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset013Address = ecKey1.getAddress(); - String testKeyForAssetIssue013 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Use transfer net when token owner has no enough net") - public void testWhenNoEnoughFreeAssetNetLimitUseTransferNet() { - - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset013Address = ecKey1.getAddress(); - final String testKeyForAssetIssue013 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - final byte[] transferAssetAddress = ecKey2.getAddress(); - final String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - logger.info(testKeyForAssetIssue013); - logger.info(transferAssetCreateKey); - - Assert.assertTrue(PublicMethed - .sendcoin(asset013Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalance(asset013Address, 100000000L, 3, testKeyForAssetIssue013, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset013Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue013, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset013Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - Assert.assertTrue(PublicMethed.transferAsset( - transferAssetAddress, assetAccountId.toByteArray(), - 10000000L, asset013Address, testKeyForAssetIssue013, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Transfer send some asset issue to default account, to test if this - // transaction use the creator net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Before use transfer net, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset013Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeNetUsed = assetCreatorNet.getNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the transaction free net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - assetCreatorNet = PublicMethed - .getAccountNet(asset013Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterNetUsed = assetCreatorNet.getNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterNetUsed - creatorBeforeNetUsed < netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed > netCostMeasure); - - PublicMethed - .freedResource(asset013Address, testKeyForAssetIssue013, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset013Address, testKeyForAssetIssue013, 0, asset013Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue014.java deleted file mode 100644 index 71d1ae22b47..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue014.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue014 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue014_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 3000L; - Long publicFreeAssetNetLimit = 300L; - String description = "for case assetissue014"; - String url = "https://stest.assetissue014.url/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset014Address = ecKey1.getAddress(); - String testKeyForAssetIssue014 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue014); - logger.info(transferAssetCreateKey); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Use transfer net when no enough public free asset net") - public void testWhenNoEnoughPublicFreeAssetNetLimitUseTransferNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset014Address = ecKey1.getAddress(); - testKeyForAssetIssue014 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset014Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset014Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue014, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset014Address, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .transferAsset(transferAssetAddress, assetAccountId.toByteArray(), 10000000L, - asset014Address, testKeyForAssetIssue014, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Transfer send some asset issue to default account, to test if this - // transaction use the creator net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Before use transfer net, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset014Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeNetUsed = assetCreatorNet.getNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the transaction free net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetCreatorNet = PublicMethed - .getAccountNet(asset014Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterNetUsed = assetCreatorNet.getNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterNetUsed - creatorBeforeNetUsed < netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed > netCostMeasure); - - PublicMethed - .freedResource(asset014Address, testKeyForAssetIssue014, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(asset014Address, testKeyForAssetIssue014, 0, asset014Address, - blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue015.java deleted file mode 100644 index 97dd589f858..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue015.java +++ /dev/null @@ -1,218 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue015 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue015_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue015"; - String url = "https://stest.assetissue015.url/"; - ByteString assetAccountId; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset015Address = ecKey1.getAddress(); - String testKeyForAssetIssue015 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey3.getAddress(); - String testKeyForNewAddress = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue015); - logger.info(transferAssetCreateKey); - logger.info(testKeyForNewAddress); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Use transfer net when token owner has not enough bandwidth") - public void atestWhenCreatorHasNoEnoughBandwidthUseTransferNet() { - ecKey1 = new ECKey(Utils.getRandom()); - asset015Address = ecKey1.getAddress(); - testKeyForAssetIssue015 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - newAddress = ecKey3.getAddress(); - testKeyForNewAddress = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset015Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset015Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue015, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset015Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - //Transfer asset to an account. - Assert.assertTrue(PublicMethed - .transferAsset(transferAssetAddress, assetAccountId.toByteArray(), 10000000L, - asset015Address, testKeyForAssetIssue015, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Before use transfer net, query the net used from creator and transfer. - AccountNetMessage assetCreatorNet = PublicMethed - .getAccountNet(asset015Address, blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorBeforeFreeNetUsed = assetCreatorNet.getFreeNetUsed(); - Long transferBeforeFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorBeforeFreeNetUsed)); - logger.info(Long.toString(transferBeforeFreeNetUsed)); - - //Transfer send some asset issue to default account, to test if this - // transaction use the transaction free net. - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetCreatorNet = PublicMethed - .getAccountNet(asset015Address, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Long creatorAfterFreeNetUsed = assetCreatorNet.getFreeNetUsed(); - Long transferAfterFreeNetUsed = assetTransferNet.getFreeNetUsed(); - logger.info(Long.toString(creatorAfterFreeNetUsed)); - logger.info(Long.toString(transferAfterFreeNetUsed)); - - Assert.assertTrue(creatorAfterFreeNetUsed - creatorBeforeFreeNetUsed < netCostMeasure); - Assert.assertTrue(transferAfterFreeNetUsed - transferBeforeFreeNetUsed > netCostMeasure); - } - - @Test(enabled = true, description = "Use balance when transfer has not enough net") - public void btestWhenTransferHasNoEnoughBandwidthUseBalance() { - Integer i = 0; - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - while (assetTransferNet.getNetUsed() < 4700 && i++ < 200) { - PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull); - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - } - - logger.info(Long.toString(assetTransferNet.getFreeNetUsed())); - Assert.assertTrue(assetTransferNet.getFreeNetUsed() >= 4700); - - Assert.assertTrue(PublicMethed.sendcoin(transferAssetAddress, - 20000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - Long beforeBalance = transferAccount.getBalance(); - logger.info(Long.toString(beforeBalance)); - - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - Long afterBalance = transferAccount.getBalance(); - logger.info(Long.toString(afterBalance)); - - Assert.assertTrue(beforeBalance - afterBalance > 2000); - } - - @Test(enabled = true, description = "Transfer asset use bandwidth when freeze balance") - public void ctestWhenFreezeBalanceUseNet() { - Assert.assertTrue(PublicMethed.freezeBalance(transferAssetAddress, 5000000, - 3, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountNetMessage assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - Account transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - - final Long transferNetUsedBefore = assetTransferNet.getNetUsed(); - final Long transferBalanceBefore = transferAccount.getBalance(); - logger.info("before " + Long.toString(transferBalanceBefore)); - - Assert.assertTrue(PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 1L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetTransferNet = PublicMethed - .getAccountNet(transferAssetAddress, blockingStubFull); - transferAccount = PublicMethed.queryAccount(transferAssetCreateKey, blockingStubFull); - final Long transferNetUsedAfter = assetTransferNet.getNetUsed(); - final Long transferBalanceAfter = transferAccount.getBalance(); - logger.info("after " + Long.toString(transferBalanceAfter)); - - Assert.assertTrue(transferBalanceAfter - transferBalanceBefore == 0); - Assert.assertTrue(transferNetUsedAfter - transferNetUsedBefore > 200); - - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(asset015Address, testKeyForAssetIssue015, fromAddress, blockingStubFull); - PublicMethed - .freedResource(transferAssetAddress, transferAssetCreateKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue016.java deleted file mode 100644 index d9e6df172e2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue016.java +++ /dev/null @@ -1,236 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue016 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static String name = "AssetIssue016_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue016"; - String url = "https://stest.assetissue016.url/"; - ByteString assetAccountId; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Get asset issue net resource") - public void test01GetAssetIssueNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset016Address = ecKey1.getAddress(); - testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - transferAssetAddress = ecKey2.getAddress(); - transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(testKeyForAssetIssue016); - PublicMethed.printAddress(transferAssetCreateKey); - - Assert.assertTrue(PublicMethed - .sendcoin(asset016Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed - .createAssetIssue(asset016Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue016, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset016Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - AccountNetMessage assetIssueInfo = PublicMethed - .getAccountNet(asset016Address, blockingStubFull); - Assert.assertTrue(assetIssueInfo.getAssetNetLimitCount() == 1); - Assert.assertTrue(assetIssueInfo.getAssetNetUsedCount() == 1); - Assert.assertFalse(assetIssueInfo.getAssetNetLimitMap().isEmpty()); - Assert.assertFalse(assetIssueInfo.getAssetNetUsedMap().isEmpty()); - - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder() - .setValue(assetAccountId).build(); - AssetIssueContract assetIssueByName = blockingStubFull.getAssetIssueByName(request); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == freeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == publicFreeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicLatestFreeNetTime() == 0); - assetIssueInfo.hashCode(); - assetIssueInfo.getSerializedSize(); - assetIssueInfo.equals(assetIssueInfo); - - PublicMethed.transferAsset(transferAssetAddress, assetAccountId.toByteArray(), 1000L, - asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - Assert.assertTrue(assetIssueByName.getPublicLatestFreeNetTime() == 0); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetUsage() == 0); - - Assert.assertTrue(PublicMethed.freezeBalance(asset016Address, 30000000L, - 3, testKeyForAssetIssue016, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.transferAsset(toAddress, assetAccountId.toByteArray(), 100L, - transferAssetAddress, transferAssetCreateKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - Assert.assertTrue(assetIssueByName.getPublicLatestFreeNetTime() > 0); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetUsage() > 150); - - PublicMethed - .freedResource(asset016Address, testKeyForAssetIssue016, fromAddress, blockingStubFull); - - - } - - @Test(enabled = true, description = "Get asset issue by name from Solidity") - public void test02GetAssetIssueByNameFromSolidity() { - Assert.assertEquals(PublicMethed.getAssetIssueByNameFromSolidity(name, - blockingStubSolidity).getTotalSupply(), totalSupply); - } - - @Test(enabled = true, description = "Get asset issue by name from PBFT") - public void test03GetAssetIssueByNameFromPbft() { - Assert.assertEquals(PublicMethed.getAssetIssueByNameFromSolidity(name, - blockingStubPbft).getTotalSupply(), totalSupply); - } - - @Test(enabled = true, description = "Get asset issue list from PBFT") - public void test04GetAssetIssueListFromPbft() { - Assert.assertTrue(PublicMethed.listAssetIssueFromSolidity( - blockingStubPbft).get().getAssetIssueCount() >= 1); - } - - - @Test(enabled = true, description = "Get asset issue list from Solidity") - public void test05GetAssetIssueListFromSolidity() { - Assert.assertTrue(PublicMethed.listAssetIssueFromSolidity( - blockingStubSoliInFull).get().getAssetIssueCount() >= 1); - Assert.assertTrue(PublicMethed.listAssetIssueFromSolidity( - blockingStubSolidity).get().getAssetIssueCount() >= 1); - } - - @Test(enabled = true, description = "Get asset issue list paginated from PBFT") - public void test06GetAssetIssetListPaginatedFromPbft() { - Assert.assertTrue(PublicMethed.listAssetIssuepaginatedFromSolidity( - blockingStubPbft, 0L, 1L).get().getAssetIssueCount() == 1); - } - - - @Test(enabled = true, description = "Get asset issue list paginated from Solidity") - public void test05GetAssetIssueListPaginatedFromSolidity() { - Assert.assertTrue(PublicMethed.listAssetIssuepaginatedFromSolidity( - blockingStubSolidity, 0L, 1L).get().getAssetIssueCount() == 1); - Assert.assertTrue(PublicMethed.listAssetIssuepaginatedFromSolidity( - blockingStubSoliInFull, 0L, 1L).get().getAssetIssueCount() == 1); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue020.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue020.java deleted file mode 100644 index a9a47bc5b4e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/WalletTestAssetIssue020.java +++ /dev/null @@ -1,225 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue020 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "Assetissue020_" + Long.toString(now); - private static final String char33Name = "To_long_asset_name_a" + Long.toString(now); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - Account assetIssue020Account; - ByteString assetAccountId; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset020Address = ecKey1.getAddress(); - String asset020Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset020SecondAddress = ecKey2.getAddress(); - String asset020SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Asset issue support precision") - public void test01AssetIssueSupportPrecision() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset020Address = ecKey1.getAddress(); - asset020Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(asset020Key); - - ecKey2 = new ECKey(Utils.getRandom()); - asset020SecondAddress = ecKey2.getAddress(); - asset020SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(asset020SecondKey); - logger.info(name); - - Assert.assertTrue(PublicMethed.sendcoin(asset020Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(asset020SecondAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Can create 32 char token name. - Long start = System.currentTimeMillis() + 2000000; - Long end = System.currentTimeMillis() + 1000000000; - - //When precision is -1, can not create asset issue - Assert.assertFalse(PublicMethed.createAssetIssue(asset020Address, - name, totalSupply, 1, 1, -1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020Key, blockingStubFull)); - - //When precision is 7, can not create asset issue - Assert.assertFalse(PublicMethed.createAssetIssue(asset020Address, - name, totalSupply, 1, 1, 7, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020Key, blockingStubFull)); - - //When precision is 6, is equal to default. - Assert.assertTrue(PublicMethed.createAssetIssue(asset020Address, - name, totalSupply, 1, 1, 6, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset020Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - AssetIssueContractOuterClass.AssetIssueContract assetIssueInfo = PublicMethed - .getAssetIssueByName(name, blockingStubFull); - final Integer preCisionByName = assetIssueInfo.getPrecision(); - final Long TotalSupplyByName = assetIssueInfo.getTotalSupply(); - - assetIssueInfo = PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull); - final Integer preCisionById = assetIssueInfo.getPrecision(); - final Long TotalSupplyById = assetIssueInfo.getTotalSupply(); - - assetIssueInfo = PublicMethed.getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - final Integer preCisionByListName = assetIssueInfo.getPrecision(); - final Long TotalSupplyByListName = assetIssueInfo.getTotalSupply(); - - logger.info("precision is " + preCisionByName); - logger.info("precision is " + preCisionById); - logger.info("precision is " + preCisionByListName); - logger.info("totalsupply is " + TotalSupplyByName); - logger.info("totalsupply is " + TotalSupplyById); - logger.info("totalsupply is " + TotalSupplyByListName); - Assert.assertEquals(preCisionById, preCisionByListName); - Assert.assertEquals(preCisionById, preCisionByName); - Assert.assertEquals(TotalSupplyById, TotalSupplyByListName); - Assert.assertEquals(TotalSupplyById, TotalSupplyByName); - - //When precision is 6, is equal to default. - Assert.assertTrue(PublicMethed.createAssetIssue(asset020SecondAddress, - name, totalSupply, 1, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset020SecondKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetIssueInfo = PublicMethed.getAssetIssueByName(name, blockingStubFull); - Assert.assertTrue(assetIssueInfo.getName().isEmpty()); - - } - - @Test(enabled = true, description = "Get asset issue by id from Solidity") - public void test02GetAssetIssueByidFromSolidity() { - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull), - PublicMethed.getAssetIssueByIdFromSolidity(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubSolidity)); - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull), - PublicMethed.getAssetIssueByIdFromSolidity(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubSoliInFull)); - } - - @Test(enabled = true, description = "Get asset issue by id from PBFT") - public void test03GetAssetIssueByIdFromPbft() { - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubFull), - PublicMethed.getAssetIssueByIdFromSolidity(ByteArray.toStr(assetAccountId - .toByteArray()), blockingStubPbft)); - } - - @Test(enabled = true, description = "Get asset issue list by name from Solidity") - public void test04GetAssetIssueListByNameFromSolidity() { - Assert.assertEquals(PublicMethed.getAssetIssueListByNameFromSolidity(name, - blockingStubSolidity).get().getAssetIssueList().get(0).getTotalSupply(), totalSupply); - } - - @Test(enabled = true, description = "Get asset issue list by name from PBFT") - public void test05GetAssetIssueListByNameFromPbft() { - Assert.assertEquals(PublicMethed.getAssetIssueListByNameFromSolidity(name, - blockingStubPbft).get().getAssetIssue(0).getTotalSupply(), totalSupply); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue017.java deleted file mode 100644 index e7391a1968f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue017.java +++ /dev/null @@ -1,347 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.exchangeandtoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.db.Manager; -import org.tron.protos.Protocol; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestAssetIssue017 { - - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static long start; - private static long end; - private static long now = System.currentTimeMillis(); - private static String name = "AssetIssue017_" + Long.toString(now); - private static long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue017"; - String url = "https://stest.assetissue016.url/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset017Address = ecKey1.getAddress(); - String testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Manager dbManager; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("failed reason is " + ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(testKeyForAssetIssue017); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void atestGetPaginatedAssetIssueList() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset017Address = ecKey1.getAddress(); - testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed - .sendcoin(asset017Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - now = System.currentTimeMillis(); - name = "AssetIssue017_" + Long.toString(now); - totalSupply = now; - Assert.assertTrue(createAssetIssue(asset017Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, - 1L, testKeyForAssetIssue017, blockingStubFull)); - - Integer offset = 0; - Integer limit = 100; - - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - - AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - for (Integer i = 0; i < assetIssueListPaginated.get().getAssetIssueCount(); i++) { - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssue(i).getTotalSupply() > 0); - } - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - } - - @Test(enabled = true) - public void btestGetPaginatedAssetIssueListException() { - //offset is 0, limit is 0. - Integer offset = 0; - Integer limit = 0; - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is -1, limit is 100. - offset = -1; - limit = 100; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is -1. - offset = 0; - limit = -1; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is 50. - offset = 0; - limit = 50; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubFull - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - } - - @Test(enabled = true) - public void ctestGetPaginatedAssetIssueListOnSolidityNode() { - - Integer offset = 0; - Integer limit = 100; - - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - Assert.assertTrue(PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, - blockingStubSolidity)); - AssetIssueList assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - for (Integer i = 0; i < assetIssueListPaginated.get().getAssetIssueCount(); i++) { - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssue(i).getTotalSupply() > 0); - } - } - - @Test(enabled = true) - public void dtestGetPaginatedAssetIssueListExceptionOnSolidityNode() { - //offset is 0, limit is 0. - Integer offset = 0; - Integer limit = 0; - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - AssetIssueList assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - Optional assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is -1. - offset = 0; - limit = -1; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - - //offset is 0, limit is 50. - offset = 0; - limit = 50; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - - //offset is 0, limit is 1000. - offset = 0; - limit = 1000; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() >= 1); - - //offset is -1, limit is 100. - offset = -1; - limit = 100; - pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(offset); - pageMessageBuilder.setLimit(limit); - assetIssueList = blockingStubSolidity - .getPaginatedAssetIssueList(pageMessageBuilder.build()); - assetIssueListPaginated = Optional.ofNullable(assetIssueList); - logger.info(Long.toString(assetIssueListPaginated.get().getAssetIssueCount())); - Assert.assertTrue(assetIssueListPaginated.get().getAssetIssueCount() == 0); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue018.java deleted file mode 100644 index deb877b2444..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue018.java +++ /dev/null @@ -1,238 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.exchangeandtoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue018 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "Asset008_" + Long.toString(now); - private static final String char32Name = "To_long_asset_name_" + Long.toString(now); - private static final String char33Name = "To_long_asset_name_a" + Long.toString(now); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] assetAccount1Address = ecKey1.getAddress(); - String assetAccount1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetAccount2Address = ecKey2.getAddress(); - String assetAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] assetAccount3Address = ecKey3.getAddress(); - String assetAccount3Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] assetAccount4Address = ecKey4.getAddress(); - String assetAccount4Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] assetAccount5Address = ecKey5.getAddress(); - String assetAccount5Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - ECKey ecKey6 = new ECKey(Utils.getRandom()); - byte[] assetAccount6Address = ecKey6.getAddress(); - String assetAccount6Key = ByteArray.toHexString(ecKey6.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(assetAccount1Key); - PublicMethed.printAddress(assetAccount2Key); - PublicMethed.printAddress(assetAccount3Key); - PublicMethed.printAddress(assetAccount4Key); - PublicMethed.printAddress(assetAccount5Key); - PublicMethed.printAddress(assetAccount6Key); - } - - @Test(enabled = true) - public void test1AssetIssueNameBelow32Char() { - - ecKey4 = new ECKey(Utils.getRandom()); - assetAccount4Address = ecKey4.getAddress(); - assetAccount4Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - ecKey5 = new ECKey(Utils.getRandom()); - assetAccount5Address = ecKey5.getAddress(); - assetAccount5Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - - ecKey6 = new ECKey(Utils.getRandom()); - assetAccount6Address = ecKey6.getAddress(); - assetAccount6Key = ByteArray.toHexString(ecKey6.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(assetAccount4Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount5Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount6Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - - //Can create 32 char token name. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount4Address, - char32Name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount4Key, blockingStubFull)); - - //Can't create 33 char token name. - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertFalse(PublicMethed.createAssetIssue(assetAccount5Address, - char33Name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount5Key, blockingStubFull)); - - // - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount6Address, - char32Name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount6Key, blockingStubFull)); - - } - - @Test(enabled = true) - public void test2SameAssetissueName() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - assetAccount1Address = ecKey1.getAddress(); - assetAccount1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - assetAccount2Address = ecKey2.getAddress(); - assetAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - assetAccount3Address = ecKey3.getAddress(); - assetAccount3Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - logger.info(name); - logger.info("total supply is " + Long.toString(totalSupply)); - //send coin to the new account - Assert.assertTrue(PublicMethed.sendcoin(assetAccount1Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount2Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(assetAccount3Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Create 3 the same name token. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount1Address, - name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, assetAccount1Key, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount2Address, - name, totalSupply, 2, 2, start, end, 2, description, url, - 3000L, 3000L, 2L, 2L, assetAccount2Key, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(assetAccount3Address, - name, totalSupply, 3, 3, start, end, 3, description, url, - 4000L, 4000L, 3L, 3L, assetAccount3Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get asset issue by name - String asset1Name = name; - ByteString assetNameBs = ByteString.copyFrom(asset1Name.getBytes()); - - BytesMessage request = BytesMessage.newBuilder().setValue(assetNameBs).build(); - - AssetIssueList assetIssueList = blockingStubFull.getAssetIssueListByName(request); - Assert.assertTrue(assetIssueList.getAssetIssueCount() == 3); - for (AssetIssueContract assetIssue : assetIssueList.getAssetIssueList()) { - Assert.assertTrue(assetIssue.getTotalSupply() == totalSupply); - - } - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(assetAccount1Key, blockingStubFull); - final ByteString assetAccount1Id = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(assetAccount2Key, blockingStubFull); - final ByteString assetAccount2Id = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(assetAccount3Key, blockingStubFull); - final ByteString assetAccount3Id = getAssetIdFromThisAccount.getAssetIssuedID(); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Transfer asset issue. - Assert.assertTrue(PublicMethed.transferAsset(assetAccount2Address, assetAccount1Id - .toByteArray(), 1L, assetAccount1Address, assetAccount1Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(assetAccount3Address, assetAccount2Id - .toByteArray(), 2L, assetAccount2Address, assetAccount2Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(assetAccount1Address, assetAccount3Id - .toByteArray(), 3L, assetAccount3Address, assetAccount3Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.transferAsset(assetAccount1Address, assetAccount2Id - .toByteArray(), 3L, assetAccount3Address, assetAccount3Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Participate asset issue. - Assert.assertTrue(PublicMethed.participateAssetIssue(assetAccount3Address, assetAccount3Id - .toByteArray(), 1L, assetAccount2Address, assetAccount2Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.participateAssetIssue(assetAccount1Address, assetAccount1Id - .toByteArray(), 2L, assetAccount3Address, assetAccount3Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.participateAssetIssue(assetAccount2Address, assetAccount2Id - .toByteArray(), 3L, assetAccount1Address, assetAccount1Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.participateAssetIssue(assetAccount2Address, assetAccount3Id - .toByteArray(), 3L, assetAccount1Address, assetAccount1Key, blockingStubFull)); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue019.java deleted file mode 100644 index b320b428025..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/exchangeandtoken/WalletTestAssetIssue019.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.exchangeandtoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAssetIssue019 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset019Address = ecKey1.getAddress(); - String asset019Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset019SecondAddress = ecKey2.getAddress(); - String asset019SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testCanNotCreateTokenNameByTrx() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - asset019Address = ecKey1.getAddress(); - asset019Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(asset019Key); - - ecKey2 = new ECKey(Utils.getRandom()); - asset019SecondAddress = ecKey2.getAddress(); - asset019SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(asset019SecondKey); - - Assert.assertTrue(PublicMethed.sendcoin(asset019Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(asset019SecondAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - - //Can create 32 char token name. - Long start = System.currentTimeMillis() + 20000000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "trx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "TRX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "Trx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "tRx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "trX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "TRx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "TrX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertFalse(PublicMethed.createAssetIssue(asset019Address, - "tRX", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.createAssetIssue(asset019Address, - "trxtrx", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.createAssetIssue(asset019SecondAddress, - "_", totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, asset019SecondKey, blockingStubFull)); - } - - @Test(enabled = true) - public void testGetAssetLastOperationTimeAndAssetIssueFreeNetUsed() { - Assert.assertTrue(PublicMethed.freezeBalance(asset019Address, 100000000L, 3, - asset019Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(asset019SecondAddress, 100000000L, 3, - asset019SecondKey, blockingStubFull)); - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019Address, blockingStubFull); - ByteString asset019AccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019SecondAddress, blockingStubFull); - ByteString asset019SecondAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - PublicMethed.transferAsset(asset019SecondAddress, asset019AccountId.toByteArray(), 100L, - asset019Address, asset019Key, blockingStubFull); - PublicMethed.transferAsset(asset019Address, asset019SecondAccountId.toByteArray(), 100L, - asset019SecondAddress, asset019SecondKey, blockingStubFull); - - PublicMethed.transferAsset(asset019Address, asset019AccountId.toByteArray(), 10L, - asset019SecondAddress, asset019SecondKey, blockingStubFull); - PublicMethed.transferAsset(asset019SecondAddress, asset019SecondAccountId.toByteArray(), - 10L, asset019Address, asset019Key, blockingStubFull); - - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019Address, blockingStubFull); - for (String id : getAssetIdFromThisAccount.getFreeAssetNetUsageV2Map().keySet()) { - if (asset019SecondAccountId.toStringUtf8().equalsIgnoreCase(id)) { - Assert.assertTrue(getAssetIdFromThisAccount.getFreeAssetNetUsageV2Map().get(id) > 0); - } - } - - getAssetIdFromThisAccount = PublicMethed.queryAccount(asset019SecondAddress, blockingStubFull); - for (String id : getAssetIdFromThisAccount.getLatestAssetOperationTimeV2Map().keySet()) { - if (asset019AccountId.toStringUtf8().equalsIgnoreCase(id)) { - Assert.assertTrue(getAssetIdFromThisAccount.getLatestAssetOperationTimeV2Map().get(id) > 0); - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar001.java deleted file mode 100644 index 56401c66b5f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar001.java +++ /dev/null @@ -1,375 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar001 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Support function type") - public void test1Grammar001() { - ecKey1 = new ECKey(Utils.getRandom()); - grammarAddress = ecKey1.getAddress(); - testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol"; - String contractName = "FunctionSelector"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "true" + "," + "10"; - txid = PublicMethed.triggerContract(contractAddress, - "select(bool,uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray.fromHexString(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber == 20); - - String num2 = "false" + "," + "10"; - txid = PublicMethed.triggerContract(contractAddress, - "select(bool,uint256)", num2, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional ById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + ById.get().getRet(0)); - logger.info("getNumber:" + ById.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + ById.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + ById.get().getRet(0).getContractRet()); - - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - contractResult.SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), 1); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "0000000000000000000000000000000000000000000000000000000000000064"); - Assert.assertEquals(contractResult.SUCCESS, infoById.get().getReceipt().getResult()); - - logger.info("ById:" + ById); - Assert.assertEquals(ById.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(ById.get().getRet(0).getRetValue(), 0); - - Long returnnumber2 = ByteArray.toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber2 == 100); - } - - @Test(enabled = true, description = "Ordinary library contract") - public void test2Grammar002() { - String filePath = "src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol"; - String contractName = "Set"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "1"; - byte[] contractAddress1 = null; - String filePath1 = "src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol"; - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbiForLibrary(filePath1, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String library = retMap1.get("library").toString(); - String libraryAddress = library + Base58.encode58Check(contractAddress); - contractAddress1 = PublicMethed - .deployContractForLibrary(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, libraryAddress, testKeyForGrammarAddress, - grammarAddress, compilerVersion, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress1, - "register(uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Library contract") - public void test3Grammar003() { - String filePath = "src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol"; - String contractName = "Set"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "1"; - byte[] contractAddress1 = null; - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbiForLibrary(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String library = retMap1.get("library").toString(); - String libraryAddress = library - + Base58.encode58Check(contractAddress); - contractAddress1 = PublicMethed - .deployContractForLibrary(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, libraryAddress, testKeyForGrammarAddress, - grammarAddress, compilerVersion, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress1, - "register(uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Extended type") - public void test4Grammar004() { - ecKey1 = new ECKey(Utils.getRandom()); - grammarAddress = ecKey1.getAddress(); - testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol"; - String contractName = "Search"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - byte[] contractAddress1 = null; - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbiForLibrary(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String library = retMap1.get("library").toString(); - String libraryAddress = null; - libraryAddress = library - + Base58.encode58Check(contractAddress); - contractAddress1 = PublicMethed - .deployContractForLibrary(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, libraryAddress, testKeyForGrammarAddress, - grammarAddress, compilerVersion, blockingStubFull); - String txid = ""; - String num = "1"; - PublicMethed.waitProduceNextBlock(blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress1, - "append(uint256)", num, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String num1 = "0"; - String txid1 = PublicMethed.triggerContract(contractAddress1, - "getData(uint256)", num1, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber == 1); - - String num2 = "1" + "," + "2"; - String txid2 = PublicMethed.triggerContract(contractAddress1, - "replace(uint256,uint256)", num2, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - String txid3 = PublicMethed.triggerContract(contractAddress1, - "getData(uint256)", num1, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber1 == 2); - - } - - @Test(enabled = true, description = "Solidity assembly") - public void test5Grammar006() { - String filePath = "src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol"; - String contractName = "InfoFeed"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String number = "1"; - final String txid1 = PublicMethed.triggerContract(contractAddress, - "f(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid2 = PublicMethed.triggerContract(contractAddress, - "d(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid3 = PublicMethed.triggerContract(contractAddress, - "d1(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid4 = PublicMethed.triggerContract(contractAddress, - "d2(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid5 = PublicMethed.triggerContract(contractAddress, - "d5(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid6 = PublicMethed.triggerContract(contractAddress, - "d4(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - final String txid8 = PublicMethed.triggerContract(contractAddress, - "d6(uint256)", number, false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull1); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid2, blockingStubFull1); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Assert.assertEquals(133,ByteArray.toInt(infoById2.get().getContractResult(0).toByteArray())); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(txid3, blockingStubFull1); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - Optional infoById4 = PublicMethed - .getTransactionInfoById(txid4, blockingStubFull1); - Assert.assertTrue(infoById4.get().getResultValue() == 0); - - Optional infoById5 = PublicMethed - .getTransactionInfoById(txid5, blockingStubFull1); - Assert.assertTrue(infoById5.get().getResultValue() == 0); - - Optional infoById6 = PublicMethed - .getTransactionInfoById(txid6, blockingStubFull1); - Assert.assertTrue(infoById6.get().getResultValue() == 0); - - Optional infoById8 = PublicMethed - .getTransactionInfoById(txid8, blockingStubFull1); - Assert.assertTrue(infoById8.get().getResultValue() == 0); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar002.java deleted file mode 100644 index 83c9f8e0129..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar002.java +++ /dev/null @@ -1,335 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar002 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress2 = ecKey1.getAddress(); - String testKeyForGrammarAddress2 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress2); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - - @Test(enabled = true, description = "Interface type function") - public void test1Grammar007() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress2, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol"; - String contractName = "Doug"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String initParmes = ByteArray.toHexString(contractAddress); - String filePath1 = "src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol"; - String contractName1 = "main"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName1); - String code1 = retMap1.get("byteCode").toString() + "0000000000000000000000" - + initParmes; - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - String txid = ""; - String number = "1"; - String txid1 = PublicMethed.triggerContract(contractAddress1, - "dougOfage(uint256)", number, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - String number1 = "687777"; - String txid2 = PublicMethed.triggerContract(contractAddress1, - "uintOfName(bytes32)", number1, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - // PublicMethed.waitProduceNextBlock(blockingStubFull); - // PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid2, blockingStubFull1); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Abstract function") - public void test2Grammar008() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol"; - String contractName = "Cat"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "getContractName()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String returnString = ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(returnString, - "0000000000000000000000000000000000000000000000000000000000000020000000000000000000" - + "000000000000000000000000000000000000000000000646656c696e650000000000000000000000000" - + "000000000000000000000000000"); - String txid1 = PublicMethed.triggerContract(contractAddress, - "utterance()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - String returnString1 = ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(returnString1, - "6d69616f77000000000000000000000000000000000000000000000000000000"); - } - - @Test(enabled = true, description = "Gas, value test") - public void test3Grammar010() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol"; - String contractName = "Consumer"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 2000L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "InfoFeed"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - String txid = ""; - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "setFeed(address)", initParmes, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid1 = PublicMethed.triggerContract(contractAddress, - "callFeed()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull1); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Call a named function") - public void test4Grammar011() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String number = "1" + "," + "2"; - String txid = PublicMethed.triggerContract(contractAddress, - "f(uint256,uint256)", number, false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 1); - - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "g()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Call a native function") - public void test5Grammar012() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol"; - String contractName = "rTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "info()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "Call a Destructor function") - public void test6Grammar013() { - String filePath = "src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol"; - String contractName = "Counter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "getCount()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 0); - - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "increment()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Optional infoById2 = null; - String txid2 = PublicMethed.triggerContract(contractAddress, - "getCount()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById2.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber1 == 10); - - Optional infoById3 = null; - String txid3 = PublicMethed.triggerContract(contractAddress, - "kill()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - Optional infoById4 = null; - String txid4 = PublicMethed.triggerContract(contractAddress, - "getCount()", "#", false, - 0, maxFeeLimit, grammarAddress2, testKeyForGrammarAddress2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(txid4 == null); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress2, testKeyForGrammarAddress2, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar003.java deleted file mode 100644 index b3aafd25e88..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar003.java +++ /dev/null @@ -1,522 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar003 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress3 = ecKey1.getAddress(); - String testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress3); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Complex structure") - public void test1Grammar014() { - ecKey1 = new ECKey(Utils.getRandom()); - grammarAddress3 = ecKey1.getAddress(); - testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress3, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid1 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 0); - - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(returnnumber1 == 0); - Optional infoById4 = null; - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid4 = PublicMethed.triggerContract(contractAddress, - "callTest(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById4 = PublicMethed.getTransactionInfoById(txid4, blockingStubFull); - - Assert.assertTrue(infoById4.get().getResultValue() == 0); - - String txid5 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById5 = null; - infoById5 = PublicMethed.getTransactionInfoById(txid5, blockingStubFull); - Long returnnumber5 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById5.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber5 == 0); - - String txid6 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById6 = null; - infoById6 = PublicMethed.getTransactionInfoById(txid6, blockingStubFull); - Long returnnumber6 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById6.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber6 == 1); - - String txid7 = PublicMethed.triggerContract(contractAddress, - "callcodeTest(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById7 = null; - infoById7 = PublicMethed.getTransactionInfoById(txid7, blockingStubFull); - - Assert.assertTrue(infoById7.get().getResultValue() == 0); - - String txid8 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById8 = null; - infoById8 = PublicMethed.getTransactionInfoById(txid8, blockingStubFull); - Long returnnumber8 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById8.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber8 == 1); - - String txid9 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById9 = null; - infoById9 = PublicMethed.getTransactionInfoById(txid9, blockingStubFull); - Long returnnumber9 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById9.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber9 == 1); - - String txid10 = PublicMethed.triggerContract(contractAddress, - "delegatecallTest(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById10 = null; - infoById10 = PublicMethed.getTransactionInfoById(txid10, blockingStubFull); - - Assert.assertTrue(infoById10.get().getResultValue() == 0); - - String txid11 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById11 = null; - infoById11 = PublicMethed.getTransactionInfoById(txid11, blockingStubFull); - Long returnnumber11 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById11.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber11 == 1); - - String txid12 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById12 = null; - infoById12 = PublicMethed.getTransactionInfoById(txid12, blockingStubFull); - Long returnnumber12 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById12.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber12 == 1); - - String initParmes1 = "\"" + Base58.encode58Check(contractAddress1) + "\""; - String txid13 = PublicMethed.triggerContract(contractAddress, - "callAddTest(address)", initParmes1, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById13 = null; - infoById13 = PublicMethed.getTransactionInfoById(txid13, blockingStubFull); - - Assert.assertTrue(infoById13.get().getResultValue() == 0); - - String txid14 = PublicMethed.triggerContract(contractAddress, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById14 = null; - infoById14 = PublicMethed.getTransactionInfoById(txid14, blockingStubFull); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById14.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber14 == 1); - - String txid15 = PublicMethed.triggerContract(contractAddress1, - "getnumberForB()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById15 = null; - infoById15 = PublicMethed.getTransactionInfoById(txid15, blockingStubFull); - Long returnnumber15 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById15.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber15 == 3); - } - - - @Test(enabled = true, description = "Fallback function ") - public void test2Grammar015() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol"; - String contractName = "ExecuteFallback"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "callExistFunc()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String i = ByteArray.toHexString(Hash.sha3("ExistFuncCalled(bytes,uint256)".getBytes())); - String resultvalue = ByteArray - .toHexString(infoById.get().getLogList().get(0).getTopicsList().get(0).toByteArray()); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(i, resultvalue); - - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "callNonExistFunc()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - String value = ByteArray.toHexString(Hash.sha3("FallbackCalled(bytes)".getBytes())); - String resultvalue1 = ByteArray - .toHexString(infoById1.get().getLogList().get(0).getTopicsList().get(0).toByteArray()); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertEquals(value, resultvalue1); - - } - - @Test(enabled = true, description = "Permission control ") - public void test3Grammar016() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "readData()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - String contractName1 = "E"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress1, - "g()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - Optional infoById2 = null; - String num = "3"; - String txid2 = PublicMethed.triggerContract(contractAddress1, - "setData(uint256)", num, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - String txid3 = PublicMethed.triggerContract(contractAddress1, - "getData()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Long returnnumber3 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById3.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber3 == 3); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "Structure") - public void test4Grammar017() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol"; - String contractName = "CrowdFunding"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress1 = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - String initParmes = "\"" + Base58.encode58Check(grammarAddress3) + "\",\"1\""; - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress1, - "candidate(address,uint256)", initParmes, false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(returnnumber1 == 1); - - String txid1 = PublicMethed.triggerContract(contractAddress1, - "check(uint256)", "1", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull1); - Long returnnumber2 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber2 == 1); - - String txid2 = PublicMethed.triggerContract(contractAddress1, - "vote(uint256)", "1", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "Built-in function") - public void test5Grammar018() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol"; - String contractName = "Grammar18"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "testAddmod()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(returnnumber == 1); - Optional infoById1 = null; - String txid1 = PublicMethed.triggerContract(contractAddress, - "testMulmod()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(returnnumber1 == 2); - - String txid2 = PublicMethed.triggerContract(contractAddress, - "testKeccak256()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - String txid3 = PublicMethed.triggerContract(contractAddress, - "testSha256()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - - Assert.assertTrue(infoById3.get().getResultValue() == 0); - - String txid4 = PublicMethed.triggerContract(contractAddress, - "testSha3()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - Optional infoById4 = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById4 = PublicMethed.getTransactionInfoById(txid4, blockingStubFull); - Assert.assertTrue(infoById4.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "Time unit") - public void test6Grammar019() { - - String filePath = "src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol"; - String contractName = "timetest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = PublicMethed.triggerContract(contractAddress, - "timetest()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - } - - - @Test(enabled = true, description = "Trx and sun unit conversion.") - public void test7Grammar020() { - String filePath = "src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol"; - String contractName = "trxtest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - String txid = PublicMethed.triggerContract(contractAddress, - "test()", "#", false, - 0, maxFeeLimit, grammarAddress3, testKeyForGrammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress3, testKeyForGrammarAddress3, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar004.java deleted file mode 100644 index ceae3fad717..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetissue/grammar/ContractGrammar004.java +++ /dev/null @@ -1,638 +0,0 @@ -package stest.tron.wallet.dailybuild.assetissue.grammar; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.BAD_JUMP_DESTINATION_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_MEMORY_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_TIME_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.REVERT_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.STACK_TOO_LARGE_VALUE; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.STACK_TOO_SMALL_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractGrammar004 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String compilerVersion = Configuration.getByPath("testng.conf") - .getString("defaultParameter.solidityCompilerVersion"); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "ContractResult is OUT_OF_TIME") - public void test1Grammar001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/walletTestMutiSign004.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - String initParmes = "\"" + "100000" + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testUseCpu(uint256)", initParmes, false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), OUT_OF_TIME_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.OUT_OF_TIME); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.OUT_OF_TIME, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is OUT_OF_MEMORY") - public void test2Grammar002() { - String filePath = "./src/test/resources/soliditycode/testOutOfMem.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - String initParmes = "\"" + "31457280" + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testOutOfMem(uint256)", initParmes, false, 0, - maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), OUT_OF_MEMORY_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.OUT_OF_MEMORY); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.OUT_OF_MEMORY, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is BAD_JUMP_DESTINATION") - public void test3Grammar003() { - String contractName = "Test"; - - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600" - + "080fd5b5061011f8061003a6000396000f30060806040526004361060485763ffffffff7c01000000000000" - + "000000000000000000000000000000000000000000006000350416634ef5a0088114604d5780639093b95b1" - + "4608c575b600080fd5b348015605857600080fd5b50d38015606457600080fd5b50d28015607057600080fd" - + "5b50607a60043560b8565b60408051918252519081900360200190f35b348015609757600080fd5b50d3801" - + "560a357600080fd5b50d2801560af57600080fd5b5060b660ee565b005b6000606082604051908082528060" - + "20026020018201604052801560e5578160200160208202803883390190505b50905050919050565b6001805" - + "600a165627a7a7230582092ba162087e13f41c6d6c00ba493edc5a5a6250a3840ece5f99aa38b66366a7000" - + "29"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\"" - + ":\"testOutOfMem\",\"outputs\":[{\"name\":\"r\",\"type\":\"bytes32\"}],\"payable\":false" - + ",\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs" - + "\":[],\"name\":\"testBadJumpDestination\",\"outputs\":[],\"payable\":false,\"stateMutab" - + "ility\":\"nonpayable\",\"type\":\"function\"}]"; - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - org.testng.Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid = null; - Optional infoById = null; - txid = PublicMethed - .triggerContract(contractAddress, "testBadJumpDestination()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), BAD_JUMP_DESTINATION_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.BAD_JUMP_DESTINATION); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert - .assertEquals(contractResult.BAD_JUMP_DESTINATION, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - - } - - - @Test(enabled = true, description = "ContractResult is OUT_OF_ENERGY") - public void test4Grammar004() { - - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 20L, 100, - null, testKeyForGrammarAddress, grammarAddress, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - logger.info("ById:" + byId); - - logger.info("infoById:" + infoById); - - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert.assertEquals(ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000001"); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(byId.get().getRet(0).getRet().getNumber(), 0); - Assert.assertEquals(byId.get().getRet(0).getRetValue(), 0); - - } - - - @Test(enabled = true, description = "ContractResult is ILLEGAL_OPERATION") - public void test5Grammar005() { - - String filePath = "src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "4" + "," + "0"; - - txid = PublicMethed - .triggerContract(contractAddress, "divideIHaveArgsReturn(int256,int256)", num, false, 0, - maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000012"); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - } - - - @Test(enabled = true, description = "ContractResult is REVERT") - public void test6Grammar006() { - - String filePath = - "src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String txid = PublicMethed - .triggerContract(contractAddress, "testRequire()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), REVERT_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "ContractResult is SUCCESS") - public void test7Grammar007() { - - String filePath = "src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "4" + "," + "2"; - - txid = PublicMethed - .triggerContract(contractAddress, "divideIHaveArgsReturn(int256,int256)", num, false, 0, - maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), - contractResult.SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), contractResult.SUCCESS_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.SUCCESS); - - Assert.assertEquals(contractResult.SUCCESS, infoById.get().getReceipt().getResult()); - - Assert.assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "0000000000000000000000000000000000000000000000000000000000000002"); - - } - - - @Test(enabled = true, description = "ContractResult is TRANSFER_FAILED") - public void test8Grammar008() { - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(grammarAddress, blockingStubFull); - info = PublicMethed.queryAccount(testKeyForGrammarAddress, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testTransferTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(testKeyForGrammarAddress, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(grammarAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info( - "infoById.get().getReceipt().getResult(): " + infoById.get().getReceipt().getResult()); - logger.info("ByteArray.toStr(infoById.get().getResMessage().toByteArray()): " + ByteArray - .toStr(infoById.get().getResMessage().toByteArray())); - /*Assert.assertEquals( - "transfer trx failed: Validate InternalTransfer error, no ToAccount." - + " And not allowed to create account in smart contract.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray()));*/ - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "ContractResult is STACK_TOO_SMALL") - public void test9Grammar009() { - - String contractName = "TestThrowsContract"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testStackTooSmall\",\"outputs\":[]" - + ",\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"}]"; - String code = "60606040523415600b57fe5b5b60608060196000396000f300606060405263ffffffff60e060020" - + "a6000350416632f3a24cc81146020575bfe5b3415602757fe5b602d602f565b005b50505b5600a165627a7a" - + "723058208184f2ff2627a8a490bfd1233a891f2f4605375d0fec375e237ffc188cdd7ec70029"; - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String txid = PublicMethed - .triggerContract(contractAddress, "testStackTooSmall()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), STACK_TOO_SMALL_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), STACK_TOO_SMALL_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.STACK_TOO_SMALL); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.STACK_TOO_SMALL, infoById.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "ContractResult is STACK_TOO_LARGE") - public void test9Grammar010() { - - String contractName = "TestThrowsContract"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testStackTooLarge\",\"outputs\":[]" - + ",\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"}]"; - String code = "6060604052341561000c57fe5b5b610b658061001c6000396000f300606060405263ffffffff60e" - + "060020a600035041663f7d9c5c68114610021575bfe5b341561002957fe5b610031610033565b005b600060" - + "0160026003600460056006600760086009600a600b600c600d600e600f60106011601260136014601560166" - + "01760186019601a601b601c601d601e601f6020602160226023602460256026602760286029602a602b602c" - + "602d602e602f6030603160326033603460356036603760386039603a603b603c603d603e603f60406041604" - + "26043604460456046604760486049604a604b604c604d604e604f6050605160526053605460556056605760" - + "586059605a605b605c605d605e605f6060606160626063606460656066606760686069606a606b606c606d6" - + "06e606f6070607160726073607460756076607760786079607a607b607c607d607e607f6080608160826083" - + "608460856086608760886089608a608b608c608d608e608f609060916092609360946095609660976098609" - + "9609a609b609c609d609e609f60a060a160a260a360a460a560a660a760a860a960aa60ab60ac60ad60ae60" - + "af60b060b160b260b360b460b560b660b760b860b960ba60bb60bc60bd60be60bf60c060c160c260c360c46" - + "0c560c660c760c860c960ca60cb60cc60cd60ce60cf60d060d160d260d360d460d560d660d760d860d960da" - + "60db60dc60dd60de60df60e060e160e260e360e460e560e660e760e860e960ea60eb60ec60ed60ee60ef60f" - + "060f160f260f360f460f560f660f760f860f960fa60fb60fc60fd60fe60ff61010061010161010261010361" - + "010461010561010661010761010861010961010a61010b61010c61010d61010e61010f61011061011161011" - + "261011361011461011561011661011761011861011961011a61011b61011c61011d61011e61011f61012061" - + "012161012261012361012461012561012661012761012861012961012a61012b61012c61012d61012e61012" - + "f61013061013161013261013361013461013561013661013761013861013961013a61013b61013c61013d61" - + "013e61013f61014061014161014261014361014461014561014661014761014861014961014a61014b61014" - + "c61014d61014e61014f61015061015161015261015361015461015561015661015761015861015961015a61" - + "015b61015c61015d61015e61015f61016061016161016261016361016461016561016661016761016861016" - + "961016a61016b61016c61016d61016e61016f61017061017161017261017361017461017561017661017761" - + "017861017961017a61017b61017c61017d61017e61017f61018061018161018261018361018461018561018" - + "661018761018861018961018a61018b61018c61018d61018e61018f61019061019161019261019361019461" - + "019561019661019761019861019961019a61019b61019c61019d61019e61019f6101a06101a16101a26101a" - + "36101a46101a56101a66101a76101a86101a96101aa6101ab6101ac6101ad6101ae6101af6101b06101b161" - + "01b26101b36101b46101b56101b66101b76101b86101b96101ba6101bb6101bc6101bd6101be6101bf6101c" - + "06101c16101c26101c36101c46101c56101c66101c76101c86101c96101ca6101cb6101cc6101cd6101ce61" - + "01cf6101d06101d16101d26101d36101d46101d56101d66101d76101d86101d96101da6101db6101dc6101d" - + "d6101de6101df6101e06101e16101e26101e36101e46101e56101e66101e76101e86101e96101ea6101eb61" - + "01ec6101ed6101ee6101ef6101f06101f16101f26101f36101f46101f56101f66101f76101f86101f96101f" - + "a6101fb6101fc6101fd6101fe6101ff61020061020161020261020361020461020561020661020761020861" - + "020961020a61020b61020c61020d61020e61020f61021061021161021261021361021461021561021661021" - + "761021861021961021a61021b61021c61021d61021e61021f61022061022161022261022361022461022561" - + "022661022761022861022961022a61022b61022c61022d61022e61022f61023061023161023261023361023" - + "461023561023661023761023861023961023a61023b61023c61023d61023e61023f61024061024161024261" - + "024361024461024561024661024761024861024961024a61024b61024c61024d61024e61024f61025061025" - + "161025261025361025461025561025661025761025861025961025a61025b61025c61025d61025e61025f61" - + "026061026161026261026361026461026561026661026761026861026961026a61026b61026c61026d61026" - + "e61026f61027061027161027261027361027461027561027661027761027861027961027a61027b61027c61" - + "027d61027e61027f61028061028161028261028361028461028561028661028761028861028961028a61028" - + "b61028c61028d61028e61028f61029061029161029261029361029461029561029661029761029861029961" - + "029a61029b61029c61029d61029e61029f6102a06102a16102a26102a36102a46102a56102a66102a76102a" - + "86102a96102aa6102ab6102ac6102ad6102ae6102af6102b06102b16102b26102b36102b46102b56102b661" - + "02b76102b86102b96102ba6102bb6102bc6102bd6102be6102bf6102c06102c16102c26102c36102c46102c" - + "56102c66102c76102c86102c96102ca6102cb6102cc6102cd6102ce6102cf6102d06102d16102d26102d361" - + "02d46102d56102d66102d76102d86102d96102da6102db6102dc6102dd6102de6102df6102e06102e16102e" - + "26102e36102e46102e56102e66102e76102e86102e96102ea6102eb6102ec6102ed6102ee6102ef6102f061" - + "02f16102f26102f36102f46102f56102f66102f76102f86102f96102fa6102fb6102fc6102fd6102fe6102f" - + "f61030061030161030261030361030461030561030661030761030861030961030a61030b61030c61030d61" - + "030e61030f61031061031161031261031361031461031561031661031761031861031961031a61031b61031" - + "c61031d61031e61031f61032061032161032261032361032461032561032661032761032861032961032a61" - + "032b61032c61032d61032e61032f61033061033161033261033361033461033561033661033761033861033" - + "961033a61033b61033c61033d61033e61033f61034061034161034261034361034461034561034661034761" - + "034861034961034a61034b61034c61034d61034e61034f61035061035161035261035361035461035561035" - + "661035761035861035961035a61035b61035c61035d61035e61035f61036061036161036261036361036461" - + "036561036661036761036861036961036a61036b61036c61036d61036e61036f61037061037161037261037" - + "361037461037561037661037761037861037961037a61037b61037c61037d61037e61037f61038061038161" - + "038261038361038461038561038661038761038861038961038a61038b61038c61038d61038e61038f61039" - + "061039161039261039361039461039561039661039761039861039961039a61039b61039c61039d61039e61" - + "039f6103a06103a16103a26103a36103a46103a56103a66103a76103a86103a96103aa6103ab6103ac6103a" - + "d6103ae6103af6103b06103b16103b26103b36103b46103b56103b66103b76103b86103b96103ba6103bb61" - + "03bc6103bd6103be6103bf6103c06103c16103c26103c36103c46103c56103c66103c76103c86103c96103c" - + "a6103cb6103cc6103cd6103ce6103cf6103d06103d16103d26103d36103d46103d56103d66103d76103d861" - + "03d96103da6103db6103dc6103dd6103de6103df6103e06103e16103e26103e36103e46103e56103e66103e" - + "76103e86103e96103ea6103eb6103ec6103ed6103ee6103ef6103f06103f16103f26103f36103f46103f561" - + "03f66103f76103f86103f96103fa6103fb6103fc6103fd6103fe6103ff6104005b5600a165627a7a7230582" - + "0998f09cc267db91352a3d0a4ab60ea08fc306fa8bc6dd78dc324a06109dcf0420029"; - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, - testKeyForGrammarAddress, grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String txid = PublicMethed - .triggerContract(contractAddress, "testStackTooLarge()", "#", false, 0, maxFeeLimit, - grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + byId.get().getRet(0)); - logger.info("getNumber:" + byId.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + byId.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + byId.get().getRet(0).getContractRet()); - - Assert.assertEquals(byId.get().getRet(0).getContractRet().getNumber(), STACK_TOO_LARGE_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRetValue(), STACK_TOO_LARGE_VALUE); - Assert.assertEquals(byId.get().getRet(0).getContractRet(), contractResult.STACK_TOO_LARGE); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), ""); - Assert.assertEquals(contractResult.STACK_TOO_LARGE, infoById.get().getReceipt().getResult()); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java deleted file mode 100644 index 59baee113a2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset001.java +++ /dev/null @@ -1,316 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MarketSellAsset001 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final String foundationKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = - Configuration.getByPath("testng.conf").getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - private String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - public String solidityNode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - - /** constructor. */ - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(solidityNode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue( - PublicMethed.sendcoin( - testAddress001, - 20000_000000L, - foundationAddress001, - foundationKey001, - blockingStubFull)); - Assert.assertTrue( - PublicMethed.sendcoin( - testAddress002, - 20000_000000L, - foundationAddress001, - foundationKey001, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue( - PublicMethed.createAssetIssue( - testAddress001, - name, - 10000_000000L, - 1, - 1, - start, - end, - 1, - description, - url, - 10000L, - 10000L, - 1L, - 1L, - testKey001, - blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue( - PublicMethed.createAssetIssue( - testAddress002, - name, - 10000_000000L, - 1, - 1, - start, - end, - 1, - description, - url, - 10000L, - 10000L, - 1L, - 1L, - testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = - PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID() - .toByteArray(); - - assetAccountId002 = - PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID() - .toByteArray(); - } - - @Test(enabled = true, description = "create sellOrder") - void marketSellAssetTest001() { - - String txid = - PublicMethed.marketSellAsset( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed.getTransactionById(txid, blockingStubFull); - - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = - PublicMethed.getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - MarketOrder order = PublicMethed.getMarketOrderById(orderId, blockingStubFull).get(); - - Assert.assertEquals(order.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order.getBuyTokenQuantity(), buyTokenQuantity); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Optional transactionFromSolidity = - PublicMethed.getTransactionByIdSolidity(txid, blockingStubSolidity); - Assert.assertEquals(transaction, transactionFromSolidity); - } - - @Test(enabled = true, description = "create sellOrder with value excption") - void marketSellAssetTest002() { - - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] testAddress = ecKey.getAddress(); - String testKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - long sendCoinValue = 10000_000000L; - Assert.assertTrue( - PublicMethed.sendcoin( - testAddress, sendCoinValue, foundationAddress001, foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - Return resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress, - testKey, - assetAccountId001, - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : SellToken balance is not enough !"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress, - testKey, - assetAccountId001, - 0, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : token quantity must greater than zero"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - Account account = PublicMethed.queryAccount(testAddress, blockingStubFull); - Assert.assertEquals(account.getBalance(), sendCoinValue); - } - - @Test(enabled = true, description = "create sellOrder with tokenId excption") - void marketSellAssetTest003() { - - long beforeBalance = PublicMethed.queryAccount(testAddress001, blockingStubFull).getBalance(); - logger.info("BeforeBalance: " + beforeBalance); - - Return resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - "xxxx".getBytes(), - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : sellTokenId is not a valid number"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - "xxx".getBytes(), - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : buyTokenId is not a valid number"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - "10001039999".getBytes(), - sellTokenQuantity, - assetAccountId002, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : No sellTokenId !"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - "10001039999".getBytes(), - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : No buyTokenId !"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - resposne = - PublicMethed.marketSellAssetGetResposne( - testAddress001, - testKey001, - assetAccountId001, - sellTokenQuantity, - assetAccountId001, - buyTokenQuantity, - blockingStubFull); - Assert.assertEquals( - ByteArray.toStr(resposne.getMessage().toByteArray()), - "Contract validate error : cannot exchange same tokens"); - Assert.assertEquals(resposne.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - - long afterBalance = PublicMethed.queryAccount(testAddress002, blockingStubFull).getBalance(); - logger.info("AfterBalance: " + afterBalance); - - Assert.assertEquals(beforeBalance, afterBalance); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java deleted file mode 100644 index d145a540f20..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset002.java +++ /dev/null @@ -1,374 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Map; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MarketSellAsset002 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress001, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey001, blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress002, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = - PublicMethed.queryAccount(testAddress001, blockingStubFull).getAssetIssuedID() - .toByteArray(); - - assetAccountId002 = - PublicMethed.queryAccount(testAddress002, blockingStubFull).getAssetIssuedID() - .toByteArray(); - } - - - @Test(enabled = true, description = "create sellOrder and Match Order") - void marketSellAssetTest001() { - - Map beforeAsset001 = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetV2Map(); - Map beforeAsset002 = PublicMethed - .queryAccount(testAddress002, blockingStubFull).getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - logger.info("beforeAsset002: " + beforeAsset002); - - String txid = PublicMethed - .marketSellAsset(testAddress001, testKey001, assetAccountId001, sellTokenQuantity, - assetAccountId002, buyTokenQuantity, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - String txid2 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity, assetAccountId001, sellTokenQuantity, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid2); - - transaction = PublicMethed - .getTransactionById(txid2, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - String assetId001 = ByteArray.toStr(assetAccountId001); - String assetId002 = ByteArray.toStr(assetAccountId002); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((buyTokenQuantity), afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(sellTokenQuantity, afterAsset002.get(assetId001).longValue()); - - - } - - @Test(enabled = true, description = "create sellOrder and Match Order twice") - void marketSellAssetTest002() { - Map beforeAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map beforeAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - logger.info("beforeAsset002: " + beforeAsset002); - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, - sellTokenQuantity * 2, - assetAccountId002, buyTokenQuantity * 2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - logger.info("beforeAsset001 :" - + PublicMethed.queryAccount(testAddress001, blockingStubFull).getAssetV2Map()); - logger.info("beforeAsset002 :" - + PublicMethed.queryAccount(testAddress002, blockingStubFull).getAssetV2Map()); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId; - orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - String txid2 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity, assetAccountId001, sellTokenQuantity, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid2); - - transaction = PublicMethed - .getTransactionById(txid2, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - // get order Message and RemainSellTokenQuantity - MarketOrder order001 = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - Assert.assertEquals(order001.getSellTokenQuantityRemain(), sellTokenQuantity); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - String assetId001 = ByteArray.toStr(assetAccountId001); - String assetId002 = ByteArray.toStr(assetAccountId002); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity * 2), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((beforeAsset001.get(assetId002) + buyTokenQuantity), - afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(beforeAsset002.get(assetId001) + sellTokenQuantity, - afterAsset002.get(assetId001).longValue()); - - - String txid3 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity, assetAccountId001, sellTokenQuantity, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid3); - - transaction = PublicMethed - .getTransactionById(txid3, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - // get order Message and RemainSellTokenQuantity - order001 = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - Assert.assertEquals(order001.getSellTokenQuantityRemain(), 0); - - afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity * 2), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((beforeAsset001.get(assetId002) + buyTokenQuantity * 2), - afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity * 2, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(beforeAsset002.get(assetId001) + sellTokenQuantity * 2, - afterAsset002.get(assetId001).longValue()); - - - - } - - @Test(enabled = true, description = "create sellOrder and not Match Order") - void marketSellAssetTest003() { - - Map beforeAsset001 = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetV2Map(); - Map beforeAsset002 = PublicMethed - .queryAccount(testAddress002, blockingStubFull).getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - logger.info("beforeAsset002: " + beforeAsset002); - - String txid = PublicMethed - .marketSellAsset(testAddress001, testKey001, assetAccountId001, sellTokenQuantity, - assetAccountId002, buyTokenQuantity, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - String txid2 = PublicMethed.marketSellAsset(testAddress002, testKey002, assetAccountId002, - buyTokenQuantity * 2, assetAccountId001, sellTokenQuantity * 5, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid2); - - transaction = PublicMethed - .getTransactionById(txid2, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - Map afterAsset002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - logger.info("afterAsset002: " + afterAsset002); - - String assetId001 = ByteArray.toStr(assetAccountId001); - String assetId002 = ByteArray.toStr(assetAccountId002); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity), - afterAsset001.get(assetId001).longValue()); - Assert.assertEquals((beforeAsset001.get(assetId002).longValue()), - afterAsset001.get(assetId002).longValue()); - - Assert.assertEquals(beforeAsset002.get(assetId002) - buyTokenQuantity * 2, - afterAsset002.get(assetId002).longValue()); - Assert.assertEquals(beforeAsset002.get(assetId001).longValue(), - afterAsset002.get(assetId001).longValue()); - } - - @Test(enabled = true, description = "CancelOrder") - void marketSellAssetTest004() { - - Map beforeAsset001 = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetV2Map(); - - logger.info("beforeAsset001: " + beforeAsset001); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - Long sellTokenQuantity001; - byte[] tokenId; - byte[] orderId001; - - orderId001 = orderList.get().getOrders(0).getOrderId().toByteArray(); - tokenId = orderList.get().getOrders(0).getSellTokenId().toByteArray(); - sellTokenQuantity001 = orderList.get().getOrders(0).getSellTokenQuantityRemain(); - - String txid = PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - - String assetId001 = ByteArray.toStr(tokenId); - - Assert.assertEquals(beforeAsset001.get(assetId001) + sellTokenQuantity001, - afterAsset001.get(assetId001).longValue()); - - Return response = PublicMethed - .marketCancelOrderGetResposne(testAddress001, testKey001, orderId001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(response); - Assert.assertEquals(response.getCode(), response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ByteArray.toStr(response.getMessage().toByteArray()).toLowerCase(), - "contract validate error : Order is not active!".toLowerCase()); - - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java deleted file mode 100644 index fb7e2898dd2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset003.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class MarketSellAsset003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - byte [] trx = ByteArray.fromString("_"); - - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001, name, 10000_000000L, - 1, 1, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, testKey001, blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress002, name, 10000_000000L, - 1, 1, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID().toByteArray(); - } - - - @Test(enabled = true, description = "CancelOrder") - void marketCancelAssetTest001() { - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, 100, - trx, 50, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - txid = PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() == 0); - - } - - @Test(enabled = true, description = "Cancel a cancelled order ") - void marketCancelAssetTest002() { - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, 100, - trx, 50, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - txid = PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() == 0); - - Assert.assertEquals(PublicMethed.marketCancelOrder(testAddress001, testKey001, orderId, - blockingStubFull).toLowerCase(), - "contract validate error : Order is not active!".toLowerCase()); - - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java deleted file mode 100644 index 2a911540df4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset004.java +++ /dev/null @@ -1,113 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class MarketSellAsset004 { - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - byte [] trx = ByteArray.fromString("_"); - - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,20000_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,20000_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001,name,10000_000000L,1,1,start, - end,1,description,url,10000L,10000L,1L, 1L,testKey001,blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress002,name,10000_000000L,1,1,start, - end,1,description,url,10000L,10000L,1L, 1L,testKey002,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID().toByteArray(); - } - - - @Test(enabled = true,description = "The order amount exceeds the balance") - void marketCancelAssetTest002() { - - String txid = PublicMethed.marketSellAsset(testAddress001,testKey001,assetAccountId001,100, - trx,50,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - txid = PublicMethed.marketCancelOrder(testAddress001,testKey001,orderId,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java deleted file mode 100644 index 951c404c6f0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset005.java +++ /dev/null @@ -1,160 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Map; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class MarketSellAsset005 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - byte [] trx = ByteArray.fromString("_"); - - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - ByteString assetAccountId; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2024_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,2024_000000L,foundationAddress001, - foundationKey001,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001,name,10000_000000L,1,1,start, - end,1,description,url,10000L,10000L,1L, 1L,testKey001,blockingStubFull)); - - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId = PublicMethed.queryAccount(testAddress001, blockingStubFull).getAssetIssuedID(); - - - } - - - @Test(enabled = true,description = "Create an order to sell Trx and buy Trc10") - void test01SellTrxBuyTrc10() { - long balanceAfter = PublicMethed.queryAccount(testKey001, blockingStubFull).getBalance(); - PublicMethed.transferAsset(testAddress002, assetAccountId001, 10000, testAddress001, - testKey001, blockingStubFull); - final Map beforeAsset001 = PublicMethed.queryAccount(testAddress001, - blockingStubFull).getAssetV2Map(); - - String txid = PublicMethed.marketSellAsset(testAddress002,testKey002,trx, - sellTokenQuantity,assetAccountId001, - buyTokenQuantity,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - logger.info("beforeAsset001: " + beforeAsset001); - - txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, - sellTokenQuantity * 2, - trx, buyTokenQuantity * 2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - - Map afterAsset001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetV2Map(); - - logger.info("afterAsset001: " + afterAsset001); - - String assetId001 = ByteArray.toStr(assetAccountId001); - Assert.assertEquals((beforeAsset001.get(assetId001) - sellTokenQuantity * 2), - afterAsset001.get(assetId001).longValue()); - - } - - @Test(enabled = true,description = "Create an order to sell Trc10 and buy Trx") - void test02SellTrc10BuyTrx() { - long balanceAfter = PublicMethed.queryAccount(testKey001, blockingStubFull).getBalance(); - - final Map beforeAsset001 = PublicMethed.queryAccount(testAddress001, - blockingStubFull).getAssetV2Map(); - - String txid = PublicMethed.marketSellAsset(testAddress002,testKey002,assetAccountId001, - sellTokenQuantity,trx, - buyTokenQuantity,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - logger.info("transaction: " + transaction); - Assert.assertEquals(transaction.get().getRet(0).getRet().toString(), "SUCESS"); - - logger.info("beforeAsset001: " + beforeAsset001); - - txid = PublicMethed.marketSellAsset(testAddress001, testKey001, trx, - sellTokenQuantity * 2, - assetAccountId001, buyTokenQuantity * 2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - - - } - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java deleted file mode 100644 index 830795dfded..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/assetmarket/MarketSellAsset006.java +++ /dev/null @@ -1,288 +0,0 @@ -package stest.tron.wallet.dailybuild.assetmarket; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import org.tron.protos.Protocol.MarketOrderPairList; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - - -public class MarketSellAsset006 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - private static final String shortname = "a"; - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String foundationKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private final byte[] foundationAddress002 = PublicMethed.getFinalAddress(foundationKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey001.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - byte[] assetAccountId001; - - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey002.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - byte[] assetAccountId002; - - long sellTokenQuantity = 100; - long buyTokenQuantity = 50; - - private ManagedChannel channelFull = null; - - private ManagedChannel channelSolidity = null; - - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - public ManagedChannel channelPbft = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002, 20000_000000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress001, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey001, blockingStubFull)); - - start = System.currentTimeMillis() + 5000; - end = System.currentTimeMillis() + 1000000000; - Assert - .assertTrue(PublicMethed.createAssetIssue(testAddress002, name, 10000_000000L, 1, 1, start, - end, 1, description, url, 10000L, 10000L, 1L, 1L, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId001 = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getAssetIssuedID().toByteArray(); - - assetAccountId002 = PublicMethed.queryAccount(testAddress002, blockingStubFull) - .getAssetIssuedID().toByteArray(); - } - - - @Test(enabled = true, description = "create sellOrder") - void marketSellAssetTest001() { - - String txid = PublicMethed.marketSellAsset(testAddress001, testKey001, assetAccountId001, - sellTokenQuantity, assetAccountId002, buyTokenQuantity, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional transaction = PublicMethed - .getTransactionById(txid, blockingStubFull); - Assert.assertEquals(transaction.get().getRet(0).getRet(), code.SUCESS); - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - MarketOrder order = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - - Assert.assertEquals(order.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order.getBuyTokenQuantity(), buyTokenQuantity); - - } - - @Test(enabled = false, description = "getMarketPairList from solidity and pbft") - void marketSellAssetTest002() { - Optional pairList = PublicMethed - .getMarketPairList(blockingStubFull); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional pairList2 = PublicMethed - .getMarketPairListSolidity(blockingStubSolidity); - - - Optional pairList3 = PublicMethed - .getMarketPairListSolidity(blockingStubPbft); - - Assert.assertEquals(pairList,pairList2); - Assert.assertEquals(pairList,pairList3); - - - - } - - @Test(enabled = true, description = "getMarketOrderListByPair from solidity and pbft") - void marketSellAssetTest003() { - Optional orderList = PublicMethed - .getMarketOrderListByPair(assetAccountId001,assetAccountId002,blockingStubFull); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional orderList2 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubSolidity); - - - Optional orderList3 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubPbft); - - System.out.println(orderList3); - - Assert.assertEquals(orderList,orderList2); - Assert.assertEquals(orderList,orderList3); - - } - - - @Test(enabled = true, description = "GetMarketOrderById from solidity and pbft") - void marketSellAssetTest004() { - Optional orderList = PublicMethed - .getMarketOrderListByPair(assetAccountId001,assetAccountId002,blockingStubFull); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional orderList2 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubSolidity); - - - Optional orderList3 = PublicMethed - .getMarketOrderListByPairSolidity(assetAccountId001,assetAccountId002,blockingStubPbft); - - System.out.println(orderList3); - - Assert.assertEquals(orderList,orderList2); - Assert.assertEquals(orderList,orderList3); - - } - - - @Test(enabled = true, description = "GetMarketOrderByAccount from solidity and pbft") - void marketSellAssetTest005() { - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - Assert.assertTrue(orderList.get().getOrdersCount() > 0); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - - Optional orderList2 = PublicMethed - .getMarketOrderByAccountSolidity(testAddress001, blockingStubSolidity); - Assert.assertTrue(orderList2.get().getOrdersCount() > 0); - - - Optional orderList3 = PublicMethed - .getMarketOrderByAccountSolidity(testAddress001, blockingStubPbft); - Assert.assertTrue(orderList3.get().getOrdersCount() > 0); - Assert.assertEquals(orderList,orderList2); - Assert.assertEquals(orderList,orderList3); - - } - - @Test(enabled = true, description = "GetMarketOrderById from solidity and pbft") - void marketSellAssetTest006() { - - Optional orderList = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull); - - byte[] orderId = orderList.get().getOrders(0).getOrderId().toByteArray(); - - MarketOrder order = PublicMethed - .getMarketOrderById(orderId, blockingStubFull).get(); - - Assert.assertEquals(order.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order.getBuyTokenQuantity(), buyTokenQuantity); - - MarketOrder order2 = PublicMethed - .getMarketOrderByIdSolidity(orderId, blockingStubSolidity).get(); - - Assert.assertEquals(order2.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order2.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order2.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order2.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order2.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order2.getBuyTokenQuantity(), buyTokenQuantity); - - MarketOrder order3 = PublicMethed - .getMarketOrderByIdSolidity(orderId, blockingStubPbft).get(); - - Assert.assertEquals(order3.getOrderId().toByteArray(), orderId); - Assert.assertEquals(order3.getOwnerAddress().toByteArray(), testAddress001); - Assert.assertEquals(order3.getSellTokenId().toByteArray(), assetAccountId001); - Assert.assertEquals(order3.getSellTokenQuantity(), sellTokenQuantity); - Assert.assertEquals(order3.getBuyTokenId().toByteArray(), assetAccountId002); - Assert.assertEquals(order3.getBuyTokenQuantity(), buyTokenQuantity); - - - } - - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java deleted file mode 100644 index 124a8d4405f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventLog2.java +++ /dev/null @@ -1,117 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class EventLog2 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/eventLog2.sol"; - String contractName = "Event"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "test opcode log2") - public void test01EmitLog2() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "messageI()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String logStr1 = ByteArray.toHexString(transactionExtention.getLogs(0).getData().toByteArray()); - Assert.assertTrue(logStr1.contains("000000000000000000000000000000000000000" - + "000000000000000000000000100000000000000000" - + "000000000000000000000000000000000000000000000010000000000000000" - + "000000000000000000000000000000000000000000000001")); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery001.java deleted file mode 100644 index 79075b8dccd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery001.java +++ /dev/null @@ -1,152 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Event query for block") - public void test01EventQueryForBlock() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("blockTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String blockMessage = ""; - - Integer retryTimes = 20; - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (message != null) { - //System.out.println("receive : " + new String(message)); - blockMessage = new String(message); - if (!blockMessage.equals("blockTrigger") && !blockMessage.isEmpty()) { - break; - } - } - } - - Assert.assertTrue(retryTimes > 0); - logger.info("block message:" + blockMessage); - JSONObject blockObject = JSONObject.parseObject(blockMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "blockTrigger"); - Assert.assertTrue(blockObject.getLong("blockNumber") > 0); - Assert.assertTrue(blockObject.containsKey("blockHash")); - Assert.assertTrue(blockObject.getInteger("transactionSize") >= 0); - } - - - @Test(enabled = true, description = "Event query for block on solidity") - public void test02EventQueryForBlockOnSolidity() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("solidityTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String blockMessage = ""; - - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (message != null) { - System.out.println("receive : " + new String(message)); - blockMessage = new String(message); - if (!blockMessage.equals("solidityTrigger") && !blockMessage.isEmpty()) { - break; - } - } - } - - Assert.assertTrue(retryTimes > 0); - logger.info("block message:" + blockMessage); - JSONObject blockObject = JSONObject.parseObject(blockMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "solidityTrigger"); - Assert.assertTrue(blockObject.getLong("latestSolidifiedBlockNumber") > 0); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java deleted file mode 100644 index 8eed6a93ae5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery002.java +++ /dev/null @@ -1,147 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress; - String txid; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, description = "Event query for transaction") - public void test01EventQueryForTransaction() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("transactionTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - transactionMessage = new String(message); - if (!transactionMessage.equals("transactionTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "transactionTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java deleted file mode 100644 index 20cb549cf1b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery003.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress; - String txid; - - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, description = "Event query for contract event") - public void test01EventQueryForContractEvent() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("contractEventTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - transactionMessage = new String(message); - if (!transactionMessage.equals("contractEventTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "contractEventTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - - @Test(enabled = true, description = "Event query for solidity contract event") - public void test02EventQueryForContractSolidityEvent() { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("solidityEventTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 40; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "triggerUintEvent()", "#", false, - 0, maxFeeLimit, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - - transactionMessage = new String(message); - logger.info("transaction message:" + transactionMessage); - if (!transactionMessage.equals("solidityEventTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "solidityEventTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java deleted file mode 100644 index f4181489708..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/eventquery/EventQuery004.java +++ /dev/null @@ -1,223 +0,0 @@ -package stest.tron.wallet.dailybuild.eventquery; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class EventQuery004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - byte[] contractAddress; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String eventnode = Configuration.getByPath("testng.conf") - .getStringList("eventnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - Assert.assertTrue(PublicMethed.sendcoin(event001Address, maxFeeLimit * 30, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "addressDemo"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractEventAndLog1"); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 50, null, event001Key, event001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, description = "Event query for contract log") - public void test01EventQueryForContractLog() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("contractLogTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 20; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - } - - if (message != null) { - transactionMessage = new String(message); - if (!transactionMessage.equals("contractLogTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "contractLogTrigger"); - - Assert.assertEquals(blockObject.getString("transactionId"), txid); - } - - - @Test(enabled = true, description = "Event query for solidity contract log") - public void test02EventQueryForContractSolidityLog() { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("solidityLogTrigger"); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect(eventnode); - req.setReceiveTimeOut(10000); - String transactionMessage = ""; - Boolean sendTransaction = true; - Integer retryTimes = 40; - String txid1 = ""; - String txid2 = ""; - String txid3 = ""; - - while (retryTimes-- > 0) { - byte[] message = req.recv(); - if (sendTransaction) { - txid1 = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - txid2 = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - txid3 = PublicMethed.triggerContract(contractAddress, - "depositForLog()", "#", false, - 1L, 100000000L, event001Address, event001Key, blockingStubFull); - logger.info(txid); - if (PublicMethed.getTransactionInfoById(txid,blockingStubFull).get() - .getResultValue() == 0) { - sendTransaction = false; - } - - } - - if (message != null) { - - transactionMessage = new String(message); - logger.info("transaction message:" + transactionMessage); - if (!transactionMessage.equals("solidityLogTrigger") && !transactionMessage.isEmpty()) { - break; - } - } - } - Assert.assertTrue(retryTimes > 0); - logger.info("transaction message:" + transactionMessage); - JSONObject blockObject = JSONObject.parseObject(transactionMessage); - Assert.assertTrue(blockObject.containsKey("timeStamp")); - Assert.assertEquals(blockObject.getString("triggerName"), "solidityLogTrigger"); - txid = blockObject.getString("transactionId"); - - Assert.assertTrue(txid1.equals(txid) || txid2.equals(txid) || txid3.equals(txid)); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/exceptionfee/AssertException.java b/framework/src/test/java/stest/tron/wallet/dailybuild/exceptionfee/AssertException.java deleted file mode 100644 index 2ca3c357777..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/exceptionfee/AssertException.java +++ /dev/null @@ -1,566 +0,0 @@ -package stest.tron.wallet.dailybuild.exceptionfee; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AssertException { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger contract Divide 0") - public void test1DivideInt() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - Account info; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "4" + "," + "0"; - - txid = PublicMethed.triggerContract(contractAddress, - "divideIHaveArgsReturn(int256,int256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Optional ById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("getRet:" + ById.get().getRet(0)); - logger.info("getNumber:" + ById.get().getRet(0).getContractRet().getNumber()); - logger.info("getContractRetValue:" + ById.get().getRet(0).getContractRetValue()); - logger.info("getContractRet:" + ById.get().getRet(0).getContractRet()); - - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - contractResult.REVERT.getNumber()); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), 2); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.REVERT); - - Assert - .assertEquals(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()), - "4e487b710000000000000000000000000000000000000000000000000000000000000012"); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract index out of bounds") - public void test2FindArgsContractMinTest() { - String filePath = - "src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol"; - String contractName = "findArgsIContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("11:" + Base58.encode58Check(contractAddress)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = -1; - txid = PublicMethed.triggerContract(contractAddress, - "findArgsByIndex1(uint256)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Trigger contract Bytes array index out of bounds") - public void test3ByteMinContract() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol"; - String contractName = "byteContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = -1; - txid = PublicMethed.triggerContract(contractAddress, - "testBytesGet(uint256)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Trigger contract convert too large value to enumerated type") - public void test4Enum() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest4Enum.sol"; - String contractName = "enumContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = 22; - - txid = PublicMethed.triggerContract(contractAddress, - "setGoStraight(uint8)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = false, description = "Trigger contract move a negative value to a binary") - public void test5MoveRight() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol"; - String contractName = "binaryRightContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - Integer triggerNum = -1; - txid = PublicMethed.triggerContract(contractAddress, - "binaryMoveR(uint256)", triggerNum.toString(), false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + maxFeeLimit + netFee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract Call an uninitialized " - + "internal function type variable") - public void test6UninitializedContract() { - String filePath = - "src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol"; - String contractName = "uni"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test2()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Trigger contract assert exception") - public void test7TestAssertContract() { - String filePath = "src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testAssert()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue((beforeBalance - fee) == afterBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpRateLimite001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpRateLimite001.java deleted file mode 100644 index 63a9e642d23..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpRateLimite001.java +++ /dev/null @@ -1,132 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpRateLimite001 { - - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - private String httpSoliditynode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(3); - private String realHttpSoliditynode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(4); - - - - /** constructor. */ - @BeforeClass - public void beforeClass() {} - - /** constructor. */ - @Test(enabled = true, description = "Rate limit QpsStrategy for ListWitness interface") - public void test1QpsStrategyForListWitnessInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.listwitnesses(httpnode); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - /** constructor. */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for ListNodes interface") - public void test2IpQpsStrategyForListNodesInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.listNodes(httpnode); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - /** constructor. */ - @Test( - enabled = true, - description = - "Rate limit IpQpsStrategy for GetBlockByLatestNumOnSolidity " - + "interface on fullnode's solidity service") - public void test3IpQpsStrategyForGetBlockByLatestNumOnSolidityInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.getBlockByLastNumFromSolidity(httpSoliditynode, 5); - HttpMethed.getBlockByLastNumFromPbft(httpPbftNode, 5); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - /** constructor. */ - @Test( - enabled = true, - description = - "Rate limit QpsStrategy for getBlockByNum " + "interface on fullnode's solidity service") - public void test4QpsStrategyForgetBlockByNumResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - HttpMethed.getBlockByLastNumFromSolidity(httpSoliditynode, 5); - HttpMethed.getBlockByLastNumFromPbft(httpPbftNode, 5); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - @Test( - enabled = false, - description = - "Rate limit QpsStrategy for " - + "getTransactionsFromThisFromSolidity " - + "interface on real solidity") - public void test6QpsStrategyForgetTransactionsToThisFromSolidity() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 15) { - logger.info(realHttpSoliditynode); - HttpMethed.getTransactionsToThisFromSolidity(realHttpSoliditynode, fromAddress, 0, 50); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 4000); - } - - @Test(enabled = true, description = "Verify getstatsinfo Interface has been disabled") - public void test7GetStatsInfo() { - response = HttpMethed.getStatsInfo(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForGetstatsinfo = responseContent.getString("Error"); - logger.info("resultForGetstatsinfo:" + resultForGetstatsinfo); - Assert.assertEquals(resultForGetstatsinfo, "this API is unavailable due to config"); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException {} -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount001.java deleted file mode 100644 index 12870a5ae5c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount001.java +++ /dev/null @@ -1,107 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by http") - public void getAccount() { - response = HttpMethed.getAccount(httpnode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account from solidity by http") - public void getAccountFromSolidity() { - response = HttpMethed.getAccountFromSolidity(httpSoliditynode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account from PBFT by http") - public void getAccountFromPbftNode() { - response = HttpMethed.getAccountFromPbft(httpPbftNode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 3); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get accountNet by http") - public void getAccountNet() { - response = HttpMethed.getAccountNet(httpnode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(Integer.parseInt(responseContent.get("freeNetLimit").toString()), 5000); - Assert.assertEquals(Long.parseLong(responseContent.get("TotalNetLimit").toString()), - 43200000000L); - Assert.assertTrue(responseContent.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get accountResource by http") - public void getAccountResource() { - response = HttpMethed.getAccountReource(httpnode, fromAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - Long.parseLong(responseContent.get("TotalEnergyLimit").toString()) >= 50000000000L); - Assert.assertTrue(responseContent.size() >= 3); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount002.java deleted file mode 100644 index d1d8f587580..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount002.java +++ /dev/null @@ -1,335 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] freezeBalanceAddress = ecKey1.getAddress(); - String freezeBalanceKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverResourceAddress = ecKey2.getAddress(); - String receiverResourceKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long berforeBalance; - Long afterBalance; - Long amount = 10000000L; - Long frozenBalance = 2000000L; - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance for bandwidth by http") - public void test001FreezebalanceForBandwidth() { - PublicMethed.printAddress(freezeBalanceKey); - //Send trx to test account - response = HttpMethed.sendCoin(httpnode, fromAddress, freezeBalanceAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 0, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance for bandwidth by http") - public void test002UnFreezebalanceForBandwidth() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance for bandwidth - response = HttpMethed.unFreezeBalance(httpnode, freezeBalanceAddress, 0, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance for energy by http") - public void test003FreezebalanceForEnergy() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance for energy - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 1, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance for energy by http") - public void test004UnFreezebalanceForEnergy() { - - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - HttpMethed.waitToProduceOneBlock(httpnode); - //UnFreeze balance for energy - response = HttpMethed.unFreezeBalance(httpnode, freezeBalanceAddress, 1, freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance with bandwidth for others by http") - public void test005FreezebalanceOfBandwidthForOthers() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, receiverResourceAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance with bandwidth for others - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 0, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource by http") - public void test006GetDelegatedResource() { - response = HttpMethed - .getDelegatedResource(httpnode, freezeBalanceAddress, receiverResourceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("delegatedResource").toString()); - Assert.assertTrue(jsonArray.size() >= 1); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("from"), - ByteArray.toHexString(freezeBalanceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("to"), - ByteArray.toHexString(receiverResourceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getLong("frozen_balance_for_bandwidth"), - frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource from solidity by http") - public void test007GetDelegatedResourceFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed.getDelegatedResourceFromSolidity(httpSoliditynode, freezeBalanceAddress, - receiverResourceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("delegatedResource").toString()); - Assert.assertTrue(jsonArray.size() >= 1); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("from"), - ByteArray.toHexString(freezeBalanceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("to"), - ByteArray.toHexString(receiverResourceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getLong("frozen_balance_for_bandwidth"), - frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource from PBFT by http") - public void test008GetDelegatedResourceFromPbft() { - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed - .getDelegatedResourceFromPbft(httpPbftNode, freezeBalanceAddress, receiverResourceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("delegatedResource").toString()); - Assert.assertTrue(jsonArray.size() >= 1); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("from"), - ByteArray.toHexString(freezeBalanceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getString("to"), - ByteArray.toHexString(receiverResourceAddress)); - Assert.assertEquals(jsonArray.getJSONObject(0).getLong("frozen_balance_for_bandwidth"), - frozenBalance); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource Account Index by http") - public void test009GetDelegatedResourceAccountIndex() { - response = HttpMethed.getDelegatedResourceAccountIndex(httpnode, freezeBalanceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("toAccounts").toString().isEmpty()); - String toAddress = responseContent.getJSONArray("toAccounts").get(0).toString(); - Assert.assertEquals(toAddress, ByteArray.toHexString(receiverResourceAddress)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource Account Index from solidity by http") - public void test010GetDelegatedResourceAccountIndexFromSolidity() { - response = HttpMethed - .getDelegatedResourceAccountIndexFromSolidity(httpSoliditynode, freezeBalanceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("toAccounts").toString().isEmpty()); - String toAddress = responseContent.getJSONArray("toAccounts").get(0).toString(); - Assert.assertEquals(toAddress, ByteArray.toHexString(receiverResourceAddress)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get Delegated Resource Account Index from PBFT by http") - public void test011GetDelegatedResourceAccountIndexFromPbft() { - response = HttpMethed - .getDelegatedResourceAccountIndexFromPbft(httpPbftNode, freezeBalanceAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("toAccounts").toString().isEmpty()); - String toAddress = responseContent.getJSONArray("toAccounts").get(0).toString(); - Assert.assertEquals(toAddress, ByteArray.toHexString(receiverResourceAddress)); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance with bandwidth for others by http") - public void test012UnFreezebalanceOfBandwidthForOthers() { - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance with bandwidth for others - response = HttpMethed - .unFreezeBalance(httpnode, freezeBalanceAddress, 0, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBalance with energy for others by http") - public void test013FreezebalanceOfEnergyForOthers() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, receiverResourceAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //Freeze balance with energy for others - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 1, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance with energy for others by http") - public void test014UnFreezebalanceOfEnergyForOthers() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance with energy for others - response = HttpMethed - .unFreezeBalance(httpnode, freezeBalanceAddress, 1, receiverResourceAddress, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "FreezeBlance for tron power by http") - public void test015FreezeTronPower() { - HttpMethed.waitToProduceOneBlock(httpnode); - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - response = HttpMethed - .freezeBalance(httpnode, freezeBalanceAddress, frozenBalance, 0, 2, null, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(berforeBalance - afterBalance == frozenBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UnFreezeBalance for tron power by http") - public void test016UnFreezeBalanceForTronPower() { - berforeBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - - //UnFreeze balance with energy for others - response = HttpMethed - .unFreezeBalance(httpnode, freezeBalanceAddress, 2, null, - freezeBalanceKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - afterBalance = HttpMethed.getBalance(httpnode, freezeBalanceAddress); - Assert.assertTrue(afterBalance - berforeBalance == frozenBalance); - } - - - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, freezeBalanceAddress, fromAddress, freezeBalanceKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount003.java deleted file mode 100644 index a63d3e7f6c0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount003.java +++ /dev/null @@ -1,230 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount003 { - - private static String updateAccountName = - "updateAccount_" + System.currentTimeMillis(); - private static String updateUrl = - "http://www.update.url/" + System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness1Address = PublicMethed.getFinalAddress(witnessKey001); - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witness2Address = PublicMethed.getFinalAddress(witnessKey002); - private final Long createWitnessAmount = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.createWitnessAmount"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey1.getAddress(); - String newAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] updateAccountAddress = ecKey2.getAddress(); - String updateAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long amount = 50000000L; - JsonArray voteKeys = new JsonArray(); - JsonObject voteElement = new JsonObject(); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "Update account by http") - public void test01UpdateAccount() { - response = HttpMethed.sendCoin(httpnode, fromAddress, updateAccountAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed - .updateAccount(httpnode, updateAccountAddress, updateAccountName, updateAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, updateAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getString("account_name") - .equalsIgnoreCase(HttpMethed.str2hex(updateAccountName))); - - Assert.assertFalse(responseContent.getString("active_permission").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Vote witness account by http") - public void test02VoteWitnessAccount() { - //Freeze balance - response = HttpMethed - .freezeBalance(httpnode, updateAccountAddress, 40000000L, 0, 2, updateAccountKey); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - voteElement.addProperty("vote_address", ByteArray.toHexString(witness1Address)); - voteElement.addProperty("vote_count", 11); - voteKeys.add(voteElement); - - voteElement.remove("vote_address"); - voteElement.remove("vote_count"); - voteElement.addProperty("vote_address", ByteArray.toHexString(witness2Address)); - voteElement.addProperty("vote_count", 12); - voteKeys.add(voteElement); - - response = HttpMethed - .voteWitnessAccount(httpnode, updateAccountAddress, voteKeys, updateAccountKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, updateAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("votes").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List witnesses by http") - public void test03ListWitness() { - response = HttpMethed.listwitnesses(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("witnesses")); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List witnesses from solidity by http") - public void test04ListWitnessFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listwitnessesFromSolidity(httpSoliditynode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("witnesses")); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List witnesses from PBFT by http") - public void test05ListWitnessFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listwitnessesFromPbft(httpPbftNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("witnesses")); - Assert.assertTrue(jsonArray.size() >= 2); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Update witness by http") - public void test06UpdateWitness() { - response = HttpMethed.updateWitness(httpnode, witness1Address, updateUrl, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.listwitnesses(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getString("witnesses").indexOf(updateUrl) != -1); - //logger.info("result is " + responseContent.getString("witnesses").indexOf(updateUrl)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Create account by http") - public void test07CreateAccount() { - PublicMethed.printAddress(newAccountKey); - response = HttpMethed.createAccount(httpnode, fromAddress, newAccountAddress, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, newAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getLong("create_time") > 3); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Create witness by http") - public void test08CreateWitness() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, newAccountAddress, createWitnessAmount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - PublicMethed.printAddress(newAccountKey); - - response = HttpMethed.createWitness(httpnode, newAccountAddress, updateUrl); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("txID").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Withdraw by http") - public void test09Withdraw() { - response = HttpMethed.withdrawBalance(httpnode, witness1Address); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert - .assertTrue(responseContent.getString("Error").indexOf("is a guard representative") != -1); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Unfreeze balance for tron power by http") - public void test10UnfreezeTronPower() { - response = HttpMethed.unFreezeBalance(httpnode, updateAccountAddress,2,updateAccountKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, updateAccountAddress, fromAddress, updateAccountKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount004.java deleted file mode 100644 index 5ae5089d057..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount004.java +++ /dev/null @@ -1,115 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] setAccountIdAddress = ecKey1.getAddress(); - String setAccountIdKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Long amount = 10000000L; - String accountId; - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - - - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "Set account by http") - public void test1setAccountId() { - response = HttpMethed.sendCoin(httpnode, fromAddress, setAccountIdAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed - .setAccountId(httpnode, setAccountIdAddress, System.currentTimeMillis() + "id", false, - setAccountIdKey); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - //Set account id. - accountId = System.currentTimeMillis() + "id"; - response = HttpMethed - .setAccountId(httpnode, setAccountIdAddress, accountId, true, setAccountIdKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by id via http") - public void test2getAccountId() { - response = HttpMethed.getAccountById(httpnode, accountId, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.get("account_id"), accountId); - Assert.assertTrue(responseContent.size() >= 10); - - response = HttpMethed.getAccountById(httpnode, accountId, false); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() <= 1); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by id via http") - public void test3getAccountIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAccountByIdFromSolidity(httpSoliditynode, accountId, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.get("account_id"), accountId); - Assert.assertTrue(responseContent.size() >= 10); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account by id via PBFT http") - public void test4getAccountIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAccountByIdFromPbft(httpPbftNode, accountId, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.get("account_id"), accountId); - Assert.assertTrue(responseContent.size() >= 10); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, setAccountIdAddress, fromAddress, setAccountIdKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount005.java deleted file mode 100644 index 4d45d5e8b0e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAccount005.java +++ /dev/null @@ -1,62 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAccount005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] toAddress = ecKey1.getAddress(); - String toAddressKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Long amount = 1L; - String sendText = "Decentralize the WEB!"; - private JSONObject responseContent; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, description = "Test transfer with notes by http") - public void test01TransferWithNotes() { - PublicMethed.printAddress(toAddressKey); - //Send trx to test account - String txid = HttpMethed - .sendCoin(httpnode, fromAddress, toAddress, amount, sendText, testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpResponse response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String rawData = responseContent.getString("raw_data"); - JSONObject rawDataObject = JSON.parseObject(rawData); - Assert.assertTrue(rawDataObject.containsKey("data")); - String hexData = rawDataObject.getString("data"); - String recoveredString = new String(ByteUtil.hexToBytes(hexData)); - Assert.assertEquals(sendText, recoveredString); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, toAddress, fromAddress, toAddressKey); - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAsset001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAsset001.java deleted file mode 100644 index f57780e5bc7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestAsset001.java +++ /dev/null @@ -1,311 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestAsset001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId; - private static String updateDescription = "Description_update_" + now; - private static String updateUrl = "Url_update_" + now; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] assetAddress = ecKey1.getAddress(); - String assetKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey2.getAddress(); - String participateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Long amount = 2048000000L; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private JSONObject getAssetIssueByIdContent; - private JSONObject getAssetIssueByNameContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "Create asset issue by http") - public void test01CreateAssetIssue() { - response = HttpMethed.sendCoin(httpnode, fromAddress, assetAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .sendCoin(httpnode, fromAddress, participateAddress, 10000000L, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, assetAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, assetAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - assetIssueId = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId); - Assert.assertTrue(Integer.parseInt(assetIssueId) > 1000000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueById by http") - public void test02GetAssetIssueById() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAssetIssueById(httpnode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - Assert.assertTrue(totalSupply == getAssetIssueByIdContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueById from solidity by http") - public void test03GetAssetIssueByIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueByIdFromSolidity(httpSoliditynode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - Assert.assertTrue(totalSupply == getAssetIssueByIdContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueById from PBFT by http") - public void test04GetAssetIssueByIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueByIdFromPbft(httpPbftNode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - Assert.assertTrue(totalSupply == getAssetIssueByIdContent.getLong("total_supply")); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueByName by http") - public void test05GetAssetIssueByName() { - response = HttpMethed.getAssetIssueByName(httpnode, name); - getAssetIssueByNameContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByNameContent); - Assert.assertTrue(totalSupply == getAssetIssueByNameContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueByName from solidity by http") - public void test06GetAssetIssueByNameFromSolidity() { - response = HttpMethed.getAssetIssueByNameFromSolidity(httpSoliditynode, name); - getAssetIssueByNameContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByNameContent); - Assert.assertTrue(totalSupply == getAssetIssueByNameContent.getLong("total_supply")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetAssetIssueByName from PBFT by http") - public void test07GetAssetIssueByNameFromPbft() { - response = HttpMethed.getAssetIssueByNameFromPbft(httpPbftNode, name); - getAssetIssueByNameContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByNameContent); - Assert.assertTrue(totalSupply == getAssetIssueByNameContent.getLong("total_supply")); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "TransferAsset by http") - public void test08TransferAsset() { - logger.info("Transfer asset."); - response = HttpMethed - .transferAsset(httpnode, assetAddress, participateAddress, assetIssueId, 100L, assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, participateAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("assetV2").isEmpty()); - //logger.info(responseContent.get("assetV2").toString()); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Participate asset issue by http") - public void test09ParticipateAssetIssue() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .participateAssetIssue(httpnode, assetAddress, participateAddress, assetIssueId, 1000L, - participateKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, participateAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Update asset issue by http") - public void test10UpdateAssetIssue() { - response = HttpMethed - .updateAssetIssue(httpnode, assetAddress, updateDescription, updateUrl, 290L, 390L, - assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAssetIssueById(httpnode, assetIssueId); - getAssetIssueByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getAssetIssueByIdContent); - - Assert.assertTrue(getAssetIssueByIdContent.getLong("public_free_asset_net_limit") == 390L); - Assert.assertTrue(getAssetIssueByIdContent.getLong("free_asset_net_limit") == 290L); - Assert.assertTrue(getAssetIssueByIdContent.getString("description") - .equalsIgnoreCase(HttpMethed.str2hex(updateDescription))); - Assert.assertTrue( - getAssetIssueByIdContent.getString("url").equalsIgnoreCase(HttpMethed.str2hex(updateUrl))); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get asset issue list by http") - public void test11GetAssetissueList() { - - response = HttpMethed.getAssetissueList(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() >= 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get asset issue list from solidity by http") - public void test12GetAssetissueListFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueListFromSolidity(httpSoliditynode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() >= 1); - } - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get asset issue list from PBFT by http") - public void test13GetAssetissueListFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueListFromPbft(httpPbftNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() >= 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated asset issue list by http") - public void test14GetPaginatedAssetissueList() { - response = HttpMethed.getPaginatedAssetissueList(httpnode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated asset issue list from solidity by http") - public void test15GetPaginatedAssetissueListFromSolidity() { - response = HttpMethed.getPaginatedAssetissueListFromSolidity(httpSoliditynode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated asset issue list from PBFT by http") - public void test16GetPaginatedAssetissueListFromPbft() { - response = HttpMethed.getPaginatedAssetissueListFromPbft(httpPbftNode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("assetIssue")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetAddress, fromAddress, assetKey); - HttpMethed.freedResource(httpnode, participateAddress, fromAddress, participateKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java deleted file mode 100644 index f091e8f4b05..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestBlock001.java +++ /dev/null @@ -1,383 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestBlock001 { - - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private Integer currentBlockNum; - private JSONObject blockContent; - private JSONObject blockContentWithVisibleTrue; - private String blockId; - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block by http") - public void get01NowBlock() { - response = HttpMethed.getNowBlock(httpnode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - blockContent = responseContent; - blockId = responseContent.get("blockID").toString(); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertFalse(responseContent.get("witness_signature").toString().isEmpty()); - HttpMethed.printJsonContent(responseContent); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(Integer.parseInt(responseContent.get("number").toString()) > 0); - currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Assert.assertTrue(Long.parseLong(responseContent.get("timestamp").toString()) > 1550724114000L); - Assert.assertFalse(responseContent.get("witness_address").toString().isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from solidity by http") - public void get02NowBlockFromSolidity() { - response = HttpMethed.getNowBlockFromSolidity(httpSoliditynode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - blockContent = responseContent; - blockId = responseContent.get("blockID").toString(); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertFalse(responseContent.get("witness_signature").toString().isEmpty()); - HttpMethed.printJsonContent(responseContent); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(Integer.parseInt(responseContent.get("number").toString()) > 0); - currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Assert.assertTrue(Long.parseLong(responseContent.get("timestamp").toString()) > 1550724114000L); - Assert.assertFalse(responseContent.get("witness_address").toString().isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from pbft by http") - public void get03NowBlockFromPbft() { - response = HttpMethed.getNowBlockFromPbft(httpPbftNode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - blockContent = responseContent; - blockId = responseContent.get("blockID").toString(); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - responseContent = HttpMethed.parseStringContent(responseContent.get("block_header").toString()); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertFalse(responseContent.get("witness_signature").toString().isEmpty()); - HttpMethed.printJsonContent(responseContent); - responseContent = HttpMethed.parseStringContent(responseContent.get("raw_data").toString()); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(Integer.parseInt(responseContent.get("number").toString()) > 0); - currentBlockNum = Integer.parseInt(responseContent.get("number").toString()); - Assert.assertTrue(Long.parseLong(responseContent.get("timestamp").toString()) > 1550724114000L); - Assert.assertFalse(responseContent.get("witness_address").toString().isEmpty()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block by num by http") - public void get04BlockByNum() { - response = HttpMethed.getBlockByNum(httpnode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent, blockContent); - - //visible=true - response = HttpMethed.getBlockByNum(httpnode, currentBlockNum, true); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent.getString("blockID"), - blockContent.getString("blockID")); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block by num from solidity by http") - public void get05BlockByNumFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBlockByNumFromSolidity(httpSoliditynode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent, blockContent); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block by num from PBFT by http") - public void get06BlockByNumFromPbft() { - response = HttpMethed.getBlockByNumFromPbft(httpPbftNode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals(responseContent, blockContent); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLimitNext by http") - public void get07BlockByLimitNext() { - response = HttpMethed.getBlockByLimitNext(httpnode, currentBlockNum - 10, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 10); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLastNum by http") - public void get08BlockByLastNum() { - response = HttpMethed.getBlockByLastNum(httpnode, 8); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 8); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockById by http") - public void get09BlockById() { - response = HttpMethed.getBlockById(httpnode, blockId); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(blockId, responseContent.get("blockID").toString()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockById by Solidity http") - public void get10BlockByIdFromSolidity() { - response = HttpMethed.getBlockByIdFromSolidity(httpSoliditynode, blockId); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(blockId, responseContent.get("blockID").toString()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockById by PBFT http") - public void get11BlockByIdFromPbft() { - response = HttpMethed.getBlockByIdFromPbft(httpPbftNode, blockId); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(blockId, responseContent.get("blockID").toString()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "List nodes by http") - public void get12ListNodes() { - response = HttpMethed.listNodes(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "get next maintenance time by http") - public void get13NextMaintaenanceTime() { - response = HttpMethed.getNextmaintenanceTime(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("num").toString().isEmpty()); - Assert.assertTrue(responseContent.getLong("num") >= System.currentTimeMillis()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "get chain parameter by http") - public void get14ChainParameter() { - response = HttpMethed.getChainParameter(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("chainParameter").toString()); - Assert.assertTrue(jsonArray.size() >= 26); - Boolean exsistDelegated = false; - for (int i = 0; i < jsonArray.size(); i++) { - if (jsonArray.getJSONObject(i).getString("key").equals("getAllowDelegateResource")) { - exsistDelegated = true; - Assert.assertTrue(jsonArray.getJSONObject(i).getString("value").equals("1")); - } - } - Assert.assertTrue(exsistDelegated); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "get Node Info by http") - public void get15NodeInfo() { - response = HttpMethed.getNodeInfo(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertFalse(responseContent.get("configNodeInfo").toString().isEmpty()); - Assert.assertTrue(responseContent.getString("configNodeInfo").contains("\"dbVersion\":2")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction count by blocknum from solidity by http") - public void get16TransactionCountByBlocknumFromSolidity() { - response = HttpMethed - .getTransactionCountByBlocknumFromSolidity(httpSoliditynode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() == 1); - Assert.assertTrue(Integer.parseInt(responseContent.get("count").toString()) >= 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction count by blocknum from PBFT by http") - public void get17TransactionCountByBlocknumFromPbft() { - response = HttpMethed.getTransactionCountByBlocknumFromPbft(httpPbftNode, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() == 1); - Assert.assertTrue(Integer.parseInt(responseContent.get("count").toString()) >= 0); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLimitNext by Solidity http") - public void get18BlockByLimitNextFromSolidity() { - response = HttpMethed - .getBlockByLimitNextFromSolidity(httpSoliditynode, currentBlockNum - 10, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 10); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLimitNext by PBFT http") - public void get19BlockByLimitNextFromPbft() { - response = HttpMethed - .getBlockByLimitNextFromPbft(httpPbftNode, currentBlockNum - 10, currentBlockNum); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 10); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLastNum by solidity http") - public void get20BlockByLastNumFromSolidity() { - response = HttpMethed.getBlockByLastNumFromSolidity(httpSoliditynode, 8); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 8); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByLastNum by PBFT http") - public void get21BlockByLastNumFromPbft() { - response = HttpMethed.getBlockByLastNumFromPbft(httpPbftNode, 8); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info(responseContent.get("block").toString()); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("block").toString()); - Assert.assertEquals(jsonArray.size(), 8); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Get block by num by http") - public void get16TestResponse() { - Integer times = 1000; - String testKey002 = "7400E3D0727F8A61041A8E8BF86599FE5597CE19DE451E59AED07D60967A5E25"; - byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Long duration = HttpMethed.getBlockByNumForResponse(httpnode, 4942435, times); - /* Long duration = HttpMethed.getAccountForResponse(httpnode, fromAddress, times);*/ - /* Long duration = HttpMethed.getTransactionByIdForResponse(httpnode, - "a265fc457551fd9cfa55daec0550268b1a2da54018cc700f1559454836de411c", times);*/ - logger.info("Total duration : " + duration); - logger.info("Average duration: " + duration / times); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java deleted file mode 100644 index 41040cc8e97..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestClearAbiContract001.java +++ /dev/null @@ -1,185 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import static org.hamcrest.core.StringContains.containsString; - -import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestClearAbiContract001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId; - private static String contractName; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String contractAddress; - String abi; - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - /** - * constructor. - */ - @Test(enabled = true, description = "Deploy smart contract by http") - public void test1DeployContract() { - PublicMethed.printAddress(assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, assetOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - logger.info("abi:" + abi); - logger.info("code:" + code); - - String txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, 0L, 0, 0L, assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddress = responseContent.getString("contract_address"); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get contract by http") - public void test2GetContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertThat(responseContent.getString("abi"), containsString("testView")); - - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger contract by http") - public void test3TriggerConstantContract() { - - HttpResponse httpResponse = HttpMethed - .triggerConstantContract(httpnode, assetOwnerAddress, contractAddress, "testView()", ""); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}"); - Assert.assertEquals(responseContent.getString("constant_result"), - "[\"0000000000000000000000000000000000000000000000000000000000000001\"]"); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode,httpSoliditynode); - httpResponse = HttpMethed.triggerConstantContractFromSolidity(httpSoliditynode, - assetOwnerAddress, contractAddress, "testView()", ""); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}"); - Assert.assertEquals(responseContent.getString("constant_result"), - "[\"0000000000000000000000000000000000000000000000000000000000000001\"]"); - - httpResponse = HttpMethed.triggerConstantContractFromPbft(httpPbftnode, assetOwnerAddress, - contractAddress, "testView()", ""); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}"); - Assert.assertEquals(responseContent.getString("constant_result"), - "[\"0000000000000000000000000000000000000000000000000000000000000001\"]"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger contract by http") - public void test4ClearAbiContract() { - - HttpResponse httpResponse = HttpMethed - .clearABiGetTxid(httpnode, assetOwnerAddress, contractAddress, assetOwnerKey); - - responseContent = HttpMethed.parseResponseContent(httpResponse); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("result"), "true"); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get contract by http") - public void test5GetContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("abi"), "{}"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetOwnerAddress, fromAddress, assetOwnerKey); - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestConstantContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestConstantContract001.java deleted file mode 100644 index 811a0b44cc7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestConstantContract001.java +++ /dev/null @@ -1,119 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestConstantContract001 { - - private static String contractName; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String contractAddress; - Long amount = 2048000000L; - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, description = "Deploy constant contract by http") - public void test1DeployConstantContract() { - PublicMethed.printAddress(assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - String filePath = "src/test/resources/soliditycode/constantContract001.sol"; - contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, 0L, 0, 0L, assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddress = responseContent.getString("contract_address"); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get constant contract by http") - public void test2GetConstantContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger constant contract without parameterString by http") - public void test3TriggerConstantContract() { - String param1 = - "000000000000000000000000000000000000000000000000000000000000000" + Integer.toHexString(3); - String param2 = - "00000000000000000000000000000000000000000000000000000000000000" + Integer.toHexString(30); - logger.info(param1); - logger.info(param2); - String param = param1 + param2; - logger.info(ByteArray.toHexString(assetOwnerAddress)); - response = HttpMethed.triggerConstantContract(httpnode, assetOwnerAddress, contractAddress, - "testPure(uint256,uint256)", param, 1000000000L, assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("transaction").isEmpty()); - JSONObject transactionObject = HttpMethed - .parseStringContent(responseContent.getString("transaction")); - Assert.assertTrue(!transactionObject.getString("raw_data").isEmpty()); - Assert.assertTrue(!transactionObject.getString("raw_data_hex").isEmpty()); - Assert.assertTrue(responseContent.getIntValue("energy_used") > 400 - && responseContent.getIntValue("energy_used") < 500); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetOwnerAddress, fromAddress, assetOwnerKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestEasyAccount001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestEasyAccount001.java deleted file mode 100644 index a4d854547fd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestEasyAccount001.java +++ /dev/null @@ -1,281 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Commons; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestEasyAccount001 { - - private static String assetIssueId; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - long beforeEasyBalance = 0L; - long afterEasyBalance = 0L; - long beforeGenerateBalance = 0L; - long afterGenerateBalance = 0L; - long beforeEasyAsset = 0L; - long afterEasyAsset = 0L; - long beforeGenerateAsset = 0L; - long afterGenerateAsset = 0L; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] assetAddress = ecKey1.getAddress(); - String assetKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private long now = System.currentTimeMillis(); - private final long totalSupply = now; - private String userPassword = "ps_" + now; - private String assetName = "httpEasyAsset_" + now; - private String easyAddress = null; - private String generatePriKey = null; - private String generateAddress = null; - private String generateHexAddress = null; - - /** - * constructor. - */ - @Test(enabled = true, description = "Create address by http") - public void test01CreateAddress() { - logger.info(userPassword); - response = HttpMethed.createAddress(httpnode, userPassword); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - easyAddress = responseContent.get("base58checkAddress").toString(); - - //Send trx to easy account - response = HttpMethed - .sendCoin(httpnode, fromAddress, Commons.decodeFromBase58Check(easyAddress), 5000000L, - testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - beforeEasyBalance = HttpMethed.getBalance(httpnode, Commons.decodeFromBase58Check(easyAddress)); - logger.info("beforeEasyBalance: " + beforeEasyBalance); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Generate address by http") - public void test02GenerateAddress() { - response = HttpMethed.generateAddress(httpnode); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - generateAddress = responseContent.get("address").toString(); - generateHexAddress = responseContent.get("hexAddress").toString(); - generatePriKey = responseContent.get("privateKey").toString(); - - //Send trx to easy account - response = HttpMethed - .sendCoin(httpnode, fromAddress, Commons.decodeFromBase58Check(generateAddress), 5000000L, - testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - beforeGenerateBalance = HttpMethed - .getBalance(httpnode, Commons.decodeFromBase58Check(generateAddress)); - logger.info("beforeGenerateBalance: " + beforeGenerateBalance); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Validate address by http") - public void test03ValideteAddress() { - // Base58check format - response = HttpMethed.validateAddress(httpnode, generateAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - // Hex string format - response = HttpMethed.validateAddress(httpnode, generateHexAddress); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Easy transfer by http") - public void test04EasyTransfer() { - response = HttpMethed - .easyTransfer(httpnode, userPassword, Commons.decodeFromBase58Check(generateAddress), - 1000000L); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Send trx to easy account - afterEasyBalance = HttpMethed.getBalance(httpnode, Commons.decodeFromBase58Check(easyAddress)); - logger.info("afterEasyBalance: " + afterEasyBalance); - - afterGenerateBalance = HttpMethed - .getBalance(httpnode, Commons.decodeFromBase58Check(generateAddress)); - logger.info("afterGenerateBalance: " + afterGenerateBalance); - - Assert.assertEquals(beforeEasyBalance - afterEasyBalance, - afterGenerateBalance - beforeGenerateBalance); - beforeEasyBalance = afterEasyBalance; - beforeGenerateBalance = afterGenerateBalance; - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Easy transfer by privateKey by http") - public void test05EasyTransferByPrivateKey() { - response = HttpMethed - .easyTransferByPrivate(httpnode, generatePriKey, Commons.decodeFromBase58Check(easyAddress), - 1000000L); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Send trx to easy account - afterEasyBalance = HttpMethed.getBalance(httpnode, Commons.decodeFromBase58Check(easyAddress)); - logger.info("beforeEasyBalance: " + beforeEasyBalance); - logger.info("afterEasyBalance: " + afterEasyBalance); - - afterGenerateBalance = HttpMethed - .getBalance(httpnode, Commons.decodeFromBase58Check(generateAddress)); - logger.info("beforeGenerateBalance: " + beforeGenerateBalance); - logger.info("afterGenerateBalance: " + afterGenerateBalance); - - Assert.assertEquals(beforeGenerateBalance - afterGenerateBalance, - afterEasyBalance - beforeEasyBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Create asset issue by http") - public void test06CreateAssetIssue() { - Long amount = 2048000000L; - response = HttpMethed.sendCoin(httpnode, fromAddress, assetAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed - .assetIssue(httpnode, assetAddress, assetName, assetName, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, - description, url, 1000L, 1000L, assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, assetAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - assetIssueId = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId); - Assert.assertTrue(Integer.parseInt(assetIssueId) > 1000000); - - response = HttpMethed - .transferAsset(httpnode, assetAddress, Commons.decodeFromBase58Check(easyAddress), - assetIssueId, 100L, assetKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, Commons.decodeFromBase58Check(easyAddress)); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - beforeEasyAsset = responseContent.getJSONArray("assetV2").getJSONObject(0) - .getLongValue("value"); - logger.info("beforeEasyAsset:" + beforeEasyAsset); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Easy transfer asset by http") - public void test07EasyTransferAsset() { - response = HttpMethed - .easyTransferAsset(httpnode, userPassword, Commons.decodeFromBase58Check(generateAddress), - 10L, assetIssueId); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, Commons.decodeFromBase58Check(easyAddress)); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - afterEasyAsset = responseContent.getJSONArray("assetV2").getJSONObject(0).getLongValue("value"); - logger.info("afterEasyAsset:" + afterEasyAsset); - - response = HttpMethed.getAccount(httpnode, Commons.decodeFromBase58Check(generateAddress)); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - beforeGenerateAsset = responseContent.getJSONArray("assetV2").getJSONObject(0) - .getLongValue("value"); - logger.info("beforeGenerateAsset:" + beforeGenerateAsset); - Assert.assertEquals(beforeEasyAsset - afterEasyAsset, beforeGenerateAsset); - beforeEasyAsset = afterEasyAsset; - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Easy transfer asset by private key by http") - public void test08EasyTransferAssetByPrivateKey() { - response = HttpMethed.easyTransferAssetByPrivate(httpnode, generatePriKey, - Commons.decodeFromBase58Check(easyAddress), 5L, assetIssueId); - logger.info("code is " + response.getStatusLine().getStatusCode()); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, Commons.decodeFromBase58Check(easyAddress)); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - afterEasyAsset = responseContent.getJSONArray("assetV2").getJSONObject(0).getLongValue("value"); - logger.info("beforeEasyAsset:" + beforeEasyAsset); - logger.info("afterEasyAsset:" + afterEasyAsset); - - response = HttpMethed.getAccount(httpnode, Commons.decodeFromBase58Check(generateAddress)); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - afterGenerateAsset = responseContent.getJSONArray("assetV2").getJSONObject(0) - .getLongValue("value"); - logger.info("afterGenerateAsset:" + afterGenerateAsset); - Assert.assertEquals(beforeGenerateAsset - afterGenerateAsset, afterEasyAsset - beforeEasyAsset); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, Commons.decodeFromBase58Check(generateAddress), fromAddress, - generatePriKey); - HttpMethed.freedResource(httpnode, assetAddress, fromAddress, assetKey); - HttpMethed.disConnect(); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java deleted file mode 100644 index 7d38b0540c6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestExchange001.java +++ /dev/null @@ -1,314 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestExchange001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId1; - private static String assetIssueId2; - private static Integer exchangeId; - private static Long beforeInjectBalance; - private static Long afterInjectBalance; - private static Long beforeWithdrawBalance; - private static Long afterWithdrawBalance; - private static Long beforeTransactionBalance; - private static Long afterTransactionBalance; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchangeOwnerAddress = ecKey1.getAddress(); - String exchangeOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset2Address = ecKey2.getAddress(); - String asset2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "Create asset issue by http") - public void test01CreateExchange() { - response = HttpMethed - .sendCoin(httpnode, fromAddress, exchangeOwnerAddress, 2048000000L, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, asset2Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, exchangeOwnerAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.assetIssue(httpnode, asset2Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, exchangeOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - - response = HttpMethed.getAccount(httpnode, asset2Address); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - response = HttpMethed - .transferAsset(httpnode, asset2Address, exchangeOwnerAddress, assetIssueId2, 10000000000L, - asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create exchange. - response = HttpMethed - .exchangeCreate(httpnode, exchangeOwnerAddress, assetIssueId1, 1000000L, assetIssueId2, - 1000000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List exchanges by http") - public void test02ListExchange() { - response = HttpMethed.listExchanges(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List exchanges from solidity by http") - public void test03ListExchangeFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listExchangesFromSolidity(httpSoliditynode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "List exchanges from PBFT by http") - public void test04ListExchangeFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.listExchangesFromPbft(httpPbftNode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "GetExchangeById by http") - public void test05GetExchangeById() { - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); - Assert.assertEquals(responseContent.getString("creator_address"), - ByteArray.toHexString(exchangeOwnerAddress)); - beforeInjectBalance = responseContent.getLong("first_token_balance"); - - logger.info("beforeInjectBalance" + beforeInjectBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetExchangeById from solidity by http") - public void test06GetExchangeByIdFromSolidity() { - response = HttpMethed.getExchangeByIdFromSolidity(httpSoliditynode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); - Assert.assertEquals(responseContent.getString("creator_address"), - ByteArray.toHexString(exchangeOwnerAddress)); - beforeInjectBalance = responseContent.getLong("first_token_balance"); - - logger.info("beforeInjectBalance" + beforeInjectBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetExchangeById from Pbft by http") - public void test07GetExchangeByIdFromPbft() { - response = HttpMethed.getExchangeByIdFromPbft(httpPbftNode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("exchange_id").equals(exchangeId)); - Assert.assertEquals(responseContent.getString("creator_address"), - ByteArray.toHexString(exchangeOwnerAddress)); - beforeInjectBalance = responseContent.getLong("first_token_balance"); - - logger.info("beforeInjectBalance" + beforeInjectBalance); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Inject exchange by http") - public void test08InjectExchange() { - //Inject exchange. - response = HttpMethed - .exchangeInject(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, 300L, - exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - afterInjectBalance = responseContent.getLong("first_token_balance"); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - logger.info("afterInjectBalance" + afterInjectBalance); - Assert.assertTrue(afterInjectBalance - beforeInjectBalance == 300L); - beforeWithdrawBalance = afterInjectBalance; - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Withdraw exchange by http") - public void test09WithdrawExchange() { - //Withdraw exchange. - response = HttpMethed - .exchangeWithdraw(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, 170L, - exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - afterWithdrawBalance = responseContent.getLong("first_token_balance"); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(beforeWithdrawBalance - afterWithdrawBalance == 170L); - beforeTransactionBalance = afterWithdrawBalance; - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Transaction exchange by http") - public void test10TransactionExchange() { - //Transaction exchange. - response = HttpMethed - .exchangeTransaction(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, 100L, 1L, - exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - afterTransactionBalance = responseContent.getLong("first_token_balance"); - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(afterTransactionBalance - beforeTransactionBalance >= 1); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get asset issue list by name by http") - public void test11GetAssetIssueListByName() { - response = HttpMethed.getAssetIssueListByName(httpnode, name); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString()); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get asset issue list by name from solidity and pbft by http") - public void test12GetAssetIssueListByNameFromSolidityAndPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getAssetIssueListByNameFromSolidity(httpSoliditynode, name); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString()); - Assert.assertTrue(jsonArray.size() >= 2); - - response = HttpMethed.getAssetIssueListByNameFromPbft(httpPbftNode, name); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - jsonArray = JSONArray.parseArray(responseContent.get("assetIssue").toString()); - Assert.assertTrue(jsonArray.size() >= 2); - } - - /** - * * constructor. * - */ - @Test(enabled = true, description = "Get paginated exchange list by http") - public void test13GetPaginatedExchangeList() { - - response = HttpMethed.getPaginatedExchangeList(httpnode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() == 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, asset2Address, fromAddress, asset2Key); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java deleted file mode 100644 index 4ce34f4cefe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestGetAccountBalance001.java +++ /dev/null @@ -1,218 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestGetAccountBalance001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] randomAddress = ecKey3.getAddress(); - Long amount = 2048000000L; - String txid; - Integer sendcoinBlockNumber; - String sendcoinBlockHash; - Integer deployContractBlockNumber; - String deployContractBlockHash; - Long fee; - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Deploy smart contract by http") - public void test01DeployContractForTest() { - HttpMethed.waitToProduceOneBlock(httpnode); - PublicMethed.printAddress(assetOwnerKey); - txid = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, "", testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - txid = HttpMethed.sendCoin(httpnode, assetOwnerAddress, randomAddress, - amount / 1000000L, "", assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sendcoinBlockNumber = responseContent.getInteger("blockNumber"); - Assert.assertTrue(sendcoinBlockNumber > 0); - - response = HttpMethed.getBlockByNum(httpnode, sendcoinBlockNumber); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sendcoinBlockHash = responseContent.getString("blockID"); - - String contractName = "transferTokenContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractTrcToken001_transferTokenContract"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractTrcToken001_transferTokenContract"); - txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, 0L, 0, 0L, assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - fee = responseContent.getLong("fee"); - deployContractBlockNumber = responseContent.getInteger("blockNumber"); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - - response = HttpMethed.getBlockByNum(httpnode, deployContractBlockNumber); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - deployContractBlockHash = responseContent.getString("blockID"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get account balance by http") - public void test01GetAccountBalance() { - response = HttpMethed.getAccountBalance(httpnode, assetOwnerAddress, - sendcoinBlockNumber, sendcoinBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - final Long beforeBalance = responseContent.getLong("balance"); - - response = HttpMethed.getAccountBalance(httpnode, assetOwnerAddress, - deployContractBlockNumber, deployContractBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - Long afterBalance = responseContent.getLong("balance"); - - Assert.assertTrue(beforeBalance - afterBalance == fee); - - - response = HttpMethed.getAccountBalance(httpnode, assetOwnerAddress, - deployContractBlockNumber, deployContractBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - - - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get block balance by http") - public void test02GetBlockBalance() { - response = HttpMethed.getBlockBalance(httpnode, - sendcoinBlockNumber, sendcoinBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - Assert.assertEquals(sendcoinBlockNumber, responseContent.getJSONObject("block_identifier") - .getInteger("number")); - JSONObject transactionObject = responseContent.getJSONArray("transaction_balance_trace") - .getJSONObject(0); - Assert.assertEquals(transactionObject.getString("type"), "TransferContract"); - Assert.assertTrue(Math.abs(transactionObject.getJSONArray("operation") - .getJSONObject(0).getLong("amount")) == 100000L); - Assert.assertTrue(Math.abs(transactionObject.getJSONArray("operation") - .getJSONObject(1).getLong("amount")) == amount / 1000000L); - Assert.assertTrue(Math.abs(transactionObject.getJSONArray("operation") - .getJSONObject(2).getLong("amount")) == amount / 1000000L); - - response = HttpMethed.getBlockBalance(httpnode, - deployContractBlockNumber, deployContractBlockHash); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() >= 2); - - transactionObject = responseContent.getJSONArray("transaction_balance_trace").getJSONObject(0); - Assert.assertEquals(transactionObject.getString("transaction_identifier"), txid); - Assert.assertEquals(transactionObject.getString("type"), "CreateSmartContract"); - Assert.assertTrue(transactionObject.getJSONArray("operation") - .getJSONObject(0).getLong("amount") == -fee); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get burn trx by http") - public void test03GetBurnTrx() { - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, "", testKey002); - HttpMethed.waitToProduceOneBlock(httpnode); - final Long beforeBurnTrxAmount = HttpMethed.getBurnTrx(httpnode); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey3.getAddress(); - - HttpMethed.sendCoin(httpnode, assetOwnerAddress, receiverAddress, amount - 103000L, - "", assetOwnerKey); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Long afterBurnTrxAmount = HttpMethed.getBurnTrx(httpnode); - logger.info(afterBurnTrxAmount + " : " + beforeBurnTrxAmount); - Assert.assertTrue(afterBurnTrxAmount - beforeBurnTrxAmount == 100000L); - - Assert.assertEquals(afterBurnTrxAmount, HttpMethed.getBurnTrxFromSolidity(httpSolidityNode)); - Assert.assertEquals(afterBurnTrxAmount, HttpMethed.getBurnTrxFromPbft(httpPbftNode)); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get receipt root by http") - public void test04GetReceiptRootByHttp() { - response = HttpMethed.getBlockByNum(httpnode,sendcoinBlockNumber); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String receiptsRoot = responseContent.getJSONObject("block_header").getJSONObject("raw_data") - .getString("receiptsRoot"); - Assert.assertNotEquals(receiptsRoot, - "0000000000000000000000000000000000000000000000000000000000000000"); - Assert.assertFalse(receiptsRoot.isEmpty()); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java deleted file mode 100644 index 8dfe0701288..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket001.java +++ /dev/null @@ -1,533 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestMarket001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId1; - private static String assetIssueId2; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sellAddress = ecKey1.getAddress(); - String sellKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - String txId1; - String txId2; - String orderId; - String orderId1; - String orderId2; - - Long amount = 2048000000L; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private JSONObject getMarketOrderByIdContent; - private JSONObject getMarketOrderByIdContentFromSolidity; - private JSONObject getMarketOrderByIdContentFromPbft; - private JSONObject getMarketOrderByAccountContent; - private JSONObject getMarketOrderByAccountContentFromSolidity; - private JSONObject getMarketOrderByAccountContentFromPbft; - private JSONObject getMarketPairListContent; - private JSONObject getMarketPairListContentFromSolidity; - private JSONObject getMarketPairListContentFromPbft; - private JSONObject getMarketOrderListByPairContent; - private JSONObject getMarketOrderListByPairContentFromSolidity; - private JSONObject getMarketOrderListByPairContentFromPbft; - private JSONObject getMarketPriceByPairContent; - private JSONObject getMarketPriceByPairContentFromSolidity; - private JSONObject getMarketPriceByPairContentFromPbft; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketSellAsset trx with trc10 by http") - public void test01MarketSellAsset() { - PublicMethed.printAddress(sellKey); - PublicMethed.printAddress(dev002Key); - - response = HttpMethed.sendCoin(httpnode, fromAddress, sellAddress, amount, testKey002); - response = HttpMethed.sendCoin(httpnode, fromAddress, dev002Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, sellAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, sellKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId1); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - - response = HttpMethed.assetIssue(httpnode, dev002Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, dev002Address); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId2); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - // transferAsset - response = HttpMethed - .transferAsset(httpnode, dev002Address, sellAddress, assetIssueId2, 10000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - // marketsellasset trc10-trc10 - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, assetIssueId2, 500L, - sellKey, "true"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId = responseContent.getString("orderId"); - logger.info("orderId:" + orderId); - - // marketsellasset trx-trc10 - txId1 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, "_", 1000L, assetIssueId1, 20L, sellKey, - "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId1); - response = HttpMethed.getTransactionInfoById(httpnode, txId1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId1 = responseContent.getString("orderId"); - logger.info("orderId1:" + orderId1); - - // marketsellasset trc10-trx - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, "_", 500L, sellKey, - "true"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject orderDetails = responseContent.getJSONArray("orderDetails").getJSONObject(0); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - Assert.assertTrue(500L == orderDetails.getLong("fillBuyQuantity")); - Assert.assertTrue(10L == orderDetails.getLong("fillSellQuantity")); - Assert - .assertEquals(responseContent.getString("orderId"), orderDetails.getString("takerOrderId")); - Assert.assertEquals(orderId1, orderDetails.getString("makerOrderId")); - orderId2 = responseContent.getString("orderId"); - logger.info("orderId2:" + orderId2); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http") - public void test02GetMarketOrderById() { - // getMarketOrderById orderId1 - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderById(httpnode, orderId1, "true"); - getMarketOrderByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContent); - Assert.assertEquals(Base58.encode58Check(sellAddress), - getMarketOrderByIdContent.getString("owner_address")); - Assert.assertEquals("_", getMarketOrderByIdContent.getString("sell_token_id")); - Assert.assertTrue(1000L == getMarketOrderByIdContent.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, getMarketOrderByIdContent.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContent.getLong("buy_token_quantity")); - Assert.assertTrue(500L == getMarketOrderByIdContent.getLong("sell_token_quantity_remain")); - - // getMarketOrderById orderId2 - HttpResponse response2 = HttpMethed.getMarketOrderById(httpnode, orderId2, "false"); - JSONObject getMarketOrderByIdContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(getMarketOrderByIdContent2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from solidity") - public void test03GetMarketOrderByIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed.getMarketOrderByIdFromSolidity(httpSolidityNode, orderId1, "true"); - getMarketOrderByIdContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromSolidity); - Assert.assertEquals(Base58.encode58Check(sellAddress), - getMarketOrderByIdContentFromSolidity.getString("owner_address")); - Assert.assertEquals("_", getMarketOrderByIdContentFromSolidity.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, - getMarketOrderByIdContentFromSolidity.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromSolidity.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from pbft") - public void test04GetMarketOrderByIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed.getMarketOrderByIdFromPbft(httpPbftNode, orderId1, "true"); - getMarketOrderByIdContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromPbft); - Assert.assertEquals(Base58.encode58Check(sellAddress), - getMarketOrderByIdContentFromPbft.getString("owner_address")); - Assert.assertEquals("_", getMarketOrderByIdContentFromPbft.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, - getMarketOrderByIdContentFromPbft.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromPbft.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http") - public void test05GetMarketOrderByAccount() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "true"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContent.getJSONArray("orders").getJSONObject(1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from solidity") - public void test06GetMarketOrderByAccountFromSolidity() { - response = HttpMethed - .getMarketOrderByAccountFromSolidity(httpSolidityNode, sellAddress, "true"); - getMarketOrderByAccountContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromSolidity.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from pbft") - public void test07GetMarketOrderByAccountFromPbft() { - response = HttpMethed.getMarketOrderByAccountFromPbft(httpPbftNode, sellAddress, "true"); - getMarketOrderByAccountContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromPbft.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http") - public void test08GetMarketPairList() { - response = HttpMethed.getMarketPairList(httpnode, "true"); - getMarketPairListContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContent.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("_", - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from solidity") - public void test09GetMarketPairListFromSolidity() { - response = HttpMethed.getMarketPairListFromSolidity(httpSolidityNode, "true"); - getMarketPairListContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromSolidity.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("_", - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from pbft") - public void test10GetMarketPairListFromPbft() { - response = HttpMethed.getMarketPairListFromPbft(httpPbftNode, "true"); - getMarketPairListContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromPbft.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("_", - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http") - public void test11GetMarketOrderListByPair() { - response = HttpMethed.getMarketOrderListByPair(httpnode, "_", assetIssueId1, "true"); - getMarketOrderListByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContent.getJSONArray("orders") - .getJSONObject(getMarketOrderListByPairContent.getJSONArray("orders").size() - 1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContent.getLong("sell_token_quantity"), - getMarketOrderListByPairContent.getLong("sell_token_quantity_remain")); - - Assert.assertTrue(getMarketOrderListByPairContent.getJSONArray("orders").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from solidity") - public void test12GetMarketOrderListByPairFromSolidity() { - response = HttpMethed - .getMarketOrderListByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "true"); - getMarketOrderListByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromSolidity.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() - 1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from pbft") - public void test13GetMarketOrderListByPairFromPbft() { - response = HttpMethed - .getMarketOrderListByPairFromPbft(httpPbftNode, "_", assetIssueId1, "true"); - getMarketOrderListByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromPbft.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() - 1); - Assert.assertEquals(Base58.encode58Check(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("_", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(assetIssueId1, orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http") - public void test14GetMarketPriceByPair() { - response = HttpMethed.getMarketPriceByPair(httpnode, "_", assetIssueId1, "true"); - getMarketPriceByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("_", getMarketPriceByPairContent.getString("sell_token_id")); - Assert.assertEquals(assetIssueId1, getMarketPriceByPairContent.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContent.getJSONArray("prices").getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContent.getJSONArray("prices").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from solidity") - public void test15GetMarketPriceByPairFromSolidity() { - response = HttpMethed - .getMarketPriceByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "true"); - getMarketPriceByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("_", getMarketPriceByPairContentFromSolidity.getString("sell_token_id")); - Assert - .assertEquals(assetIssueId1, - getMarketPriceByPairContentFromSolidity.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromSolidity.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromSolidity.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from pbft") - public void test16GetMarketPriceByPairFromPbft() { - response = HttpMethed - .getMarketPriceByPairFromPbft(httpPbftNode, "_", assetIssueId1, "true"); - getMarketPriceByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("_", getMarketPriceByPairContentFromPbft.getString("sell_token_id")); - Assert - .assertEquals(assetIssueId1, - getMarketPriceByPairContentFromPbft.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromPbft.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromPbft.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketCancelOrder trx with trc10 by http") - public void test17MarketCancelOrder() { - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "true"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(2, getMarketOrderByAccountContent.getJSONArray("orders").size()); - - // MarketCancelOrder - String txId = HttpMethed.marketCancelOrder(httpnode, sellAddress, orderId1, sellKey, "true"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId); - response = HttpMethed.getTransactionInfoById(httpnode, txId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "true"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(1, getMarketOrderByAccountContent.getJSONArray("orders").size()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, sellAddress, fromAddress, sellKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java deleted file mode 100644 index 91217ff06ea..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMarket002.java +++ /dev/null @@ -1,534 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestMarket002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId1; - private static String assetIssueId2; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sellAddress = ecKey1.getAddress(); - String sellKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - String txId1; - String txId2; - String orderId; - String orderId1; - String orderId2; - - Long amount = 2048000000L; - - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private JSONObject getMarketOrderByIdContent; - private JSONObject getMarketOrderByIdContentFromSolidity; - private JSONObject getMarketOrderByIdContentFromPbft; - private JSONObject getMarketOrderByAccountContent; - private JSONObject getMarketOrderByAccountContentFromSolidity; - private JSONObject getMarketOrderByAccountContentFromPbft; - private JSONObject getMarketPairListContent; - private JSONObject getMarketPairListContentFromSolidity; - private JSONObject getMarketPairListContentFromPbft; - private JSONObject getMarketOrderListByPairContent; - private JSONObject getMarketOrderListByPairContentFromSolidity; - private JSONObject getMarketOrderListByPairContentFromPbft; - private JSONObject getMarketPriceByPairContent; - private JSONObject getMarketPriceByPairContentFromSolidity; - private JSONObject getMarketPriceByPairContentFromPbft; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketSellAsset trx with trc10 by http") - public void test01MarketSellAsset() { - PublicMethed.printAddress(sellKey); - PublicMethed.printAddress(dev002Key); - - response = HttpMethed.sendCoin(httpnode, fromAddress, sellAddress, amount, testKey002); - response = HttpMethed.sendCoin(httpnode, fromAddress, dev002Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, sellAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, sellKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId1); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - - response = HttpMethed.assetIssue(httpnode, dev002Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, dev002Address); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - logger.info(assetIssueId2); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - // transferAsset - response = HttpMethed - .transferAsset(httpnode, dev002Address, sellAddress, assetIssueId2, 10000L, dev002Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, sellAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - // marketsellasset trc10-trc10 - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, assetIssueId2, 500L, - sellKey, "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId = responseContent.getString("orderId"); - logger.info("orderId:" + orderId); - - // marketsellasset trx-trc10 - txId1 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, "_", 1000L, assetIssueId1, 20L, sellKey, - "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId1); - response = HttpMethed.getTransactionInfoById(httpnode, txId1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - orderId1 = responseContent.getString("orderId"); - logger.info("orderId1:" + orderId1); - - // marketsellasset trc10-trx - txId2 = HttpMethed - .marketSellAssetGetTxId(httpnode, sellAddress, assetIssueId1, 10L, "_", 500L, sellKey, - "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId2); - response = HttpMethed.getTransactionInfoById(httpnode, txId2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject orderDetails = responseContent.getJSONArray("orderDetails").getJSONObject(0); - Assert.assertTrue(!responseContent.getString("orderId").isEmpty()); - Assert.assertTrue(500L == orderDetails.getLong("fillBuyQuantity")); - Assert.assertTrue(10L == orderDetails.getLong("fillSellQuantity")); - Assert - .assertEquals(responseContent.getString("orderId"), orderDetails.getString("takerOrderId")); - Assert.assertEquals(orderId1, orderDetails.getString("makerOrderId")); - orderId2 = responseContent.getString("orderId"); - logger.info("orderId2:" + orderId2); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http") - public void test02GetMarketOrderById() { - // getMarketOrderById orderId1 - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderById(httpnode, orderId1, "false"); - getMarketOrderByIdContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContent); - Assert.assertEquals(ByteArray.toHexString(sellAddress), - getMarketOrderByIdContent.getString("owner_address")); - Assert.assertEquals("5f", getMarketOrderByIdContent.getString("sell_token_id")); - Assert.assertTrue(1000L == getMarketOrderByIdContent.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketOrderByIdContent.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContent.getLong("buy_token_quantity")); - Assert.assertTrue(500L == getMarketOrderByIdContent.getLong("sell_token_quantity_remain")); - - // getMarketOrderById orderId2 - HttpResponse response2 = HttpMethed.getMarketOrderById(httpnode, orderId2, "false"); - JSONObject getMarketOrderByIdContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(getMarketOrderByIdContent2); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from solidity") - public void test03GetMarketOrderByIdFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed.getMarketOrderByIdFromSolidity(httpSolidityNode, orderId1, "false"); - getMarketOrderByIdContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromSolidity); - Assert.assertEquals(ByteArray.toHexString(sellAddress), - getMarketOrderByIdContentFromSolidity.getString("owner_address")); - Assert.assertEquals("5f", getMarketOrderByIdContentFromSolidity.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketOrderByIdContentFromSolidity.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromSolidity.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromSolidity.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderById by http from pbft") - public void test04GetMarketOrderByIdFromPbft() { - HttpMethed.waitToProduceOneBlockFromPbft(httpnode, httpPbftNode); - response = HttpMethed.getMarketOrderByIdFromPbft(httpPbftNode, orderId1, "false"); - getMarketOrderByIdContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByIdContentFromPbft); - Assert.assertEquals(ByteArray.toHexString(sellAddress), - getMarketOrderByIdContentFromPbft.getString("owner_address")); - Assert.assertEquals("5f", getMarketOrderByIdContentFromPbft.getString("sell_token_id")); - Assert - .assertTrue(1000L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketOrderByIdContentFromPbft.getString("buy_token_id")); - Assert.assertTrue(20L == getMarketOrderByIdContentFromPbft.getLong("buy_token_quantity")); - Assert.assertTrue( - 500L == getMarketOrderByIdContentFromPbft.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByIdContent, getMarketOrderByIdContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http") - public void test05GetMarketOrderByAccount() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "false"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContent.getJSONArray("orders").getJSONObject(1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from solidity") - public void test06GetMarketOrderByAccountFromSolidity() { - response = HttpMethed - .getMarketOrderByAccountFromSolidity(httpSolidityNode, sellAddress, "false"); - getMarketOrderByAccountContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromSolidity.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderByAccount by http from pbft") - public void test07GetMarketOrderByAccountFromPbft() { - response = HttpMethed.getMarketOrderByAccountFromPbft(httpPbftNode, sellAddress, "false"); - getMarketOrderByAccountContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderByAccountContentFromPbft.getJSONArray("orders") - .getJSONObject(1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertTrue(500L == orders.getLong("sell_token_quantity_remain")); - Assert.assertEquals(getMarketOrderByAccountContent, getMarketOrderByAccountContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http") - public void test08GetMarketPairList() { - response = HttpMethed.getMarketPairList(httpnode, "false"); - getMarketPairListContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContent.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("5f", - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPairListContent.getJSONArray("orderPair").getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from solidity") - public void test09GetMarketPairListFromSolidity() { - response = HttpMethed.getMarketPairListFromSolidity(httpSolidityNode, "false"); - getMarketPairListContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromSolidity.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("5f", - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPairListContentFromSolidity.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPairList by http from pbft") - public void test10GetMarketPairListFromPbft() { - response = HttpMethed.getMarketPairListFromPbft(httpPbftNode, "false"); - getMarketPairListContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPairListContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - int orderPairSize = getMarketPairListContentFromPbft.getJSONArray("orderPair").size(); - Assert.assertTrue(orderPairSize > 0); - Assert.assertEquals("5f", - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPairListContentFromPbft.getJSONArray("orderPair") - .getJSONObject(orderPairSize - 1) - .getString("buy_token_id")); - Assert.assertEquals(getMarketPairListContent, getMarketPairListContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http") - public void test11GetMarketOrderListByPair() { - response = HttpMethed.getMarketOrderListByPair(httpnode, "_", assetIssueId1, "false"); - getMarketOrderListByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContent.getJSONArray("orders") - .getJSONObject(getMarketOrderListByPairContent.getJSONArray("orders").size() - 1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContent.getLong("sell_token_quantity"), - getMarketOrderListByPairContent.getLong("sell_token_quantity_remain")); - - Assert.assertTrue(getMarketOrderListByPairContent.getJSONArray("orders").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from solidity") - public void test12GetMarketOrderListByPairFromSolidity() { - response = HttpMethed - .getMarketOrderListByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "false"); - getMarketOrderListByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromSolidity.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() - 1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromSolidity.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromSolidity.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromSolidity); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketOrderListByPair by http from pbft") - public void test13GetMarketOrderListByPairFromPbft() { - response = HttpMethed - .getMarketOrderListByPairFromPbft(httpPbftNode, "_", assetIssueId1, "false"); - getMarketOrderListByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderListByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - JSONObject orders = getMarketOrderListByPairContentFromPbft.getJSONArray("orders") - .getJSONObject( - getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() - 1); - Assert.assertEquals(ByteArray.toHexString(sellAddress), orders.getString("owner_address")); - Assert.assertEquals("5f", orders.getString("sell_token_id")); - Assert.assertTrue(1000L == orders.getLong("sell_token_quantity")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), orders.getString("buy_token_id")); - Assert.assertTrue(20L == orders.getLong("buy_token_quantity")); - Assert.assertEquals(getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity"), - getMarketOrderListByPairContentFromPbft.getLong("sell_token_quantity_remain")); - - Assert - .assertTrue(getMarketOrderListByPairContentFromPbft.getJSONArray("orders").size() > 0); - Assert - .assertEquals(getMarketOrderListByPairContent, getMarketOrderListByPairContentFromPbft); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http") - public void test14GetMarketPriceByPair() { - response = HttpMethed.getMarketPriceByPair(httpnode, "_", assetIssueId1, "false"); - getMarketPriceByPairContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("5f", getMarketPriceByPairContent.getString("sell_token_id")); - Assert.assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPriceByPairContent.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContent.getJSONArray("prices").getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContent.getJSONArray("prices").size() > 0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from solidity") - public void test15GetMarketPriceByPairFromSolidity() { - response = HttpMethed - .getMarketPriceByPairFromSolidity(httpSolidityNode, "_", assetIssueId1, "false"); - getMarketPriceByPairContentFromSolidity = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromSolidity); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("5f", getMarketPriceByPairContentFromSolidity.getString("sell_token_id")); - Assert - .assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPriceByPairContentFromSolidity.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromSolidity.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromSolidity.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetMarketPriceByPair from by http from pbft") - public void test16GetMarketPriceByPairFromPbft() { - response = HttpMethed - .getMarketPriceByPairFromPbft(httpPbftNode, "_", assetIssueId1, "false"); - getMarketPriceByPairContentFromPbft = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketPriceByPairContentFromPbft); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals("5f", getMarketPriceByPairContentFromPbft.getString("sell_token_id")); - Assert - .assertEquals(HttpMethed.str2hex(assetIssueId1), - getMarketPriceByPairContentFromPbft.getString("buy_token_id")); - JSONObject prices = getMarketPriceByPairContentFromPbft.getJSONArray("prices") - .getJSONObject(0); - Assert.assertEquals("50", prices.getString("sell_token_quantity")); - Assert.assertEquals("1", prices.getString("buy_token_quantity")); - Assert.assertTrue(getMarketPriceByPairContentFromPbft.getJSONArray("prices").size() > 0); - Assert.assertEquals(getMarketPriceByPairContent, getMarketPriceByPairContentFromPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "MarketCancelOrder trx with trc10 by http") - public void test17MarketCancelOrder() { - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "false"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(2, getMarketOrderByAccountContent.getJSONArray("orders").size()); - - // MarketCancelOrder - String txId = HttpMethed.marketCancelOrder(httpnode, sellAddress, orderId1, sellKey, "false"); - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txId); - response = HttpMethed.getTransactionInfoById(httpnode, txId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - response = HttpMethed.getMarketOrderByAccount(httpnode, sellAddress, "false"); - getMarketOrderByAccountContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(getMarketOrderByAccountContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - Assert.assertEquals(1, getMarketOrderByAccountContent.getJSONArray("orders").size()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, sellAddress, fromAddress, sellKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMortgageMechanism01.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMortgageMechanism01.java deleted file mode 100644 index d41e49ead51..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMortgageMechanism01.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.math.BigInteger; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestMortgageMechanism01 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - private final String witnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessAddress2 = PublicMethed.getFinalAddress(witnessKey2); - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBrokerage by http") - public void test01GetBrokerage() { - response = HttpMethed.getBrokerage(httpnode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - response = HttpMethed.getBrokerageOnVisible(httpnode, witnessAddress2, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - response = HttpMethed.getBrokerageOnVisible(httpnode, fromAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - } - - @Test(enabled = true, description = "GetBrokerage from solidity by http") - public void test02GetBrokerageFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBrokerageFromSolidity(httpSoliditynode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed - .getBrokerageFromSolidityOnVisible(httpSoliditynode, witnessAddress2, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBrokerageFromSolidityOnVisible(httpSoliditynode, fromAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBrokerage from PBFT by http") - public void test03GetBrokerageFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getBrokerageFromPbft(httpPbftNode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals("20", responseContent.getString("brokerage")); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "UpdateBrokerage by http") - public void test04UpdateBrokerage() { - response = HttpMethed.sendCoin(httpnode, fromAddress, witnessAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage - response = HttpMethed.updateBrokerage(httpnode, witnessAddress, 11L, witnessKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.sendCoin(httpnode, fromAddress, witnessAddress2, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage onvisible true - response = HttpMethed - .updateBrokerageOnVisible(httpnode, witnessAddress2, 24L, witnessKey2, "true"); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage onvisible false - response = HttpMethed - .updateBrokerageOnVisible(httpnode, witnessAddress, 88L, witnessKey, "false"); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - //update brokerage onvisible false for notwitness - response = HttpMethed.sendCoin(httpnode, fromAddress, dev001Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.updateBrokerageOnVisible(httpnode, dev001Address, 78L, dev001Key, "true"); - Assert.assertFalse(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetReward by http") - public void test05GetReward() { - response = HttpMethed.getReward(httpnode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardOnVisible(httpnode, witnessAddress2, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardOnVisible(httpnode, witnessAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetReward from solidity by http") - public void test06GetRewardFromSolidity() { - response = HttpMethed.getRewardFromSolidity(httpSoliditynode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardFromSolidityOnVisible(httpSoliditynode, witnessAddress, "true"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - - response = HttpMethed.getRewardFromSolidityOnVisible(httpSoliditynode, witnessAddress, "false"); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) == 1); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetReward from PBFT by http") - public void test07GetRewardFromPbft() { - response = HttpMethed.getRewardFromPbft(httpPbftNode, witnessAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue( - (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0")) == 0) - || (new BigInteger(responseContent.getString("reward")).compareTo(new BigInteger("0"))) - == 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - //update brokerage - HttpMethed.freedResource(httpnode, witnessAddress, fromAddress, witnessKey); - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMutiSign001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMutiSign001.java deleted file mode 100644 index 09ba3d8c737..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestMutiSign001.java +++ /dev/null @@ -1,224 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class HttpTestMutiSign001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String manager1Key = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] manager1Address = PublicMethed.getFinalAddress(manager1Key); - private final String manager2Key = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] manager2Address = PublicMethed.getFinalAddress(manager2Key); - private final String manager3Key = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] manager3Address = PublicMethed.getFinalAddress(manager3Key); - private final String manager4Key = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] manager4Address = PublicMethed.getFinalAddress(manager4Key); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey1.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] hexTestAddress = ecKey2.getAddress(); - String hexTestKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String[] permissionKeyString; - Long amount = 1000000000L; - JsonArray keys = new JsonArray(); - JsonArray activeKeys = new JsonArray(); - JsonObject manager1Wight = new JsonObject(); - JsonObject manager2Wight = new JsonObject(); - JsonObject manager3Wight = new JsonObject(); - JsonObject manager4Wight = new JsonObject(); - JsonObject ownerObject = new JsonObject(); - JsonObject witnessObject = new JsonObject(); - JsonObject activeObject = new JsonObject(); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Account Permission Up Date by http") - public void test1AccountPermissionUpDate() { - PublicMethed.printAddress(ownerKey); - response = HttpMethed.sendCoin(httpnode, fromAddress, ownerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - manager1Wight.addProperty("address", ByteArray.toHexString(manager1Address)); - manager1Wight.addProperty("weight", 1); - - logger.info(manager1Wight.toString()); - manager2Wight.addProperty("address", ByteArray.toHexString(manager2Address)); - manager2Wight.addProperty("weight", 1); - - logger.info(manager2Wight.toString()); - - keys.add(manager1Wight); - keys.add(manager2Wight); - - ownerObject.addProperty("type", 0); - ownerObject.addProperty("permission_name", "owner"); - ownerObject.addProperty("threshold", 2); - ownerObject.add("keys", keys); - - manager3Wight.addProperty("address", ByteArray.toHexString(manager3Address)); - manager3Wight.addProperty("weight", 1); - - logger.info(manager3Wight.toString()); - manager4Wight.addProperty("address", ByteArray.toHexString(manager4Address)); - manager4Wight.addProperty("weight", 1); - - logger.info(manager4Wight.toString()); - - activeKeys.add(manager3Wight); - activeKeys.add(manager4Wight); - - activeObject.addProperty("type", 2); - activeObject.addProperty("permission_name", "active0"); - activeObject.addProperty("threshold", 2); - activeObject.addProperty("operations", - "7fff1fc0037e0000000000000000000000000000000000000000000000000000"); - activeObject.add("keys", activeKeys); - - response = HttpMethed - .accountPermissionUpdate(httpnode, ownerAddress, ownerObject, witnessObject, activeObject, - ownerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Add transaction sign by http with permission id") - public void test2AddTransactionSign() { - - HttpMethed.waitToProduceOneBlock(httpnode); - permissionKeyString = new String[2]; - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - - String[] permissionKeyActive = new String[2]; - permissionKeyActive[0] = manager3Key; - permissionKeyActive[1] = manager4Key; - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 10L, 0, permissionKeyString); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 10L, 2, permissionKeyString); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - logger.info("start permission id 2"); - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 12L, 2, permissionKeyActive); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 12L, 0, permissionKeyActive); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 11L, 1, permissionKeyActive); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - response = HttpMethed - .sendCoin(httpnode, ownerAddress, fromAddress, 11L, 3, permissionKeyString); - Assert.assertFalse(HttpMethed.verificationResult(response)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Add broadcasthex http interface to " - + "broadcast hex transaction string") - public void test3Broadcasthex() { - PublicMethed.printAddress(hexTestKey); - String transactionHex = PublicMethed - .sendcoinGetTransactionHex(hexTestAddress, 1000L, fromAddress, testKey002, - blockingStubFull); - - //Wrong type of hex - response = HttpMethed.broadcasthex(httpnode, transactionHex); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - String wrongTransactionHex = transactionHex + "wrong"; - response = HttpMethed.broadcasthex(httpnode, wrongTransactionHex); - logger.info("transaction wrong:"); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - //SingleSign for broadcastHex - response = HttpMethed.broadcasthex(httpnode, transactionHex); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - //Mutisign for broadcastHex - String mutiSignTransactionHex = PublicMethedForMutiSign - .sendcoinGetTransactionHex(hexTestAddress, 999L, ownerAddress, ownerKey, blockingStubFull, - permissionKeyString); - response = HttpMethed.broadcasthex(httpnode, mutiSignTransactionHex); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - //Hex is null - response = HttpMethed.broadcasthex(httpnode, ""); - Assert.assertFalse(HttpMethed.verificationResult(response)); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestProposal001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestProposal001.java deleted file mode 100644 index 8fdaa8ddaa3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestProposal001.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.utils.ByteArray; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestProposal001 { - - private static Integer proposalId; - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = - Configuration.getByPath("testng.conf").getString("witness.key1"); - private final byte[] witness1Address = PublicMethed.getFinalAddress(witnessKey001); - private final String witnessKey002 = - Configuration.getByPath("testng.conf").getString("witness.key2"); - private final byte[] witness2Address = PublicMethed.getFinalAddress(witnessKey002); - private String httpnode = - Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list").get(0); - private JSONObject responseContent; - private HttpResponse response; - - /** constructor. */ - @Test(enabled = true, description = "Create proposal by http") - public void test1CreateProposal() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.createProposal(httpnode, witness1Address, 21L, 1L, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - /** * constructor. * */ - @Test(enabled = true, description = "List proposals by http") - public void test2ListProposals() { - response = HttpMethed.listProposals(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("proposals")); - Assert.assertTrue(jsonArray.size() >= 1); - proposalId = jsonArray.size(); - } - - /** constructor. */ - @Test(enabled = true, description = "GetProposalById by http") - public void test3GetExchangeById() { - response = HttpMethed.getProposalById(httpnode, proposalId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getInteger("proposal_id") == proposalId); - Assert.assertEquals( - responseContent.getString("proposer_address"), ByteArray.toHexString(witness1Address)); - } - - /** constructor. */ - @Test(enabled = true, description = "Approval proposal by http") - public void test4ApprovalProposal() { - response = - HttpMethed.approvalProposal(httpnode, witness1Address, proposalId, true, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = - HttpMethed.approvalProposal(httpnode, witness2Address, proposalId, true, witnessKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getProposalById(httpnode, proposalId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("approvals")); - Assert.assertTrue(jsonArray.size() == 2); - } - - /** * constructor. * */ - @Test(enabled = true, description = "Get paginated proposal list by http") - public void test5GetPaginatedProposalList() { - - response = HttpMethed.getPaginatedProposalList(httpnode, 0, 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("proposals")); - Assert.assertTrue(jsonArray.size() == 1); - } - - /** constructor. */ - @Test(enabled = true, description = "Delete proposal by http") - public void test6DeleteProposal() { - response = HttpMethed.deleteProposal(httpnode, witness1Address, proposalId, witnessKey001); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getProposalById(httpnode, proposalId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("state"), "CANCELED"); - } - - /** constructor. */ - @Test(enabled = true, description = "Get chain parameters by http") - public void test7GetChainParameters() { - response = HttpMethed.getChainParameters(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals( - "getMaintenanceTimeInterval", - responseContent.getJSONArray("chainParameter").getJSONObject(0).get("key")); - Assert.assertEquals( - 300000, responseContent.getJSONArray("chainParameter").getJSONObject(0).get("value")); - Assert.assertEquals( - "getCreateAccountFee", - responseContent.getJSONArray("chainParameter").getJSONObject(2).get("key")); - Assert.assertEquals( - 100000, responseContent.getJSONArray("chainParameter").getJSONObject(2).get("value")); - } - /** constructor. */ - - @Test(enabled = true, description = "Get energy price by http") - public void test8GetEnergyPrice() { - response = HttpMethed.getEnergyPric(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String prices = responseContent.getString("prices"); - String expectPrices = "0:100"; - logger.info("prices:" + prices); - Assert.assertEquals(prices, expectPrices); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSendCoin001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSendCoin001.java deleted file mode 100644 index 5741bcc6d65..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSendCoin001.java +++ /dev/null @@ -1,164 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestSendCoin001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Long amount = 1000L; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(1); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @Test(enabled = true, description = "SendCoin by http") - public void test1SendCoin() { - response = HttpMethed.sendCoin(httpnode, fromAddress, receiverAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - Assert.assertEquals(HttpMethed.getBalance(httpnode, receiverAddress), amount); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from solidity by http") - public void test2GetTransactionByIdFromSolidity() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - - response = HttpMethed.getTransactionByIdFromSolidity(httpSoliditynode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String retString = responseContent.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() > 4); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from PBFT by http") - public void test3GetTransactionByIdFromPbft() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - - response = HttpMethed.getTransactionByIdFromPbft(httpPbftNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String retString = responseContent.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() > 4); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by id from solidity by http") - public void test4GetTransactionInfoByIdFromSolidity() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getTransactionInfoByIdFromSolidity(httpSoliditynode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 4); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by id from PBFT by http") - public void test5GetTransactionInfoByIdFromPbft() { - String txid = HttpMethed - .sendCoinGetTxid(httpnode, fromAddress, receiverAddress, amount, testKey002); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSoliditynode); - response = HttpMethed.getTransactionInfoByIdFromPbft(httpPbftNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() > 4); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Get transactions from this from solidity by http") - public void test4GetTransactionsFromThisFromSolidity() { - response = HttpMethed - .getTransactionsFromThisFromSolidity(httpSoliditynode, fromAddress, 0, 100); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject transactionObject = HttpMethed.parseStringContent( - JSONArray.parseArray(responseContent.getString("transaction")).get(0).toString()); - String retString = transactionObject.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() == 1); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get transactions to this from solidity by http") - public void test5GetTransactionsToThisFromSolidity() { - response = HttpMethed - .getTransactionsFromThisFromSolidity(httpSoliditynode, fromAddress, 0, 100); - Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject transactionObject = HttpMethed.parseStringContent( - JSONArray.parseArray(responseContent.getString("transaction")).get(0).toString()); - String retString = transactionObject.getString("ret"); - JSONArray array = JSONArray.parseArray(retString); - Assert.assertEquals( - HttpMethed.parseStringContent(array.get(0).toString()).getString("contractRet"), "SUCCESS"); - Assert.assertTrue(responseContent.size() == 1); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, receiverAddress, fromAddress, receiverKey); - HttpMethed.disConnect(); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSmartContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSmartContract001.java deleted file mode 100644 index 8f1d7c17ee7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestSmartContract001.java +++ /dev/null @@ -1,373 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestSmartContract001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + now; - private static String assetIssueId; - private static String contractName; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetOwnerAddress = ecKey2.getAddress(); - String assetOwnerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] assetReceiverAddress = ecKey3.getAddress(); - String assetReceiverKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - String contractAddress; - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf").getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpRealSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(3); - - /** - * constructor. - */ - @Test(enabled = true, description = "Deploy smart contract by http") - public void test1DeployContract() { - PublicMethed.printAddress(assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetOwnerAddress, amount, testKey002); - response = HttpMethed.sendCoin(httpnode, fromAddress, assetReceiverAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed - .freezeBalance(httpnode, assetOwnerAddress, 100000000L, 3, 1, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - response = HttpMethed.assetIssue(httpnode, assetOwnerAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, 2, 3, description, - url, 1000L, 1000L, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, assetOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - assetIssueId = responseContent.getString("asset_issued_ID"); - - contractName = "transferTokenContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_ContractTrcToken001_transferTokenContract"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_ContractTrcToken001_transferTokenContract"); - - long tokenValue = 100000; - long callValue = 5000; - - //This deploy is test too large call_token_value will made the witness node cpu 100% - /*response = HttpMethed.deployContractGetTxidWithTooBigLong(httpnode, - contractName, abi, code, 1000000L,1000000000L, 100, 11111111111111L, - callValue, Integer.parseInt(assetIssueId), tokenValue, assetOwnerAddress, assetOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertTrue(responseContent.getString("Error").contains("Overflow"));*/ - - String txid = HttpMethed - .deployContractGetTxid(httpnode, contractName, abi, code, 1000000L, 1000000000L, 100, - 11111111111111L, callValue, Integer.parseInt(assetIssueId), tokenValue, - assetOwnerAddress, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("contract_address").isEmpty()); - contractAddress = responseContent.getString("contract_address"); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get contract by http") - public void test2GetContract() { - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "100"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("call_value"), "5000"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger contract by http") - public void test3TriggerContract() { - - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info(addressParam); - logger.info(tokenIdParam); - logger.info(tokenValueParam); - final Long beforeBalance = HttpMethed.getBalance(httpnode, assetOwnerAddress); - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - //String txid = "49a30653d6e648da1e9a104b051b1b55c185fcaa0c2885405ae1d2fb258e3b3c"; - logger.info(txid); - response = HttpMethed.getTransactionById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(txid, responseContent.getString("txID")); - Assert.assertTrue(!responseContent.getString("raw_data").isEmpty()); - Assert.assertTrue(!responseContent.getString("raw_data_hex").isEmpty()); - Long afterBalance = HttpMethed.getBalance(httpnode, assetOwnerAddress); - logger.info("beforeBalance: " + beforeBalance); - logger.info("afterBalance: " + afterBalance); - Assert.assertTrue(beforeBalance - afterBalance == callValue); - - response = HttpMethed.getTransactionInfoById(httpnode, txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String receiptString = responseContent.getString("receipt"); - Assert - .assertEquals(HttpMethed.parseStringContent(receiptString).getString("result"), "SUCCESS"); - Assert.assertTrue(HttpMethed.parseStringContent(receiptString).getLong("energy_usage") > 0); - Assert.assertTrue(responseContent.getLong("blockNumber") > 0); - - response = HttpMethed.getAccount(httpnode, assetReceiverAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(!responseContent.getString("assetV2").isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by http") - public void test4GetTransactionInfoByBlocknum() { - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid1 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - String txid2 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid1); - HttpResponse response2 = HttpMethed.getTransactionInfoById(httpnode, txid2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject responseContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(responseContent2); - if (responseContent.getLong("blockNumber").equals(responseContent2.getLong("blockNumber"))) { - HttpResponse responseByBlocknum = HttpMethed - .getTransactionInfoByBlocknum(httpnode, responseContent.getLong("blockNumber")); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(responseByBlocknum); - Assert.assertEquals(2, responseContentByBlocknum.size()); - HttpMethed.printJsonContent(responseContentByBlocknum.get(0)); - HttpMethed.printJsonContent(responseContentByBlocknum.get(1)); - if (responseContent.getString("id") - .equals(responseContentByBlocknum.get(0).getString("id"))) { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(0)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(1)); - } else { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(1)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(0)); - } - } - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by http from solidity") - public void test5GetTransactionInfoByBlocknumFromSolidity() { - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid1 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - String txid2 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed.getTransactionInfoById(httpnode, txid1); - HttpResponse response2 = HttpMethed.getTransactionInfoById(httpnode, txid2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject responseContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(responseContent2); - if (responseContent.getLong("blockNumber").equals(responseContent2.getLong("blockNumber"))) { - HttpResponse responseByBlocknum = HttpMethed - .getTransactionInfoByBlocknumFromSolidity(httpSolidityNode, - responseContent.getLong("blockNumber")); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(responseByBlocknum); - Assert.assertEquals(2, responseContentByBlocknum.size()); - HttpMethed.printJsonContent(responseContentByBlocknum.get(0)); - HttpMethed.printJsonContent(responseContentByBlocknum.get(1)); - if (responseContent.getString("id") - .equals(responseContentByBlocknum.get(0).getString("id"))) { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(0)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(1)); - } else { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(1)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(0)); - } - } - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction info by http from real solidity") - public void test6GetTransactionInfoByBlocknumFromRealSolidity() { - String hexReceiverAddress = ByteArray.toHexString(assetReceiverAddress); - String addressParam = "000000000000000000000000" + hexReceiverAddress.substring(2);//[0,3) - String tokenIdParam = "00000000000000000000000000000000000000000000000000000000000" + Integer - .toHexString(Integer.parseInt(assetIssueId)); - String tokenValueParam = "0000000000000000000000000000000000000000000000000000000000000001"; - String param = addressParam + tokenIdParam + tokenValueParam; - Long callValue = 10L; - String txid1 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - String txid2 = HttpMethed.triggerContractGetTxid(httpnode, assetOwnerAddress, contractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, 1000000000L, callValue, - Integer.parseInt(assetIssueId), 20L, assetOwnerKey); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpRealSolidityNode); - response = HttpMethed.getTransactionInfoById(httpnode, txid1); - HttpResponse response2 = HttpMethed.getTransactionInfoById(httpnode, txid2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONObject responseContent2 = HttpMethed.parseResponseContent(response2); - HttpMethed.printJsonContent(responseContent2); - if (responseContent.getLong("blockNumber").equals(responseContent2.getLong("blockNumber"))) { - HttpResponse responseByBlocknum = HttpMethed - .getTransactionInfoByBlocknumFromSolidity(httpRealSolidityNode, - responseContent.getLong("blockNumber")); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(responseByBlocknum); - Assert.assertEquals(2, responseContentByBlocknum.size()); - HttpMethed.printJsonContent(responseContentByBlocknum.get(0)); - HttpMethed.printJsonContent(responseContentByBlocknum.get(1)); - if (responseContent.getString("id") - .equals(responseContentByBlocknum.get(0).getString("id"))) { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(0)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(1)); - } else { - Assert.assertEquals(responseContent, responseContentByBlocknum.get(1)); - Assert.assertEquals(responseContent2, responseContentByBlocknum.get(0)); - } - } - } - - /** - * constructor. - */ - @Test(enabled = true, description = "UpdateSetting contract by http") - public void test7UpdateSetting() { - - //assetOwnerAddress, assetOwnerKey - response = HttpMethed - .updateSetting(httpnode, assetOwnerAddress, contractAddress, 75, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "75"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("call_value"), "5000"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "11111111111111"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "UpdateEnergyLimit contract by http") - public void test8UpdateEnergyLimit() { - - //assetOwnerAddress, assetOwnerKey - response = HttpMethed - .updateEnergyLimit(httpnode, assetOwnerAddress, contractAddress, 1234567, assetOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - response = HttpMethed.getContract(httpnode, contractAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertEquals(responseContent.getString("consume_user_resource_percent"), "75"); - Assert.assertEquals(responseContent.getString("contract_address"), contractAddress); - Assert.assertEquals(responseContent.getString("origin_address"), - ByteArray.toHexString(assetOwnerAddress)); - Assert.assertEquals(responseContent.getString("call_value"), "5000"); - Assert.assertEquals(responseContent.getString("origin_energy_limit"), "1234567"); - Assert.assertEquals(responseContent.getString("name"), contractName); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.freedResource(httpnode, assetOwnerAddress, fromAddress, assetOwnerKey); - HttpMethed.freedResource(httpnode, assetReceiverAddress, fromAddress, assetReceiverKey); - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestTransactionPending001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestTransactionPending001.java deleted file mode 100644 index 58c09f1836d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestTransactionPending001.java +++ /dev/null @@ -1,100 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestTransactionPending001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid; - JSONObject transaction; - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction pending size by http") - public void test01GetTransactionPendingSize() { - int pendingSize = 0; - int retryTimes = 50; - - while (pendingSize == 0 && retryTimes-- > 0) { - HttpMethed.sendCoin(httpnode,fromAddress,receiverAddress,1L,testKey002); - if (retryTimes % 5 == 0) { - pendingSize = HttpMethed.getTransactionPendingSize(httpnode); - } - } - - Assert.assertNotEquals(pendingSize,0); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get pending transaction list by http") - public void test02GetPendingTransactionList() { - int transactionSize = 0; - int retryTimes = 50; - - while (transactionSize == 0 && retryTimes-- > 0) { - HttpMethed.sendCoin(httpnode,fromAddress,receiverAddress,1L,testKey002); - if (retryTimes % 5 == 0) { - response = HttpMethed.getTransactionListFromPending(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - transactionSize = responseContent.getJSONArray("txId").size(); - } - } - Assert.assertNotEquals(transactionSize,0); - - txid = responseContent.getJSONArray("txId").getString(0); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction from pending by http") - public void test03GetPendingTransactionList() { - response = HttpMethed.getTransactionFromPending(httpnode,txid); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - Assert.assertEquals(txid,responseContent.getString("txID")); - Assert.assertNotEquals(null,responseContent); - } - - - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken001.java deleted file mode 100644 index bb070512fe7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken001.java +++ /dev/null @@ -1,382 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken001 { - - List shieldOutList = new ArrayList<>(); - Optional shieldAddressOptionalInfo1; - Optional shieldAddressOptionalInfo2; - Optional shieldAddressOptionalInfo3; - ShieldAddressInfo shieldAddressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo3 = new ShieldAddressInfo(); - String assetIssueId; - ShieldNoteInfo shieldNote1; - ShieldNoteInfo shieldNote2; - ShieldNoteInfo shieldNote3; - String memo; - String sk; - String d1; - String d2; - String d3; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD1; - String pkD2; - String pkD3; - String paymentAddress1; - String paymentAddress2; - String paymentAddress3; - String rcm; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private String tokenId = zenTokenId; - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - Args.setFullNodeAllowShieldedTransaction(true); - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - } - - @Test(enabled = false, description = "Get spending key by http") - public void test01GetSpendingKey() { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sk = responseContent.getString("value"); - logger.info("sk: " + sk); - - } - - @Test(enabled = false, description = "Get diversifier by http") - public void test02GetDiversifier() { - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d1 = responseContent.getString("d"); - logger.info("d1: " + d1); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d2 = responseContent.getString("d"); - logger.info("d2: " + d2); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d3 = responseContent.getString("d"); - logger.info("d3: " + d3); - } - - @Test(enabled = false, description = "Get expanded spending key by http") - public void test03GetExpandedSpendingKey() { - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - logger.info("ask: " + ask); - logger.info("nsk: " + nsk); - logger.info("ovk: " + ovk); - } - - @Test(enabled = false, description = "Get AK from ASK by http") - public void test04GetAkFromAsk() { - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ak = responseContent.getString("value"); - logger.info("ak: " + ak); - } - - @Test(enabled = false, description = "Get Nk from Nsk by http") - public void test05GetNkFromNsk() { - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - nk = responseContent.getString("value"); - logger.info("nk: " + nk); - } - - @Test(enabled = false, description = "Get incoming viewing Key by http") - public void test06GetIncomingViewingKey() { - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ivk = responseContent.getString("ivk"); - logger.info("ivk: " + ivk); - } - - @Test(enabled = false, description = "Get Zen Payment Address by http") - public void test07GetZenPaymentAddress() { - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD1 = responseContent.getString("pkD"); - paymentAddress1 = responseContent.getString("payment_address"); - System.out.println("pkd1: " + pkD1); - System.out.println("address1: " + paymentAddress1); - shieldAddressInfo1.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo1.setD(new DiversifierT(ByteArray.fromHexString(d1))); - shieldAddressInfo1.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo1.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo1.setPkD(ByteArray.fromHexString(pkD1)); - shieldAddressOptionalInfo1 = Optional.of(shieldAddressInfo1); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD2 = responseContent.getString("pkD"); - paymentAddress2 = responseContent.getString("payment_address"); - System.out.println("pkd2: " + pkD2); - System.out.println("address2: " + paymentAddress2); - shieldAddressInfo2.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo2.setD(new DiversifierT(ByteArray.fromHexString(d2))); - shieldAddressInfo2.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo2.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo2.setPkD(ByteArray.fromHexString(pkD2)); - shieldAddressOptionalInfo2 = Optional.of(shieldAddressInfo2); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d3); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD3 = responseContent.getString("pkD"); - paymentAddress3 = responseContent.getString("payment_address"); - System.out.println("pkd3: " + pkD3); - System.out.println("address3: " + paymentAddress3); - shieldAddressInfo3.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo3.setD(new DiversifierT(ByteArray.fromHexString(d3))); - shieldAddressInfo3.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo3.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo3.setPkD(ByteArray.fromHexString(pkD3)); - shieldAddressOptionalInfo3 = Optional.of(shieldAddressInfo3); - } - - @Test(enabled = false, description = "Get rcm by http") - public void test08GetRcm() { - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - rcm = responseContent.getString("value"); - logger.info("rcm: " + rcm); - } - - @Test(enabled = false, description = "Public to shield transaction withoutask by http") - public void test09PublicToShieldTransactionWithoutAsk() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - String memo1 = "Shield memo11 in " + System.currentTimeMillis(); - String memo2 = "Shield memo22 in " + System.currentTimeMillis(); - Long sendSheldAddressAmount1 = zenTokenFee * 2; - Long sendSheldAddressAmount2 = zenTokenFee * 3; - Long sendAmount = sendSheldAddressAmount1 + sendSheldAddressAmount2 + zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, shieldAddressOptionalInfo1.get().getAddress(), - "" + sendSheldAddressAmount1, memo1); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, shieldAddressOptionalInfo2.get().getAddress(), - "" + sendSheldAddressAmount2, memo2); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, zenTokenOwnerAddress, - sendAmount, null, null, shieldOutList, null, 0, zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - String memo3 = "Shield memo33 in " + System.currentTimeMillis(); - Long sendSheldAddressAmount3 = costTokenAmount - sendAmount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, shieldAddressOptionalInfo3.get().getAddress(), - "" + sendSheldAddressAmount3, memo3); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, zenTokenOwnerAddress, - sendSheldAddressAmount3 + zenTokenFee, null, null, shieldOutList, null, 0, - zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - List shieldNoteInfoByIvkList = HttpMethed - .scanNoteByIvk(httpnode, shieldAddressOptionalInfo1.get()); - logger.info("size are:" + shieldNoteInfoByIvkList.size()); - Assert.assertTrue(shieldNoteInfoByIvkList.size() == 3); - List shieldNoteInfoByMarkList = HttpMethed - .scanAndMarkNoteByIvk(httpnode, shieldAddressOptionalInfo2.get()); - Assert.assertTrue(shieldNoteInfoByMarkList.size() == 3); - - shieldNote1 = shieldNoteInfoByIvkList.get(0); - shieldNote2 = shieldNoteInfoByIvkList.get(1); - shieldNote3 = shieldNoteInfoByIvkList.get(2); - Assert.assertTrue(shieldNote1.getValue() == sendSheldAddressAmount1); - Assert.assertEquals(memo1.getBytes(), shieldNote1.getMemo()); - Assert.assertTrue(shieldNote2.getValue() == sendSheldAddressAmount2); - Assert.assertEquals(memo2.getBytes(), shieldNote2.getMemo()); - Assert.assertTrue(shieldNote3.getValue() == sendSheldAddressAmount3); - Assert.assertEquals(memo3.getBytes(), shieldNote3.getMemo()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(0).getIsSpend()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(1).getIsSpend()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(2).getIsSpend()); - } - - @Test(enabled = false, description = "Shield to shield transaction withoutask by http") - public void test10ShieldToShieldTransactionWithoutAsk() { - Optional receiverShieldAddressInfo1 = HttpMethed - .generateShieldAddress(httpnode); - String receiverShieldAddress1 = receiverShieldAddressInfo1.get().getAddress(); - logger.info("receiverShieldAddress1:" + receiverShieldAddress1); - Optional receiverShieldAddressInfo2 = HttpMethed - .generateShieldAddress(httpnode); - String receiverShieldAddress2 = receiverShieldAddressInfo2.get().getAddress(); - logger.info("receiverShieldAddress2:" + receiverShieldAddress2); - Optional receiverShieldAddressInfo3 = HttpMethed - .generateShieldAddress(httpnode); - String receiverShieldAddress3 = receiverShieldAddressInfo3.get().getAddress(); - logger.info("receiverShieldAddress3:" + receiverShieldAddress3); - - shieldOutList.clear(); - String receiverMemo1 = "Shield memo1 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress1, - "" + (shieldNote1.getValue() - zenTokenFee), receiverMemo1); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, null, 0, - shieldAddressOptionalInfo1.get(), shieldNote1, shieldOutList, null, 0, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - /*shieldOutList.clear(); - String receiverMemo2 = "Shield memo2 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress2, - "" + (shieldNote2.getValue() - zenTokenFee), receiverMemo2); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, null, 0, shieldAddressOptionalInfo2.get(), shieldNote2, - shieldOutList, - null, 0, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent);*/ - shieldOutList.clear(); - String receiverMemo3 = "Shield memo3 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress3, - "" + (shieldNote3.getValue() - zenTokenFee), receiverMemo3); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, null, 0, - shieldAddressOptionalInfo3.get(), shieldNote3, shieldOutList, null, 0, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - List shieldNoteInfoByOvkList = HttpMethed - .scanNoteByOvk(httpnode, shieldAddressOptionalInfo3.get()); - Assert.assertTrue(shieldNoteInfoByOvkList.size() == 2); - List shieldNoteInfoByMarkList = HttpMethed - .scanAndMarkNoteByIvk(httpnode, shieldAddressOptionalInfo2.get()); - Assert.assertTrue(shieldNoteInfoByMarkList.size() == 3); - - Assert.assertTrue( - shieldNoteInfoByOvkList.get(0).getValue() == shieldNote1.getValue() - zenTokenFee); - Assert.assertEquals(receiverMemo1.getBytes(), shieldNoteInfoByOvkList.get(0).getMemo()); - /*Assert.assertTrue( - shieldNoteInfoByOvkList.get(1).getValue() == shieldNote2.getValue() - zenTokenFee); - Assert.assertEquals(receiverMemo2.getBytes(), shieldNoteInfoByOvkList.get(1).getMemo());*/ - Assert.assertTrue( - shieldNoteInfoByOvkList.get(1).getValue() == shieldNote3.getValue() - zenTokenFee); - Assert.assertEquals(receiverMemo3.getBytes(), shieldNoteInfoByOvkList.get(1).getMemo()); - Assert.assertTrue(shieldNoteInfoByMarkList.get(0).getIsSpend()); - Assert.assertFalse(shieldNoteInfoByMarkList.get(1).getIsSpend()); - Assert.assertTrue(shieldNoteInfoByMarkList.get(2).getIsSpend()); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken002.java deleted file mode 100644 index 7355cff0dfe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken002.java +++ /dev/null @@ -1,332 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken002 { - - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - ShieldNoteInfo sendNote; - ShieldNoteInfo receiverNote; - ShieldNoteInfo noteByOvk; - ShieldNoteInfo noteByIvk; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long sendTokenAmount = 7 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - Args.setFullNodeAllowShieldedTransaction(true); - - } - - @Test(enabled = false, description = "Public to shield transaction by http") - public void test01PublicToShieldTransaction() { - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo1); - - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - null, 0, zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - Assert.assertTrue(sendNote.getValue() == sendTokenAmount - zenTokenFee); - Assert.assertEquals(memo1.getBytes(), sendNote.getMemo()); - - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - Assert.assertFalse(scanAndMarkNoteSendNote.getIsSpend()); - } - - @Test(enabled = false, description = "Shield to shield transaction by http") - public void test02ShieldToShieldTransaction() { - receiverShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - memo2 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress, - "" + (sendNote.getValue() - zenTokenFee), memo2); - - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - null, 0, null); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - receiverNote = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - - Assert.assertTrue(receiverNote.getValue() == sendNote.getValue() - zenTokenFee); - Assert.assertEquals(ByteArray.toHexString(memo2.getBytes()), - ByteArray.toHexString(receiverNote.getMemo())); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - Assert.assertFalse( - HttpMethed.getSpendResult(httpnode, receiverShieldAddressInfo.get(), receiverNote)); - } - - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on FullNode by http") - public void test03ScanNoteByIvkAndOvk() { - //Scan sender note by ovk equals scan receiver note by ivk on FullNode - noteByOvk = HttpMethed.scanNoteByOvk(httpnode, sendShieldAddressInfo.get()).get(0); - noteByIvk = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - Assert.assertEquals(noteByIvk.getValue(), noteByOvk.getValue()); - Assert.assertEquals(noteByIvk.getMemo(), noteByOvk.getMemo()); - Assert.assertEquals(noteByIvk.getR(), noteByOvk.getR()); - Assert.assertEquals(noteByIvk.getPaymentAddress(), noteByOvk.getPaymentAddress()); - } - - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on Solidity by http") - public void test04ScanNoteByIvkAndOvkFromSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - //Scan sender note by ovk equals scan receiver note by ivk on Solidity - noteByOvk = HttpMethed.scanNoteByOvkFromSolidity(httpSolidityNode, sendShieldAddressInfo.get()) - .get(0); - noteByIvk = HttpMethed - .scanNoteByIvkFromSolidity(httpSolidityNode, receiverShieldAddressInfo.get()).get(0); - Assert.assertEquals(noteByIvk.getValue(), noteByOvk.getValue()); - Assert.assertEquals(noteByIvk.getMemo(), noteByOvk.getMemo()); - Assert.assertEquals(noteByIvk.getR(), noteByOvk.getR()); - Assert.assertEquals(noteByIvk.getPaymentAddress(), noteByOvk.getPaymentAddress()); - } - - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on PBFT by http") - public void test05ScanNoteByIvkAndOvkFromPbft() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - //Scan sender note by ovk equals scan receiver note by ivk on Solidity - noteByOvk = HttpMethed.scanNoteByOvkFromPbft(httpPbftNode, sendShieldAddressInfo.get()).get(0); - noteByIvk = HttpMethed.scanNoteByIvkFromPbft(httpPbftNode, receiverShieldAddressInfo.get()) - .get(0); - Assert.assertEquals(noteByIvk.getValue(), noteByOvk.getValue()); - Assert.assertEquals(noteByIvk.getMemo(), noteByOvk.getMemo()); - Assert.assertEquals(noteByIvk.getR(), noteByOvk.getR()); - Assert.assertEquals(noteByIvk.getPaymentAddress(), noteByOvk.getPaymentAddress()); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on solidity by http") - public void test06QueryNoteIsSpendOnSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, sendShieldAddressInfo.get(), - sendNote)); - Assert.assertFalse(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, receiverShieldAddressInfo.get(), - receiverNote)); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on PBFT by http") - public void test07QueryNoteIsSpendOnSolidity() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(HttpMethed - .getSpendResultFromPbft(httpnode, httpPbftNode, sendShieldAddressInfo.get(), sendNote)); - Assert.assertFalse(HttpMethed - .getSpendResultFromPbft(httpnode, httpPbftNode, receiverShieldAddressInfo.get(), - receiverNote)); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Query note and spend status on fullnode") - public void test08QueryNoteAndSpendStatusOnFullnode() { - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - Assert.assertTrue(scanAndMarkNoteSendNote.isSpend); - Assert.assertEquals(scanAndMarkNoteSendNote.getValue(), sendNote.getValue()); - Assert.assertEquals(scanAndMarkNoteSendNote.getMemo(), sendNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteSendNote.getR(), sendNote.getR()); - Assert.assertEquals(scanAndMarkNoteSendNote.getPaymentAddress(), sendNote.getPaymentAddress()); - - ShieldNoteInfo scanAndMarkNoteReceiverNote = HttpMethed - .scanAndMarkNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - Assert.assertFalse(scanAndMarkNoteReceiverNote.getIsSpend()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getValue(), receiverNote.getValue()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getMemo(), receiverNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getR(), receiverNote.getR()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getPaymentAddress(), - receiverNote.getPaymentAddress()); - } - - @Test(enabled = false, description = "Query note and spend status on solidity") - public void test09QueryNoteAndSpendStatusOnSolidity() { - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvkFromSolidity(httpnode, httpSolidityNode, sendShieldAddressInfo.get()) - .get(0); - Assert.assertTrue(scanAndMarkNoteSendNote.isSpend); - Assert.assertEquals(scanAndMarkNoteSendNote.getValue(), sendNote.getValue()); - Assert.assertEquals(scanAndMarkNoteSendNote.getMemo(), sendNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteSendNote.getR(), sendNote.getR()); - Assert.assertEquals(scanAndMarkNoteSendNote.getPaymentAddress(), sendNote.getPaymentAddress()); - - ShieldNoteInfo scanAndMarkNoteReceiverNote = HttpMethed - .scanAndMarkNoteByIvkFromSolidity(httpnode, httpSolidityNode, - receiverShieldAddressInfo.get()).get(0); - Assert.assertFalse(scanAndMarkNoteReceiverNote.getIsSpend()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getValue(), receiverNote.getValue()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getMemo(), receiverNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getR(), receiverNote.getR()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getPaymentAddress(), - receiverNote.getPaymentAddress()); - - } - - @Test(enabled = false, description = "Query note and spend status on PBFT") - public void test10QueryNoteAndSpendStatusOnPbft() { - ShieldNoteInfo scanAndMarkNoteSendNote = HttpMethed - .scanAndMarkNoteByIvkFromPbft(httpnode, httpPbftNode, sendShieldAddressInfo.get()).get(0); - Assert.assertTrue(scanAndMarkNoteSendNote.isSpend); - Assert.assertEquals(scanAndMarkNoteSendNote.getValue(), sendNote.getValue()); - Assert.assertEquals(scanAndMarkNoteSendNote.getMemo(), sendNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteSendNote.getR(), sendNote.getR()); - Assert.assertEquals(scanAndMarkNoteSendNote.getPaymentAddress(), sendNote.getPaymentAddress()); - - ShieldNoteInfo scanAndMarkNoteReceiverNote = HttpMethed - .scanAndMarkNoteByIvkFromPbft(httpnode, httpPbftNode, receiverShieldAddressInfo.get()) - .get(0); - Assert.assertFalse(scanAndMarkNoteReceiverNote.getIsSpend()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getValue(), receiverNote.getValue()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getMemo(), receiverNote.getMemo()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getR(), receiverNote.getR()); - Assert.assertEquals(scanAndMarkNoteReceiverNote.getPaymentAddress(), - receiverNote.getPaymentAddress()); - - } - - - @Test(enabled = false, description = "Shield to public transaction by http") - public void test11ShieldToPublicTransaction() { - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, receiverShieldAddressInfo.get(), receiverNote, - shieldOutList, zenTokenOwnerAddress, receiverNote.getValue() - zenTokenFee, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue( - afterAssetBalance - beforeAssetBalance == receiverNote.getValue() - zenTokenFee); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - Assert.assertTrue( - HttpMethed.getSpendResult(httpnode, receiverShieldAddressInfo.get(), receiverNote)); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken003.java deleted file mode 100644 index ca1889b0423..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken003.java +++ /dev/null @@ -1,308 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken003 { - - Optional receiverShieldAddressInfo1; - Optional receiverShieldAddressInfo2; - Optional receiverShieldAddressInfo3; - Optional receiverShieldAddressInfo4; - Optional receiverShieldAddressInfo5; - String receiverShieldAddress1; - String receiverShieldAddress2; - String receiverShieldAddress3; - String receiverShieldAddress4; - String receiverShieldAddress5; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - String memo3; - String memo4; - String memo5; - ShieldNoteInfo receiverNote1; - ShieldNoteInfo receiverNote2; - ShieldNoteInfo receiverNote3; - ShieldNoteInfo receiverNote4; - ShieldNoteInfo receiverNote5; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - private Long sendTokenAmount = 18 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - Args.setFullNodeAllowShieldedTransaction(true); - - } - - @Test(enabled = false, description = "Public to two shield transaction by http") - public void test01PublicToTwoShieldTransaction() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverShieldAddressInfo1 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddressInfo2 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress1 = receiverShieldAddressInfo1.get().getAddress(); - receiverShieldAddress2 = receiverShieldAddressInfo2.get().getAddress(); - logger.info("receiverShieldAddress1:" + receiverShieldAddress1); - logger.info("receiverShieldAddress2:" + receiverShieldAddress2); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - memo2 = "Shield memo2 in " + System.currentTimeMillis(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = sendTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - null, 0, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - receiverNote1 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo1.get()).get(0); - receiverNote2 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo2.get()).get(0); - Assert.assertTrue(receiverNote1.getValue() == sendToShiledAddress1Amount); - Assert.assertTrue(receiverNote2.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo1.getBytes(), receiverNote1.getMemo()); - Assert.assertEquals(memo2.getBytes(), receiverNote2.getMemo()); - } - - @Test(enabled = false, description = "Public to one public and one shield transaction by http") - public void test02ShieldToOneShieldAndOnePublicTransaction() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverShieldAddressInfo3 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress3 = receiverShieldAddressInfo3.get().getAddress(); - - final Long beforeAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long beforeBalanceSendAddress = responseContent.getLong("balance"); - - final Long beforeAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddressAmount = - sendTokenAmount - sendToPublicAddressAmount - zenTokenWhenCreateNewAddress; - memo3 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress3, - "" + sendToShiledAddressAmount, memo3); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterBalanceSendAddress = responseContent.getLong("balance"); - - final Long afterAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue( - beforeAssetBalanceSendAddress - afterAssetBalanceSendAddress == sendTokenAmount); - Assert.assertTrue(beforeNetUsedSendAddress == afterNetUsedSendAddress); - Assert.assertTrue(beforeBalanceSendAddress == afterBalanceSendAddress); - - Assert.assertTrue(afterAssetBalanceReceiverAddress - beforeAssetBalanceReceiverAddress - == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsedReceiverAddress == afterNetUsedReceiverAddress); - - receiverNote3 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo3.get()).get(0); - - Assert.assertTrue(receiverNote3.getValue() == sendToShiledAddressAmount); - Assert.assertEquals(memo3.getBytes(), receiverNote3.getMemo()); - } - - @Test(enabled = false, description = "Public to one public and two shield transaction by http") - public void test03ShieldToOneShieldAndTwoPublicTransaction() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverShieldAddressInfo4 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress4 = receiverShieldAddressInfo4.get().getAddress(); - receiverShieldAddressInfo5 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress5 = receiverShieldAddressInfo5.get().getAddress(); - - final Long beforeAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long beforeBalanceSendAddress = responseContent.getLong("balance"); - - final Long beforeAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddress1Amount = 2 * zenTokenFee; - Long sendToShiledAddress2Amount = - sendTokenAmount - sendToPublicAddressAmount - sendToShiledAddress1Amount - zenTokenFee; - memo4 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - memo5 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress4, - "" + sendToShiledAddress1Amount, memo4); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress5, - "" + sendToShiledAddress2Amount, memo5); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - Long afterAssetBalanceSendAddress = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsedSendAddress = responseContent.getLong("freeNetUsed"); - response = HttpMethed.getAccount(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterBalanceSendAddress = responseContent.getLong("balance"); - - final Long afterAssetBalanceReceiverAddress = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsedReceiverAddress = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue( - beforeAssetBalanceSendAddress - afterAssetBalanceSendAddress == sendTokenAmount); - Assert.assertTrue(beforeNetUsedSendAddress == afterNetUsedSendAddress); - Assert.assertTrue(beforeBalanceSendAddress == afterBalanceSendAddress); - - Assert.assertTrue(afterAssetBalanceReceiverAddress - beforeAssetBalanceReceiverAddress - == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsedReceiverAddress == afterNetUsedReceiverAddress); - - receiverNote4 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo4.get()).get(0); - Assert.assertTrue(receiverNote4.getValue() == sendToShiledAddress1Amount); - Assert.assertEquals(memo4.getBytes(), receiverNote4.getMemo()); - - receiverNote5 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo5.get()).get(0); - Assert.assertTrue(receiverNote5.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo5.getBytes(), receiverNote5.getMemo()); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance1 = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance1, zenTokenOwnerKey); - - final Long assetBalance2 = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, receiverPublicAddress, foundationZenTokenAddress, assetIssueId, - assetBalance2, receiverPublicKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken004.java deleted file mode 100644 index d7d9bcb6e5d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken004.java +++ /dev/null @@ -1,289 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken004 { - - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo1; - Optional receiverShieldAddressInfo2; - Optional receiverShieldAddressInfo3; - Optional receiverShieldAddressInfo4; - Optional receiverShieldAddressInfo5; - String sendShieldAddress; - String receiverShieldAddress1; - String receiverShieldAddress2; - String receiverShieldAddress3; - String receiverShieldAddress4; - String receiverShieldAddress5; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - String memo3; - String memo4; - String memo5; - ShieldNoteInfo sendNote; - ShieldNoteInfo receiverNote1; - ShieldNoteInfo receiverNote2; - ShieldNoteInfo receiverNote3; - ShieldNoteInfo receiverNote4; - ShieldNoteInfo receiverNote5; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey1.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - private Long sendTokenAmount = 18 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, description = "Shield to two shield transaction by http") - public void test01ShieldToTwoShieldTransaction() { - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - String memo = "Shield memo in " + System.currentTimeMillis(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, "" + sendTokenAmount, - memo); - response = HttpMethed - .sendShieldCoin(httpnode, foundationZenTokenAddress, sendTokenAmount + zenTokenFee, null, - null, shieldOutList, null, 0, foundationZenTokenKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - - receiverShieldAddressInfo1 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddressInfo2 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress1 = receiverShieldAddressInfo1.get().getAddress(); - receiverShieldAddress2 = receiverShieldAddressInfo2.get().getAddress(); - logger.info("receiverShieldAddress1:" + receiverShieldAddress1); - logger.info("receiverShieldAddress2:" + receiverShieldAddress2); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - memo2 = "Shield memo2 in " + System.currentTimeMillis(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = sendTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - null, 0, null); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - - receiverNote1 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo1.get()).get(0); - receiverNote2 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo2.get()).get(0); - Assert.assertTrue(receiverNote1.getValue() == sendToShiledAddress1Amount); - Assert.assertTrue(receiverNote2.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo1.getBytes(), receiverNote1.getMemo()); - Assert.assertEquals(memo2.getBytes(), receiverNote2.getMemo()); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - } - - @Test(enabled = false, description = "Shield to one public and one shield transaction by http") - public void test02ShieldToOnePublicAndOneShieldTransaction() { - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - String memo = "Shield memo in " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, "" + sendTokenAmount, - memo); - response = HttpMethed - .sendShieldCoin(httpnode, foundationZenTokenAddress, sendTokenAmount + zenTokenFee, null, - null, shieldOutList, null, 0, foundationZenTokenKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - - receiverShieldAddressInfo3 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress3 = receiverShieldAddressInfo3.get().getAddress(); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddressAmount = - sendTokenAmount - sendToPublicAddressAmount - zenTokenWhenCreateNewAddress; - memo3 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress3, - "" + sendToShiledAddressAmount, memo3); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - final Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(afterAssetBalance - beforeAssetBalance == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - receiverNote3 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo3.get()).get(0); - Assert.assertTrue(receiverNote3.getValue() == sendToShiledAddressAmount); - Assert.assertEquals(memo3.getBytes(), receiverNote3.getMemo()); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, sendShieldAddressInfo.get(), - sendNote)); - Assert.assertFalse(HttpMethed - .getSpendResultFromSolidity(httpnode, httpSolidityNode, receiverShieldAddressInfo3.get(), - receiverNote3)); - - Assert.assertTrue( - HttpMethed.scanAndMarkNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0).getIsSpend()); - Assert.assertFalse( - HttpMethed.scanAndMarkNoteByIvk(httpnode, receiverShieldAddressInfo3.get()).get(0) - .getIsSpend()); - } - - @Test(enabled = false, description = "Shield to one public and two shield transaction by http") - public void test03ShieldToOnePublicAndTwoShieldTransaction() { - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - String memo = "Shield memo in " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, "" + sendTokenAmount, - memo); - response = HttpMethed - .sendShieldCoin(httpnode, foundationZenTokenAddress, sendTokenAmount + zenTokenFee, null, - null, shieldOutList, null, 0, foundationZenTokenKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - - receiverShieldAddressInfo4 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress4 = receiverShieldAddressInfo4.get().getAddress(); - receiverShieldAddressInfo5 = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress5 = receiverShieldAddressInfo5.get().getAddress(); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - shieldOutList.clear(); - Long sendToPublicAddressAmount = 1 * zenTokenFee; - Long sendToShiledAddress1Amount = 2 * zenTokenFee; - Long sendToShiledAddress2Amount = - sendTokenAmount - sendToPublicAddressAmount - sendToShiledAddress1Amount - zenTokenFee; - memo4 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - memo5 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress4, - "" + sendToShiledAddress1Amount, memo4); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress5, - "" + sendToShiledAddress2Amount, memo5); - - PublicMethed.printAddress(receiverPublicKey); - response = HttpMethed - .sendShieldCoin(httpnode, null, 0, sendShieldAddressInfo.get(), sendNote, shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, null); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - final Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, receiverPublicAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(afterAssetBalance - beforeAssetBalance == sendToPublicAddressAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - receiverNote4 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo4.get()).get(0); - Assert.assertTrue(receiverNote4.getValue() == sendToShiledAddress1Amount); - Assert.assertEquals(memo4.getBytes(), receiverNote4.getMemo()); - - receiverNote5 = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo5.get()).get(0); - Assert.assertTrue(receiverNote5.getValue() == sendToShiledAddress2Amount); - Assert.assertEquals(memo5.getBytes(), receiverNote5.getMemo()); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, receiverPublicAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, receiverPublicAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, receiverPublicKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken005.java deleted file mode 100644 index 2075fd37b8c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken005.java +++ /dev/null @@ -1,174 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; - -@Slf4j -public class HttpTestZenToken005 { - - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - String memo1; - String memo2; - ShieldNoteInfo sendNote; - ShieldNoteInfo receiveNote; - String assetIssueId; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long sendTokenAmount = 7 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, zenTokenId, - sendTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddress:" + sendShieldAddress); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo1); - - response = HttpMethed - .sendShieldCoin(httpnode, zenTokenOwnerAddress, sendTokenAmount, null, null, shieldOutList, - null, 0, zenTokenOwnerKey); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - shieldOutList.clear(); - HttpMethed.waitToProduceOneBlock(httpnode); - sendNote = HttpMethed.scanNoteByIvk(httpnode, sendShieldAddressInfo.get()).get(0); - } - - @Test(enabled = false, description = "Shield to shield transaction without ask by http") - public void test01ShieldToShieldWithoutAskTransaction() { - receiverShieldAddressInfo = HttpMethed.generateShieldAddress(httpnode); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - memo2 = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = HttpMethed.addShieldOutputList(httpnode, shieldOutList, receiverShieldAddress, - "" + (sendNote.getValue() - zenTokenFee), memo2); - - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpPbftNode, null, 0, - sendShieldAddressInfo.get(), sendNote, shieldOutList, null, 0, null); - org.junit.Assert.assertEquals(response.getStatusLine().getStatusCode(), 200); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - HttpMethed.printJsonContent(responseContent); - HttpMethed.waitToProduceOneBlock(httpnode); - - receiveNote = HttpMethed.scanNoteByIvk(httpnode, receiverShieldAddressInfo.get()).get(0); - - Assert.assertTrue(receiveNote.getValue() == sendNote.getValue() - zenTokenFee); - Assert.assertEquals(ByteArray.toHexString(memo2.getBytes()), - ByteArray.toHexString(receiveNote.getMemo())); - - Assert.assertTrue(HttpMethed.getSpendResult(httpnode, sendShieldAddressInfo.get(), sendNote)); - } - - @Test(enabled = false, description = "Get merkle tree voucher info by http") - public void test02GetMerkleTreeVoucherInfo() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .getMerkleTreeVoucherInfo(httpnode, sendNote.getTrxId(), sendNote.getIndex(), 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains("tree")); - Assert.assertTrue(responseContent.toJSONString().contains("rt")); - Assert.assertTrue(responseContent.toJSONString().contains("paths")); - - response = HttpMethed - .getMerkleTreeVoucherInfo(httpnode, receiveNote.getTrxId(), receiveNote.getIndex(), 1000); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains( - "synBlockNum is too large, cmBlockNum plus synBlockNum must be <= latestBlockNumber")); - } - - @Test(enabled = false, description = "Get merkle tree voucher info by http from solidity") - public void test03GetMerkleTreeVoucherInfoFromSolidity() { - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, sendNote.getTrxId(), - sendNote.getIndex(), 1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains("tree")); - Assert.assertTrue(responseContent.toJSONString().contains("rt")); - Assert.assertTrue(responseContent.toJSONString().contains("paths")); - - response = HttpMethed - .getMerkleTreeVoucherInfoFromSolidity(httpSolidityNode, receiveNote.getTrxId(), - receiveNote.getIndex(), 1000); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.toJSONString().contains( - "synBlockNum is too large, cmBlockNum plus synBlockNum must be <= latestBlockNumber")); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - assetIssueId = responseContent.getString("asset_issued_ID"); - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken006.java deleted file mode 100644 index 8cb5b71a406..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/http/HttpTestZenToken006.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.http; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpTestZenToken006 { - - List shieldOutList = new ArrayList<>(); - String assetIssueId; - String sk; - String d1; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD1; - String paymentAddress1; - String rcm; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private String tokenId = zenTokenId; - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - Args.setFullNodeAllowShieldedTransaction(true); - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - } - - @Test(enabled = false, description = "Get new shielded address by http") - public void test01GetNewShieldedAddress() { - response = HttpMethed.getNewShieldedAddress(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.size() == 10); - Assert.assertTrue(responseContent.containsKey("d")); - Assert.assertTrue(responseContent.containsKey("ovk")); - Assert.assertTrue(responseContent.containsKey("nsk")); - Assert.assertTrue(responseContent.containsKey("payment_address")); - Assert.assertTrue(responseContent.containsKey("sk")); - Assert.assertTrue(responseContent.containsKey("ask")); - Assert.assertTrue(responseContent.containsKey("pkD")); - Assert.assertTrue(responseContent.containsKey("ak")); - Assert.assertTrue(responseContent.containsKey("nk")); - Assert.assertTrue(responseContent.containsKey("ivk")); - - sk = responseContent.getString("sk"); - d1 = responseContent.getString("d"); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - ak = responseContent.getString("ak"); - nk = responseContent.getString("nk"); - ivk = responseContent.getString("ivk"); - pkD1 = responseContent.getString("pkD"); - paymentAddress1 = responseContent.getString("payment_address"); - } - - @Test(enabled = false, description = "Get expanded spending key by http") - public void test02GetExpandedSpendingKey() { - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - String askFromSk = responseContent.getString("ask"); - String nskFromSk = responseContent.getString("nsk"); - String ovkFromSk = responseContent.getString("ovk"); - Assert.assertEquals(ask, askFromSk); - Assert.assertEquals(nsk, nskFromSk); - Assert.assertEquals(ovk, ovkFromSk); - - } - - - @Test(enabled = false, description = "Get rcm by http") - public void test03GetRcm() { - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - rcm = responseContent.getString("value"); - logger.info("rcm: " + rcm); - } - - @Test(enabled = false, description = "Public to shield transaction withoutask by http") - public void test04PublicToShieldTransactionWithoutAsk() { - response = HttpMethed - .transferAsset(httpnode, foundationZenTokenAddress, zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenKey); - org.junit.Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - - response = HttpMethed.getAccount(httpnode, foundationZenTokenAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId = responseContent.getString("asset_issued_ID"); - - final Long beforeAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - final Long beforeNetUsed = responseContent.getLong("freeNetUsed"); - - String memo1 = "Shield memo11 in " + System.currentTimeMillis(); - Long sendSheldAddressAmount1 = zenTokenFee * 2; - Long sendAmount = sendSheldAddressAmount1 + zenTokenFee; - shieldOutList.clear(); - shieldOutList = HttpMethed - .addShieldOutputList(httpnode, shieldOutList, paymentAddress1, "" + sendSheldAddressAmount1, - memo1); - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - response = HttpMethed - .sendShieldCoinWithoutAsk(httpnode, httpSolidityNode, httpnode, zenTokenOwnerAddress, - sendAmount, null, null, shieldOutList, null, 0, zenTokenOwnerKey); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - HttpMethed.waitToProduceOneBlock(httpnode); - Long afterAssetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - - response = HttpMethed.getAccountReource(httpnode, zenTokenOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long afterNetUsed = responseContent.getLong("freeNetUsed"); - - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - final Long assetBalance = HttpMethed - .getAssetIssueValue(httpnode, zenTokenOwnerAddress, assetIssueId); - HttpMethed - .transferAsset(httpnode, zenTokenOwnerAddress, foundationZenTokenAddress, assetIssueId, - assetBalance, zenTokenOwnerKey); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction001.java deleted file mode 100644 index 4bb08861889..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction001.java +++ /dev/null @@ -1,503 +0,0 @@ -package stest.tron.wallet.dailybuild.internaltransaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class ContractInternalTransaction001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "Create->call.Two-level nesting") - public void testInternalTransaction001() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction001.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(7, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - String initParmes2 = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2(address,uint256)", initParmes2, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(10, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertFalse(infoById1.get().getInternalTransactions(i).getRejected()); - } - } - - @Test(enabled = true, description = "There is one internalTransaction.Only call") - public void testInternalTransaction002() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction002.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes2 = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2(address,uint256)", initParmes2, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(1, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - Assert.assertFalse(infoById1.get().getInternalTransactions(0).getRejected()); - String note = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - Assert.assertEquals("call", note); - Assert.assertEquals(1, - infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue()); - - } - - @Test(enabled = true, description = "There is one internalTransaction.Only create") - public void testInternalTransaction003() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction003.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "transfer()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(1, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - Assert.assertFalse(infoById1.get().getInternalTransactions(0).getRejected()); - String note = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - Assert.assertEquals("create", note); - Assert.assertEquals(10, - infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue()); - - } - - @Test(enabled = true, description = "Test suicide type in internalTransaction") - public void testInternalTransaction004() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction004.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String initParmes = "\"" + Base58.encode58Check(contractAddress) - + "\",\"" + Base58.encode58Check(contractAddress1) + "\""; - txid = PublicMethed.triggerContract(contractAddress1, - "kill(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note); - Assert.assertEquals("suicide", note1); - Assert.assertTrue(0 == vaule1); - Assert.assertTrue(1000000L == vaule2); - - String txid1 = PublicMethed.triggerContract(contractAddress1, - "kill2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(3, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - String note3 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note4 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - String note5 = ByteArray - .toStr(infoById1.get().getInternalTransactions(2).getNote().toByteArray()); - Assert.assertEquals("create", note3); - Assert.assertEquals("call", note4); - Assert.assertEquals("suicide", note5); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertFalse(infoById1.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals(0, - infoById1.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - - } - } - - @Test(enabled = true, description = "Type is create call") - public void testInternalTransaction005() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction005.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test1()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertTrue(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - String note3 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note4 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - - Long vaule3 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById1.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(10 == vaule3); - Assert.assertTrue(0 == vaule4); - Assert.assertEquals("create", note3); - Assert.assertEquals("call", note4); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - - - } - } - - @Test(enabled = true, description = "Type is create call call") - public void testInternalTransaction006() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction001testInternalTransaction006.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test1()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(3, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount; i++) { - Assert.assertTrue(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertEquals("call", note2); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - Assert.assertTrue(0 == vaule3); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(3, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - String note4 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note5 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - String note6 = ByteArray - .toStr(infoById1.get().getInternalTransactions(2).getNote().toByteArray()); - Long vaule4 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule5 = infoById1.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule6 = infoById1.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - - Assert.assertTrue(10 == vaule4); - Assert.assertTrue(0 == vaule5); - Assert.assertTrue(0 == vaule6); - Assert.assertEquals("create", note4); - Assert.assertEquals("call", note5); - Assert.assertEquals("call", note6); - - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - } - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - /** - * constructor. - */ - - public void dupInternalTrsansactionHash( - List internalTransactionList) { - List hashList = new ArrayList<>(); - internalTransactionList.forEach( - internalTransaction -> hashList - .add(Hex.toHexString(internalTransaction.getHash().toByteArray()))); - List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) - .entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) - .collect(Collectors.toList()); - Assert.assertEquals(dupHash.size(), 0); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction002.java deleted file mode 100644 index 0794f29dfa0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction002.java +++ /dev/null @@ -1,580 +0,0 @@ -package stest.tron.wallet.dailybuild.internaltransaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class ContractInternalTransaction002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - - @Test(enabled = true, description = "Type is create create call call") - public void test1InternalTransaction007() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test1InternalTransaction007.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - - String txid = ""; - - txid = PublicMethed.triggerContract(contractAddress, - "test1(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertNotNull(infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(4, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertTrue(infoById.get().getInternalTransactions(i).getRejected()); - } - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("create", note); - Assert.assertEquals("create", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - Assert.assertTrue(5 == vaule3); - Assert.assertTrue(0 == vaule4); - String initParmes1 = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "test2(address,uint256)", initParmes1, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(1, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - String note5 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - Long vaule5 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(1 == vaule5); - Assert.assertEquals("call", note5); - Assert.assertTrue(infoById1.get().getInternalTransactions(0).getRejected()); - - - } - - @Test(enabled = true, description = "Type is call call") - public void test2InternalTransaction008() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test2InternalTransaction008.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\",\"1\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testAssert(address,uint256)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - Assert.assertTrue(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertFalse(infoById.get().getInternalTransactions(1).getRejected()); - - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note); - Assert.assertEquals("call", note1); - Assert.assertTrue(1 == vaule1); - Assert.assertTrue(1 == vaule2); - String contractName2 = "C"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes1 = "\"" + Base58.encode58Check(contractAddress2) + "\",\"1\""; - String txid1 = PublicMethed.triggerContract(contractAddress, - "testRequire(address,uint256)", initParmes1, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - Assert.assertTrue(infoById1.get().getInternalTransactions(0).getRejected()); - Assert.assertFalse(infoById1.get().getInternalTransactions(1).getRejected()); - String note2 = ByteArray - .toStr(infoById1.get().getInternalTransactions(0).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById1.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule3 = infoById1.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById1.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - Assert.assertTrue(1 == vaule3); - Assert.assertTrue(1 == vaule4); - - String txid2 = PublicMethed.triggerContract(contractAddress, - "testAssert1(address,uint256)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - int transactionsCount2 = infoById2.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount2); - dupInternalTrsansactionHash(infoById2.get().getInternalTransactionsList()); - Assert.assertFalse(infoById2.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById2.get().getInternalTransactions(1).getRejected()); - - String note5 = ByteArray - .toStr(infoById2.get().getInternalTransactions(0).getNote().toByteArray()); - String note6 = ByteArray - .toStr(infoById2.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule5 = infoById2.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule6 = infoById2.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note5); - Assert.assertEquals("call", note6); - Assert.assertTrue(1 == vaule5); - Assert.assertTrue(1 == vaule6); - - String txid3 = PublicMethed.triggerContract(contractAddress, - "testtRequire2(address,uint256)", initParmes1, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - int transactionsCount3 = infoById3.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount3); - dupInternalTrsansactionHash(infoById3.get().getInternalTransactionsList()); - - Assert.assertFalse(infoById3.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById3.get().getInternalTransactions(1).getRejected()); - String note7 = ByteArray - .toStr(infoById3.get().getInternalTransactions(0).getNote().toByteArray()); - String note8 = ByteArray - .toStr(infoById3.get().getInternalTransactions(1).getNote().toByteArray()); - Long vaule7 = infoById3.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule8 = infoById3.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("call", note7); - Assert.assertEquals("call", note8); - Assert.assertTrue(1 == vaule7); - Assert.assertTrue(1 == vaule8); - - } - - @Test(enabled = true, description = "Test suicide type in internalTransaction after call") - public void test3InternalTransaction009() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test3InternalTransaction009.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "C"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName3 = "D"; - HashMap retMap3 = PublicMethed.getBycodeAbi(filePath, contractName3); - String code3 = retMap3.get("byteCode").toString(); - String abi3 = retMap3.get("abI").toString(); - byte[] contractAddress3 = PublicMethed - .deployContract(contractName3, abi3, code3, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String initParmes = "\"" + Base58.encode58Check(contractAddress2) - + "\",\"" + Base58.encode58Check(contractAddress3) + "\",\"" + Base58 - .encode58Check(contractAddress1) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(7, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(6).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertEquals("suicide", note2); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(5 == vaule2); - - String txid1 = ""; - txid1 = PublicMethed.triggerContract(contractAddress, - "test1(address,address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(6, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - } - - @Test(enabled = false, description = "Test maxfeelimit can trigger create type max time") - public void test4InternalTransaction010() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test4InternalTransaction010.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "transfer()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(76, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("create", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid1 = PublicMethed.triggerContract(contractAddress, - "transfer2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 1); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - Assert.assertEquals(76, transactionsCount1); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("create", ByteArray - .toStr(infoById1.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById1.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - - } - - - } - - - @Test(enabled = true, description = "Type is call create->call->call.Three-level nesting") - public void test5InternalTransaction012() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction002test5InternalTransaction012.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "E"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap1.get("byteCode").toString(); - String abi2 = retMap1.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(4, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Assert.assertEquals("call", note); - Assert.assertEquals("create", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(1 == vaule1); - Assert.assertTrue(1000 == vaule2); - Assert.assertTrue(0 == vaule3); - Assert.assertTrue(1 == vaule4); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - /** - * constructor. - */ - - public void dupInternalTrsansactionHash( - List internalTransactionList) { - List hashList = new ArrayList<>(); - internalTransactionList.forEach( - internalTransaction -> hashList - .add(Hex.toHexString(internalTransaction.getHash().toByteArray()))); - List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) - .entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) - .collect(Collectors.toList()); - Assert.assertEquals(dupHash.size(), 0); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java deleted file mode 100644 index 1c7a94d3002..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/internaltransaction/ContractInternalTransaction003.java +++ /dev/null @@ -1,584 +0,0 @@ -package stest.tron.wallet.dailybuild.internaltransaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Retry; - -@Slf4j - -public class ContractInternalTransaction003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - - @Test(enabled = true, description = "Three-level nesting.Type is Create call->call->create") - public void testInternalTransaction013() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction013.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "D"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(4, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Assert.assertEquals("create", note); - Assert.assertEquals("call", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("create", note3); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - Assert.assertTrue(10 == vaule1); - Assert.assertTrue(0 == vaule2); - Assert.assertTrue(2 == vaule3); - Assert.assertTrue(5 == vaule4); - - - } - - - @Test(enabled = true, description = "Test delegatecall and callcode.") - public void testInternalTransaction014() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction014.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "calledContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "c"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "sendToB(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("call", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - } - Assert.assertEquals(ByteArray - .toHexString(infoById.get().getInternalTransactions(0).getCallerAddress() - .toByteArray()), - ByteArray.toHexString( - infoById.get().getInternalTransactions(0).getTransferToAddress().toByteArray())); - - Assert.assertEquals(ByteArray - .toHexString(contractAddress2), - ByteArray.toHexString( - infoById.get().getInternalTransactions(1).getTransferToAddress().toByteArray())); - String txid2 = ""; - txid2 = PublicMethed.triggerContract(contractAddress, - "sendToB2(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - int transactionsCount2 = infoById2.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount2); - for (int i = 0; i < transactionsCount2; i++) { - Assert.assertFalse(infoById2.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("call", ByteArray - .toStr(infoById2.get().getInternalTransactions(i).getNote().toByteArray())); - } - Assert.assertEquals(ByteArray - .toHexString(contractAddress), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(0).getCallerAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress1), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(0).getTransferToAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress1), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(1).getCallerAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress2), - ByteArray.toHexString( - infoById2.get().getInternalTransactions(1).getTransferToAddress().toByteArray())); - - String txid3 = ""; - txid3 = PublicMethed.triggerContract(contractAddress, - "sendToB3(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = null; - infoById3 = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 0); - int transactionsCount3 = infoById3.get().getInternalTransactionsCount(); - Assert.assertEquals(2, transactionsCount3); - for (int i = 0; i < transactionsCount3; i++) { - Assert.assertFalse(infoById3.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("call", ByteArray - .toStr(infoById3.get().getInternalTransactions(i).getNote().toByteArray())); - } - Assert.assertEquals(ByteArray - .toHexString(infoById3.get().getInternalTransactions(0).getCallerAddress() - .toByteArray()), - ByteArray.toHexString( - infoById3.get().getInternalTransactions(0).getTransferToAddress().toByteArray())); - Assert.assertEquals(ByteArray - .toHexString(contractAddress2), - ByteArray.toHexString( - infoById3.get().getInternalTransactions(1).getTransferToAddress().toByteArray())); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - dupInternalTrsansactionHash(infoById2.get().getInternalTransactionsList()); - dupInternalTrsansactionHash(infoById3.get().getInternalTransactionsList()); - - } - - @Test(enabled = true, description = "Three-level nesting.Type " - + "is create call->call->create call->suicide") - public void testInternalTransaction015() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction015.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "D"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "E"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(6, transactionsCount); - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - - - } - - - @Test(enabled = false, description = "After create 80 times,then suicide") - public void testInternalTransaction016() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction016.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "transfer()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(69, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - Assert.assertEquals("suicide", ByteArray - .toStr(infoById.get().getInternalTransactions(68).getNote().toByteArray())); - Assert.assertEquals("call", ByteArray - .toStr(infoById.get().getInternalTransactions(67).getNote().toByteArray())); - Assert.assertEquals(0, - infoById.get().getInternalTransactions(67).getCallValueInfo(0).getCallValue()); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(68).getCallValueInfo(0).getCallValue()); - for (int i = 0; i < transactionsCount - 2; i++) { - Assert.assertEquals("create", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - } - String txid1 = ""; - txid1 = PublicMethed.triggerContract(contractAddress, - "transfer2()", "#", false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - int transactionsCount1 = infoById1.get().getInternalTransactionsCount(); - - Assert.assertEquals(68, transactionsCount1); - for (int i = 0; i < transactionsCount1; i++) { - Assert.assertTrue(infoById1.get().getInternalTransactions(i).getRejected()); - Assert.assertEquals("create", ByteArray - .toStr(infoById1.get().getInternalTransactions(i).getNote().toByteArray())); - - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - dupInternalTrsansactionHash(infoById1.get().getInternalTransactionsList()); - - } - - @Test(enabled = false, description = "After create 88 times,then suicide") - public void testInternalTransaction017() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction017.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress) + "\""; - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "transfer(address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(77, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - Assert.assertEquals("suicide", ByteArray - .toStr(infoById.get().getInternalTransactions(76).getNote().toByteArray())); - Assert.assertEquals(1000000 - 76, - infoById.get().getInternalTransactions(76).getCallValueInfo(0).getCallValue()); - for (int i = 0; i < transactionsCount - 1; i++) { - Assert.assertEquals("create", ByteArray - .toStr(infoById.get().getInternalTransactions(i).getNote().toByteArray())); - Assert.assertEquals(1, - infoById.get().getInternalTransactions(i).getCallValueInfo(0).getCallValue()); - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - } - - @Test(enabled = true,retryAnalyzer = Retry.class, - description = "Test maxfeelimit can trigger call create call max time") - public void testInternalTransaction018() { - Assert.assertTrue(PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/" - + "contractInternalTransaction003testInternalTransaction018.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName1 = "B"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "E"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] contractAddress2 = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed - .sendcoin(internalTxsAddress, 2000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 100000, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("InfoById:" + infoById); - - int retryTimes = 1; - while (retryTimes++ < 5 && infoById.get().getResultValue() != 0) { - // retry 5 times - txid = PublicMethed.triggerContract(contractAddress, - "test1(address,address)", initParmes, false, - 100000, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("InfoById retry " + retryTimes + " : " + infoById); - } - - - - Assert.assertEquals(0, infoById.get().getResultValue()); - int transactionsCount = infoById.get().getInternalTransactionsCount(); - Assert.assertEquals(184, transactionsCount); - for (int i = 0; i < transactionsCount; i++) { - Assert.assertFalse(infoById.get().getInternalTransactions(i).getRejected()); - } - dupInternalTrsansactionHash(infoById.get().getInternalTransactionsList()); - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - String note1 = ByteArray - .toStr(infoById.get().getInternalTransactions(1).getNote().toByteArray()); - String note2 = ByteArray - .toStr(infoById.get().getInternalTransactions(2).getNote().toByteArray()); - String note3 = ByteArray - .toStr(infoById.get().getInternalTransactions(3).getNote().toByteArray()); - Long vaule1 = infoById.get().getInternalTransactions(0).getCallValueInfo(0).getCallValue(); - Long vaule2 = infoById.get().getInternalTransactions(1).getCallValueInfo(0).getCallValue(); - Long vaule3 = infoById.get().getInternalTransactions(2).getCallValueInfo(0).getCallValue(); - Long vaule4 = infoById.get().getInternalTransactions(3).getCallValueInfo(0).getCallValue(); - - Assert.assertEquals("call", note); - Assert.assertEquals("create", note1); - Assert.assertEquals("call", note2); - Assert.assertEquals("call", note3); - Assert.assertTrue(1 == vaule1); - Assert.assertTrue(100 == vaule2); - Assert.assertTrue(0 == vaule3); - Assert.assertTrue(1 == vaule4); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - - /** - * constructor. - */ - - public void dupInternalTrsansactionHash( - List internalTransactionList) { - List hashList = new ArrayList<>(); - internalTransactionList.forEach( - internalTransaction -> hashList - .add(Hex.toHexString(internalTransaction.getHash().toByteArray()))); - List dupHash = hashList.stream() - .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) - .entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey()) - .collect(Collectors.toList()); - Assert.assertEquals(dupHash.size(), 0); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java deleted file mode 100644 index 174f6d1d8d2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts001.java +++ /dev/null @@ -1,1225 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Accounts001 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; - String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Json rpc api of eth_accounts") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromJsonRpcNode = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromJsonRpcNode:" + blockNumFromJsonRpcNode); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromJsonRpcNode - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromJsonRpcNode = responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNum(httpFullNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromJsonRpcNode:" + blockIdFromJsonRpcNode); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromJsonRpcNode, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoById(httpFullNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_gasPrice") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameter(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } - } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - Long balance2 = HttpMethed.getBalance(httpFullNode, foundationAccountAddress); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknum(httpFullNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNode, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("16blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumResult = responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } - } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } - } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("16indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("16requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); - } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("16transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("16jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknum(httpFullNode, blockNum); - logger.info("16response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("16responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } - } - - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), "0x" + getBlockByNumResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; - } else { - data = getBlockByNumResult.getJSONObject("raw_data").getString("data").substring(2); - } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = Long.parseLong(getBlockByNumResult.getString("signature").substring(130, 131), 16); - long v = Long.parseLong(getBlockByNumResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; - } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumResult.getString("signature").substring(66, 130)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByHash") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("17blockNum:" + blockNum); - JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("17blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("17requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("17responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromJsonRpcNode = Integer.parseInt(transactionNum, 16); - logger.info("17transactionNumFromJsonRpcNode:" + transactionNumFromJsonRpcNode); - response = HttpMethed.getTransactionCountByBlocknum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromJsonRpcNode); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockTransactionCountByNumber") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByBlockHashAndIndex") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - logger.info("20transacionHash:" + transacionHash); - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("20responseContent:" + responseContent); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { - logger.info("trc20Txid:" + trc20Txid); - JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("21requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - logger.info("21response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("21resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("21logs:" + logs); - logger.info("21result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } - } - - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNode, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); - /* Assert.assertEquals( - resultFromTransactionReceipt.getString("contractAddress").substring(2), - trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = HttpMethed.getTransactionInfoByBlocknum(httpFullNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("21responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockHashAndIndex") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleByBlockNumberAndIndex") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockNumber") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getWork") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - String resultFromJsonRpcNode = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - String resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromJsonRpcNode:" + resultFromJsonRpcNode); - logger.info("resultFromHttp:" + resultFromHttp); - Assert.assertEquals(resultFromJsonRpcNode, resultFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_hashrate") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); - } - - @Test(enabled = true, description = "Json rpc api of eth_mining") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } - - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - long currentNum = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("currentNum:" + currentNum); - logger.info("currentNumFromRpc:" + Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertEquals(currentNum, Long.parseLong(currentNumFromRpc.substring(2), 16)); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); - } - - @Test(enabled = true, description = "Json rpc api of net_listening") - public void test31JsonRpcApiTestForNetListening() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - Boolean temp = responseContent.getBoolean("result"); - logger.info(temp.toString()); - response = HttpMethed.getNodeInfo(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - boolean expect = false; - int num = responseContent.getInteger("activeConnectCount"); - if (num >= 1) { - expect = true; - } - Assert.assertEquals(temp, expect); - } - - @Test(enabled = true, description = "Json rpc api of net_peerCount") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); - } - - @Test(enabled = true, description = "Json rpc api of net_version") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNum(httpFullNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of web3_clientVersion") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); - } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); - } - - @Test(enabled = true, description = "Json rpc api of web3_sha3") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNode, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileLLL") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { - JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sign") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_signTransaction") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitWork") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of parity_nextNonce") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash params is false") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNum(httpFullNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("48getBlockByNumFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - if (accountStateRoot == null) { - accountStateRoot = ""; - } - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("48sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "48sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } - } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByNumber params is true") - public void test49JsonRpcApiTestForEthGetBlockByNumber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("49blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByNumberResult = responseContent.getJSONObject("result"); - logger.info("49getBlockByHashResult:" + getBlockByNumberResult); - - Assert.assertNull(getBlockByNumberResult.getString("nonce")); - Assert.assertNull(getBlockByNumberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumberResult.getString("extraData")); - Assert.assertNull(getBlockByNumberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumberResult.getString("mixHash")); - Assert.assertEquals(getBlockByNumberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByNumberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumberResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByNumberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByNumberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByNumberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong(getBlockByNumberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("49size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumberResult.getString("size").substring(2), 16), size); - - JSONArray transactionsList = getBlockByNumberResult.getJSONArray("transactions"); - logger.info("49transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } - } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("49index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNode, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("49responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("49result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); - } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java deleted file mode 100644 index e4d2407bdb4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts002.java +++ /dev/null @@ -1,1290 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Accounts002 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - String realGasPrice; - String bid = null; - int indexNum = 0; - String indexHex = null; - JSONObject result = null; - String transacionHash = null; - String blockHash = null; - String blockNumHex = null; - String parentHash = null; - String txTrieRoot = null; - String witnessAddress = null; - String feeLimit = null; - String accountStateRoot = null; - String energyUsed = "0x135c6"; - - List transactionIdList = null; - long size = 0; - long gas = 0; - long blockTimeStamp = 0; - long gasPriceFromHttp = 0; - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Json rpc api of eth_accounts from solidity") - public void test01JsonRpcApiTestForEthAccounts() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_accounts", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - List result = new ArrayList(); - logger.info(String.valueOf(result)); - Assert.assertEquals(responseContent.get("result"), result); - } - - @Test(enabled = true, description = "Json rpc api of eth_blockNumber from solidity") - public void test02JsonRpcApiTestForEthBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_blockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockNum = responseContent.getString("result").substring(2); - long blockNumFromjsonRpcNodeForSolidity = Long.parseLong(blockNum, 16); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - long blockNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blocknumFromjsonRpcNodeForSolidity:" + blockNumFromjsonRpcNodeForSolidity); - logger.info("blocknumFromHttp:" + blockNumFromHttp); - Assert.assertTrue(Math.abs(blockNumFromjsonRpcNodeForSolidity - blockNumFromHttp) <= 3); - } - - @Test(enabled = true, description = "Json rpc api of eth_call from solidity") - public void test03JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call", params); - logger.info("03params:" + params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals( - "0x000000000000000000000000000000000000000000000000000" - + "00000000000200000000000000000000000000000000000000000" - + "00000000000000000000000a546f6b656e5452433230000000000" - + "00000000000000000000000000000000000", - dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_chainId from solidity") - public void test04JsonRpcApiTestForEthChainId() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_chainId", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String blockIdFromjsonRpcNodeForSolidity = - responseContent.get("result").toString().substring(2); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String blockIdFromHttp = responseContent.getString("blockID").substring(56); - logger.info("blockIdFromjsonRpcNodeForSolidity:" + blockIdFromjsonRpcNodeForSolidity); - logger.info("blockIdFromHttp:" + blockIdFromHttp); - Assert.assertEquals(blockIdFromjsonRpcNodeForSolidity, blockIdFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_coinbase from solidity") - public void test05JsonRpcApiTestForEthCoinbase() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_coinbase", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals( - "0x410be88a918d74d0dfd71dc84bd4abf036d0562991", responseContent.getString("result")); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas from solidity") - public void test06JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test06requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x147", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasHasPayable") - public void test07JsonRpcApiTestForEthEstimateGasHasPayable() throws Exception { - response = HttpMethed.getTransactionInfoByIdFromSolidity(httpsolidityNode, txid); - responseContent = HttpMethed.parseResponseContent(response); - Long realEnergyUsed = responseContent.getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("realEnergyUsed:" + realEnergyUsed); - JsonObject param = new JsonObject(); - param.addProperty("from", "0x" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2)); - param.addProperty("to", "0x" + contractAddressFrom58); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1389"); - param.addProperty("data", data); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test07requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals((long) realEnergyUsed, Long.parseLong(dataResult.substring(2), 16)); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasWithoutTo from solidity") - public void test08JsonRpcApiTestForEthEstimateGasWithoutTo() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", "0x6C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty( - "data", - "0x6080604052d3600055d2600155346002556101418061001f6000396000f30060806040" - + "52600436106100565763ffffffff7c010000000000000000000000000000000000000000" - + "000000000000000060003504166305c24200811461005b5780633be9ece7146100815780" - + "6371dc08ce146100aa575b600080fd5b6100636100b2565b6040805193845260208401929" - + "0925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffff" - + "ffffffffff600435166024356044356100c0565b005b61006361010d565b60005460015460" - + "0254909192565b60405173ffffffffffffffffffffffffffffffffffffffff841690821561" - + "08fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d" - + "6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5" - + "f9e7905ef98e66e60dd4b38e00b05de418da3154e757002900000000000000000000000000" - + "00000000000000000000000000000090fa17bb"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test08requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - logger.info("dataResult:" + dataResult); - Assert.assertEquals(energyUsed, dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_estimateGasSendTrx from solidity") - public void test09JsonRpcApiTestForEthEstimateGasSendTrx() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", "0xC1A74CD01732542093F5A87910A398AD70F04BD7"); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x1"); - param.addProperty("data", "0x0"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("test09requestBody:" + requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals("0x0", dataResult); - } - - @Test(enabled = true, description = "Json rpc api of eth_gasPrice from solidity") - public void test10JsonRpcApiTestForEthGasPrice() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_gasPrice", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - responseContent.get("result"); - String gasPrice = responseContent.get("result").toString().substring(2); - long gasPriceFromJsonrpc = Long.parseLong(gasPrice, 16); - logger.info(String.valueOf(gasPriceFromJsonrpc)); - response = HttpMethed.getChainParameters(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - JSONArray temp; - temp = responseContent.getJSONArray("chainParameter"); - for (int i = 0; i < temp.size(); i++) { - if (temp.getJSONObject(i).get("key").equals("getEnergyFee")) { - gasPriceFromHttp = temp.getJSONObject(i).getLong("value"); - } - } - logger.info("gasPriceFromHttp:" + gasPriceFromHttp); - Assert.assertEquals(gasPriceFromJsonrpc, gasPriceFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getBalance from solidity") - public void test11JsonRpcApiTestForEthGetBalance() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + ByteArray.toHexString(foundationAccountAddress).substring(2)); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getBalance", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String balance = responseContent.getString("result").substring(2); - Long balance1 = Long.parseLong(balance, 16); - logger.info("balance1:" + balance1); - response = HttpMethed.getAccountFromSolidity(httpsolidityNode, foundationAccountAddress); - responseContent = HttpMethed.parseResponseContent(response); - Long balance2 = responseContent.getLong("balance"); - logger.info(balance1.toString()); - logger.info(balance2.toString()); - Assert.assertEquals(balance1, balance2); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockTransactionCountByNumber from solidity") - public void test12JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - JsonArray params = new JsonArray(); - params.add("earliest"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCode from solidity") - public void test13JsonRpcApiTestForEthGetCode() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromJsonRpc = responseContent.getString("result").substring(2); - logger.info(codeFromJsonRpc); - response = HttpMethed.getContractInfo(httpFullNode, contractAddressFrom58); - logger.info("13contractAddressFrom58:" + contractAddressFrom58); - responseContent = HttpMethed.parseResponseContent(response); - String codeFromHttp = responseContent.getString("runtimecode"); - logger.info(codeFromHttp); - Assert.assertEquals(codeFromJsonRpc, codeFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt from solidity") - public void test14JsonRpcApiTestForEthGetStorageAt01() throws Exception { - - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add("0x0"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("14responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - long resultExpect = Long.parseLong(result, 16); - logger.info("result:" + resultExpect); - Assert.assertEquals("1234", String.valueOf(resultExpect)); - } - - @Test(enabled = true, description = "Json rpc api of eth_getStorageAt from solidity") - public void test15JsonRpcApiTestForEthGetStorageAt02() throws Exception { - - String address = - "000000000000000000000000" + ByteArray.toHexString(jsonRpcOwnerAddress).substring(2); - String str = address + "0000000000000000000000000000000000000000000000000000000000000001"; - logger.info("str:" + str); - JsonArray paramsForSha3 = new JsonArray(); - paramsForSha3.add(str); - JsonObject requestBodyForSha3 = getJsonRpcBody("web3_sha3", paramsForSha3); - logger.info("requestBodyForSha3:" + requestBodyForSha3); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForSha3); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String resultForSha3 = responseContent.getString("result"); - logger.info("resultForSha3:" + resultForSha3); - JsonArray params = new JsonArray(); - params.add(contractAddressFrom58); - params.add(resultForSha3); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getStorageAt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("15responseContent:" + responseContent); - String result = responseContent.getString("result").substring(2); - logger.info("15result:" + result); - logger.info("mapResult:" + Integer.parseInt(result, 16)); - Assert.assertEquals("5678", String.valueOf(Integer.parseInt(result, 16))); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getTransactionByBlockNumberAndIndex from solidity") - public void test16JsonRpcApiTestForEthGetTransactionByBlockNumberAndIndex() throws Exception { - logger.info("16blockNum:" + blockNum); - blockNumHex = "0x" + Integer.toHexString(blockNum); - logger.info("blockNumHex:" + blockNumHex); - JsonArray params = new JsonArray(); - params.add(blockNumHex); - indexNum = 0; - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - parentHash = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("parentHash"); - txTrieRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("txTrieRoot"); - witnessAddress = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("witness_address"); - feeLimit = - responseContent - .getJSONArray("transactions") - .getJSONObject(0) - .getJSONObject("raw_data") - .getString("fee_limit"); - logger.info(feeLimit); - - JSONObject getBlockByNumFromSolidityResult = null; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - indexNum = i; - getBlockByNumFromSolidityResult = - responseContent.getJSONArray("transactions").getJSONObject(i); - bid = responseContent.getString("blockID"); - break; - } - } - transactionIdList = new ArrayList<>(); - if (responseContent.getJSONArray("transactions").size() > 0) { - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - transactionIdList.add( - "0x" + responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID")); - } - } - logger.info("16transactionIdList:" + transactionIdList); - logger.info(String.valueOf(indexNum)); - indexHex = "0x" + Integer.toHexString(indexNum); - logger.info("indexHex:" + indexHex); - params.add(indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockNumberAndIndex", params); - logger.info("13requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - result = responseContent.getJSONObject("result"); - logger.info("16 result" + result); - Map jsonrpcResult = new HashMap(); - for (Map.Entry entry : result.entrySet()) { - jsonrpcResult.put(entry.getKey(), entry.getValue()); - } - transacionHash = jsonrpcResult.get("hash").toString(); - logger.info("transactionHash:" + transacionHash); - blockHash = jsonrpcResult.get("blockHash").toString(); - logger.info("jsonrpcResult:" + jsonrpcResult); - response = HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNum); - logger.info("response:" + response); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - blockTimeStamp = responseContent1.get(0).getLong("blockTimeStamp"); - - for (int i = 0; i < responseContent1.size(); i++) { - if (responseContent1.get(i).getString("id").equals(transactionIdList.get(0).substring(2))) { - gas = responseContent1.get(i).getJSONObject("receipt").getLong("energy_usage_total"); - logger.info("gas:" + gas); - break; - } - } - - Assert.assertEquals(jsonrpcResult.get("gas").toString(), "0x" + Long.toHexString(gas)); - Assert.assertNull(jsonrpcResult.get("nonce")); - Assert.assertEquals( - jsonrpcResult.get("hash").toString(), - "0x" + getBlockByNumFromSolidityResult.getString("txID")); - Assert.assertEquals(jsonrpcResult.get("blockHash").toString(), "0x" + bid); - Assert.assertEquals(jsonrpcResult.get("blockNumber").toString(), blockNumHex); - Assert.assertEquals(jsonrpcResult.get("transactionIndex").toString(), indexHex); - Assert.assertEquals( - jsonrpcResult.get("from").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("owner_address") - .substring(2)); - Assert.assertEquals( - jsonrpcResult.get("to").toString(), - "0x" - + getBlockByNumFromSolidityResult - .getJSONObject("raw_data") - .getJSONArray("contract") - .getJSONObject(0) - .getJSONObject("parameter") - .getJSONObject("value") - .getString("contract_address") - .substring(2)); - - Assert.assertEquals(jsonrpcResult.get("value").toString(), "0x1389"); - String data; - if (getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data") == null) { - data = "0x"; - } else { - data = - getBlockByNumFromSolidityResult.getJSONObject("raw_data").getString("data").substring(2); - } - Assert.assertEquals(jsonrpcResult.get("input").toString(), data); - - long temp = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 131), 16); - long v = - Long.parseLong( - getBlockByNumFromSolidityResult.getString("signature").substring(130, 132), 16); - if (temp < 27) { - v += 27; - } - Assert.assertEquals(Long.parseLong(jsonrpcResult.get("v").toString().substring(2), 16), v); - Assert.assertEquals( - jsonrpcResult.get("r").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(2, 66)); - Assert.assertEquals( - jsonrpcResult.get("s").toString().substring(2), - getBlockByNumFromSolidityResult.getString("signature").substring(66, 130)); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockTransactionCountByHash from solidity") - public void test17JsonRpcApiTestForEthGetBlockTransactionCountByHash() throws Exception { - logger.info("blockNum:" + blockNum); - JsonArray params = new JsonArray(); - params.add(blockHash); - logger.info("blockHash:" + blockHash); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByHash", params); - logger.info("requestBody:" + requestBody); - HttpMethed.waitToProduceOneBlock(httpFullNode); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNumFromjsonRpcNodeForSolidity = Integer.parseInt(transactionNum, 16); - logger.info( - "transactionNumFromjsonRpcNodeForSolidity:" + transactionNumFromjsonRpcNodeForSolidity); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNumFromHttp = responseContent.getInteger("count"); - logger.info("transactionNumFromHttp:" + transactionNumFromHttp); - Assert.assertEquals(transactionNumFromHttp, transactionNumFromjsonRpcNodeForSolidity); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockTransactionCountByNumber from solidity") - public void test18JsonRpcApiTestForEthGetBlockTransactionCountByNum() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockNum); - logger.info(String.valueOf(blockNum)); - JsonObject requestBody = getJsonRpcBody("eth_getBlockTransactionCountByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - HttpMethed.waitToProduceOneBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - String transactionNum = responseContent.getString("result").substring(2); - int transactionNum1 = Integer.parseInt(transactionNum, 16); - logger.info(String.valueOf(transactionNum1)); - response = HttpMethed.getTransactionCountByBlocknumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - int transactionNum2 = responseContent.getInteger("count"); - logger.info(String.valueOf(transactionNum2)); - Assert.assertEquals(transactionNum1, transactionNum2); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getTransactionByBlockHashAndIndex from solidity") - public void test19JsonRpcApiTestForEthGetTransactionByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x" + bid); - params.add(indexHex); - logger.info("indexHex:" + indexHex); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultForGetTransactionByBlockHashAndIndex = responseContent.getJSONObject("result"); - Assert.assertEquals(result, resultForGetTransactionByBlockHashAndIndex); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionByHash from solidity") - public void test20JsonRpcApiTestForEthGetTransactionByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(transacionHash); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject result1 = responseContent.getJSONObject("result"); - Assert.assertEquals(result, result1); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionReceipt from solidity") - public void test21JsonRpcApiTestForEthGetTransactionReceipt() throws Exception { - JsonArray params = new JsonArray(); - Thread.sleep(6000); - params.add(trc20Txid); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionReceipt", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - logger.info("response:" + response); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionReceipt = responseContent.getJSONObject("result"); - logger.info("resultFromTransactionReceipt:" + resultFromTransactionReceipt); - JSONArray logs = resultFromTransactionReceipt.getJSONArray("logs"); - logger.info("logs:" + logs); - logger.info("result:" + resultFromTransactionReceipt.toString()); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - int index = 0; - for (int i = 0; i < responseContent.getJSONArray("transactions").size(); i++) { - if (trc20Txid.equals( - responseContent.getJSONArray("transactions").getJSONObject(i).getString("txID"))) { - index = i; - break; - } - } - - JsonArray paramsForTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(blockNumForTrc20)); - paramsForTransactionByBlockNumberAndIndex.add("0x" + Integer.toHexString(index)); - JsonObject requestBody1 = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", paramsForTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - logger.info("requestBody1:" + requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject resultFromTransactionByBlockNumberAndIndex = responseContent.getJSONObject("result"); - logger.info( - "resultFromTransactionByBlockNumberAndIndex:" + resultFromTransactionByBlockNumberAndIndex); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockHash"), - resultFromTransactionByBlockNumberAndIndex.getString("blockHash")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("blockNumber"), - resultFromTransactionByBlockNumberAndIndex.getString("blockNumber")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionIndex"), - resultFromTransactionByBlockNumberAndIndex.getString("transactionIndex")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("transactionHash"), "0x" + trc20Txid); - Assert.assertEquals( - resultFromTransactionReceipt.getString("from"), - resultFromTransactionByBlockNumberAndIndex.getString("from")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("to"), - resultFromTransactionByBlockNumberAndIndex.getString("to")); - logger.info("effectiveGasPrice:" + resultFromTransactionReceipt.getString("effectiveGasPrice")); - logger.info("gasPriceFromHttp:" + Long.toHexString(gasPriceFromHttp)); - Assert.assertEquals( - resultFromTransactionReceipt.getString("effectiveGasPrice"), - "0x" + Long.toHexString(gasPriceFromHttp)); - /* Assert.assertEquals( - resultFromTransactionReceipt.getString("contractAddress").substring(2), - trc20AddressHex.substring(2));*/ - Assert.assertNull(resultFromTransactionReceipt.getString("contractAddress")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("logsBloom"), - "0x000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000"); - Assert.assertEquals("0x1", resultFromTransactionReceipt.getString("status")); - Assert.assertEquals("0x0", resultFromTransactionReceipt.getString("type")); - logger.info("gas:" + resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("gasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - resultFromTransactionReceipt.getString("cumulativeGasUsed"), - resultFromTransactionByBlockNumberAndIndex.getString("gas")); - Assert.assertEquals( - logs.getJSONObject(0).getString("logIndex"), "0x" + Integer.toHexString(index)); - Assert.assertEquals(logs.getJSONObject(0).getString("removed"), "false"); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockHash"), - resultFromTransactionReceipt.getString("blockHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("blockNumber"), - resultFromTransactionReceipt.getString("blockNumber")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionIndex"), - resultFromTransactionReceipt.getString("transactionIndex")); - Assert.assertEquals( - logs.getJSONObject(0).getString("transactionHash"), - resultFromTransactionReceipt.getString("transactionHash")); - Assert.assertEquals( - logs.getJSONObject(0).getString("address"), resultFromTransactionReceipt.getString("to")); - response = - HttpMethed.getTransactionInfoByBlocknumFromSolidity(httpsolidityNode, blockNumForTrc20); - List responseContent1 = HttpMethed.parseResponseContentArray(response); - logger.info("responseContent1:" + responseContent1); - - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - Assert.assertEquals( - logs.getJSONObject(0).getString("data").substring(2), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("data")); - - Assert.assertEquals( - logs.getJSONObject(0).getString("topics").replace("0x", ""), - responseContent1.get(index).getJSONArray("log").getJSONObject(0).getString("topics")); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getUncleByBlockHashAndIndex from solidity") - public void test22JsonRpcApiTestForEthGetUncleByBlockHashAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockHashAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getUncleByBlockNumberAndIndex from solidity") - public void test23JsonRpcApiTestForEthGetUncleByBlockNumberAndIndex() throws Exception { - JsonArray params = new JsonArray(); - params.add("0xeb82f0"); - params.add("0x"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleByBlockNumberAndIndex", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNull(result); - } - - @Test(enabled = true, description = "Json rpc api of eth_getUncleCountByBlockHash from solidity") - public void test24JsonRpcApiTestForEthGetUncleCountByBlockHash() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000f9cc56243898cbe88685678855e07f51c5af91322c225ce3693868"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getUncleCountByBlockNumber from solidity") - public void test25JsonRpcApiTestForEthGetUncleCountByBlockNumber() throws Exception { - JsonArray params = new JsonArray(); - params.add("eth_getUncleCountByBlockNumber"); - JsonObject requestBody = getJsonRpcBody("eth_getUncleCountByBlockNumber", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "0x0"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getWork from solidity") - public void test26JsonRpcApiTestForEthGetWork() throws Exception { - String resultFromjsonRpcNodeForSolidity = ""; - String resultFromHttp = ""; - for (int i = 0; i < 5; i++) { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - int resultLen = result.length(); - resultFromjsonRpcNodeForSolidity = result.substring(4, resultLen - 12); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - resultFromHttp = responseContent.getString("blockID"); - logger.info("resultFromjsonRpcNodeForSolidity" + i + ":" + resultFromjsonRpcNodeForSolidity); - logger.info("resultFromHttp" + i + ":" + resultFromHttp); - if (resultFromjsonRpcNodeForSolidity.equals(resultFromHttp)) { - break; - } - HttpMethed.waitToProduceOneBlock(httpFullNode); - } - Assert.assertEquals(resultFromjsonRpcNodeForSolidity, resultFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of eth_hashrate from solidity ") - public void test27JsonRpcApiTestForEthHashRate() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_hashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals("0x0", result); - } - - @Test(enabled = true, description = "Json rpc api of eth_mining from solidity") - public void test28JsonRpcApiTestForEthMining() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_mining", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertEquals(result, "true"); - } - - @Test(enabled = true, description = "Json rpc api of eth_protocolVersion from solidity") - public void test29JsonRpcApiTestForEthProtocolVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_protocolVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String protocolVersion = responseContent.getString("result").substring(2); - Long protocolVersion1 = Long.parseLong(protocolVersion, 16); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - Long protocolVersion2 = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("version"); - logger.info(protocolVersion1.toString()); - logger.info(protocolVersion2.toString()); - Assert.assertEquals(protocolVersion1, protocolVersion2); - } - - @Test(enabled = true, description = "Json rpc api of eth_syncing from solidity") - public void test30JsonRpcApiTestForEthSyncing() throws Exception { - long currentNumFromHttp = 0; - long currentNumFromJsonRpc = 0; - JSONObject temp = responseContent; - for (int i = 0; i < 5; i++) { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_syncing", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - temp = responseContent.getJSONObject("result"); - String currentNumFromRpc = temp.getString("currentBlock"); - logger.info(currentNumFromRpc); - logger.info(temp.toString()); - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - currentNumFromHttp = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - currentNumFromJsonRpc = Long.parseLong(currentNumFromRpc.substring(2), 16); - logger.info("currentNumFromHttp" + i + ":" + currentNumFromHttp); - logger.info("currentNumFromJsonRpc:" + currentNumFromJsonRpc); - if (currentNumFromHttp == currentNumFromJsonRpc) { - break; - } - HttpMethed.waitToProduceOneBlock(httpFullNode); - } - Assert.assertEquals(currentNumFromHttp, currentNumFromJsonRpc); - Assert.assertTrue(temp.containsKey("startingBlock")); - Assert.assertTrue(temp.containsKey("currentBlock")); - Assert.assertTrue(temp.containsKey("highestBlock")); - } - - @Test(enabled = true, description = "Json rpc api of net_listening from solidity") - public void test31JsonRpcApiTestForNetListening() throws Exception { - boolean temp = false; - boolean expect = false; - for (int i = 0; i < 5; i++) { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_listening", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - temp = responseContent.getBoolean("result"); - response = HttpMethed.getNodeInfo(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - int num = responseContent.getInteger("activeConnectCount"); - logger.info("num" + i + ":" + num); - if (num >= 1) { - expect = true; - } - logger.info("temp" + i + ":" + temp); - logger.info("expect" + i + ":" + expect); - if (temp == true && expect == true) { - break; - } - HttpMethed.waitToProduceOneBlock(httpFullNode); - } - Assert.assertEquals(expect, temp); - } - - @Test(enabled = true, description = "Json rpc api of net_peerCount from solidity") - public void test32JsonRpcApiTestForNetPeerCount() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_peerCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - logger.info(result); - Assert.assertNotNull(result); - } - - @Test(enabled = true, description = "Json rpc api of net_version from solidity") - public void test33JsonRpcApiTestForEthVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("net_version", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromJsonRpc = responseContent.getString("result").substring(2); - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, 0); - responseContent = HttpMethed.parseResponseContent(response); - String firstBlockHashFromHttp = responseContent.getString("blockID").substring(56); - logger.info("firstBlockHashFromJsonRpc" + firstBlockHashFromJsonRpc); - logger.info("firstBlockHashFromHttp" + firstBlockHashFromHttp); - Assert.assertEquals(firstBlockHashFromJsonRpc, firstBlockHashFromHttp); - } - - @Test(enabled = true, description = "Json rpc api of web3_clientVersion from solidity") - public void test34JsonRpcApiTestForWeb3ClientVersion() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("web3_clientVersion", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String result = responseContent.getString("result"); - List resultList = new ArrayList<>(); - for (String str : result.split("/")) { - resultList.add(str); - } - Assert.assertEquals(resultList.size(), 5); - Assert.assertEquals(resultList.get(0), "TRON"); - Assert.assertEquals(resultList.get(1).substring(0, 1), "v"); - Assert.assertEquals(resultList.get(2), "Linux"); - Assert.assertEquals(resultList.get(3), "Java1.8"); - Assert.assertEquals(resultList.get(4).substring(0, 11), "GreatVoyage"); - } - - @Test(enabled = true, description = "Json rpc api of web3_sha3 from solidity") - public void test35JsonRpcApiTestForWeb3Sha3() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x08"); - JsonObject requestBody1 = getJsonRpcBody("web3_sha3", params); - response = getEthHttps(ethHttpsNode, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String result1 = responseContent.getString("result"); - JsonObject requestBody2 = getJsonRpcBody("web3_sha3", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody2); - responseContent = HttpMethed.parseResponseContent(response); - String result2 = responseContent.getString("result"); - Assert.assertEquals(result1, result2); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileLLL from solidity") - public void test36JsonRpcApiTestForEthCompileLll() throws Exception { - JsonArray params = new JsonArray(); - params.add("(returnlll (suicide (caller)))"); - JsonObject requestBody1 = getJsonRpcBody("eth_compileLLL", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody1); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_compileLLL does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSerpent from solidity") - public void test37JsonRpcApiTestForEthCompileSerpent() throws Exception { - JsonArray params = new JsonArray(); - params.add("/* some serpent */"); - JsonObject requestBody = getJsonRpcBody("eth_compileSerpent", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSerpent does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_compileSolidity from solidity") - public void test38JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - params.add("contract test { function multiply(uint a) returns(uint d) { return a * 7; } }"); - JsonObject requestBody = getJsonRpcBody("eth_compileSolidity", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_compileSolidity does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getCompilers from solidity") - public void test39JsonRpcApiTestForEthCompileSolidity() throws Exception { - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_getCompilers", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getCompilers does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_getTransactionCount from solidity") - public void test40JsonRpcApiTestForEthGetTransactionCount() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x407d73d8a49eeb85d32cf465507dd71d507100c1"); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getTransactionCount", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_getTransactionCount does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendRawTransaction from solidity") - public void test41JsonRpcApiTestForEthSendRawTransaction() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x234"); - JsonObject requestBody = getJsonRpcBody("eth_sendRawTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendRawTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sendTransaction") - public void test42JsonRpcApiTestForEthSendTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_sendTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_sendTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_sign from solidity") - public void test43JsonRpcApiTestForEthSign() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - params.add("0xdeadbeaf"); - JsonObject requestBody = getJsonRpcBody("eth_sign", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_sign does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_signTransaction from solidity") - public void test44JsonRpcApiTestForEthSignTransaction() throws Exception { - JsonArray params = new JsonArray(); - JsonObject temp = new JsonObject(); - params.add(temp); - temp.addProperty( - "data", - "0xd46e8dd67c5d32be8d46e8dd67c5d32be8058bb8eb970870f072445675058bb8eb970870f072445675"); - temp.addProperty("from", "0xb60e8dd61c5d32be8058bb8eb970870f07233155"); - temp.addProperty("gas", "0x76c0"); - temp.addProperty("gasPrice", "0x9184e72a000"); - temp.addProperty("to", "0xd46e8dd67c5d32be8058bb8eb970870f07244567"); - temp.addProperty("value", "0x9184e72a"); - - JsonObject requestBody = getJsonRpcBody("eth_signTransaction", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_signTransaction does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitWork from solidity") - public void test45JsonRpcApiTestForEthSubmitWork() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000001"); - params.add("0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"); - params.add("0xD1GE5700000000000000000000000000D1GE5700000000000000000000000000"); - JsonObject requestBody = getJsonRpcBody("eth_submitWork", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals(errorMessage, "the method eth_submitWork does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of parity_nextNonce from solidity") - public void test46JsonRpcApiTestForParityNextNonce() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x9b2055d370f73ec7d8a03e965129118dc8f5bf83"); - JsonObject requestBody = getJsonRpcBody("parity_nextNonce", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method parity_nextNonce does not exist/is not available"); - } - - @Test(enabled = true, description = "Json rpc api of eth_submitHashrate from solidity") - public void test47JsonRpcApiTestForEthSubmitHashrate() throws Exception { - JsonArray params = new JsonArray(); - params.add("0x0000000000000000000000000000000000000000000000000000000000500000"); - params.add("0x59daa26581d0acd1fce254fb7e85952f4c09d0915afd33d3886cd914bc7d283c"); - JsonObject requestBody = getJsonRpcBody("eth_submitHashrate", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String errorMessage = responseContent.getJSONObject("error").getString("message"); - Assert.assertEquals( - errorMessage, "the method eth_submitHashrate does not exist/is not available"); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByHash params is false from solidity") - public void test48JsonRpcApiTestForEthGetBlockByHash() throws Exception { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNum); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("45getBlockByNumFromSolidityFromHttp:" + responseContent); - accountStateRoot = - responseContent - .getJSONObject("block_header") - .getJSONObject("raw_data") - .getString("accountStateRoot"); - JsonArray params = new JsonArray(); - params.add(blockHash); - params.add(false); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - JSONObject getBlockByHashResult = responseContent.getJSONObject("result"); - - Assert.assertNull(getBlockByHashResult.getString("nonce")); - Assert.assertNull(getBlockByHashResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByHashResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByHashResult.getString("difficulty")); - Assert.assertNull(getBlockByHashResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByHashResult.getString("extraData")); - Assert.assertNull(getBlockByHashResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByHashResult.getString("mixHash")); - Assert.assertEquals(getBlockByHashResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals(getBlockByHashResult.getString("stateRoot"), "0x" + accountStateRoot); - - Assert.assertEquals( - getBlockByHashResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000"); - Assert.assertEquals(getBlockByHashResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByHashResult.getString("hash"), "0x" + bid); - Assert.assertEquals(getBlockByHashResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals(getBlockByHashResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByHashResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals(getBlockByHashResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf(Long.parseLong(getBlockByHashResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - final GrpcAPI.NumberMessage message = - GrpcAPI.NumberMessage.newBuilder().setNum(blockNum).build(); - HttpMethed.waitToProduceOneBlock(httpFullNode); - Block block = blockingStubFull.getBlockByNum(message); - logger.info("sizeFromJrpc:" + block.getSerializedSize()); - logger.info( - "sizeFromJsonRPc:" - + Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16)); - size = block.getSerializedSize(); - Assert.assertEquals( - Long.parseLong(getBlockByHashResult.getString("size").substring(2), 16), - block.getSerializedSize()); - - Long.parseLong(getBlockByHashResult.getString("timestamp").substring(2), 16); - JSONArray transactionId = getBlockByHashResult.getJSONArray("transactions"); - List transactionIdListFromGetBlockByHash = new ArrayList<>(); - if (transactionId.size() > 0) { - for (int i = 0; i < transactionId.size(); i++) { - transactionIdListFromGetBlockByHash.add(transactionId.get(i).toString()); - } - } - Assert.assertEquals(transactionIdListFromGetBlockByHash, transactionIdList); - } - - @Test( - enabled = true, - description = "Json rpc api of eth_getBlockByNumFromSolidityber params is true from solidity") - public void test49JsonRpcApiTestForEthgetBlockByNumFromSolidityber() throws Exception { - - JsonArray params = new JsonArray(); - params.add(blockNumHex); - logger.info("46blockNumHex:" + blockNumHex); - params.add(true); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByNumber", params); - logger.info("requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - JSONObject getBlockByNumFromSolidityberResult = responseContent.getJSONObject("result"); - logger.info("getBlockByHashResult:" + getBlockByNumFromSolidityberResult); - - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("nonce")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("sha3Uncles")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("receiptsRoot")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("difficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("totalDifficulty")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("extraData")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("baseFeePerGas")); - Assert.assertNull(getBlockByNumFromSolidityberResult.getString("mixHash")); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("uncles"), new ArrayList<>().toString()); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("stateRoot"), "0x" + accountStateRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("logsBloom"), - "0x00000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000"); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("number"), blockNumHex); - Assert.assertEquals(getBlockByNumFromSolidityberResult.getString("hash"), "0x" + bid); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("parentHash"), "0x" + parentHash); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("transactionsRoot"), "0x" + txTrieRoot); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("miner"), "0x" + witnessAddress.substring(2)); - Assert.assertEquals( - getBlockByNumFromSolidityberResult.getString("gasUsed"), "0x" + Long.toHexString(gas)); - Assert.assertEquals( - String.valueOf( - Long.parseLong( - getBlockByNumFromSolidityberResult.getString("gasLimit").substring(2), 16)), - feeLimit); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("timestamp").substring(2), 16), - blockTimeStamp); - logger.info("size:" + size); - Assert.assertEquals( - Long.parseLong(getBlockByNumFromSolidityberResult.getString("size").substring(2), 16), - size); - - JSONArray transactionsList = getBlockByNumFromSolidityberResult.getJSONArray("transactions"); - logger.info("transactionsList:" + transactionsList); - List transactionInfoListFromGetBlockByHash = new ArrayList<>(); - if (transactionsList.size() > 0) { - for (int i = 0; i < transactionsList.size(); i++) { - transactionInfoListFromGetBlockByHash.add(transactionsList.get(i).toString()); - } - } - List transactionInfoListFromTransactionByBlockNumberAndIndex = new ArrayList<>(); - for (int i = 0; i < transactionsList.size(); i++) { - JsonArray paramsForEthGetTransactionByBlockNumberAndIndex = new JsonArray(); - paramsForEthGetTransactionByBlockNumberAndIndex.add(blockNumHex); - String index = "0x" + Integer.toHexString(i); - logger.info("index:" + index); - paramsForEthGetTransactionByBlockNumberAndIndex.add(index); - logger.info( - "paramsForEthGetTransactionByBlockNumberAndIndex:" - + paramsForEthGetTransactionByBlockNumberAndIndex); - JsonObject requestBodyForTransactionByBlockNumberAndIndex = - getJsonRpcBody( - "eth_getTransactionByBlockNumberAndIndex", - paramsForEthGetTransactionByBlockNumberAndIndex); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBodyForTransactionByBlockNumberAndIndex); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - result = responseContent.getJSONObject("result"); - logger.info("result:" + result); - transactionInfoListFromTransactionByBlockNumberAndIndex.add(result.toString()); - } - Assert.assertEquals( - transactionInfoListFromGetBlockByHash, - transactionInfoListFromTransactionByBlockNumberAndIndex); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java deleted file mode 100644 index c566fc5532c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts003.java +++ /dev/null @@ -1,373 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; - -@Slf4j -public class Accounts003 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; - - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains address,fromBlock and toBlock.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); - } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNum(httpFullNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter contains topic and address.") - public void test04GetNewFilterContainsTopicAndAddress() { - - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter only contain topic and blockHash.") - public void test05GetNewFilterOnlyContainTopic() { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter which only contains blockHash.") - public void test06GetNewFilterHasOnlyBlockHash() { - - response = HttpMethed.getNowBlock(httpFullNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newFilter check new and after block.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newBlockFilter") - public void test08GetEthNewBlockFilter() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterChanges has less 20 elements.") - public void test09GetFilterChanges() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_getLogs contains address ,fromBlock and toBlock.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } - - @Test(enabled = true, description = "Eth api of eth_getLogs both contains topic and address.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test12GetFilterLogsContainsAddress() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs .") - public void test13GetFilterLogsContainsTopic() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element ") - public void test15EthUninstallFilter() { - // create ID - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java deleted file mode 100644 index 6a1a67f00c4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/Accounts004.java +++ /dev/null @@ -1,388 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; - -@Slf4j -public class Accounts004 extends JsonRpcBase { - JSONObject responseContent; - HttpResponse response; - String topic0 = null; - String topic1 = null; - String fromBlock = null; - String toBlock = null; - String newFilterResultIdfrom01 = null; - String newFilterResultIdfrom02 = null; - String blockHash = null; - - @Test(enabled = true, description = "Eth api of eth_newFilter contains nothing from solidity.") - public void test01GetNewFilterContainNothing() { - JsonObject paramBody = new JsonObject(); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test01GetNewFilterContainNothing_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test01GetNewFilterContainNothing_responseContent" + responseContent); - logger.info("result:" + responseContent.getString("result")); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_newFilter contains address,fromBlock and toBlock from solidity.") - public void test02GetNewFilterContainAddress() { - if (blockNumForTrc20 - 10 < 0) { - fromBlock = "0"; - } else { - fromBlock = "0x" + Integer.toHexString(blockNumForTrc20 - 10); - } - toBlock = "0x" + Integer.toHexString(blockNumForTrc20 + 10); - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test02GetNewFilterContainAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test02GetNewFilterContainAddress_responseContent" + responseContent); - newFilterResultIdfrom01 = responseContent.getString("result"); - logger.info("test02GetNewFilterContainAddress_id:" + responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic fromBlock and toBlock from solidity.") - public void test03GetNewFilterContainTopic() { - response = HttpMethed.getBlockByNumFromSolidity(httpsolidityNode, blockNumForTrc20); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("responseContent:" + responseContent); - logger.info("blockHash:" + responseContent.getString("blockID")); - blockHash = responseContent.getString("blockID"); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test03GetNewFilterContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test03GetNewFilterContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - newFilterResultIdfrom02 = responseContent.getString("result"); - logger.info("test03GetNewFilterContainTopic_id:" + newFilterResultIdfrom02); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter contains topic and address from solidity.") - public void test04GetNewFilterContainsTopicAndAddress() { - - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", fromBlock); - paramBody.addProperty("toBlock", toBlock); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test04GetNewFilterContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test04GetNewFilterContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter only contain topic and blockHash from solidity.") - public void test05GetNewFilterOnlyContainTopic() throws InterruptedException { - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test05GetNewFilterOnlyContainTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test05GetNewFilterOnlyContainTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter which only contains blockHash from solidity.") - public void test06GetNewFilterHasOnlyBlockHash() throws InterruptedException { - response = HttpMethed.getNowBlockFromSolidity(httpsolidityNode); - responseContent = HttpMethed.parseResponseContent(response); - String blockHash = responseContent.getString("blockID"); - Thread.sleep(30000); - JsonObject paramBody = new JsonObject(); - paramBody.addProperty("blockHash", blockHash); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test06GetNewFilterHasOnlyBlockHash_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test06GetNewFilterHasOnlyBlockHash_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_newFilter check new and after block from solidity.") - public void test07GetNewFilterCheckNewBlock() { - JsonObject paramBody = new JsonObject(); - JsonArray topicArray = new JsonArray(); - topicArray.add("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"); - paramBody.add("topics", topicArray); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test07GetNewFilterCheckNewBlock_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test07GetNewFilterCheckNewBlock_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_newBlockFilter from solidity") - public void test08GetEthNewBlockFilter() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test08GetEthNewBlockFilter_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test08GetEthNewBlockFilter_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = "Eth api of eth_getFilterChanges has less 20 elements from solidity.") - public void test09GetFilterChanges() { - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - String newFilterId = responseContent.getString("result"); - logger.info("newFilterId:" + newFilterId); - params = new JsonArray(); - params.add(newFilterId); - requestBody = getJsonRpcBody("eth_getFilterChanges", params); - logger.info("test09GetFilterChanges_requestBody: " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test09GetFilterChanges_responseContent:" + responseContent); - Assert.assertEquals("[]", responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_getLogs contains address ,fromBlock and toBlock from solidity.") - public void test10GetLogsOnlyContainAddress() { - JsonArray addressArray = new JsonArray(); - logger.info("contractTrc20AddressFrom58:" + contractTrc20AddressFrom58); - addressArray.add(contractTrc20AddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - logger.info("blockNumForTrc20:" + blockNumForTrc20); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 20))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 20))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test10GetLogsOnlyContainAddress_requestBody:" + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test10GetLogsOnlyContainAddress_responseContent:" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String address = - responseContent.getJSONArray("result").getJSONObject(0).getString("address").substring(2); - Assert.assertEquals(address, contractTrc20AddressFrom58.substring(2)); - topic0 = responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - } - - @Test( - enabled = true, - description = "Eth api of eth_getLogs both contains topic and address from solidity.") - public void test11GetLogsContainsTopicAndAddress() { - JsonArray topicArray = new JsonArray(); - topicArray.add(topic0); - JsonObject paramBody = new JsonObject(); - paramBody.add("topics", topicArray); - paramBody.addProperty("fromBlock", "0x" + (Integer.toHexString(blockNumForTrc20 - 10))); - paramBody.addProperty("toBlock", "0x" + (Integer.toHexString(blockNumForTrc20 + 10))); - JsonArray params = new JsonArray(); - params.add(paramBody); - HttpMethed.waitToProduceOneBlockFromSolidity(httpFullNode, httpsolidityNode); - JsonObject requestBody = getJsonRpcBody("eth_getLogs", params); - logger.info("test11GetLogsContainsTopicAndAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test11GetLogsContainsTopicAndAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - String topicFromResult = - responseContent.getJSONArray("result").getJSONObject(0).getString("topic"); - Assert.assertEquals(topicFromResult, topic0); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs from solidity.") - public void test12GetFilterLogsContainsAddress() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom01); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test12GetFilterLogsContainsAddress_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test12GetFilterLogsContainsAddress_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test(enabled = true, description = "Eth api of eth_getFilterLogs from solidity.") - public void test13GetFilterLogsContainsTopic() { - - JsonArray params = new JsonArray(); - params.add(newFilterResultIdfrom02); - JsonObject requestBody = getJsonRpcBody("eth_getFilterLogs", params); - logger.info("test13GetFilterLogsContainsTopic_requestBody " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test13GetFilterLogsContainsTopic_responseContent" + responseContent); - Assert.assertNotNull(responseContent.getString("result")); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newFilter from solidity" - + " and params has one element ") - public void test14EthUninstallFilter() { - // create ID - JsonArray addressArray = new JsonArray(); - addressArray.add(contractAddressFrom58.substring(2)); - JsonObject paramBody = new JsonObject(); - paramBody.add("address", addressArray); - paramBody.addProperty("fromBlock", "0x1f8b6a7"); - paramBody.addProperty("toBlock", "0x1f8b6a7"); - JsonArray params = new JsonArray(); - params.add(paramBody); - JsonObject requestBody = getJsonRpcBody("eth_newFilter", params); - logger.info("test14_newfilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_newfilter_responseContentr" + responseContent); - String ethNewFilterResult = responseContent.get("result").toString(); - logger.info("EthNewFilterResult:" + ethNewFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test14_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - logger.info("test14_eth_uninstallFilter_second " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14_eth_uninstallFilter_responseContentr_second " + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test14EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } - - @Test( - enabled = true, - description = - "Eth api of eth_uninstallFilter which method is eth_newBlockFilter" - + " and params has one element from solidity") - public void test15EthUninstallFilter() { - // create ID - - JsonArray params = new JsonArray(); - JsonObject requestBody = getJsonRpcBody("eth_newBlockFilter", params); - logger.info("test15EthUninstallFilter_newBlockFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_newBlockFilter_responseContentr" + responseContent); - String ethNewBlockFilterResult = responseContent.get("result").toString(); - logger.info("ethNewBlockFilterResult:" + ethNewBlockFilterResult); - Assert.assertNotNull(responseContent.getString("result")); - - // verify ID invalid - // first time - params = new JsonArray(); - params.add(responseContent.get("result").toString()); - requestBody = getJsonRpcBody("eth_uninstallFilter", params); - logger.info("test15_eth_uninstallFilter " + requestBody); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_first" + responseContent); - Assert.assertEquals(responseContent.get("result"), true); - // second time - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15_eth_uninstallFilter_responseContentr_second" + responseContent); - Assert.assertEquals( - responseContent.getJSONObject("error").getString("message"), "filter not found"); - // query getFilterChanges to verify ID has invalid - params = new JsonArray(); - params.add(ethNewBlockFilterResult); - requestBody = getJsonRpcBody("getFilterChanges", params); - response = getJsonRpc(jsonRpcNodeForSolidity, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - logger.info("test15EthUninstallFilter_responseContent" + responseContent); - String expectResult = "{\"code\":-32000,\"data\":\"{}\",\"message\":\"filter not found\"}"; - Assert.assertEquals(responseContent.get("error").toString(), expectResult); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/BuildTransaction001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/BuildTransaction001.java deleted file mode 100644 index 0521f094147..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/BuildTransaction001.java +++ /dev/null @@ -1,121 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j - -public class BuildTransaction001 extends JsonRpcBase { - - JSONArray jsonRpcReceives = new JSONArray(); - //String txid; - private JSONObject responseContent; - private HttpResponse response; - String transactionString; - String transactionSignString; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - final String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - - - @Test(enabled = true, description = "Json rpc api of buildTransaction for transfer trx") - public void test01JsonRpcApiTestOfBuildTransactionForTransferTrx() throws Exception { - final Long beforeRecevierBalance = HttpMethed.getBalance(httpFullNode, receiverAddress); - - - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", ByteArray.toHexString(receiverAddress)); - param.addProperty("value", "0x1"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - transactionString = responseContent.getJSONObject("result").getString("transaction"); - transactionSignString = HttpMethed.gettransactionsign(httpFullNode, transactionString, - jsonRpcOwnerKey); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterRecevierBalance = HttpMethed.getBalance(httpFullNode, receiverAddress); - - Assert.assertEquals(afterRecevierBalance - beforeRecevierBalance,1L); - - } - - @Test(enabled = true, description = "Json rpc api of buildTransaction for transfer trc10") - public void test02JsonRpcApiTestOfBuildTransactionForTransferTrc10() throws Exception { - PublicMethed.waitProduceNextBlock(blockingStubFull); - final Long beforeTokenBalance = PublicMethed.getAssetBalanceByAssetId(ByteString - .copyFromUtf8(jsonRpcAssetId), receiverKey, blockingStubFull); - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", ByteArray.toHexString(receiverAddress)); - param.addProperty("tokenId", Long.valueOf(jsonRpcAssetId)); - param.addProperty("tokenValue", 1); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("buildTransaction",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - transactionString = responseContent.getJSONObject("result").getString("transaction"); - transactionSignString = HttpMethed.gettransactionsign(httpFullNode, transactionString, - jsonRpcOwnerKey); - response = HttpMethed.broadcastTransaction(httpFullNode, transactionSignString); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpFullNode); - Long afterTokenBalance = PublicMethed.getAssetBalanceByAssetId(ByteString - .copyFromUtf8(jsonRpcAssetId), receiverKey, blockingStubFull); - - Assert.assertEquals(afterTokenBalance - beforeTokenBalance,1L); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java deleted file mode 100644 index 0fe564ad177..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/EthSmartContract001.java +++ /dev/null @@ -1,80 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - - -@Slf4j - -public class EthSmartContract001 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - - @Test(enabled = true, description = "Json rpc api of eth_call") - public void test01JsonRpcApiTestForEthCall() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x06fdde03"); - JsonArray params = new JsonArray(); - params.add(param); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_call",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals(dataResult,"0x000000000000000000000000000000000000000000000000000" - + "0000000000020000000000000000000000000000000000000000000000000000000000000000a546f6b65" - + "6e545243323000000000000000000000000000000000000000000000"); - } - - - @Test(enabled = true, description = "Json rpc api of eth_estimateGas") - public void test02JsonRpcApiTestForEthEstimateGas() throws Exception { - JsonObject param = new JsonObject(); - param.addProperty("from", ByteArray.toHexString(jsonRpcOwnerAddress)); - param.addProperty("to", trc20AddressHex); - param.addProperty("gas", "0x0"); - param.addProperty("gasPrice", "0x0"); - param.addProperty("value", "0x0"); - param.addProperty("data", "0x1249c58b"); - JsonArray params = new JsonArray(); - params.add(param); - JsonObject requestBody = getJsonRpcBody("eth_estimateGas",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertEquals(dataResult,"0x147"); - } - - - @Test(enabled = true, description = "Json rpc api of eth_getCode") - public void test03JsonRpcApiTestForEthGetCode() throws Exception { - JsonArray params = new JsonArray(); - params.add(trc20AddressHex); - params.add("latest"); - JsonObject requestBody = getJsonRpcBody("eth_getCode",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - String dataResult = responseContent.getString("result"); - Assert.assertTrue(dataResult.length() > 1000L); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/GetBlock001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/GetBlock001.java deleted file mode 100644 index ee30990dd65..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/jsonrpc/GetBlock001.java +++ /dev/null @@ -1,69 +0,0 @@ -package stest.tron.wallet.dailybuild.jsonrpc; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; - - -@Slf4j - -public class GetBlock001 extends JsonRpcBase { - private JSONObject responseContent; - private HttpResponse response; - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - - - - @Test(enabled = true, description = "Json rpc api of eth_getBlockByHash") - public void test01JsonRpcApiTestForEthGetBlockByHash() throws Exception { - JsonArray params = new JsonArray(); - params.add(blockId); - params.add("true"); - JsonObject requestBody = getJsonRpcBody("eth_getBlockByHash",params); - response = getJsonRpc(jsonRpcNode, requestBody); - responseContent = HttpMethed.parseResponseContent(response); - - Assert.assertEquals(Integer.toHexString(blockNum), responseContent.getJSONObject("result") - .getString("number").substring(2)); - Assert.assertEquals(blockId, responseContent.getJSONObject("result").getString("hash") - .substring(2)); - Assert.assertTrue(responseContent.getJSONObject("result") - .getJSONArray("transactions").size() >= 1); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage001.java deleted file mode 100644 index 7dc75caa32f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage001.java +++ /dev/null @@ -1,343 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage001Address = ecKey1.getAddress(); - String linkage001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage001Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = true, description = "Deploy contract with valid or invalid value") - public void deployContentValue() { - Assert.assertTrue(PublicMethed.sendcoin(linkage001Address, 20000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - info = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Value is equal balance,this will be failed.Only use FreeNet,Other not change. - String filePath = "./src/test/resources/soliditycode/contractLinkage001.sol"; - String contractName = "divideIHaveArgsReturnStorage"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String payableCode = retMap.get("byteCode").toString(); - String payableAbi = retMap.get("abI").toString(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account accountGet = PublicMethed.queryAccount(linkage001Key, blockingStubFull); - Long accountBalance = accountGet.getBalance(); - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, payableAbi, - payableCode, "", maxFeeLimit, accountBalance, 100, null, - linkage001Key, linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long fee = infoById.get().getFee(); - Long energyFee = infoById.get().getReceipt().getEnergyFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - - Account infoafter = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertTrue(fee == 0); - Assert.assertTrue(afterNetUsed == 0); - Assert.assertTrue(afterEnergyUsed == 0); - Assert.assertTrue(afterFreeNetUsed > 0); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage001Address, 50000000L, - 0, 1, linkage001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - maxFeeLimit = maxFeeLimit - 50000000L; - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - - //Value is 1,use BalanceGetEnergy,use FreeNet,fee==0. - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, payableAbi, payableCode, - "", maxFeeLimit, 1L, 100, null, linkage001Key, - linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - Long fee1 = infoById1.get().getFee(); - Long energyFee1 = infoById1.get().getReceipt().getEnergyFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - logger.info("fee1:" + fee1); - logger.info("energyFee1:" + energyFee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - Account infoafter1 = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - - Assert.assertTrue(beforeBalance1 - fee1 - 1L == afterBalance1); - byte[] contractAddress = infoById1.get().getContractAddress().toByteArray(); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - Assert.assertTrue(account.getBalance() == 1L); - Assert.assertTrue(afterNetUsed1 == 0); - Assert.assertTrue(afterEnergyUsed1 > 0); - Assert.assertTrue(afterFreeNetUsed1 > 0); - - //Value is account all balance plus 1. balance is not sufficient,Nothing changde. - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - - account = PublicMethed.queryAccount(linkage001Key, blockingStubFull); - Long valueBalance = account.getBalance(); - contractAddress = PublicMethed.deployContract(contractName, payableAbi, payableCode, "", - maxFeeLimit, valueBalance + 1, 100, null, linkage001Key, - linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(contractAddress == null); - Account infoafter2 = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - Assert.assertTrue(afterNetUsed2 == 0); - Assert.assertTrue(afterEnergyUsed2 > 0); - Assert.assertTrue(afterFreeNetUsed2 > 0); - Assert.assertEquals(beforeBalance2, afterBalance2); - - //Value is account all balance.use freezeBalanceGetEnergy ,freezeBalanceGetNet .Balance ==0 - Assert.assertTrue(PublicMethed.freezeBalance(linkage001Address, 5000000L, - 0, linkage001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull); - Account info3 = PublicMethed.queryAccount(linkage001Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyLimit3 = resourceInfo3.getEnergyLimit(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeFreeNetLimit3 = resourceInfo3.getFreeNetLimit(); - Long beforeNetLimit3 = resourceInfo3.getNetLimit(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - logger.info("beforeBalance3:" + beforeBalance3); - logger.info("beforeEnergyLimit3:" + beforeEnergyLimit3); - logger.info("beforeEnergyUsed3:" + beforeEnergyUsed3); - logger.info("beforeFreeNetLimit3:" + beforeFreeNetLimit3); - logger.info("beforeNetLimit3:" + beforeNetLimit3); - logger.info("beforeNetUsed3:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed3:" + beforeFreeNetUsed3); - account = PublicMethed.queryAccount(linkage001Key, blockingStubFull); - valueBalance = account.getBalance(); - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, payableAbi, payableCode, - "", maxFeeLimit, valueBalance, 100, null, linkage001Key, - linkage001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - fee = infoById.get().getFee(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Account infoafter3 = PublicMethed.queryAccount(linkage001Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(linkage001Address, - blockingStubFull1); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyLimit3 = resourceInfoafter3.getEnergyLimit(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterFreeNetLimit3 = resourceInfoafter3.getFreeNetLimit(); - Long afterNetLimit3 = resourceInfoafter3.getNetLimit(); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - logger.info("afterBalance3:" + afterBalance3); - logger.info("afterEnergyLimit3:" + afterEnergyLimit3); - logger.info("afterEnergyUsed3:" + afterEnergyUsed3); - logger.info("afterFreeNetLimit3:" + afterFreeNetLimit3); - logger.info("afterNetLimit3:" + afterNetLimit3); - logger.info("afterNetUsed3:" + afterNetUsed3); - logger.info("afterFreeNetUsed3:" + afterFreeNetUsed3); - - Assert.assertTrue(afterNetUsed3 > 0); - Assert.assertTrue(afterEnergyUsed3 > 0); - Assert.assertTrue(afterFreeNetUsed3 > 0); - Assert.assertTrue(beforeBalance2 - fee == afterBalance2); - Assert.assertTrue(afterBalance3 == 0); - Assert.assertTrue(PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance() == valueBalance); - PublicMethed - .unFreezeBalance(linkage001Address, linkage001Key, 1, - linkage001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(linkage001Address, linkage001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage005.java deleted file mode 100644 index 691ce5dadab..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage005.java +++ /dev/null @@ -1,345 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage005 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - String contractName; - String code; - String abi; - Long zeroForCycleCost; - Long firstForCycleCost; - Long secondForCycleCost; - Long thirdForCycleCost; - Long forthForCycleCost; - Long fifthForCycleCost; - Long zeroForCycleTimes = 498L; - Long firstForCycleTimes = 500L; - Long secondForCycleTimes = 502L; - Long thirdForCycleTimes = 504L; - Long forthForCycleTimes = 506L; - Long fifthForCycleTimes = 508L; - byte[] contractAddress; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage005Address = ecKey1.getAddress(); - String linkage005Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage005Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Every same trigger use same energy and net") - public void testEnergyCostDetail() { - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Assert.assertTrue(PublicMethed.sendcoin(linkage005Address, 5000000000000L, fromAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(linkage005Address, 250000000000L, - 0, linkage005Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage005Address, 250000000000L, - 0, 1, linkage005Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(linkage005Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage005.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 0L, 100, null, linkage005Key, - linkage005Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Account infoafter = PublicMethed.queryAccount(linkage005Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("---------------:"); - long fee = infoById.get().getFee(); - - Assert.assertTrue(beforeBalance - fee == afterBalance); - //Assert.assertTrue(afterEnergyUsed > 0); - //Assert.assertTrue(afterFreeNetUsed > 0); - firstForCycleTimes = 1000L; - secondForCycleTimes = 1002L; - thirdForCycleTimes = 1004L; - - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage005Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - byte[] contractAddress = infoById.get().getContractAddress().toByteArray(); - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", firstForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Account infoafter1 = PublicMethed.queryAccount(linkage005Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("---------------:"); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - fee = infoById.get().getFee(); - firstForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - Assert.assertTrue((beforeBalance1 - fee) == afterBalance1); - Assert.assertTrue(afterEnergyUsed1 > beforeEnergyUsed1); - Assert.assertTrue(afterNetUsed1 > beforeNetUsed1); - //use EnergyUsed and NetUsed.balance not change - - String txid6 = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", secondForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - final String txid7 = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", thirdForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid6, blockingStubFull); - secondForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid7, blockingStubFull); - thirdForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - Assert.assertTrue(thirdForCycleCost - secondForCycleCost - == secondForCycleCost - firstForCycleCost); - - zeroForCycleTimes = 498L; - firstForCycleTimes = 500L; - secondForCycleTimes = 502L; - thirdForCycleTimes = 504L; - forthForCycleTimes = 506L; - fifthForCycleTimes = 508L; - AccountResourceMessage resourceInfo4 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull); - Account info4 = PublicMethed.queryAccount(linkage005Address, blockingStubFull); - Long beforeBalance4 = info4.getBalance(); - Long beforeEnergyLimit4 = resourceInfo4.getEnergyLimit(); - Long beforeEnergyUsed4 = resourceInfo4.getEnergyUsed(); - Long beforeFreeNetLimit4 = resourceInfo4.getFreeNetLimit(); - Long beforeNetLimit4 = resourceInfo4.getNetLimit(); - Long beforeNetUsed4 = resourceInfo4.getNetUsed(); - Long beforeFreeNetUsed4 = resourceInfo4.getFreeNetUsed(); - logger.info("beforeBalance4:" + beforeBalance4); - logger.info("beforeEnergyLimit4:" + beforeEnergyLimit4); - logger.info("beforeEnergyUsed4:" + beforeEnergyUsed4); - logger.info("beforeFreeNetLimit4:" + beforeFreeNetLimit4); - logger.info("beforeNetLimit4:" + beforeNetLimit4); - logger.info("beforeNetUsed4:" + beforeNetUsed4); - logger.info("beforeFreeNetUsed4:" + beforeFreeNetUsed4); - txid = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", zeroForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - fee = infoById.get().getFee(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Account infoafter4 = PublicMethed.queryAccount(linkage005Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter4 = PublicMethed.getAccountResource(linkage005Address, - blockingStubFull1); - Long afterBalance4 = infoafter4.getBalance(); - Long afterEnergyLimit4 = resourceInfoafter4.getEnergyLimit(); - Long afterEnergyUsed4 = resourceInfoafter4.getEnergyUsed(); - Long afterFreeNetLimit4 = resourceInfoafter4.getFreeNetLimit(); - Long afterNetLimit4 = resourceInfoafter4.getNetLimit(); - Long afterNetUsed4 = resourceInfoafter4.getNetUsed(); - Long afterFreeNetUsed4 = resourceInfoafter4.getFreeNetUsed(); - logger.info("afterBalance4:" + afterBalance4); - logger.info("afterEnergyLimit4:" + afterEnergyLimit4); - logger.info("afterEnergyUsed4:" + afterEnergyUsed4); - logger.info("afterFreeNetLimit4:" + afterFreeNetLimit4); - logger.info("afterNetLimit4:" + afterNetLimit4); - logger.info("afterNetUsed4:" + afterNetUsed4); - logger.info("afterFreeNetUsed4:" + afterFreeNetUsed4); - logger.info("---------------:"); - Assert.assertTrue(beforeBalance4 - fee == afterBalance4); - Assert.assertTrue(afterEnergyUsed4 > beforeEnergyUsed4); - Assert.assertTrue(afterNetUsed4 > beforeNetUsed4); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - zeroForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - String txid1 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", firstForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid2 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", secondForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid3 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", thirdForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid4 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", forthForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - final String txid5 = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", fifthForCycleTimes.toString(), false, - 0, 100000000L, linkage005Address, linkage005Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - firstForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - secondForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - thirdForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid4, blockingStubFull); - forthForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - infoById = PublicMethed.getTransactionInfoById(txid5, blockingStubFull); - fifthForCycleCost = infoById.get().getReceipt().getEnergyUsageTotal(); - - Assert.assertTrue(thirdForCycleCost - secondForCycleCost - == secondForCycleCost - firstForCycleCost); - Assert.assertTrue(fifthForCycleCost - forthForCycleCost - == forthForCycleCost - thirdForCycleCost); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(linkage005Address, linkage005Key, 1, - linkage005Address, blockingStubFull); - PublicMethed.unFreezeBalance(linkage005Address, linkage005Key, 0, - linkage005Address, blockingStubFull); - PublicMethed.freedResource(linkage005Address, linkage005Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage006.java deleted file mode 100644 index 74fde7b7fc6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractLinkage006.java +++ /dev/null @@ -1,331 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractLinkage006 { - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey003); - String contractName; - String code; - String abi; - byte[] contractAddress; - String txid; - Optional infoById; - String initParmes; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] linkage006Address = ecKey1.getAddress(); - String linkage006Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] linkage006Address2 = ecKey2.getAddress(); - String linkage006Key2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(linkage006Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Deploy contract with stack function") - public void teststackOutByContract() { - - Assert.assertTrue(PublicMethed.sendcoin(linkage006Address, 20000000000L, fromAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(linkage006Address, 1000000L, - 0, linkage006Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage006Address, 1000000L, - 0, 1, linkage006Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(linkage006Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(linkage006Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyLimit = resourceInfo.getEnergyLimit(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeFreeNetLimit = resourceInfo.getFreeNetLimit(); - Long beforeNetLimit = resourceInfo.getNetLimit(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyLimit:" + beforeEnergyLimit); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeFreeNetLimit:" + beforeFreeNetLimit); - logger.info("beforeNetLimit:" + beforeNetLimit); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/contractLinkage006.sol"; - String contractName = "AA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - //success ,balnace change.use EnergyUsed and NetUsed - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, 1000L, 100, null, linkage006Key, - linkage006Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid is " + txid); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long fee = infoById.get().getFee(); - Long energyFee = infoById.get().getReceipt().getEnergyFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("fee:" + fee); - logger.info("energyFee:" + energyFee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - Account infoafter = PublicMethed.queryAccount(linkage006Address, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(linkage006Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyLimit = resourceInfoafter.getEnergyLimit(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterFreeNetLimit = resourceInfoafter.getFreeNetLimit(); - Long afterNetLimit = resourceInfoafter.getNetLimit(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyLimit:" + afterEnergyLimit); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterFreeNetLimit:" + afterFreeNetLimit); - logger.info("afterNetLimit:" + afterNetLimit); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue((beforeBalance - fee - 1000L) == afterBalance); - Assert.assertTrue((beforeNetUsed + netUsed) >= afterNetUsed); - Assert.assertTrue((beforeEnergyUsed + energyUsed) >= afterEnergyUsed); - PublicMethed.unFreezeBalance(linkage006Address, linkage006Key, 1, - null, blockingStubFull); - } - - @Test(enabled = true, description = "Boundary value for contract stack(63 is the largest level)") - public void teststackOutByContract1() { - Assert.assertTrue(PublicMethed.sendcoin(linkage006Address2, 20000000000L, fromAddress, - testKey003, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalance(linkage006Address2, 1000000L, - 0, linkage006Key2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(linkage006Address2, 1000000L, - 0, 1, linkage006Key2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(linkage006Address2, - blockingStubFull); - Account info1 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyLimit1 = resourceInfo1.getEnergyLimit(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeFreeNetLimit1 = resourceInfo1.getFreeNetLimit(); - Long beforeNetLimit1 = resourceInfo1.getNetLimit(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeEnergyLimit1:" + beforeEnergyLimit1); - logger.info("beforeEnergyUsed1:" + beforeEnergyUsed1); - logger.info("beforeFreeNetLimit1:" + beforeFreeNetLimit1); - logger.info("beforeNetLimit1:" + beforeNetLimit1); - logger.info("beforeNetUsed1:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed1:" + beforeFreeNetUsed1); - - //success ,balance change.use EnergyUsed and NetUsed - initParmes = "\"" + Base58.encode58Check(fromAddress) + "\",\"63\""; - txid = PublicMethed.triggerContract(contractAddress, - "init(address,uint256)", initParmes, false, - 0, 100000000L, linkage006Address2, linkage006Key2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - Long fee1 = infoById1.get().getFee(); - Long energyFee1 = infoById1.get().getReceipt().getEnergyFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - logger.info("fee1:" + fee1); - logger.info("energyFee1:" + energyFee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - Account infoafter1 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull1); - AccountResourceMessage resourceInfoafter1 = PublicMethed - .getAccountResource(linkage006Address2, - blockingStubFull1); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyLimit1 = resourceInfoafter1.getEnergyLimit(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterFreeNetLimit1 = resourceInfoafter1.getFreeNetLimit(); - Long afterNetLimit1 = resourceInfoafter1.getNetLimit(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyLimit1:" + afterEnergyLimit1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterFreeNetLimit1:" + afterFreeNetLimit1); - logger.info("afterNetLimit1:" + afterNetLimit1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("---------------:"); - Assert.assertTrue((beforeBalance1 - fee1) == afterBalance1); - Assert.assertTrue(afterNetUsed1 > beforeNetUsed1); - Assert.assertTrue((beforeEnergyUsed1 + energyUsed1) >= afterEnergyUsed1); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Boundary value for contract stack" - + "(Trigger 64 level can't success)") - public void teststackOutByContract2() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - initParmes = "\"" + Base58.encode58Check(fromAddress) + "\",\"64\""; - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(linkage006Address2, - blockingStubFull); - Account info2 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyLimit2 = resourceInfo2.getEnergyLimit(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeFreeNetLimit2 = resourceInfo2.getFreeNetLimit(); - Long beforeNetLimit2 = resourceInfo2.getNetLimit(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - logger.info("beforeBalance2:" + beforeBalance2); - logger.info("beforeEnergyLimit2:" + beforeEnergyLimit2); - logger.info("beforeEnergyUsed2:" + beforeEnergyUsed2); - logger.info("beforeFreeNetLimit2:" + beforeFreeNetLimit2); - logger.info("beforeNetLimit2:" + beforeNetLimit2); - logger.info("beforeNetUsed2:" + beforeNetUsed2); - logger.info("beforeFreeNetUsed2:" + beforeFreeNetUsed2); - //failed ,use EnergyUsed and NetUsed - txid = PublicMethed.triggerContract(contractAddress, - "init(address,uint256)", initParmes, false, - 1000, 100000000L, linkage006Address2, linkage006Key2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - Long fee2 = infoById2.get().getFee(); - Long energyFee2 = infoById2.get().getReceipt().getEnergyFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - logger.info("fee2:" + fee2); - logger.info("energyFee2:" + energyFee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - - Account infoafter2 = PublicMethed.queryAccount(linkage006Address2, blockingStubFull1); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(linkage006Address2, - blockingStubFull1); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyLimit2 = resourceInfoafter2.getEnergyLimit(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterFreeNetLimit2 = resourceInfoafter2.getFreeNetLimit(); - Long afterNetLimit2 = resourceInfoafter2.getNetLimit(); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - logger.info("afterBalance2:" + afterBalance2); - logger.info("afterEnergyLimit2:" + afterEnergyLimit2); - logger.info("afterEnergyUsed2:" + afterEnergyUsed2); - logger.info("afterFreeNetLimit2:" + afterFreeNetLimit2); - logger.info("afterNetLimit2:" + afterNetLimit2); - logger.info("afterNetUsed2:" + afterNetUsed2); - logger.info("afterFreeNetUsed2:" + afterFreeNetUsed2); - - Assert.assertTrue((beforeBalance2 - fee2) == afterBalance2); - Assert.assertTrue((beforeEnergyUsed2 + energyUsed2) >= afterEnergyUsed2); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - PublicMethed.unFreezeBalance(linkage006Address2, linkage006Key2, 1, - linkage006Address2, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(linkage006Address, linkage006Key, 1, - linkage006Address, blockingStubFull); - PublicMethed.unFreezeBalance(linkage006Address, linkage006Key, 0, - linkage006Address, blockingStubFull); - PublicMethed.unFreezeBalance(linkage006Address2, linkage006Key2, 1, - linkage006Address2, blockingStubFull); - PublicMethed.unFreezeBalance(linkage006Address2, linkage006Key2, 0, - linkage006Address2, blockingStubFull); - PublicMethed.freedResource(linkage006Address, linkage006Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(linkage006Address2, linkage006Key2, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario002.java deleted file mode 100644 index fe16f92575c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario002.java +++ /dev/null @@ -1,239 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract002Address = ecKey1.getAddress(); - String contract002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String txid; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract002Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = true, description = "Deploy contract with java-tron support interface") - public void test01DeployTronNative() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract002Address = ecKey1.getAddress(); - String contract002Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(contract002Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract002Address, 1000000L, - 0, 1, contract002Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract002Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(contract002Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String contractName = "TronNative"; - String filePath = "./src/test/resources/soliditycode/contractScenario002.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract002Key, contract002Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - logger.info(txid); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress.toByteArray(), blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed.getAccountResource(contract002Address, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - Long balanceAfter = PublicMethed.queryAccount(contract002Address, blockingStubFull1) - .getBalance(); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after balance is " + Long.toString(balanceAfter)); - logger.info("transaction fee is " + Long.toString(infoById.get().getFee())); - - Assert.assertTrue(energyUsage > 0); - Assert.assertTrue(balanceBefore == balanceAfter + infoById.get().getFee()); - PublicMethed.unFreezeBalance(contract002Address, contract002Key, 1, - contract002Address, blockingStubFull); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get smart contract with invalid address") - public void test02GetContractWithInvalidAddress() { - byte[] contractAddress = contract002Address; - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - logger.info(smartContract.getAbi().toString()); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from solidity") - public void test03GetTransactionByIdFromSolidity() { - Assert.assertFalse(PublicMethed.getTransactionById(txid, blockingStubSolidity) - .get().getSignature(0).isEmpty()); - Assert.assertEquals(PublicMethed.getTransactionById(txid, blockingStubFull), - PublicMethed.getTransactionById(txid, blockingStubSolidity)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from PBFT") - public void test04GetTransactionByIdFromPbft() { - Assert.assertFalse(PublicMethed.getTransactionById(txid, blockingStubPbft) - .get().getSignature(0).isEmpty()); - Assert.assertEquals(PublicMethed.getTransactionById(txid, blockingStubSoliInFull), - PublicMethed.getTransactionById(txid, blockingStubPbft)); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from Solidity") - public void test05GetTransactionInfoByIdFromSolidity() throws Exception { - long netUsage = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get().getReceipt() - .getNetUsage(); - - Assert.assertEquals(PublicMethed.getTransactionInfoByIdFromSolidity(txid, blockingStubSolidity) - .get().getReceipt().getNetUsage(), netUsage); - - Assert - .assertEquals(PublicMethed.getTransactionInfoByIdFromSolidity(txid, blockingStubSoliInFull) - .get().getReceipt().getNetUsage(), netUsage); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get transaction by id from PBFT") - public void test06GetTransactionInfoByIdFromPbft() { - long energyUsage = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get() - .getReceipt() - .getEnergyUsage(); - - Assert.assertEquals(PublicMethed.getTransactionInfoByIdFromSolidity(txid, blockingStubPbft) - .get().getReceipt().getEnergyUsage(), energyUsage); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contract002Address, contract002Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario011.java deleted file mode 100644 index c0630d1e6eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario011.java +++ /dev/null @@ -1,511 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.springframework.util.StringUtils; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String kittyCoreAddressAndCut = ""; - byte[] kittyCoreContractAddress = null; - byte[] saleClockAuctionContractAddress = null; - byte[] siringClockAuctionContractAddress = null; - byte[] geneScienceInterfaceContractAddress = null; - Integer consumeUserResourcePercent = 50; - String txid = ""; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] deployAddress = ecKey1.getAddress(); - String deployKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] triggerAddress = ecKey2.getAddress(); - String triggerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(deployKey); - PublicMethed.printAddress(triggerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.sendcoin(triggerAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Kitty Core\"") - public void deployErc721KittyCore() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(deployAddress, 100000000L, - 0, 1, deployKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Assert.assertTrue(PublicMethed.freezeBalance(deployAddress, 100000000L, 0, - deployKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - Assert.assertTrue(PublicMethed.freezeBalance(triggerAddress, 100000000L, 0, - triggerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployAddress, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "KittyCore"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - logger.info("Kitty Core"); - kittyCoreContractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(kittyCoreContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress).substring(2)); - - kittyCoreAddressAndCut = "000000000000000000000000" + ByteArray - .toHexString(kittyCoreContractAddress).substring(2); - kittyCoreAddressAndCut = kittyCoreAddressAndCut + "0000000000000000000000000000000000000000000" - + "000000000000000000100"; - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Sale Clock Auction\"") - public void deploySaleClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "SaleClockAuction"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - logger.info("Sale Clock Auction"); - //saleClockAuctionContractAddress; - String data = "\"" + Base58.encode58Check(kittyCoreContractAddress) + "\"," + 100; - String deplTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address,uint256)", - data, "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, deployAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - - saleClockAuctionContractAddress = info.get().getContractAddress().toByteArray(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(saleClockAuctionContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - - String triggerTxid = PublicMethed - .triggerContract(saleClockAuctionContractAddress, "isSaleClockAuction()", "#", false, 0, - maxFeeLimit, deployAddress, deployKey, blockingStubFull); - Optional inFoByid = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Ttttt " + triggerTxid); - Assert.assertTrue(inFoByid.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Siring Clock Auction\"") - public void deploySiringClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "SiringClockAuction"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String data = "\"" + Base58.encode58Check(kittyCoreContractAddress) + "\"," + 100; - String siringClockAuctionContractAddressTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address,uint256)", - data, - "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info2 = PublicMethed - .getTransactionInfoById(siringClockAuctionContractAddressTxid, blockingStubFull); - siringClockAuctionContractAddress = info2.get().getContractAddress().toByteArray(); - Assert.assertTrue(info2.get().getResultValue() == 0); - SmartContract smartContract = PublicMethed.getContract(siringClockAuctionContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - } - - @Test(enabled = true, description = "Deploy Erc721 contract \"Gene Science Interface\"") - public void deployGeneScienceInterface() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - String contractName = "GeneScienceInterface"; - String filePath = "./src/test/resources/soliditycode/contractScenario011.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, - "", maxFeeLimit, - 0L, consumeUserResourcePercent, null, deployKey, deployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - geneScienceInterfaceContractAddress = info2.get().getContractAddress().toByteArray(); - Assert.assertTrue(info2.get().getResultValue() == 0); - - SmartContract smartContract = PublicMethed.getContract(geneScienceInterfaceContractAddress, - blockingStubFull); - Assert.assertFalse(StringUtils.isEmpty(smartContract.getBytecode())); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - cpuUsage = accountResource.getEnergyUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - } - - @Test(enabled = true, description = "Set three contract address for Kitty Core, " - + "set three CXO roles") - public void triggerToSetThreeContractAddressToKittyCore() { - //Set SaleAuctionAddress to kitty core. - String saleContractString = "\"" + Base58.encode58Check(saleClockAuctionContractAddress) + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "setSaleAuctionAddress(address)", - saleContractString, false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - //Set SiringAuctionAddress to kitty core. - String siringContractString = "\"" + Base58.encode58Check(siringClockAuctionContractAddress) - + "\""; - txid = PublicMethed - .triggerContract(kittyCoreContractAddress, "setSiringAuctionAddress(address)", - siringContractString, false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - logger.info(txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - //Set gen contract to kitty core - String genContractString = "\"" + Base58.encode58Check(geneScienceInterfaceContractAddress) - + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setGeneScienceAddress(address)", genContractString, - false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - //Start the game. - Integer result = 1; - Integer times = 0; - while (result == 1) { - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "unpause()", "", false, 0, - 10000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - result = infoById.get().getResultValue(); - if (times++ == 3) { - break; - } - } - - Assert.assertTrue(result == 0); - logger.info("start the game " + txid); - - //Create one gen0 cat. - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "-1000000000000000", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "gen0CreatedCount()", "#", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "getKitty(uint256)", "1", false, 0, 10000000, triggerAddress, - triggerKey, blockingStubFull); - logger.info("getKitty " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - String newCxoAddress = "\"" + Base58.encode58Check(triggerAddress) - + "\""; - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCOO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("COO " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCFO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CFO " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCEO(address)", newCxoAddress, false, 0, 1000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CEO " + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = true, description = "Create Gen0 cat") - public void triggerUseTriggerEnergyUsage() { - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] triggerUseTriggerEnergyUsageAddress = ecKey3.getAddress(); - final String triggerUseTriggerEnergyUsageKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(triggerUseTriggerEnergyUsageAddress, 100000000000L, - fromAddress, testKey002, blockingStubFull)); - String newCxoAddress = "\"" + Base58.encode58Check(triggerUseTriggerEnergyUsageAddress) - + "\""; - PublicMethed.waitProduceNextBlock(blockingStubFull); - final String txid1; - final String txid2; - final String txid3; - txid1 = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCOO(address)", newCxoAddress, false, 0, maxFeeLimit, triggerAddress, - triggerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("COO " + txid); - - txid2 = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCFO(address)", newCxoAddress, false, 0, maxFeeLimit, triggerAddress, - triggerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("CFO " + txid); - - txid3 = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCEO(address)", newCxoAddress, false, 0, maxFeeLimit, triggerAddress, - triggerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("CEO " + txid); - - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - infoById = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - infoById = PublicMethed.getTransactionInfoById(txid3, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long beforeBalance = PublicMethed - .queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull).getBalance(); - logger.info("before balance is " + Long.toString(beforeBalance)); - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "0", false, - 0, 100000000L, triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - logger.info("Q " + Long - .toString(infoById.get().getReceipt().getEnergyFee())); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsage() == 0); - Assert.assertTrue(infoById.get().getReceipt().getEnergyFee() > 10000); - // Assert.assertTrue(infoById.get().getReceipt().getOriginEnergyUsage() > 10000); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() - == infoById.get().getReceipt().getEnergyFee() / 100 + infoById.get().getReceipt() - .getOriginEnergyUsage()); - - Long fee = infoById.get().getFee(); - Long afterBalance = PublicMethed - .queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull1).getBalance(); - logger.info("after balance is " + Long.toString(afterBalance)); - logger.info("fee is " + Long.toString(fee)); - Assert.assertTrue(beforeBalance == afterBalance + fee); - - logger.info("before EnergyUsage is " + infoById.get().getReceipt().getEnergyUsage()); - logger.info("before EnergyFee is " + infoById.get().getReceipt().getEnergyFee()); - logger.info("before OriginEnergyUsage is " + infoById.get().getReceipt() - .getOriginEnergyUsage()); - logger.info("before EnergyTotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue( - PublicMethed.freezeBalanceGetEnergy(triggerUseTriggerEnergyUsageAddress, 100000000L, - 0, 1, triggerUseTriggerEnergyUsageKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - beforeBalance = PublicMethed.queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull) - .getBalance(); - logger.info("before balance is " + Long.toString(beforeBalance)); - - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(triggerUseTriggerEnergyUsageAddress, blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - logger.info("before EnergyLimit is " + Long.toString(energyLimit)); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "0", false, - 0, 100000000L, triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull1); - logger.info("after EnergyUsage is " + infoById.get().getReceipt().getEnergyUsage()); - logger.info("after EnergyFee is " + infoById.get().getReceipt().getEnergyFee()); - logger.info("after OriginEnergyUsage is " + infoById.get().getReceipt().getOriginEnergyUsage()); - logger.info("after EnergyTotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - fee = infoById.get().getFee(); - afterBalance = PublicMethed.queryAccount(triggerUseTriggerEnergyUsageKey, blockingStubFull1) - .getBalance(); - logger.info("after balance is " + Long.toString(afterBalance)); - logger.info("fee is " + Long.toString(fee)); - - accountResource = PublicMethed - .getAccountResource(triggerUseTriggerEnergyUsageAddress, blockingStubFull1); - energyLimit = accountResource.getEnergyLimit(); - - logger.info("after EnergyLimit is " + Long.toString(energyLimit)); - - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsage() > 10000); - Assert.assertTrue(infoById.get().getReceipt().getEnergyFee() == 0); - - //Assert.assertTrue(infoById.get().getReceipt().getOriginEnergyUsage() > 10000); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() == infoById.get() - .getReceipt().getEnergyUsage() + infoById.get().getReceipt().getOriginEnergyUsage()); - // Assert.assertTrue(infoById.get().getReceipt().getEnergyUsage() == infoById.get() - // .getReceipt().getOriginEnergyUsage()); - - Assert.assertTrue(beforeBalance == afterBalance + fee); - PublicMethed.unFreezeBalance(deployAddress, deployKey, 1, - deployAddress, blockingStubFull); - PublicMethed.unFreezeBalance(triggerAddress, triggerKey, 1, - triggerAddress, blockingStubFull); - - PublicMethed - .unFreezeBalance(triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, 1, - triggerUseTriggerEnergyUsageAddress, blockingStubFull); - PublicMethed.freedResource(triggerUseTriggerEnergyUsageAddress, triggerUseTriggerEnergyUsageKey, - fromAddress, blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario014.java deleted file mode 100644 index 7e11bc176dd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario014.java +++ /dev/null @@ -1,231 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario014 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress1 = null; - byte[] contractAddress2 = null; - byte[] contractAddress3 = null; - String txid = ""; - Optional infoById = null; - String contractName = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract014Address = ecKey1.getAddress(); - String contract014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String priKey014 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey2.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Triple trigger in smart contract") - public void testTripleTrigger() { - - ecKey2 = new ECKey(Utils.getRandom()); - receiverAddress = ecKey2.getAddress(); - receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(contract014Key); - PublicMethed.printAddress(receiverKey); - - Assert.assertTrue(PublicMethed.sendcoin(contract014Address, 50_000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceGetEnergy(contract014Address, 10_000_000_000L, 0, 1, priKey014, - blockingStubFull)); - - logger.info("contract014Address : == " + contract014Key); - //Deploy contract1, contract1 has a function to transaction 5 sun to target account - String contractName = "Contract1"; - String filePath = "./src/test/resources/soliditycode/contractScenario014.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100, null, contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - - //Deploy contract2, contract2 has a function to call contract1 transaction sun function. - // and has a revert function. - contractName = "contract2"; - String filePath1 = "./src/test/resources/soliditycode/contractScenario014.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String parame = "\"" + Base58.encode58Check(contractAddress1) + "\""; - - txid = PublicMethed.deployContractWithConstantParame(contractName, abi1, code1, - "constructor(address)", parame, "", maxFeeLimit, 1000000L, 100, null, - contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress2 = infoById.get().getContractAddress().toByteArray(); - - //Deploy contract3, trigger contrct2 function. - contractName = "contract3"; - String filePath2 = "./src/test/resources/soliditycode/contractScenario014.sol"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - parame = "\"" + Base58.encode58Check(contractAddress2) + "\""; - - txid = PublicMethed.deployContractWithConstantParame(contractName, abi2, code2, - "constructor(address)", parame, "", maxFeeLimit, 1000000L, 100, null, - contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress3 = infoById.get().getContractAddress().toByteArray(); - - Assert.assertTrue(PublicMethed.sendcoin(receiverAddress, 1000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Test contract2 trigger contract1 to test call function - Account contract2AccountInfo = PublicMethed.queryAccount(contractAddress2, blockingStubFull); - final Long contract2BeforeBalance = contract2AccountInfo.getBalance(); - Account receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - Long receiverBeforeBalance = receiverAccountInfo.getBalance(); - Account contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - Long contract1BeforeBalance = contract1AccountInfo.getBalance(); - logger.info("before contract1 balance is " + Long.toString(contract1BeforeBalance)); - logger.info("before receiver balance is " + Long.toString(receiverBeforeBalance)); - String receiveAddress = "\"" + Base58.encode58Check(receiverAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress2, - "triggerContract1(address)", receiveAddress, false, - 0, maxFeeLimit, contract014Address, contract014Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contract2AccountInfo = PublicMethed.queryAccount(contractAddress2, blockingStubFull); - final Long contract2AfterBalance = contract2AccountInfo.getBalance(); - //contract2AccountInfo.getAccountResource().getFrozenBalanceForEnergy(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - Long receiverAfterBalance = receiverAccountInfo.getBalance(); - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - Long contract1AfterBalance = contract1AccountInfo.getBalance(); - logger.info("after contract1 balance is " + Long.toString(contract1AfterBalance)); - Assert.assertTrue(receiverAfterBalance - receiverBeforeBalance == 5); - Assert.assertTrue(contract2BeforeBalance - contract2AfterBalance == 0); - Assert.assertTrue(contract1BeforeBalance - contract1AfterBalance == 5); - - //Test contract2 trigger contract1 but revert - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1BeforeBalance = contract1AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverBeforeBalance = receiverAccountInfo.getBalance(); - receiveAddress = "\"" + Base58.encode58Check(receiverAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress2, - "triggerContract1ButRevert(address)", receiveAddress, false, - 0, 10000000L, contract014Address, contract014Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1AfterBalance = contract1AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverAfterBalance = receiverAccountInfo.getBalance(); - logger.info("after receiver balance is " + Long.toString(receiverAfterBalance)); - Assert.assertTrue(receiverAfterBalance - receiverBeforeBalance == 0); - Assert.assertTrue(contract1BeforeBalance - contract1AfterBalance == 0); - - //Test contract3 trigger contract2 to call contract1 - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1BeforeBalance = contract1AccountInfo.getBalance(); - Account contract3AccountInfo = PublicMethed.queryAccount(contractAddress3, blockingStubFull); - final Long contract3BeforeBalance = contract3AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverBeforeBalance = receiverAccountInfo.getBalance(); - logger.info("before receiver balance is " + Long.toString(receiverBeforeBalance)); - logger.info("before contract3 balance is " + Long.toString(contract3BeforeBalance)); - receiveAddress = "\"" + Base58.encode58Check(receiverAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress3, - "triggerContract2(address)", receiveAddress, false, - 0, 10000000L, contract014Address, contract014Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contract3AccountInfo = PublicMethed.queryAccount(contractAddress3, blockingStubFull); - final Long contract3AfterBalance = contract3AccountInfo.getBalance(); - receiverAccountInfo = PublicMethed.queryAccount(receiverAddress, blockingStubFull); - receiverAfterBalance = receiverAccountInfo.getBalance(); - logger.info("after receiver balance is " + Long.toString(receiverAfterBalance)); - logger.info("after contract3 balance is " + Long.toString(contract3AfterBalance)); - contract1AccountInfo = PublicMethed.queryAccount(contractAddress1, blockingStubFull); - contract1AfterBalance = contract1AccountInfo.getBalance(); - - Assert.assertTrue(receiverAfterBalance - receiverBeforeBalance == 5); - Assert.assertTrue(contract3BeforeBalance - contract3AfterBalance == 0); - Assert.assertTrue(contract1BeforeBalance - contract1AfterBalance == 5); - - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(contract014Address, contract014Key, 1, contract014Address, - blockingStubFull); - PublicMethed.freedResource(contract014Address, contract014Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario015.java deleted file mode 100644 index e937f957b67..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractScenario015.java +++ /dev/null @@ -1,132 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractScenario015 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress1 = null; - byte[] contractAddress2 = null; - byte[] contractAddress3 = null; - String txid = ""; - Optional infoById = null; - String contractName = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract014Address = ecKey1.getAddress(); - String contract014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey2.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "TRON TRC20 transfer token") - public void trc20Tron() { - ecKey1 = new ECKey(Utils.getRandom()); - contract014Address = ecKey1.getAddress(); - contract014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - receiverAddress = ecKey2.getAddress(); - receiverKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(contract014Key); - PublicMethed.printAddress(receiverKey); - - Assert.assertTrue(PublicMethed.sendcoin(contract014Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Deploy contract1, contract1 has a function to transaction 5 sun to target account - String contractName = "TRON TRC20"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_Scenario015_TRC20_TRON"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_Scenario015_TRC20_TRON"); - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, contract014Key, contract014Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - //Set SiringAuctionAddress to kitty core. - String siringContractString = "\"" + Base58.encode58Check(fromAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress1, "balanceOf(address)", siringContractString, - false, 0, 10000000L, contract014Address, contract014Key, blockingStubFull); - logger.info(txid); - - siringContractString = "\"" + Base58.encode58Check(fromAddress) + "\",\"" + 17 + "\""; - txid = PublicMethed.triggerContract(contractAddress1, "transfer(address,uint256)", - siringContractString, false, 0, 10000000L, contract014Address, - contract014Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - siringContractString = "\"" + Base58.encode58Check(fromAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress1, "balanceOf(address)", - siringContractString, false, 0, 10000000L, contract014Address, - contract014Key, blockingStubFull); - logger.info(txid); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contract014Address, contract014Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractTrc1155.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractTrc1155.java deleted file mode 100644 index d6786d6695a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractTrc1155.java +++ /dev/null @@ -1,696 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.dailybuild.exceptionfee.AssertException; - -@Slf4j -public class ContractTrc1155 { - - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private final String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - Optional infoById = null; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] ownerAddressByte = ecKey2.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String ownerAddressString = null; - String holderAddressString = null; - String noHolderAddress = null; - String txid = null; - byte[] trc1155AddressByte = null; - /** constructor. */ - - @BeforeSuite - public void beforeSuite() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - deployTrc1155(); - - deployHolder(); - deployNoHolder(); - } - - @Test(enabled = true, description = "Trigger Trc1155 balanceOf method") - public void test01triggerTrc1155BalanceOfMethod() { - int coinType = 3; - List parameters = Arrays.asList(ownerAddressString, coinType); - String data = PublicMethed.parametersString(parameters); - - logger.info("data:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals((long) Math.pow(10, 4), result); - } - - @Test(enabled = true, description = "Trigger Trc1155 balanceOfBatch method") - public void test02triggerTrc1155BalanceOfBatchMethod() { - List address = - Stream.of( - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString) - .collect(Collectors.toList()); - List coinType = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - List parameters = Arrays.asList(address, coinType); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - GrpcAPI.TransactionExtention transactionExtention1 = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention1.getConstantResult(0).toByteArray()); - logger.info("hexBalance:" + hexBalance); - final long trxAmount = (long) Math.pow(10, 3); - final long bttAmount = (long) Math.pow(10, 2); - final long winAmount = (long) Math.pow(10, 5); - final long sunAmount = (long) Math.pow(10, 4); - final long apenftAmount = 1L; - final long apenft1Amount = 1L; - Assert.assertEquals(trxAmount, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals(bttAmount, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals(winAmount, Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals(sunAmount, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(apenftAmount, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(apenft1Amount, Long.parseLong(hexBalance.substring(448, 512), 16)); - } - - @Test(enabled = true, description = "Trigger Trc1155 safeTransferFrom function") - public void test03triggerTrc1155SafeTransferFromFunction() { - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] contract003Address = ecKey3.getAddress(); - String sendAddress = WalletClient.encode58Check(contract003Address); - logger.info(sendAddress); - int coinType = 3; - final int coinAmount = 2; - List parameters1 = Arrays.asList(ownerAddressString, coinType); - String data = PublicMethed.parametersString(parameters1); - logger.info("data1:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals((long) Math.pow(10, 4), result); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - List parameters = - Arrays.asList(ownerAddressString, sendAddress, coinType, coinAmount, bytes); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - String txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeTransferFrom(address,address,uint256,uint256,bytes)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - - List parameters3 = Arrays.asList(ownerAddressString, coinType); - data = PublicMethed.parametersString(parameters3); - logger.info("data3:" + data); - GrpcAPI.TransactionExtention transactionExtention3 = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - hexBalance = Hex.toHexString(transactionExtention3.getConstantResult(0).toByteArray()); - result = Long.parseLong(hexBalance, 16); - Assert.assertEquals((long) Math.pow(10, 4) - coinAmount, result); - - parameters = Arrays.asList(sendAddress, coinType); - data = PublicMethed.parametersString(parameters); - - logger.info("data2:" + data); - transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - result = Long.parseLong(hexBalance, 16); - Assert.assertEquals(coinAmount, result); - } - - @Test(enabled = true, description = "trigger Trc1155 SafeBatchTransferFrom function") - public void test04triggerTrc1155SafeBatchTransferFromFunction() { - - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey4.getAddress(); - String sendAddress = WalletClient.encode58Check(receiverAddress); - List coinType = Stream.of(0, 1, 5).collect(Collectors.toList()); - List coinAccount = Stream.of(50, 10, 1).collect(Collectors.toList()); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - List parameters = - Arrays.asList(ownerAddressString, sendAddress, coinType, coinAccount, bytes); - String input = PublicMethed.parametersString(parameters); - logger.info("input:" + input); - String txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)", - input, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - List address = - Stream.of( - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString, - ownerAddressString) - .collect(Collectors.toList()); - List coinType1 = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - List parameters1 = Arrays.asList(address, coinType1); - String data = PublicMethed.parametersString(parameters1); - - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("hexBalance:" + hexBalance); - Assert.assertEquals( - (long) Math.pow(10, 3) - 50, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals( - (long) Math.pow(10, 2) - 10, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals((long) Math.pow(10, 5), Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals( - (long) Math.pow(10, 4) - 2, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(1, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(0, Long.parseLong(hexBalance.substring(448, 512), 16)); - - address = - Stream.of( - sendAddress, - sendAddress, - ownerAddressString, - ownerAddressString, - ownerAddressString, - sendAddress) - .collect(Collectors.toList()); - coinType = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - parameters = Arrays.asList(address, coinType); - data = PublicMethed.parametersString(parameters); - - logger.info("data2:" + data); - transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(50, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals(10, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals((long) Math.pow(10, 5), Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals( - (long) Math.pow(10, 4) - 2, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(1, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(1, Long.parseLong(hexBalance.substring(448, 512), 16)); - } - - @Test(enabled = true, description = "Trc1155Holder can receive trc1155") - public void test05Trc1155HolderCanReceiveTrc1155() { - List parameters = Arrays.asList(holderAddressString, true); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "setApprovalForAll(address,bool)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("setApprovalForAll_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - int coinType = 0; - int coinAmount = 10; - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - parameters = - Arrays.asList(ownerAddressString, holderAddressString, coinType, coinAmount, bytes); - data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeTransferFrom(address,address,uint256,uint256,bytes)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("safeTransferFrom_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - logger.info("infobyid1 : --- " + byId); - - logger.info("infobyid1 : --- " + infoById); - - parameters = Arrays.asList(holderAddressString, coinType); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals(coinAmount, result); - } - - @Test(enabled = true, description = "Trc1155Holder can receive trc1155[]") - public void test06Trc1155HolderCanReceiveTrc1155_01() { - - List parameters = Arrays.asList(holderAddressString, true); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "setApprovalForAll(address,bool)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("setApprovalForAll_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - int trxAmount = 50; - int bttAmount = 30; - int winAmount = 25; - int sunAmount = 10; - int apenftAmount = 1; - List coinType = Stream.of(0, 1, 2, 3, 4).collect(Collectors.toList()); - List coinAmount = - Stream.of(trxAmount, bttAmount, winAmount, sunAmount, apenftAmount) - .collect(Collectors.toList()); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - parameters = - Arrays.asList(ownerAddressString, holderAddressString, coinType, coinAmount, bytes); - data = PublicMethed.parametersString(parameters); - logger.info("data1:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("safeBatchTransferFrom_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid1 : --- " + infoById); - Optional byId = PublicMethed.getTransactionById(txid, blockingStubFull); - String s = ByteArray.toHexString(byId.get().getRawData().getContract(0).toByteArray()); - Assert.assertTrue(s.contains(bytes)); - List address = - Stream.of( - holderAddressString, - holderAddressString, - holderAddressString, - holderAddressString, - holderAddressString, - holderAddressString) - .collect(Collectors.toList()); - coinType = Stream.of(0, 1, 2, 3, 4, 5).collect(Collectors.toList()); - parameters = Arrays.asList(address, coinType); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOfBatch(address[],uint256[])", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - String hexBalance = Hex.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(trxAmount + 10, Long.parseLong(hexBalance.substring(128, 192), 16)); - Assert.assertEquals(bttAmount, Long.parseLong(hexBalance.substring(192, 256), 16)); - Assert.assertEquals(winAmount, Long.parseLong(hexBalance.substring(256, 320), 16)); - Assert.assertEquals(sunAmount, Long.parseLong(hexBalance.substring(320, 384), 16)); - Assert.assertEquals(apenftAmount, Long.parseLong(hexBalance.substring(384, 448), 16)); - Assert.assertEquals(0, Long.parseLong(hexBalance.substring(448, 512), 16)); - } - - @Test(enabled = true, description = "Non-trc1155Holder can not receive trc1155") - public void test07NonTrc1155HolderCanNotReceiveTrc1155() { - List parameters = Arrays.asList(noHolderAddress, true); - String data = PublicMethed.parametersString(parameters); - logger.info("data:" + data); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "setApprovalForAll(address,bool)", - data, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("setApprovalForAll_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - String bytes = "0000000000000000000000000000000000e6b58be8af95e5ad97e7aca6e4b8b2"; - List parameters1 = Arrays.asList(ownerAddressString, noHolderAddress, 1, 1, bytes); - String data1 = PublicMethed.parametersString(parameters1); - logger.info("data:" + data1); - txid = - PublicMethed.triggerContract( - trc1155AddressByte, - "safeTransferFrom(address,address,uint256,uint256,bytes)", - data1, - false, - 0, - maxFeeLimit, - ownerAddressByte, - ownerKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("safeTransferFrom_txid:" + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid1 : --- " + infoById); - parameters = Arrays.asList(noHolderAddress, 1); - data = PublicMethed.parametersString(parameters); - logger.info("data2:" + data); - GrpcAPI.TransactionExtention transactionExtention1 = - PublicMethed.triggerConstantContractForExtention( - trc1155AddressByte, - "balanceOf(address,uint256)", - data, - false, - 0, - 0, - "0", - 0, - ownerAddressByte, - ownerKey, - blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention1.getConstantResult(0).toByteArray()); - long result = Long.parseLong(hexBalance, 16); - Assert.assertEquals(0, result); - } - - /** constructor. */ - public void deployTrc1155() throws Exception { - Assert.assertTrue( - PublicMethed.sendcoin( - ownerAddressByte, 500000000000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "TronCoins"; - String filePath = "./src/test/resources/soliditycode/contractTrc1155.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - int deploySuccessFlag = 1; - Integer retryTimes = 5; - - while (retryTimes-- > 0 && deploySuccessFlag != 0) { - String txid = - PublicMethed.deployContractAndGetTransactionInfoById( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - ownerKey, - ownerAddressByte, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("Deploy IssueCoins txid:" + txid); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContractOuterClass.SmartContract smartContract = - PublicMethed.getContract(contractAddress.toByteArray(), blockingStubFull); - logger.info("smartContract:" + smartContract); - trc1155AddressByte = contractAddress.toByteArray(); - ownerAddressString = WalletClient.encode58Check(ownerAddressByte); - logger.info("trc1155AddressByte:" + trc1155AddressByte); - logger.info("ownerAddressString:" + ownerAddressString); - deploySuccessFlag = infoById.get().getResult().getNumber(); - } - - Assert.assertEquals(deploySuccessFlag, 0); - } - - /** constructor. */ - public void deployHolder() throws Exception { - String contractName = "MyContractCanReceiver"; - String filePath = "./src/test/resources/soliditycode/contractTrc1155.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = - PublicMethed.deployContractAndGetTransactionInfoById( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - ownerKey, - ownerAddressByte, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("Deploy IssueCoins txid:" + txid); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContractOuterClass.SmartContract smartContract = - PublicMethed.getContract(contractAddress.toByteArray(), blockingStubFull); - - holderAddressString = WalletClient.encode58Check(contractAddress.toByteArray()); - - logger.info("HolderAddress:" + holderAddressString); - Assert.assertTrue(smartContract.getAbi() != null); - Assert.assertEquals(infoById.get().getResult().getNumber(), 0); - } - - /** constructor. */ - public void deployNoHolder() throws Exception { - String contractName = "MyContractCanNotReceiver"; - String filePath = "./src/test/resources/soliditycode/contractTrc1155.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = - PublicMethed.deployContractAndGetTransactionInfoById( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - ownerKey, - ownerAddressByte, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("Deploy IssueCoins txid:" + txid); - Optional infoById = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContractOuterClass.SmartContract smartContract = - PublicMethed.getContract(contractAddress.toByteArray(), blockingStubFull); - - noHolderAddress = WalletClient.encode58Check(contractAddress.toByteArray()); - logger.info("NoHolderAddress:" + noHolderAddress); - Assert.assertTrue(smartContract.getAbi() != null); - Assert.assertEquals(infoById.get().getResult().getNumber(), 0); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(fromAddress, ownerKey, ownerAddressByte, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractUnknownException.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractUnknownException.java deleted file mode 100644 index 17fa1ef3f4a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/ContractUnknownException.java +++ /dev/null @@ -1,343 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractUnknownException { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] grammarAddress2 = ecKey2.getAddress(); - String testKeyForGrammarAddress2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] grammarAddress3 = ecKey3.getAddress(); - String testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] grammarAddress4 = ecKey4.getAddress(); - String testKeyForGrammarAddress4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "trigger selfdestruct method") - public void testGrammar001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress, 204800000, - 0, 1, testKeyForGrammarAddress, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final String s = infoById.get().getResMessage().toStringUtf8(); - long fee = infoById.get().getFee(); - long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - Account infoafter = PublicMethed.queryAccount(grammarAddress, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - Assert.assertThat(s, containsString("REVERT opcode executed")); - PublicMethed.unFreezeBalance(grammarAddress, testKeyForGrammarAddress, 1, grammarAddress, - blockingStubFull); - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "trigger revert method") - public void testGrammar002() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress2, 100000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress2, 10000000L, - 0, 1, testKeyForGrammarAddress2, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress2, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress2, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testB"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress2, - grammarAddress2, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final long fee = infoById.get().getFee(); - final long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - final long energyFee = infoById.get().getReceipt().getEnergyFee(); - - final String s = infoById.get().getResMessage().toStringUtf8(); - - Account infoafter = PublicMethed.queryAccount(grammarAddress2, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress2, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - Assert.assertThat(s, containsString("REVERT opcode executed")); - Assert.assertFalse(energyFee == 1000000000); - - Assert.assertTrue(beforeBalance - fee == afterBalance); - PublicMethed.unFreezeBalance(grammarAddress2, testKeyForGrammarAddress2, 1, grammarAddress2, - blockingStubFull); - PublicMethed.freedResource(grammarAddress2, testKeyForGrammarAddress2, testNetAccountAddress, - blockingStubFull); - - } - - @Test(enabled = true, description = "trigger assert method") - public void testGrammar003() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress3, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress3, 1000000000L, - 0, 1, testKeyForGrammarAddress3, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress3, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress3, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final long fee = infoById.get().getFee(); - final long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - final long energyFee = infoById.get().getReceipt().getEnergyFee(); - String s = infoById.get().getResMessage().toStringUtf8(); - Account infoafter = PublicMethed.queryAccount(grammarAddress3, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress3, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - logger.info("s:" + s); - Assert.assertThat(s, containsString("REVERT opcode executed")); - Assert.assertTrue(beforeBalance - fee == afterBalance); - PublicMethed.unFreezeBalance(grammarAddress3, testKeyForGrammarAddress3, 1, grammarAddress3, - blockingStubFull); - PublicMethed.freedResource(grammarAddress3, testKeyForGrammarAddress3, testNetAccountAddress, - blockingStubFull); - - } - - - @Test(enabled = true, description = "trigger require method") - public void testGrammar004() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress4, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(grammarAddress4, 100000000L, - 0, 1, testKeyForGrammarAddress4, blockingStubFull)); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(grammarAddress4, - blockingStubFull); - info = PublicMethed.queryAccount(grammarAddress4, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - long beforeenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeenergyLimit:" + beforeenergyLimit); - String filePath = "src/test/resources/soliditycode/contractUnknownException.sol"; - String contractName = "testD"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 20L, 100, null, testKeyForGrammarAddress4, - grammarAddress4, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - final String s = infoById.get().getResMessage().toStringUtf8(); - final long fee = infoById.get().getFee(); - long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - final long energyFee = infoById.get().getReceipt().getEnergyFee(); - - Account infoafter = PublicMethed.queryAccount(grammarAddress4, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(grammarAddress4, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfo.getNetUsed(); - Long afterFreeNetUsed = resourceInfo.getFreeNetUsed(); - long aftereenergyLimit = resourceInfo.getEnergyLimit(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterenergyLimit:" + aftereenergyLimit); - Assert.assertThat(s, containsString("REVERT opcode executed")); - Assert.assertTrue(beforeBalance - fee == afterBalance); - Assert.assertFalse(energyFee == 1000000000); - PublicMethed.unFreezeBalance(grammarAddress4, testKeyForGrammarAddress4, 1, grammarAddress4, - blockingStubFull); - PublicMethed.freedResource(grammarAddress4, testKeyForGrammarAddress4, testNetAccountAddress, - blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/GetTransactionInfoByBlockNumFromSolidity.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/GetTransactionInfoByBlockNumFromSolidity.java deleted file mode 100644 index 459d96c5cec..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/GetTransactionInfoByBlockNumFromSolidity.java +++ /dev/null @@ -1,53 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import org.junit.Assert; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class GetTransactionInfoByBlockNumFromSolidity { - - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - public String fullNode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - public String solidityNode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - - @Test(enabled = true, description = "test getTransactionInfoByBlockNumFromSolidity") - public void test01GetTransactionInfoByBlockNumFromSolidity() { - channelFull = ManagedChannelBuilder.forTarget(fullNode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(solidityNode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Protocol.Block solidityCurrentBlock = - blockingStubSolidity.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - long block = solidityCurrentBlock.getBlockHeader().getRawData().getNumber(); - long targetBlock; - for (targetBlock = block; targetBlock > 0; targetBlock--) { - GrpcAPI.NumberMessage.Builder builder = GrpcAPI.NumberMessage.newBuilder(); - builder.setNum(targetBlock); - if (blockingStubSolidity.getTransactionCountByBlockNum(builder.build()).getNum() > 0) { - break; - } - } - - GrpcAPI.TransactionInfoList transactionList = - PublicMethed.getTransactionInfoByBlockNum(targetBlock, blockingStubFull).get(); - - GrpcAPI.TransactionInfoList transactionListFromSolidity = - PublicMethed.getTransactionInfoByBlockNum(targetBlock, blockingStubFull).get(); - Assert.assertEquals(transactionList, transactionListFromSolidity); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RateLimite001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RateLimite001.java deleted file mode 100644 index 7070ab0db33..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RateLimite001.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class RateLimite001 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub realBlockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelRealSolidity = ManagedChannelBuilder.forTarget(realSoliditynode) - .usePlaintext(true) - .build(); - realBlockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for ListWitness interface") - public void test1QpsStrategyForListWitnessInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 20) { - blockingStubFull.listWitnesses(EmptyMessage.newBuilder().build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for ListNodes interface") - public void test2IpQpsStrategyForListNodesInterface() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - while (repeatTimes++ < 20) { - blockingStubFull.listNodes(EmptyMessage.newBuilder().build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for getBlockByNum2 " - + "interface on fullnode's solidity service") - public void test3IpQpsStrategyForgetBlockByNum2ResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - - while (repeatTimes++ < 20) { - blockingStubSolidity.getBlockByNum2(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit QpsStrategy for getBlockByNum " - + "interface on fullnode's solidity service") - public void test4QpsStrategyForgetBlockByNumResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - while (repeatTimes++ < 20) { - blockingStubSolidity.getBlockByNum(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit IpQpsStrategy for getBlockByNum2 " - + "interface on real solidity") - public void test5IpQpsStrategyForgetBlockByNum2ResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - - while (repeatTimes++ < 20) { - realBlockingStubSolidity.getBlockByNum2(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Rate limit QpsStrategy for getBlockByNum " - + "interface on real solidity") - public void test6QpsStrategyForgetBlockByNumResourceInterfaceOnFullnodeSolidityService() { - Long startTimeStamp = System.currentTimeMillis(); - Integer repeatTimes = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(5); - while (repeatTimes++ < 20) { - realBlockingStubSolidity.getBlockByNum(builder.build()); - } - Long endTimesStap = System.currentTimeMillis(); - logger.info("startTimeStamp - endTimesStap:" + (endTimesStap - startTimeStamp)); - Assert.assertTrue(endTimesStap - startTimeStamp > 5000); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RequireException.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RequireException.java deleted file mode 100644 index ce5ec3bfaf3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/RequireException.java +++ /dev/null @@ -1,791 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class RequireException { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelFull2 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull2 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForAssetIssue016); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Require Exception") - public void test1TestRequireContract() { - ecKey1 = new ECKey(Utils.getRandom()); - asset016Address = ecKey1.getAddress(); - testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - - Assert.assertTrue(PublicMethed - .sendcoin(asset016Address, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = - "src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "testRequire()", "#", false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Throw Exception") - public void test2TestThrowsContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "testThrow()", "#", false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testTestThrowsContract"); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - - @Test(enabled = true, description = "Call Revert ") - public void test3TestRevertContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol"; - String contractName = "TestThrowsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "testRevert()", "#", false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = false, description = "No payable function call value") - public void test4noPayableContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol"; - String contractName = "noPayableContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - final String txid = PublicMethed.triggerContract(contractAddress, - "noPayable()", "#", false, - 22, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = false, description = "No payable Constructor") - public void test5noPayableConstructor() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String filePath = - "src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol"; - String contractName = "MyContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 22L, 100, null, - testKeyForAssetIssue016, asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - @Test(enabled = true, description = "Transfer failed") - public void test6transferTestContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol"; - String contractName = "transferTestContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - final Account info; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String newCxoAddress = "\"" + Base58.encode58Check(testNetAccountAddress) - + "\""; - final String txid = PublicMethed.triggerContract(contractAddress, - "tranferTest(address) ", newCxoAddress, false, - 5, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("transferTestContract"); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "No payable fallback call value") - public void test7payableFallbakContract() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Integer times = 0; - String contractName1 = "Test"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] contractAddress1; - contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, 0L, - 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Account info; - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String saleContractString = "\"" + Base58.encode58Check(contractAddress) + "\""; - final String txid = PublicMethed.triggerContract(contractAddress1, - "callTest(address)", saleContractString, false, - 5, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "New contract gas not enough") - public void test8newContractGasNoenough() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol"; - String contractName = "Account"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName1 = "Initialize"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - final byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, - testKeyForAssetIssue016, asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - final String txid = PublicMethed.triggerContract(contractAddress1, - "newAccount()", "#", false, - 0, 5226000, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - @Test(enabled = true, description = "Message used error") - public void test9MessageUsedErrorFeed() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol"; - String contractName = "MathedFeed"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String saleContractString = "\"" + Base58.encode58Check(contractAddress) + "\""; - String contractName1 = "MathedUseContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - final byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 100, null, - testKeyForAssetIssue016, asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - final String txid = PublicMethed.triggerContract(contractAddress1, - "messageUse(address)", saleContractString, false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - @Test(enabled = true, description = "Function used error") - public void testFunctionUsedErrorFeed() { - String filePath = - "src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol"; - String contractName = "MessageFeed"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String saleContractString = "\"" + Base58.encode58Check(contractAddress) + "\""; - - String contractName1 = "MessageUseContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - final byte[] contractAddress1 = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, 0L, - 100, null, testKeyForAssetIssue016, - asset016Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(asset016Address, - blockingStubFull); - info = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - final String txid = PublicMethed.triggerContract(contractAddress1, - "messageUse(address)", saleContractString, false, - 0, maxFeeLimit, asset016Address, testKeyForAssetIssue016, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - - Account infoafter = PublicMethed.queryAccount(testKeyForAssetIssue016, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(asset016Address, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - PublicMethed.freedResource(asset016Address, testKeyForAssetIssue016, testNetAccountAddress, - blockingStubFull); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount002.java deleted file mode 100644 index cdf1adfd022..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount002.java +++ /dev/null @@ -1,163 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /* @Test(enabled = true) - public void TestGetAllAccount(){ - GrpcAPI.AccountList accountlist = - blockingStubFull.listAccounts(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(accountlist); - if (result.isPresent()) { - GrpcAPI.AccountList accountList = result.get(); - List list = accountList.getAccountsList(); - List newList = new ArrayList(); - newList.addAll(list); - newList.sort(new AccountComparator()); - GrpcAPI.AccountList.Builder builder = GrpcAPI.AccountList.newBuilder(); - newList.forEach(account -> builder.addAccounts(account)); - result = Optional.of(builder.build()); - } - Assert.assertTrue(result.get().getAccountsCount() > 0); - logger.info(Integer.toString(result.get().getAccountsCount())); - for (int j = 0; j < result.get().getAccountsCount(); j++){ - Assert.assertFalse(result.get().getAccounts(j).getAddress().isEmpty()); - } - - - }*/ - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - class AccountComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long.compare(((Account) o2).getBalance(), ((Account) o1).getBalance()); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount010.java deleted file mode 100644 index c9437546cda..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount010.java +++ /dev/null @@ -1,128 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount010 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account010Address = ecKey1.getAddress(); - String account010Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account010SecondAddress = ecKey2.getAddress(); - String account010SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] account010InvalidAddress = ecKey3.getAddress(); - String account010InvalidKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(account010Key); - PublicMethed.printAddress(account010SecondKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = false) - public void testGetStorage() { - Assert.assertTrue(PublicMethed.sendcoin(account010Address, 100000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account010SecondAddress, 100000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account010InvalidAddress, 100000000, - fromAddress, testKey002, blockingStubFull)); - Account account010Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account010Info.getAccountResource().getStorageLimit() == 0); - Assert.assertTrue(account010Info.getAccountResource().getLatestExchangeStorageTime() == 0); - - Assert.assertTrue(PublicMethed.buyStorage(100000000L, account010Address, account010Key, - blockingStubFull)); - - account010Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account010Info.getAccountResource().getStorageLimit() > 0); - Assert.assertTrue(account010Info.getAccountResource().getLatestExchangeStorageTime() > 0); - - AccountResourceMessage account010Resource = PublicMethed.getAccountResource(account010Address, - blockingStubFull); - Assert.assertTrue(account010Resource.getStorageLimit() > 0); - } - - @Test(enabled = false) - public void testSellStorage() { - AccountResourceMessage account010Resource = PublicMethed.getAccountResource(account010Address, - blockingStubFull); - Long storageLimit = account010Resource.getStorageLimit(); - Account account001Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account001Info.getBalance() == 0); - //When there is no enough storage,sell failed. - Assert.assertFalse(PublicMethed.sellStorage(storageLimit + 1, account010Address, account010Key, - blockingStubFull)); - //Can not sell 0 storage - Assert.assertFalse(PublicMethed.sellStorage(0, account010Address, account010Key, - blockingStubFull)); - //Sell all storage. - Assert.assertTrue(PublicMethed.sellStorage(storageLimit, account010Address, account010Key, - blockingStubFull)); - account010Resource = PublicMethed.getAccountResource(account010Address, - blockingStubFull); - storageLimit = account010Resource.getStorageLimit(); - Assert.assertTrue(storageLimit == 0); - account001Info = PublicMethed.queryAccount(account010Key, blockingStubFull); - Assert.assertTrue(account001Info.getBalance() > 0); - - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount012.java deleted file mode 100644 index f4aa3b2d523..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount012.java +++ /dev/null @@ -1,188 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount012 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("mainWitness.key25"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("mainWitness.key2"); - private final byte[] testAddress003 = PublicMethed.getFinalAddress(testKey003); - - private final String testKey004 = Configuration.getByPath("testng.conf") - .getString("mainWitness.key3"); - private final byte[] testAddress004 = PublicMethed.getFinalAddress(testKey004); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - //get account - - /** - * constructor. - */ - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - PublicMethed.printAddress(testKey003); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - beforeTime = System.currentTimeMillis(); - } - - @Test(enabled = false, threadPoolSize = 20, invocationCount = 20) - public void storageAndCpu() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset011Address = ecKey1.getAddress(); - String testKeyForAssetIssue011 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(testKeyForAssetIssue011); - - PublicMethed - .sendcoin(asset011Address, 100000000000000L, fromAddress, testKey002, blockingStubFull); - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_WalletTestAccount012_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_WalletTestAccount012_storageAndCpu"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, testKeyForAssetIssue011, asset011Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - String txid; - - Integer i = 1; - AccountResourceMessage accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - Long beforeEnergyLimit = accountResource.getEnergyLimit(); - Long afterEnergyLimit; - Long beforeTotalEnergyLimit = accountResource.getTotalEnergyLimit(); - Account account = PublicMethed.queryAccount(testKeyForAssetIssue011, blockingStubFull); - Long afterTotalEnergyLimit; - while (i++ < 20000) { - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - beforeEnergyLimit = accountResource.getEnergyLimit(); - beforeTotalEnergyLimit = accountResource.getTotalEnergyLimit(); - String initParmes = "\"" + "21" + "\""; - /* txid = PublicMethed.triggerContract(contractAddress, - "storage8Char()", "", false, - 0, maxFeeLimit, asset011Address, testKeyForAssetIssue011, blockingStubFull);*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - txid = PublicMethed.triggerContract(contractAddress, - "add2(uint256)", initParmes, false, - 0, maxFeeLimit, asset011Address, testKeyForAssetIssue011, blockingStubFull); - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - //logger.info("Current limit is " + accountResource.getTotalEnergyLimit()); - //PublicMethed.freezeBalanceGetEnergy(asset011Address,1000000L,3, - // 1,testKeyForAssetIssue011,blockingStubFull); - - accountResource = PublicMethed.getAccountResource(asset011Address, - blockingStubFull); - afterEnergyLimit = accountResource.getEnergyLimit(); - afterTotalEnergyLimit = accountResource.getTotalEnergyLimit(); - - logger.info("Total energy limit is " + (float) afterTotalEnergyLimit / 50000000000L); - Float rate = - (float) (afterTotalEnergyLimit - beforeTotalEnergyLimit) / beforeTotalEnergyLimit; - //logger.info("rate is " + rate); - //Assert.assertTrue(rate >= 0.001001000 && rate <= 0.001001002); - //txidList.add(txid); - try { - Thread.sleep(30); - } catch (InterruptedException e) { - e.printStackTrace(); - } - account = PublicMethed.queryAccount(testKeyForAssetIssue011, blockingStubFull); - Float energyrate = (float) (beforeEnergyLimit) / account.getAccountResource() - .getFrozenBalanceForEnergy().getFrozenBalance(); - //logger.info("energy rate is " + energyrate); - if (i % 20 == 0) { - PublicMethed.freezeBalanceForReceiver(fromAddress, 1000000L, 3, 1, - ByteString.copyFrom(asset011Address), testKey002, blockingStubFull); - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount013.java deleted file mode 100644 index e6d94b64fed..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount013.java +++ /dev/null @@ -1,515 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount013 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Optional infoById = null; - long account013BeforeBalance; - long freezeAmount = 10000000L; - long freezeDuration = 0; - byte[] account013Address; - String testKeyForAccount013; - byte[] receiverDelegateAddress; - String receiverDelegateKey; - byte[] emptyAddress; - String emptyKey; - byte[] account4DelegatedResourceAddress; - String account4DelegatedResourceKey; - byte[] account5DelegatedResourceAddress; - String account5DelegatedResourceKey; - byte[] accountForDeployAddress; - String accountForDeployKey; - byte[] accountForAssetIssueAddress; - String accountForAssetIssueKey; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "Delegate resource for bandwidth and energy") - public void test1DelegateResourceForBandwidthAndEnergy() { - //Create account013 - ECKey ecKey1 = new ECKey(Utils.getRandom()); - account013Address = ecKey1.getAddress(); - testKeyForAccount013 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(testKeyForAccount013); - //Create receiver - ECKey ecKey2 = new ECKey(Utils.getRandom()); - receiverDelegateAddress = ecKey2.getAddress(); - receiverDelegateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(receiverDelegateKey); - //Create Empty account - ECKey ecKey3 = new ECKey(Utils.getRandom()); - emptyAddress = ecKey3.getAddress(); - emptyKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - //sendcoin to Account013 - Assert.assertTrue(PublicMethed - .sendcoin(account013Address, 10000000000L, fromAddress, testKey002, blockingStubFull)); - //sendcoin to receiver - Assert.assertTrue(PublicMethed - .sendcoin(receiverDelegateAddress, 10000000000L, toAddress, testKey003, blockingStubFull)); - - //getAccountResource account013 - PublicMethed.waitProduceNextBlock(blockingStubFull); - AccountResourceMessage account013Resource = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - logger.info("013 energy limit is " + account013Resource.getEnergyLimit()); - logger.info("013 net limit is " + account013Resource.getNetLimit()); - //getAccountResource receiver - AccountResourceMessage receiverResource = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - logger.info("receiver energy limit is " + receiverResource.getEnergyLimit()); - logger.info("receiver net limit is " + receiverResource.getNetLimit()); - Protocol.Account account013infoBefore = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //get resources of account013 before DelegateResource - account013BeforeBalance = account013infoBefore.getBalance(); - AccountResourceMessage account013ResBefore = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - final long account013BeforeBandWidth = account013ResBefore.getNetLimit(); - AccountResourceMessage receiverResourceBefore = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - long receiverBeforeBandWidth = receiverResourceBefore.getNetLimit(); - //Account013 DelegateResource for BandWidth to receiver - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(receiverDelegateAddress), testKeyForAccount013, blockingStubFull)); - Protocol.Account account013infoAfter = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //get balance of account013 after DelegateResource - long account013AfterBalance = account013infoAfter.getBalance(); - AccountResourceMessage account013ResAfter = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - //get BandWidth of account013 after DelegateResource - long account013AfterBandWidth = account013ResAfter.getNetLimit(); - AccountResourceMessage receiverResourceAfter = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - //Bandwidth of receiver after DelegateResource - long receiverAfterBandWidth = receiverResourceAfter.getNetLimit(); - //Balance of Account013 reduced amount same as DelegateResource - Assert.assertTrue(account013BeforeBalance == account013AfterBalance + freezeAmount); - //Bandwidth of account013 is equally before and after DelegateResource - Assert.assertTrue(account013AfterBandWidth == account013BeforeBandWidth); - //Bandwidth of receiver after DelegateResource is greater than before - Assert.assertTrue(receiverAfterBandWidth > receiverBeforeBandWidth); - Protocol.Account account013Before1 = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //balance of account013 before DelegateResource - long account013BeforeBalance1 = account013Before1.getBalance(); - AccountResourceMessage account013ResBefore1 = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - //Energy of account013 before DelegateResource - long account013BeforeEnergy = account013ResBefore1.getEnergyLimit(); - AccountResourceMessage receiverResourceBefore1 = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - //Energy of receiver before DelegateResource - long receiverBeforeEnergy = receiverResourceBefore1.getEnergyLimit(); - //Account013 DelegateResource Energy to receiver - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 1, - ByteString.copyFrom(receiverDelegateAddress), testKeyForAccount013, blockingStubFull)); - Protocol.Account account013infoAfter1 = PublicMethed - .queryAccount(account013Address, blockingStubFull); - //balance of account013 after DelegateResource - long account013AfterBalance1 = account013infoAfter1.getBalance(); - AccountResourceMessage account013ResAfter1 = PublicMethed - .getAccountResource(account013Address, blockingStubFull); - long account013AfterEnergy = account013ResAfter1.getEnergyLimit(); - //Energy of account013 after DelegateResource - AccountResourceMessage receiverResourceAfter1 = PublicMethed - .getAccountResource(receiverDelegateAddress, blockingStubFull); - //Energy of receiver after DelegateResource - long receiverAfterEnergy = receiverResourceAfter1.getEnergyLimit(); - //Balance of Account013 reduced amount same as DelegateResource - Assert.assertTrue(account013BeforeBalance1 == account013AfterBalance1 + freezeAmount); - //Bandwidth of account013 is equally before and after DelegateResource - Assert.assertTrue(account013AfterEnergy == account013BeforeEnergy); - //Bandwidth of receiver after DelegateResource is greater than before - Assert.assertTrue(receiverAfterEnergy > receiverBeforeEnergy); - //account013 DelegateResource to Empty failed - Assert.assertFalse(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(emptyAddress), testKeyForAccount013, blockingStubFull)); - //account013 DelegateResource to account013 failed - Assert.assertFalse(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(account013Address), testKeyForAccount013, blockingStubFull)); - account013Resource = PublicMethed.getAccountResource(account013Address, blockingStubFull); - logger.info("After 013 energy limit is " + account013Resource.getEnergyLimit()); - logger.info("After 013 net limit is " + account013Resource.getNetLimit()); - - receiverResource = PublicMethed.getAccountResource(receiverDelegateAddress, blockingStubFull); - logger.info("After receiver energy limit is " + receiverResource.getEnergyLimit()); - logger.info("After receiver net limit is " + receiverResource.getNetLimit()); - } - - @Test(enabled = true, description = "Get delegate resource") - public void test2getDelegatedResource() { - //Create Account4 - ECKey ecKey4 = new ECKey(Utils.getRandom()); - account4DelegatedResourceAddress = ecKey4.getAddress(); - account4DelegatedResourceKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - //Create Account5 - ECKey ecKey5 = new ECKey(Utils.getRandom()); - account5DelegatedResourceAddress = ecKey5.getAddress(); - account5DelegatedResourceKey = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - - //sendcoin to Account4 - Assert.assertTrue(PublicMethed - .sendcoin(account4DelegatedResourceAddress, 10000000000L, fromAddress, testKey002, - blockingStubFull)); - - //sendcoin to Account5 - Assert.assertTrue(PublicMethed - .sendcoin(account5DelegatedResourceAddress, 20000000000L, toAddress, testKey003, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Protocol.Account account4infoBefore = PublicMethed - .queryAccount(account4DelegatedResourceAddress, blockingStubFull); - //Balance of Account4 before DelegateResource - final long account4BeforeBalance = account4infoBefore.getBalance(); - //account013 DelegateResource of bandwidth to Account4 - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, freezeAmount, freezeDuration, 0, - ByteString.copyFrom(account4DelegatedResourceAddress), testKeyForAccount013, - blockingStubFull)); - //Account4 DelegateResource of energy to Account5 - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account4DelegatedResourceAddress, freezeAmount, freezeDuration, 1, - ByteString.copyFrom(account5DelegatedResourceAddress), account4DelegatedResourceKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //check DelegatedResourceList,from:account013 to:Account4 - Optional delegatedResourceResult1 = PublicMethed - .getDelegatedResource(account013Address, account4DelegatedResourceAddress, - blockingStubFull); - long afterFreezeBandwidth = delegatedResourceResult1.get().getDelegatedResource(0) - .getFrozenBalanceForBandwidth(); - //check DelegatedResourceList,from:Account4 to:Account5 - Optional delegatedResourceResult2 = PublicMethed - .getDelegatedResource(account4DelegatedResourceAddress, account5DelegatedResourceAddress, - blockingStubFull); - long afterFreezeEnergy = delegatedResourceResult2.get().getDelegatedResource(0) - .getFrozenBalanceForEnergy(); - //FrozenBalanceForBandwidth > 0 - Assert.assertTrue(afterFreezeBandwidth > 0); - //FrozenBalanceForEnergy > 0 - Assert.assertTrue(afterFreezeEnergy > 0); - - //check DelegatedResourceAccountIndex for Account4 - Optional delegatedResourceIndexResult1 = PublicMethed - .getDelegatedResourceAccountIndex(account4DelegatedResourceAddress, blockingStubFull); - //result of From list, first Address is same as account013 address - Assert.assertTrue(new String(account013Address) - .equals(new String(delegatedResourceIndexResult1.get().getFromAccounts(0).toByteArray()))); - //result of To list, first Address is same as Account5 address - Assert.assertTrue(new String(account5DelegatedResourceAddress) - .equals(new String(delegatedResourceIndexResult1.get().getToAccounts(0).toByteArray()))); - - //unfreezebalance of bandwidth from Account013 to Account4 - Assert.assertTrue(PublicMethed.unFreezeBalance(account013Address, testKeyForAccount013, 0, - account4DelegatedResourceAddress, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //check DelegatedResourceAccountIndex of Account4 - Optional delegatedResourceIndexResult1AfterUnfreeze = - PublicMethed - .getDelegatedResourceAccountIndex(account4DelegatedResourceAddress, blockingStubFull); - //result of From list is empty - Assert.assertTrue( - delegatedResourceIndexResult1AfterUnfreeze.get().getFromAccountsList().isEmpty()); - Assert.assertFalse( - delegatedResourceIndexResult1AfterUnfreeze.get().getToAccountsList().isEmpty()); - //Balance of Account013 after unfreezeBalance - // (013 -> receiver(bandwidth), 013 -> receiver(Energy), 013 -> Account4(bandwidth)) - Assert.assertTrue(PublicMethed.queryAccount(account013Address, blockingStubFull).getBalance() - == account013BeforeBalance - 2 * freezeAmount); - //bandwidth from Account013 to Account4 gone - Assert.assertTrue( - PublicMethed.getAccountResource(account4DelegatedResourceAddress, blockingStubFull) - .getNetLimit() == 0); - - //unfreezebalance of Energy from Account4 to Account5 - Assert.assertTrue(PublicMethed - .unFreezeBalance(account4DelegatedResourceAddress, account4DelegatedResourceKey, 1, - account5DelegatedResourceAddress, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account account4infoAfterUnfreezeEnergy = PublicMethed - .queryAccount(account4DelegatedResourceAddress, blockingStubFull); - //balance of Account4 after unfreezebalance - long account4BalanceAfterUnfreezeEnergy = account4infoAfterUnfreezeEnergy.getBalance(); - //balance of Account4 is same as before - Assert.assertTrue(account4BeforeBalance == account4BalanceAfterUnfreezeEnergy); - //Energy from Account4 to Account5 gone - Assert.assertTrue( - PublicMethed.getAccountResource(account5DelegatedResourceAddress, blockingStubFull) - .getEnergyLimit() == 0); - - //Unfreezebalance of Bandwidth from Account4 to Account5 fail - Assert.assertFalse(PublicMethed - .unFreezeBalance(account4DelegatedResourceAddress, account4DelegatedResourceKey, 0, - account5DelegatedResourceAddress, blockingStubFull)); - } - - @Test(enabled = true, description = "Prepare delegate resource token") - public void test3PrepareToken() { - //Create Account7 - ECKey ecKey7 = new ECKey(Utils.getRandom()); - accountForAssetIssueAddress = ecKey7.getAddress(); - accountForAssetIssueKey = ByteArray.toHexString(ecKey7.getPrivKeyBytes()); - //sendcoin to Account7 - Assert.assertTrue(PublicMethed - .sendcoin(accountForAssetIssueAddress, 10000000000L, toAddress, testKey003, - blockingStubFull)); - //account013 DelegateResource of bandwidth to accountForAssetIssue - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(account013Address, 1000000000L, freezeDuration, 0, - ByteString.copyFrom(accountForAssetIssueAddress), testKeyForAccount013, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //accountForAssetIssue AssetIssue - long now = System.currentTimeMillis(); - String name = "testAccount013_" + Long.toString(now); - long totalSupply = 100000000000L; - String description = "zfbnb"; - String url = "aaa.com"; - Assert.assertTrue(PublicMethed - .createAssetIssue(accountForAssetIssueAddress, name, totalSupply, 1, 1, - System.currentTimeMillis() + 2000, System.currentTimeMillis() + 1000000000, 1, - description, url, 2000L, 2000L, 500L, 1L, accountForAssetIssueKey, blockingStubFull)); - - } - - @Test(enabled = true, description = "Delegate resource about transfer asset") - public void test4DelegateResourceAboutTransferAsset() { - //Wait for 3s - PublicMethed.waitProduceNextBlock(blockingStubFull); - //get AssetIssue Id - Protocol.Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed - .queryAccount(accountForAssetIssueAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - //Account5 Participate AssetIssue - Assert.assertTrue(PublicMethed - .participateAssetIssue(accountForAssetIssueAddress, assetAccountId.toByteArray(), 1000000, - account5DelegatedResourceAddress, account5DelegatedResourceKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //get account013,accountForAssetIssue,Account5 account resources before transferAssets - final long account013CurrentBandwidth = PublicMethed - .getAccountResource(account013Address, blockingStubFull).getNetUsed(); - long accountForAssetIssueCurrentBandwidth = PublicMethed - .getAccountResource(accountForAssetIssueAddress, blockingStubFull).getNetUsed(); - final long account5CurrentBandwidth = PublicMethed - .getAccountResource(account5DelegatedResourceAddress, blockingStubFull).getNetUsed(); - //Account5 transfer Assets receiver - Assert.assertTrue(PublicMethed - .transferAsset(receiverDelegateAddress, assetAccountId.toByteArray(), 100000, - account5DelegatedResourceAddress, account5DelegatedResourceKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(accountForAssetIssueKey); - PublicMethed.printAddress(account5DelegatedResourceKey); - - //get account013,accountForAssetIssue,Account5 resource after transferAsset - final long account013CurrentBandwidthAfterTrans = PublicMethed - .getAccountResource(account013Address, blockingStubFull).getNetUsed(); - final long accountForAssetIssueCurrentBandwidthAfterTrans = PublicMethed - .getAccountResource(accountForAssetIssueAddress, blockingStubFull).getFreeNetUsed(); - final long account5CurrentBandwidthAfterTrans = PublicMethed - .getAccountResource(account5DelegatedResourceAddress, blockingStubFull).getNetUsed(); - AccountResourceMessage account5ResourceAfterTrans = PublicMethed - .getAccountResource(account5DelegatedResourceAddress, blockingStubFull); - - String result = ""; - if (account5ResourceAfterTrans.getAssetNetLimitCount() > 0) { - logger.info("getAssetNetLimitCount > 0 "); - for (String name1 : account5ResourceAfterTrans.getAssetNetLimitMap().keySet()) { - logger.info(name1); - result += account5ResourceAfterTrans.getAssetNetUsedMap().get(name1); - - } - } - logger.info(result); - PublicMethed.printAddress(receiverDelegateKey); - PublicMethed.printAddress(account5DelegatedResourceKey); - long account5FreeAssetNetUsed = accountForAssetIssueCurrentBandwidthAfterTrans; - - //check resource diff - Assert.assertTrue(Long.parseLong(result) > 0); - Assert.assertTrue(account013CurrentBandwidth == account013CurrentBandwidthAfterTrans); - Assert.assertTrue(account5CurrentBandwidth == account5CurrentBandwidthAfterTrans); - } - - @Test(enabled = true, description = "Can't delegate resource for contract") - public void test5CanNotDelegateResourceToContract() { - //Create Account6 - ECKey ecKey6 = new ECKey(Utils.getRandom()); - accountForDeployAddress = ecKey6.getAddress(); - accountForDeployKey = ByteArray.toHexString(ecKey6.getPrivKeyBytes()); - //PublicMethed.printAddress(accountForDeployKey); - //sendcoin to Account6 - Assert.assertTrue(PublicMethed - .sendcoin(accountForDeployAddress, 10000000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //deploy contract under Account6 - Integer consumeUserResourcePercent = 0; - Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - String contractName = "TestSStore"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_WalletTestAccount013"); - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_WalletTestAccount013"); - - logger.info("TestSStore"); - final byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, consumeUserResourcePercent, - null, accountForDeployKey, accountForDeployAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Account4 DelegatedResource of Energy to Contract - //After 3.6 can not delegate resource to contract - Assert.assertFalse(PublicMethed - .freezeBalanceForReceiver(account4DelegatedResourceAddress, freezeAmount, freezeDuration, 1, - ByteString.copyFrom(contractAddress), account4DelegatedResourceKey, blockingStubFull)); - } - - - @Test(enabled = true, description = "Get delegate resource from solidity") - public void test6GetDelegateResourceFromSolidity() { - Optional delegateResource = PublicMethed - .getDelegatedResourceFromSolidity(account013Address, receiverDelegateAddress, - blockingStubSolidity); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForEnergy() == 10000000); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForBandwidth() == 10000000); - } - - @Test(enabled = true, description = "Get delegate resource from PBFT") - public void test7GetDelegateResourceFromPbft() { - Optional delegateResource = PublicMethed - .getDelegatedResourceFromSolidity(account013Address, receiverDelegateAddress, - blockingStubPbft); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForEnergy() == 10000000); - Assert.assertTrue(delegateResource.get().getDelegatedResource(0) - .getFrozenBalanceForBandwidth() == 10000000); - } - - @Test(enabled = true, description = "Get delegate resource index from solidity") - public void test8GetDelegateResourceIndexFromSolidity() { - Optional delegateResourceIndex = PublicMethed - .getDelegatedResourceAccountIndexFromSolidity(account013Address, - blockingStubSolidity); - Assert.assertTrue(delegateResourceIndex.get().getToAccountsCount() == 2); - } - - @Test(enabled = true, description = "Get delegate resource index from PBFT") - public void test9GetDelegateResourceIndexFromPbft() { - Optional delegateResourceIndex = PublicMethed - .getDelegatedResourceAccountIndexFromSolidity(account013Address, - blockingStubSolidity); - Assert.assertTrue(delegateResourceIndex.get().getToAccountsCount() == 2); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(account013Address, testKeyForAccount013, - fromAddress, blockingStubFull); - PublicMethed.freedResource(receiverDelegateAddress, receiverDelegateKey, fromAddress, - blockingStubFull); - PublicMethed.freedResource(account4DelegatedResourceAddress, account4DelegatedResourceKey, - fromAddress, blockingStubFull); - PublicMethed.freedResource(account5DelegatedResourceAddress, account5DelegatedResourceKey, - fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount014.java deleted file mode 100644 index 2dbf04b380b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount014.java +++ /dev/null @@ -1,229 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount014 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account014Address = ecKey1.getAddress(); - String account014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] account014SecondAddress = ecKey2.getAddress(); - String account014SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - } - - @Test(enabled = true, description = "Query freeNetUsage in 50061") - public void fullAndSoliMerged1ForFreeNetUsage() { - //Create account014 - ecKey1 = new ECKey(Utils.getRandom()); - account014Address = ecKey1.getAddress(); - account014Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ecKey2 = new ECKey(Utils.getRandom()); - account014SecondAddress = ecKey2.getAddress(); - account014SecondKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(account014Key); - PublicMethed.printAddress(account014SecondKey); - Assert.assertTrue(PublicMethed.sendcoin(account014Address, 1000000000L, fromAddress, - testKey002, blockingStubFull)); - - //Test freeNetUsage in fullnode and soliditynode. - Assert.assertTrue(PublicMethed.sendcoin(account014SecondAddress, 5000000L, - account014Address, account014Key, - blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account014SecondAddress, 5000000L, - account014Address, account014Key, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account account014 = PublicMethed.queryAccount(account014Address, blockingStubFull); - final long freeNetUsageInFullnode = account014.getFreeNetUsage(); - final long createTimeInFullnode = account014.getCreateTime(); - final long lastOperationTimeInFullnode = account014.getLatestOprationTime(); - final long lastCustomeFreeTimeInFullnode = account014.getLatestConsumeFreeTime(); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSoliInFull); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSoliInFull); - final long freeNetUsageInSoliInFull = account014.getFreeNetUsage(); - final long createTimeInSoliInFull = account014.getCreateTime(); - final long lastOperationTimeInSoliInFull = account014.getLatestOprationTime(); - final long lastCustomeFreeTimeInSoliInFull = account014.getLatestConsumeFreeTime(); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSolidity); - final long freeNetUsageInSolidity = account014.getFreeNetUsage(); - final long createTimeInSolidity = account014.getCreateTime(); - final long lastOperationTimeInSolidity = account014.getLatestOprationTime(); - final long lastCustomeFreeTimeInSolidity = account014.getLatestConsumeFreeTime(); - Assert.assertTrue(freeNetUsageInSoliInFull > 0 && freeNetUsageInSolidity > 0 - && freeNetUsageInFullnode > 0); - Assert.assertTrue(freeNetUsageInFullnode <= freeNetUsageInSoliInFull + 5 - && freeNetUsageInFullnode >= freeNetUsageInSoliInFull - 5); - Assert.assertTrue(freeNetUsageInFullnode <= freeNetUsageInSolidity + 5 - && freeNetUsageInFullnode >= freeNetUsageInSolidity - 5); - Assert.assertTrue(createTimeInFullnode == createTimeInSolidity && createTimeInFullnode - == createTimeInSoliInFull); - Assert.assertTrue(createTimeInSoliInFull != 0); - Assert.assertTrue(lastOperationTimeInFullnode == lastOperationTimeInSolidity - && lastOperationTimeInFullnode == lastOperationTimeInSoliInFull); - Assert.assertTrue(lastOperationTimeInSoliInFull != 0); - Assert.assertTrue(lastCustomeFreeTimeInFullnode == lastCustomeFreeTimeInSolidity - && lastCustomeFreeTimeInFullnode == lastCustomeFreeTimeInSoliInFull); - Assert.assertTrue(lastCustomeFreeTimeInSoliInFull != 0); - } - - @Test(enabled = true, description = "Query net usage in 50061") - public void fullAndSoliMerged2ForNetUsage() { - - Assert.assertTrue(PublicMethed.freezeBalance(account014Address, 1000000L, 3, - account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(account014SecondAddress, 1000000L, - account014Address, account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(account014Address, 1000000, - 3, 1, account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014Address, 1000000, - 3, 0, ByteString.copyFrom( - account014SecondAddress), account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014Address, 1000000, - 3, 1, ByteString.copyFrom( - account014SecondAddress), account014Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014SecondAddress, 1000000, - 3, 0, ByteString.copyFrom( - account014Address), account014SecondKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(account014SecondAddress, 1000000, - 3, 1, ByteString.copyFrom( - account014Address), account014SecondKey, blockingStubFull)); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSoliInFull); - Account account014 = PublicMethed.queryAccount(account014Address, blockingStubFull); - final long lastCustomeTimeInFullnode = account014.getLatestConsumeTime(); - final long netUsageInFullnode = account014.getNetUsage(); - final long acquiredForBandwidthInFullnode = account014 - .getAcquiredDelegatedFrozenBalanceForBandwidth(); - final long delegatedBandwidthInFullnode = account014.getDelegatedFrozenBalanceForBandwidth(); - final long acquiredForEnergyInFullnode = account014 - .getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(); - final long delegatedForEnergyInFullnode = account014 - .getAccountResource().getDelegatedFrozenBalanceForEnergy(); - logger.info("delegatedForEnergyInFullnode " + delegatedForEnergyInFullnode); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSoliInFull); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSoliInFull); - final long lastCustomeTimeInSoliInFull = account014.getLatestConsumeTime(); - logger.info("freeNetUsageInSoliInFull " + lastCustomeTimeInSoliInFull); - final long netUsageInSoliInFull = account014.getNetUsage(); - final long acquiredForBandwidthInSoliInFull = account014 - .getAcquiredDelegatedFrozenBalanceForBandwidth(); - final long delegatedBandwidthInSoliInFull = account014.getDelegatedFrozenBalanceForBandwidth(); - final long acquiredForEnergyInSoliInFull = account014 - .getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(); - final long delegatedForEnergyInSoliInFull = account014 - .getAccountResource().getDelegatedFrozenBalanceForEnergy(); - logger.info("delegatedForEnergyInSoliInFull " + delegatedForEnergyInSoliInFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - account014 = PublicMethed.queryAccount(account014Address, blockingStubSolidity); - final long netUsageInSolidity = account014.getNetUsage(); - final long lastCustomeTimeInSolidity = account014.getLatestConsumeTime(); - final long acquiredForBandwidthInSolidity = account014 - .getAcquiredDelegatedFrozenBalanceForBandwidth(); - final long delegatedBandwidthInSolidity = account014.getDelegatedFrozenBalanceForBandwidth(); - final long acquiredForEnergyInSolidity = account014.getAccountResource() - .getAcquiredDelegatedFrozenBalanceForEnergy(); - final long delegatedForEnergyInSolidity = account014.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(); - - logger.info("delegatedForEnergyInSolidity " + delegatedForEnergyInSolidity); - Assert.assertTrue(netUsageInSoliInFull > 0 && netUsageInSolidity > 0 - && netUsageInFullnode > 0); - Assert.assertTrue(netUsageInFullnode <= netUsageInSoliInFull + 5 - && netUsageInFullnode >= netUsageInSoliInFull - 5); - Assert.assertTrue(netUsageInFullnode <= netUsageInSolidity + 5 - && netUsageInFullnode >= netUsageInSolidity - 5); - Assert.assertTrue(acquiredForBandwidthInFullnode == acquiredForBandwidthInSoliInFull - && acquiredForBandwidthInFullnode == acquiredForBandwidthInSolidity); - Assert.assertTrue(delegatedBandwidthInFullnode == delegatedBandwidthInSoliInFull - && delegatedBandwidthInFullnode == delegatedBandwidthInSolidity); - Assert.assertTrue(acquiredForEnergyInFullnode == acquiredForEnergyInSoliInFull - && acquiredForEnergyInFullnode == acquiredForEnergyInSolidity); - Assert.assertTrue(delegatedForEnergyInFullnode == delegatedForEnergyInSoliInFull - && delegatedForEnergyInFullnode == delegatedForEnergyInSolidity); - Assert.assertTrue(acquiredForBandwidthInSoliInFull == 1000000 - && delegatedBandwidthInSoliInFull == 1000000 && acquiredForEnergyInSoliInFull == 1000000 - && delegatedForEnergyInSoliInFull == 1000000); - logger.info("lastCustomeTimeInSoliInFull " + lastCustomeTimeInSoliInFull); - Assert.assertTrue(lastCustomeTimeInFullnode == lastCustomeTimeInSolidity - && lastCustomeTimeInFullnode == lastCustomeTimeInSoliInFull); - logger.info("lastCustomeTimeInSoliInFull " + lastCustomeTimeInSoliInFull); - Assert.assertTrue(lastCustomeTimeInSoliInFull != 0); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(account014Address, account014Key, fromAddress, blockingStubFull); - PublicMethed - .freedResource(account014SecondAddress, account014SecondKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount015.java deleted file mode 100644 index 640f6f202ad..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestAccount015.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestAccount015 { - - private static final long now = System.currentTimeMillis(); - private static long amount = 100000000L; - private static String accountId = "accountid_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account015Address = ecKey1.getAddress(); - String account015Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - Random rand = new Random(); - amount = amount + rand.nextInt(10000); - } - - @Test(enabled = true, description = "Set account id") - public void test01SetAccountId() { - //Create account014 - ecKey1 = new ECKey(Utils.getRandom()); - account015Address = ecKey1.getAddress(); - account015Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - PublicMethed.printAddress(account015Key); - Assert.assertTrue(PublicMethed.sendcoin(account015Address, amount, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.setAccountId(accountId.getBytes(), - account015Address, account015Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Get account by id") - public void test02GetAccountById() { - Assert.assertEquals(amount, PublicMethed.getAccountById( - accountId, blockingStubFull).getBalance()); - } - - - @Test(enabled = true, description = "Get account by id from solidity") - public void test03GetAccountByIdFromSolidity() { - Assert.assertEquals(amount, PublicMethed.getAccountByIdFromSolidity( - accountId, blockingStubSoliInFull).getBalance()); - } - - @Test(enabled = true, description = "Get account by id from PBFT") - public void test04GetAccountByIdFromPbft() { - Assert.assertEquals(amount, PublicMethed.getAccountByIdFromSolidity( - accountId, blockingStubPbft).getBalance()); - } - - - @Test(enabled = true, description = "Get account from PBFT") - public void test05GetAccountFromPbft() { - Assert.assertEquals(amount, PublicMethed.queryAccount( - account015Address, blockingStubPbft).getBalance()); - } - - - @Test(enabled = true, description = "List witnesses") - public void test06ListWitness() { - Assert.assertTrue(PublicMethed.listWitnesses(blockingStubFull) - .get().getWitnessesCount() >= 2); - } - - @Test(enabled = true, description = "List witnesses from solidity node") - public void test07ListWitnessFromSolidity() { - Assert.assertTrue(PublicMethed.listWitnessesFromSolidity(blockingStubSolidity) - .get().getWitnessesCount() >= 2); - Assert.assertTrue(PublicMethed.listWitnessesFromSolidity(blockingStubSoliInFull) - .get().getWitnessesCount() >= 2); - } - - @Test(enabled = true, description = "List witnesses from PBFT node") - public void test08ListWitnessFromPbft() { - Assert.assertTrue(PublicMethed.listWitnessesFromSolidity(blockingStubPbft) - .get().getWitnessesCount() >= 2); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(account015Address, account015Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock001.java deleted file mode 100644 index e38dc2065eb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock001.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class WalletTestBlock001 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from fullnode") - public void testCurrentBlock() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock is " + Long.toString(currentBlock.getBlockHeader() - .getRawData().getNumber())); - - //Improve coverage. - currentBlock.equals(currentBlock); - Block newBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - newBlock.equals(currentBlock); - newBlock.hashCode(); - newBlock.getSerializedSize(); - newBlock.getTransactionsCount(); - newBlock.getTransactionsList(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Get now block from solidity") - public void testCurrentBlockFromSolidity() { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock in soliditynode is " + Long.toString(currentBlock - .getBlockHeader().getRawData().getNumber())); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java deleted file mode 100644 index 3517f4696cd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestBlock002.java +++ /dev/null @@ -1,381 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestBlock002 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSoliInFull = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSoliInFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSoliInFull = ManagedChannelBuilder.forTarget(soliInFullnode) - .usePlaintext(true) - .build(); - blockingStubSoliInFull = WalletSolidityGrpc.newBlockingStub(channelSoliInFull); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "GetBlockByNum from fullnode") - public void test01GetBlockByNum() { - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubFull.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader()); - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - Block firstBlock = blockingStubFull.getBlockByNum(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - Block lastSecondBlock = blockingStubFull.getBlockByNum(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - } - - @Test(enabled = true, description = "GetBlockByNum from solidity") - public void test02GetBlockByNumFromSolidity() { - Block currentBlock = blockingStubSolidity - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubSolidity.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader()); - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - Block firstBlock = blockingStubSolidity.getBlockByNum(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("firstblock test from solidity succesfully"); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - Block lastSecondBlock = blockingStubSolidity.getBlockByNum(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from solidity succesfully"); - } - - @Test(enabled = true, description = "Get block by id") - public void test03GetBlockById() { - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - ByteString currentHash = currentBlock.getBlockHeader().getRawData().getParentHash(); - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(currentHash).build(); - Block setIdOfBlock = blockingStubFull.getBlockById(request); - Assert.assertTrue(setIdOfBlock.hasBlockHeader()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - logger.info(Long.toString(setIdOfBlock.getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString(currentBlock.getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - setIdOfBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlock.getBlockHeader() - .getRawData().getNumber()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("By ID test succesfully"); - } - - - @Test(enabled = true, description = "Get transaction count by block num") - public void test04GetTransactionCountByBlockNum() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - - Assert.assertTrue(blockingStubFull.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - } - - @Test(enabled = true, description = "Get transaction count by block num from solidity") - public void test05GetTransactionCountByBlockNumFromSolidity() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - - Assert.assertTrue(blockingStubSolidity.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - Assert.assertTrue(blockingStubSoliInFull.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - } - - @Test(enabled = true, description = "Get transaction count by block num from PBFT") - public void test06GetTransactionCountByBlockNumFromPbft() { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(0); - - Assert.assertTrue(blockingStubPbft.getTransactionCountByBlockNum(builder.build()) - .getNum() > 3); - } - - @Test(enabled = true, description = "Get now block from PBFT") - public void test07GetNowBlockFromPbft() { - Block nowBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nowBlockNum = nowBlock.getBlockHeader().getRawData().getNumber(); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubPbft); - Block pbftNowBlock = blockingStubPbft.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long nowPbftBlockNum = pbftNowBlock.getBlockHeader().getRawData().getNumber(); - logger.info("nowBlockNum:" + nowBlockNum + " , nowPbftBlockNum:" + nowPbftBlockNum); - Assert.assertTrue(nowPbftBlockNum >= nowBlockNum); - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubPbft); - GrpcAPI.BlockExtention pbftNowBlock2 = blockingStubPbft.getNowBlock2(GrpcAPI.EmptyMessage - .newBuilder().build()); - Long nowPbftBlockNum2 = pbftNowBlock2.getBlockHeader().getRawData().getNumber(); - logger.info("nowBlockNum:" + nowBlockNum + " , nowPbftBlockNum2:" + nowPbftBlockNum2); - Assert.assertTrue(nowPbftBlockNum2 >= nowBlockNum); - } - - - @Test(enabled = true, description = "Get block by num from PBFT") - public void test08GetBlockByNumFromPbft() { - Block currentBlock = blockingStubPbft - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubPbft.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader()); - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - Block firstBlock = blockingStubPbft.getBlockByNum(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("firstblock test from solidity succesfully"); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - Block lastSecondBlock = blockingStubPbft.getBlockByNum(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from solidity succesfully"); - - //Query the second latest block getBlockByNum2. - NumberMessage.Builder builder4 = NumberMessage.newBuilder(); - builder4.setNum(currentBlockNum - 1); - GrpcAPI.BlockExtention lastSecondBlock1 = blockingStubPbft.getBlockByNum2(builder4.build()); - Assert.assertTrue(lastSecondBlock1.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock1.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock1.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock1.getBlockHeader().getRawData().getWitnessAddress() - .isEmpty()); - Assert.assertTrue( - lastSecondBlock1.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock1.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock1.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from getBlockByNum2 succesfully"); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSoliInFull != null) { - channelSoliInFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestMutiSign002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestMutiSign002.java deleted file mode 100644 index 7b69b3b11b6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestMutiSign002.java +++ /dev/null @@ -1,459 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.PaginatedMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey3.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey4.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "MutiSign for create token") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(exchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "MutiSign for create exchange") - public void test2CreateExchange() { - ecKey3 = new ECKey(Utils.getRandom()); - manager1Address = ecKey3.getAddress(); - manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - ecKey4 = new ECKey(Utils.getRandom()); - manager2Address = ecKey4.getAddress(); - manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = exchange001Key; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(exchange001Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, exchange001Address, exchange001Key, - blockingStubFull, ownerKeyString); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = updateAccountPermissionFee + multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1024_000_000L); - - } - - @Test(enabled = true, description = "List exchange after create exchange by MutiSign") - public void test3ListExchange() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - for (Integer i = 0; i < listExchange.get().getExchangesCount(); i++) { - Assert.assertFalse(ByteArray.toHexString(listExchange.get().getExchanges(i) - .getCreatorAddress().toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getExchangeId() > 0); - Assert.assertFalse(ByteArray.toStr(listExchange.get().getExchanges(i).getFirstTokenId() - .toByteArray()).isEmpty()); - Assert.assertTrue(listExchange.get().getExchanges(i).getFirstTokenBalance() > 0); - } - } - - @Test(enabled = true, description = "Mutisign for inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethedForMutiSign.injectExchange( - exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "MutiSign for withdraw exchange") - public void test5WithdrawExchange() { - - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw( - exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "MutiSign for transaction exchange") - public void test6TransactionExchange() { - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - long needCoin = multiSignFee; - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "GetExchangeListPaginated after " - + "MutiSign exchange kind of transaction") - - public void test7GetExchangeListPaginated() { - PaginatedMessage.Builder pageMessageBuilder = PaginatedMessage.newBuilder(); - pageMessageBuilder.setOffset(0); - pageMessageBuilder.setLimit(100); - ExchangeList exchangeList = blockingStubFull - .getPaginatedExchangeList(pageMessageBuilder.build()); - Assert.assertTrue(exchangeList.getExchangesCount() >= 1); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - //Solidity support getExchangeId - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubSolidity); - logger.info("createtime is" + exchangeIdInfo.get().getCreateTime()); - Assert.assertTrue(exchangeIdInfo.get().getCreateTime() > 0); - - //Solidity support listexchange - listExchange = PublicMethed.getExchangeList(blockingStubSolidity); - Assert.assertTrue(listExchange.get().getExchangesCount() > 0); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, exchange001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .unFreezeBalance(exchange001Address, exchange001Key, 0, fromAddress, blockingStubFull); - PublicMethed.freedResource(exchange001Address, exchange001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(secondExchange001Address, secondExchange001Key, fromAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestNode001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestNode001.java deleted file mode 100644 index e9496dc9a7d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestNode001.java +++ /dev/null @@ -1,106 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestNode001 { - - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - - @Test(enabled = true, description = "List all nodes") - public void testGetAllNode() { - GrpcAPI.NodeList nodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - GrpcAPI.NodeList nodeList1 = blockingStubFull1 - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - Integer times = 0; - while (nodeList.getNodesCount() == 0 && times++ < 5) { - nodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - nodeList1 = blockingStubFull1 - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - if (nodeList.getNodesCount() != 0 || nodeList1.getNodesCount() != 0) { - break; - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - //Assert.assertTrue(nodeList.getNodesCount() != 0 || nodeList1.getNodesCount() != 0); - - for (Integer j = 0; j < nodeList.getNodesCount(); j++) { - //Assert.assertTrue(nodeList.getNodes(j).hasAddress()); - //Assert.assertFalse(nodeList.getNodes(j).getAddress().getHost().isEmpty()); - //Assert.assertTrue(nodeList.getNodes(j).getAddress().getPort() < 65535); - //logger.info(ByteArray.toStr(nodeList.getNodes(j).getAddress().getHost().toByteArray())); - } - logger.info("get listnode succesuflly"); - - //Improve coverage. - GrpcAPI.NodeList newNodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - nodeList.equals(nodeList); - nodeList.equals(newNodeList); - nodeList.getNodesList(); - nodeList.hashCode(); - nodeList.isInitialized(); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer002.java deleted file mode 100644 index 06760b8f94d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer002.java +++ /dev/null @@ -1,208 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.TransferContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestTransfer002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false) - public void testGetTotalTransaction() { - NumberMessage beforeGetTotalTransaction = blockingStubFull - .totalTransaction(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(beforeGetTotalTransaction.getNum())); - Long beforeTotalTransaction = beforeGetTotalTransaction.getNum(); - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - NumberMessage afterGetTotalTransaction = blockingStubFull - .totalTransaction(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Long.toString(afterGetTotalTransaction.getNum())); - Long afterTotalTransaction = afterGetTotalTransaction.getNum(); - Assert.assertTrue(afterTotalTransaction - beforeTotalTransaction > 0); - - //Improve coverage. - afterGetTotalTransaction.equals(beforeGetTotalTransaction); - afterGetTotalTransaction.equals(afterGetTotalTransaction); - afterGetTotalTransaction.hashCode(); - afterGetTotalTransaction.isInitialized(); - afterGetTotalTransaction.getSerializedSize(); - afterGetTotalTransaction.getDefaultInstanceForType(); - afterGetTotalTransaction.getParserForType(); - afterGetTotalTransaction.getUnknownFields(); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer005.java deleted file mode 100644 index 39c8ad9daef..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer005.java +++ /dev/null @@ -1,227 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer005 { - - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - - } - - @Test(enabled = false) - public void testgetTransactionsFromThis() { - //Create a transfer. - //Assert.assertTrue(PublicMethed.sendcoin(toAddress,1000000,fromAddress, - // testKey002,blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - Optional gettransactionsfromthis = Optional - .ofNullable(transactionList); - - if (gettransactionsfromthis.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, - blockingStubSolidity)); - } - - Assert.assertTrue(gettransactionsfromthis.isPresent()); - Integer beforecount = gettransactionsfromthis.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse(gettransactionsfromthis.get().getTransaction(j) - .getRawData().getContractList().isEmpty()); - } - } - - @Test(enabled = false) - public void testgetTransactionsFromThisByInvaildAddress() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - Optional gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionList = blockingStubExtension - .getTransactionsFromThis(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer006.java deleted file mode 100644 index 4223cdafca6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestTransfer006.java +++ /dev/null @@ -1,229 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer006 { - - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - - } - - @Test(enabled = false) - public void testgetTransactionsToThis() { - //Create a transfer. - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(toAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - - Optional gettransactionstothis = Optional - .ofNullable(transactionList); - - if (gettransactionstothis.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, - blockingStubSolidity)); - //logger.info("This account didn't transfation any coin to other"); - } - - Assert.assertTrue(gettransactionstothis.isPresent()); - Integer beforecount = gettransactionstothis.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse(gettransactionstothis.get().getTransaction(j) - .getRawData().getContractList().isEmpty()); - } - } - - @Test(enabled = false) - public void testgetTransactionsToThisByInvaildAddress() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionList transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - Optional gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionList = blockingStubExtension - .getTransactionsToThis(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionList); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(toAddress, testKey003, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestWitness003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestWitness003.java deleted file mode 100644 index f76efdfd6ed..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/manual/WalletTestWitness003.java +++ /dev/null @@ -1,326 +0,0 @@ -package stest.tron.wallet.dailybuild.manual; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.WitnessContract.WitnessCreateContract; -import org.tron.protos.contract.WitnessContract.WitnessUpdateContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class WalletTestWitness003 { - - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final Long costForCreateWitness = 9999000000L; - private static final String tooLongUrl = "qagwqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqas" - + "wqaswqasw1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazx" - + "swedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String testUpdateWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] updateAddress = PublicMethed.getFinalAddress(testUpdateWitnessKey); - String createWitnessUrl = "http://www.createwitnessurl.com/"; - String updateWitnessUrl = "http://www.updatewitnessurl.com/"; - String nullUrl = ""; - String spaceUrl = " ##################~!@#$%^&*()_+}{|:'/.,<>?|]=-"; - byte[] createUrl = createWitnessUrl.getBytes(); - byte[] updateUrl = updateWitnessUrl.getBytes(); - byte[] wrongUrl = nullUrl.getBytes(); - byte[] updateSpaceUrl = spaceUrl.getBytes(); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(lowBalTest); - logger.info(ByteArray.toHexString(PublicMethed.getFinalAddress(lowBalTest))); - logger.info(Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest))); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Invaild account to apply create witness") - public void testInvaildToApplyBecomeWitness() { - Assert.assertFalse(createWitnessNotBroadcast(INVAILD_ADDRESS, createUrl, testKey002)); - } - - @Test(enabled = true, description = "Create witness") - public void testCreateWitness() { - //If you are already is witness, apply failed - //createWitness(fromAddress, createUrl, testKey002); - //Assert.assertFalse(createWitness(fromAddress, createUrl, testKey002)); - - //No balance,try to create witness. - Assert.assertFalse(createWitnessNotBroadcast(lowBalAddress, createUrl, lowBalTest)); - - //Send enough coin to the apply account to make that account - // has ability to apply become witness. - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - GrpcAPI.WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - Assert.assertTrue(PublicMethed - .sendcoin(lowBalAddress, costForCreateWitness, fromAddress, testKey002, - blockingStubFull)); - //null url, update failed - Assert.assertFalse(createWitnessNotBroadcast(lowBalAddress, wrongUrl, testUpdateWitnessKey)); - //too long url, update failed - Assert.assertFalse(createWitnessNotBroadcast(lowBalAddress, - tooLongUrl.getBytes(), testUpdateWitnessKey)); - Assert.assertTrue(createWitnessNotBroadcast(lowBalAddress, createUrl, lowBalTest)); - - } - } - - @Test(enabled = true, description = "Update witness") - public void testUpdateWitness() { - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - GrpcAPI.WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - //null url, update failed - Assert.assertFalse(updateWitness(updateAddress, wrongUrl, testUpdateWitnessKey)); - //too long url, update failed - Assert.assertFalse(updateWitness(updateAddress, tooLongUrl.getBytes(), testUpdateWitnessKey)); - //Content space and special char, update success - Assert.assertTrue(updateWitness(updateAddress, updateSpaceUrl, testUpdateWitnessKey)); - //update success - Assert.assertTrue(updateWitness(updateAddress, updateUrl, testUpdateWitnessKey)); - } else { - logger.info("Update witness case had been test.This time skip it."); - } - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitnessNotBroadcast(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessCreateContract.Builder builder = WitnessCreateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - return true; - } - - /** - * constructor. - */ - - public Boolean updateWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessUpdateContract.Builder builder = WitnessUpdateContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = PublicMethed.broadcastTransaction(transaction, blockingStubFull); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign01.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign01.java deleted file mode 100644 index eb9f64b1073..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign01.java +++ /dev/null @@ -1,894 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign01 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner permission_name is owner") - public void testOwnerName01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner permission_name is owner1") - public void testOwnerName02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner1\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name is string \"123\"") - public void testOwnerName03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"123\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name is string \"\"") - public void testOwnerName04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner permission_name is null") - public void testOwnerName05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - // null - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":" + null - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner without permission_name") - public void testOwnerName06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner permission_name is numbers") - public void testOwnerName07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":123,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name is 0.1") - public void testOwnerName08() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"0.1\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner permission_name length is 32") - public void testOwnerName09() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdef\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - - @Test(enabled = true, description = "Owner permission_name length is 33") - public void testOwnerName10() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdefg\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's name is too long", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner permission_name contains special char") - public void testOwnerName11() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"0&^%\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0&^%%09\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - logger.info("1111___" + PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getOwnerPermission().toString()); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("22222___" + PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getOwnerPermission().toString()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign02.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign02.java deleted file mode 100644 index b732a0e1619..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign02.java +++ /dev/null @@ -1,719 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign02 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner threshold in exception condition") - public void testOwnerThreshold01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - ownerPermissionKeys.add(ownerKey); - - // threshold = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":-2147483648," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":0," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":-1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - logger.info("** update owner and active permission to two address"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":-9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":-9223372036855775828,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":-9223372036854775809,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":\"12a\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":\"\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\":" + null + ",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = 1.1 - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 1.1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = Long.MAX_VALUE < sum(weight) - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner threshold is 1") - public void testOwnerThreshold02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner threshold is more than sum of keys' weight") - public void testOwnerThreshold03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // theshold = Long.MAX_VALUE > sum(weight) - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":214748364}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not" - + " be less than threshold in permission Owner", - response.getMessage().toStringUtf8()); - - // theshold = Integer.MAX_VALUE > sum(weight) - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 2147483647,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":214748364}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight " - + "should not be less than threshold in permission Owner", - response.getMessage().toStringUtf8()); - - // theshold = Long.MAX_VALUE + 1 > sum(weight) - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner threshold is Long.MAX_VALUE and equal sum(weight)") - public void testOwnerThreshold04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner threshold is Integer.MAX_VALUE") - public void testOwnerThreshold05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\"," - + "\"threshold\": 2147483647,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign03.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign03.java deleted file mode 100644 index cb0817fb70b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign03.java +++ /dev/null @@ -1,541 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign03 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Owner doesn't have parent_id") - public void testOwnerParent01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner parent_id in exception condition") - public void testOwnerParent02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // parent_id = "123" - String accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":\"123\",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = "abc" - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":\"abc\",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("Expected NumberFormatException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = "" - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":\"\",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = null - - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":" + null + ",\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = 1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":1,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 2 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":2,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 3 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":3,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = -1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":3,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":2147483647,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE +1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":2147483648,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":-2147483648,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE -1 - accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":-2147483649,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner parent_id is 0") - public void testOwnerParent03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"parent_id\":0,\"type\":0," - + "\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign04.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign04.java deleted file mode 100644 index abb64dc6274..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign04.java +++ /dev/null @@ -1,550 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign04 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Owner weight in exception condition") - public void testOwnerWeight01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - - // weight = Integer.MIN_VALUE - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = 0 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":0}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":0}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = -1 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-9223372036854775808}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - 1000020 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-9223372036855775828}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "12a" - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":\"12a\"}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "" - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":\"\"}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = null - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":" + null + "}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // sum(weight) > Long.MAX_VALUE - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - // weight = 1.1 - accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1.1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner weight is 1") - public void testOwnerWeight02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - - @Test(enabled = true, description = "Owner weight is Long.MAX_VALUE") - public void testOwnerWeight04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign05.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign05.java deleted file mode 100644 index b4c639089cc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign05.java +++ /dev/null @@ -1,746 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign05 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Owner key-address is witness account") - public void testOwnerKeyAddress01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "Owner key-address is contract address") - public void testOwnerKeyAddress02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner key-address is inactive address") - public void testOwnerKeyAddress03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey01); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner key-address is owner address") - public void testOwnerKeyAddress04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner key-address in exception condition") - public void testOwnerKeyAddress05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address = owner_address more than once - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : address should be distinct " - + "in permission Owner", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = short address - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = - fakeAddress = ""; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":5}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = null - - fakeAddress = null; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + fakeAddress - + "\",\"weight\":5}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, fakeAddress.getBytes(), ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = "1.1" - fakeAddress = "1.1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + fakeAddress - + "\",\"weight\":5}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (IllegalArgumentException e) { - logger.info("IllegalArgumentException!"); - ret = true; - } - - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner key-address count is 5") - public void testOwnerKeyAddress06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(5, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(testKey002); - ownerPermissionKeys.add(witnessKey001); - ownerPermissionKeys.add(tmpKey01); - ownerPermissionKeys.add(tmpKey02); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner key-address count in exception condition") - public void testOwnerKeyAddress07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address count = 6 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : number of keys in permission should" - + " not be greater than 5", - response.getMessage().toStringUtf8()); - - // address count = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":5," - + "\"keys\":[]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's count should be greater than 0", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign06.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign06.java deleted file mode 100644 index f5c58d5b7b0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign06.java +++ /dev/null @@ -1,689 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign06 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner type in exception condition") - public void testOwnerType01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - // type = 1 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = 2 - accountPermissionJson = - "{\"owner_permission\":{\"type\":2,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":-1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":-9223372036855775828,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":\"12a\",\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException: For input string: \"12a\""); - ret = true; - } - Assert.assertTrue(ret); - - // type = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":\"\",\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = - accountPermissionJson = - "{\"owner_permission\":{\"type\":,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":" + null + ",\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - // type = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":2147483647,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":9223372036854775807,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":-9223372036854775809,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE + 10 - accountPermissionJson = "{\"owner_permission\":{\"type\":9223372036854775817," - + "\"permission_name\":\"owner\",\"threshold\": 1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission type is error", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner type is 0") - public void testOwnerType02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "Owner type is Long.Min") - public void testOwnerType03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":-9223372036854775808,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Owner type is Long.MAX_VALUE + 1") - public void testOwnerType04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":9223372036854775808,\"permission_name\":\"Owner\"," - + "\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - - @Test(enabled = true, description = "Owner type is 0.1") - public void testOwnerType05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] ownerAddress = ecKey1.getAddress(); - final String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0.1," - + "\"permission_name\":\"owner\",\"threshold\": 1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign07.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign07.java deleted file mode 100644 index 41745b6047b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign07.java +++ /dev/null @@ -1,662 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign07 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner permission_name is owner") - public void testActiveName01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"owner\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - @Test(enabled = true, description = "Owner permission_name is active") - public void testActiveName02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - @Test(enabled = true, description = "Owner permission_name is activea") - public void testActiveName03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"activea\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Owner permission_name is \"123\"") - public void testActiveName04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"123\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Owner permission_name is \"\"") - public void testActiveName05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Owner permission_name in exception condition") - public void testActiveName06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" + null - + ",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // name = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":,\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("Expected com.alibaba.fastjson.JSONException!"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Owner permission_name is 1.1") - public void testActiveName07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":1.1,\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active permission_name length is 32") - public void testActiveName08() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1000000, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdef\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - - @Test(enabled = true, description = "Active permission_name length is 33") - public void testActiveName09() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner001\",\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2," - + "\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdefg\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's name is too long", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign08.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign08.java deleted file mode 100644 index e23d5d7d6ca..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign08.java +++ /dev/null @@ -1,623 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign08 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active threshold is exception condition") - public void testActiveTheshold01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // threshold = Integer.Min_Value - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-2147483648," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":0," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-9223372036854775808," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : permission's" + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // threshold = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-9223372036855775828," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":-9223372036854775809," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":\"-12a\"," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException : -12a !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":\"\"," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":" + null + "," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = 1.9 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1.9," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":21}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // threshold = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - // theshold = 1.1 > sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1.1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active threshold is 1") - public void testActiveTheshold02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active threshold is more than sum of weight") - public void testActiveTheshold03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // threshold = Integer.MAX_VALUE *2 + 5 > sum(weight) - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":4294967299," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2147483647}," + "{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\",\"weight\":3}," + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":2147483647}" + "]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not" - + " be less than threshold in permission Active", response.getMessage().toStringUtf8()); - - } - - @Test(enabled = true, description = "Active threshold is Long.MAX_VALUE") - public void testActiveTheshold04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active threshold is Integer.MAX_VALUE") - public void testActiveTheshold05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":2147483647," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483646}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":2147483647}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign09.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign09.java deleted file mode 100644 index 44463b368c7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign09.java +++ /dev/null @@ -1,489 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign09 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active doesn't have parent_id") - public void testActiveParent01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":4," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Active parent_id is exception condition") - public void testActiveParent02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // parent_id = "123" - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":\"123\",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - - // parent_id = "abc" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":\"abc\",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("Expected NumberFormatException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":\"\",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":" + null - + ",\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":1,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 2 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":2,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 3 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":3,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":-1,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":2147483647,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE +1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":2147483648,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":-2147483648,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" + "{\"parent_id\":-2147483649,\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active parent_id is 0") - public void testActiveParent03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}]}," - + "\"active_permissions\":[" - + "{\"parent_id\":0,\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign10.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign10.java deleted file mode 100644 index 31ce7e37c8f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign10.java +++ /dev/null @@ -1,651 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign10 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active weight is exception condition") - public void testActiveWeight01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // weight = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-2147483648}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":0}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-9223372036854775808}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" - + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-9223372036855775828}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":\"12a\"}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":\"\"}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":-9223372036855775828}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":" - + null + "}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = Long.MIN -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":-9223372036854775809}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1.1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active weight is 1") - public void testActiveWeight02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(3, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active weight is Integer.MAX_VALUE") - public void testActiveWeight03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":21474836471}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":21474836471}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active sum of weight is more than Long.MAX_VALUE") - public void testActiveWeight04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : long overflow", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active weight is Long.MAX_VALUE") - public void testActiveWeight05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775807}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign11.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign11.java deleted file mode 100644 index 2c0a4aa4696..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign11.java +++ /dev/null @@ -1,1089 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign11 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active address is witness") - public void testActiveAddress01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":4," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(witnessKey001); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is contract address") - public void testActiveAddress02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," + "{\"address\":\"" - + PublicMethed.getAddressString(testKey002) + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":3}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(3, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is inactive address") - public void testActiveAddress03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":5," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(tmpKey01); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is owner address") - public void testActiveAddress04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active address is exception condition") - public void testActiveAddress05() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address = same address more than once - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":3}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : address should be distinct" + " in permission Active", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = short address - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = - fakeAddress = ""; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = null - fakeAddress = null; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = 1.1 - fakeAddress = "1.1"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (IllegalArgumentException e) { - logger.info("IllegalArgumentException!"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - - } - - @Test(enabled = true, description = "Active address count is 5") - public void testActiveAddress06() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - activePermissionKeys.add(tmpKey02); - activePermissionKeys.add(testKey002); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"" - + ",\"threshold\":10," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(5, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(tmpKey01); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - - } - - @Test(enabled = true, description = "Active address count is more than 5") - public void testActiveAddress07() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":3}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : number of keys in permission should" + " not be greater than 5", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active address count is 0") - public void testActiveAddress08() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[]}]}"; - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's count should be greater than 0", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active address count is 1") - public void testActiveAddress09() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(witnessKey001); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active permission count is 8") - public void testActiveAddress10() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey01); - activePermissionKeys.add(tmpKey02); - activePermissionKeys.add(testKey002); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," + "\"active_permissions\":[" - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active1\",\"threshold\":5," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active2\",\"threshold\":7," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active3\",\"threshold\":9," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active4\",\"threshold\":10," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active5\",\"threshold\":11," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active6\",\"threshold\":10," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active7\",\"threshold\":11," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(40, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(tmpKey01); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 9, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Active permission count is 9") - public void testActiveAddress11() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," + "\"active_permissions\":[" - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active1\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active2\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active3\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active4\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active5\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active6\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active7\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active8\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is too many", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Active permission count is 8, " - + "sum of weight is less than threshold") - public void testActiveAddress12() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":2147483647}]}," + "\"active_permissions\":[" - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active1\",\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active2\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active3\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active4\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active5\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active6\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}," - + "{\"type\":2,\"permission_name\":\"active7\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":2}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) - + "\",\"weight\":3}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should" - + " not be less than threshold in permission Active", response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign12.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign12.java deleted file mode 100644 index 2f7ba226b32..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign12.java +++ /dev/null @@ -1,501 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign12 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active type is exception condition") - public void testActiveType01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // type = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-2147483648,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":0,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-1,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-9223372036854775808," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-9223372036855775828," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":-9223372036854775809," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":\"12a\",\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":\"\",\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":" + null + ",\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":1,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":9223372036854775807," - + "\"permission_name\":\"active0\"," - + "\"threshold\":9223372036854775807," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":9223372036854775808," - + "\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - // type = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":1.1,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":9223372036854775806}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission type is error", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Active type is 2.9") - public void testActiveType02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long needCoin = updateAccountPermissionFee; - - PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(tmpKey02); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2.9,\"permission_name\":\"active0\"," - + "\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":21}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign13.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign13.java deleted file mode 100644 index 2dd2a2c8d67..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign13.java +++ /dev/null @@ -1,845 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign13 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness permission_name is witness") - public void testWitnessName01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed - .sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is witness12") - public void testWitnessName02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000L, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is \"123\"") - public void testWitnessName03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"123\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is \"\"") - public void testWitnessName04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness permission_name is null") - public void testWitnessName05() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":" + null - + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness doesn't have permission_name") - public void testWitnessName06() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness permission_name is 123") - public void testWitnessName07() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"permission_name\":123,\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name is 0.1") - public void testWitnessName08() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"permission_name\":\"0.1\",\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness permission_name length is 32") - public void testWitnessName09() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":" - + "{\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdef\",\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - - @Test(enabled = true, description = "Witness permission_name length is 33") - public void testWitnessName10() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":" - + "{\"permission_name\":\"abcdefghijklmnopqrstuvwxyzabcdefg\",\"type\":1," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's name is too long", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign14.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign14.java deleted file mode 100644 index 25fadd1e082..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign14.java +++ /dev/null @@ -1,699 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign14 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness threshold is exception condition") - public void testWitnessThreshold01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // theshold = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-2147483648,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":0,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's" - + " threshold should be greater than 0", - response.getMessage().toStringUtf8()); - - // theshold = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-9223372036855775828,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":-9223372036854775809,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = "12a" - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":\"12a\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":\"\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":" + null + ",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = Long.MAX_VALUE < sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not be" - + " less than threshold in permission Witness", - response.getMessage().toStringUtf8()); - - // theshold = Long.MAX_VALUE + 1 > sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":9223372036854775808,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // theshold = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1.1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775806}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - Assert.assertTrue(PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - @Test(enabled = true, description = "Witness threshold is 1") - public void testWitnessThreshold02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness threshold is more than sum of weight") - public void testWitnessThreshold03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // threshold > sum(weight) - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":4294967299,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight should not be" - + " less than threshold in permission Witness", - response.getMessage().toStringUtf8()); - - // threshold = Integer.MAX_VALUE > sum(weight) - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":2147483647,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":214748364}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : sum of all key's weight " - + "should not be less than threshold in permission Witness", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness threshold is Long.MAX_VALUE") - public void testWitnessThreshold04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign15.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign15.java deleted file mode 100644 index a0e7124bd69..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign15.java +++ /dev/null @@ -1,597 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign15 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull); - } - - @Test(enabled = true, description = "Witness doesn't have parent_id") - public void testWitnessParent01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness parent_id is exception condition") - public void testWitnessParent02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // parent_id = "123" - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":\"123\",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 123 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":123,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = "abc" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":\"abc\",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("Expected NumberFormatException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":\"\",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":" + null + ",\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // parent_id = 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":1,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 2 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":2,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = 3 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":3,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":-1,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":2147483647,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MAX_VALUE +1 - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":2147483648,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":-2147483648,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - - // parent_id = Integer.MIN_VALUE -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":-2147483649,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : permission's parent should be owner", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness parent_id is 0") - public void testWitnessParent03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"parent_id\":0,\"type\":1," - + "\"permission_name\":\"witness\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign16.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign16.java deleted file mode 100644 index 8504f12df7b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign16.java +++ /dev/null @@ -1,574 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign16 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness weight is exception condition") - public void testWitnessWeight01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // weight = Integer.MIN_VALUE - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":0}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-9223372036854775808}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's weight" + " should be greater than 0", - response.getMessage().toStringUtf8()); - - // weight = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":-9223372036855775828}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":\"12a\"}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":\"\"}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":" + null + "}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // Long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":9223372036854775808}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - // weight = 1.1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1.1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - @Test(enabled = true, description = "Witness weight is 1") - public void testWitnessWeight02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness weight is Integer.MAX_VALUE") - public void testWitnessWeight03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2147483647}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness weight is Long.MAX_VALUE") - public void testWitnessWeight04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":9223372036854775807,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":9223372036854775807}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign17.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign17.java deleted file mode 100644 index 735933714fc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign17.java +++ /dev/null @@ -1,735 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign17 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness address is witness") - public void testWitnessAddress01() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is contract") - public void testWitnessAddress02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + contractTronDiceAddr + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is inactive address") - public void testWitnessAddress03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is owner_address") - public void testWitnessAddress04() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address is exception condition") - public void testWitnessAddress05() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // address = owner_address more than once - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Witness permission's key count should be 1", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // address = short address - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - // address = - fakeAddress = ""; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = null - fakeAddress = null; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, fakeAddress.getBytes(), ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException!"); - ret = true; - } - - Assert.assertTrue(ret); - - // address = "1.1" - fakeAddress = "1.1"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + fakeAddress + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (IllegalArgumentException e) { - logger.info("IllegalArgumentException!"); - ret = true; - } - - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness address account is 5") - public void testWitnessAddress06() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Witness permission's key count should be 1", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Witness address account is 0") - public void testWitnessAddress07() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness12\"," - + "\"threshold\":1,\"keys\":[]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : key's count should be greater than 0", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign18.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign18.java deleted file mode 100644 index 809f7d484ec..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign18.java +++ /dev/null @@ -1,612 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign18 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Witness type is 1") - public void testWitnessType01() { - // type = 1 - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness type is exception condition") - public void testWitnessType02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // type = 2 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":2,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = 0 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":0,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = -1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-1,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-9223372036854775808,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1000020 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-9223372036855775828,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = "12a" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":\"12a\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException: For input string: \"12a\""); - ret = true; - } - Assert.assertTrue(ret); - - // type = "" - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":\"\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = null - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":" + null + ",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // type = Integer.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":2147483647,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":9223372036854775807,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":9223372036854775808,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = long.min - 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":-9223372036854775809,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - - // type = Long.MAX_VALUE + 1 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":9223372036854775808,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission type is error", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore, balanceAfter); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Witness type is 1.5") - public void testWitnessType03() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1.5,\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign19.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign19.java deleted file mode 100644 index a2a61d4d5b2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign19.java +++ /dev/null @@ -1,647 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign19 { - - public static final String DEFAULT_OPERATION = - "7fff1fc0033e0000000000000000000000000000000000000000000000000000"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Active operation is ContractType.TransferContract_VALUE") - public void testActiveOperations01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - List activePermissionKeys2 = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - activePermissionKeys2.add(witnessKey001); - - Integer[] ints = {ContractType.TransferContract_VALUE}; - String operationsTransfer = PublicMethedForMutiSign.getOperations(ints); - Integer[] ints2 = {ContractType.TransferAssetContract_VALUE}; - String operationsTransferAsset = PublicMethedForMutiSign.getOperations(ints2); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operationsTransfer + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operationsTransferAsset + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "]}]}"; - - Assert.assertTrue( - PublicMethedForMutiSign.accountPermissionUpdateWithPermissionId(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, 0, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign - .getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 3, ownerKey, - blockingStubFull, - activePermissionKeys2.toArray(new String[activePermissionKeys2.size()]))); - - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys2.toArray(new String[activePermissionKeys2.size()]))); - - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - - } - - @Test(enabled = true, description = "Active operation is" - + " 0000000000000000000000000000000000000000000000000000000000000000") - public void testActiveOperations02() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(testKey002); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"0000000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue( - PublicMethedForMutiSign.accountPermissionUpdateWithPermissionId(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, 0, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(1, PublicMethedForMutiSign - .getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Active operation include invalid contract") - public void testActiveOperations03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - // operation include invalid 99 contract - Integer[] ints = {0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 31, - 32, 33, 41, 42, 43, 44, 45, 99}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : 99 isn't a validate ContractType", - response.getMessage().toStringUtf8()); - - // operation's length is less then 64, - // 63: 7fff1fc0033e000000000000000000000000000000000000000000000000000 - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : 21 isn't a validate ContractType", - response.getMessage().toStringUtf8()); - - // operation's length is less then 64, - // 62: 7fff1fc0033e00000000000000000000000000000000000000000000000000 - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e00000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // operation's length is more then 64, - // 65: 7fff1fc0033e00000000000000000000000000000000000000000000000000000 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":" - + "\"7fff1fc0033e00000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // operation's length is more then 64, - // 66: 7fff1fc0033e00000000000000000000000000000000000000000000000000000 - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":" - + "\"7fff1fc0033e000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // oprations = "12aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - // same result 12eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee - - operations = "12aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : 21 isn't a validate ContractType", - response.getMessage().toStringUtf8()); - - // operation = "" - - operations = ""; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - - // Operation = - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - // Operation = null - operations = null; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (org.bouncycastle.util.encoders.DecoderException e) { - logger.info("org.bouncycastle.util.encoders.DecoderException !"); - ret = true; - } - Assert.assertTrue(ret); - - // no Operation - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : operations size must 32", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Owner sets operation") - public void testActiveOperations04() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Owner permission needn't operations", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Witness sets operation") - public void testActiveOperations05() { - String ownerKey = witnessKey001; - byte[] ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + DEFAULT_OPERATION + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Witness permission needn't operations", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign20.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign20.java deleted file mode 100644 index e6cc4123bc0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign20.java +++ /dev/null @@ -1,518 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign20 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private final String contractTronDiceAddr = "TMYcx6eoRXnePKT1jVn25ZNeMNJ6828HWk"; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Owner address is witness") - public void testOwnerAddress01() { - // address = witness - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed - .freezeBalanceForReceiver(fromAddress, 50000000L, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull); - PublicMethed - .freezeBalanceForReceiver(fromAddress, 50000000L, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull); - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getWitnessPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Owner address is witness with exception condition") - public void testOwnerAddress02() { - // address = witness, without witness permission - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - PublicMethed.sendcoin(ownerAddress, 1_000000, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : witness permission is missed", - response.getMessage().toStringUtf8()); - - // address = witness, without active permission - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is missed", - response.getMessage().toStringUtf8()); - - // address = witness, without owner permission - accountPermissionJson = "{\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission is missed", - response.getMessage().toStringUtf8()); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @Test(enabled = true, description = "Owner address is normal address with exception condition") - public void testOwnerAddress03() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - // address = normal address, with witness permission - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"witness\"," - + "\"threshold\":1,\"keys\":[" + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : account isn't witness can't set" + " witness permission", - response.getMessage().toStringUtf8()); - - // address = normal address, without owner permission - accountPermissionJson = - "{\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : owner permission is missed", - response.getMessage().toStringUtf8()); - - // address = normal address, without active permission - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is missed", - response.getMessage().toStringUtf8()); - - // address = contract address - byte[] ownerAddress02 = contractTronDiceAddr.getBytes(); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress02, ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = not active address - ECKey ecKeyTmp = new ECKey(Utils.getRandom()); - final byte[] ownerAddressTmp = ecKeyTmp.getAddress(); - final String ownerKeyTmp = ByteArray.toHexString(ecKeyTmp.getPrivKeyBytes()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddressTmp, ownerKeyTmp, - blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : ownerAddress account does not exist", - response.getMessage().toStringUtf8()); - - // address = not exist - String fakeAddress = "THph9K2M2nLvkianrMGswRhz5hjSA9fuH1"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = long address - fakeAddress = "TR3FAbhiSeP7kSh39RjGYpwCqfMDHPMhX4d121"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = short address - - fakeAddress = "THph9K2M2nLvkianrMGswRhz5hj"; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = - fakeAddress = ""; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - // address = null - fakeAddress = null; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), - ownerKey, blockingStubFull); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - - // address = "1ab(*c" - fakeAddress = "1ab(*c"; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) - + "\",\"weight\":1}" + "]}]}"; - - response = PublicMethed - .accountPermissionUpdateForResponse(accountPermissionJson, fakeAddress.getBytes(), ownerKey, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : invalidate ownerAddress", - response.getMessage().toStringUtf8()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @AfterMethod - public void aftertest() { - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull); - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign21.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign21.java deleted file mode 100644 index eafca020b4a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign21.java +++ /dev/null @@ -1,228 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign21 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Permission Count is in exception condition") - public void testPermissionCount01() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - // count = 1 - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}}"; - - GrpcAPI.Return response = PublicMethed.accountPermissionUpdateForResponse(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull); - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : active permission is missed", - response.getMessage().toStringUtf8()); - - // count = 0 - accountPermissionJson = "[]"; - - boolean ret = false; - try { - PublicMethed.accountPermissionUpdateForResponse( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull); - } catch (com.alibaba.fastjson.JSONException e) { - logger.info("com.alibaba.fastjson.JSONException !"); - ret = true; - } - Assert.assertTrue(ret); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Permission Count is 4") - public void testPermissionCount02() { - ownerKey = witnessKey001; - ownerAddress = new WalletClient(ownerKey).getAddress(); - long needCoin = updateAccountPermissionFee * 2; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey01) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(1, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getWitnessPermission())); - - PublicMethedForMutiSign - .recoverWitnessPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign22.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign22.java deleted file mode 100644 index f56eef85291..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign22.java +++ /dev/null @@ -1,682 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.tron.api.GrpcAPI.Return.response_code.SIGERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign22 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Sign permission transaction by owner permission") - public void test01SignByOwnerKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(ownerKey); - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - ownerPermissionKeys.add(testKey002); - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, 0, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - - @Test(enabled = true, description = "Sign normal transaction by owner permission") - public void test02SignByOwnerKeyForNormal() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - - logger.info("** update owner permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(ownerKey); - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - ownerPermissionKeys.add(testKey002); - - logger.info("** trigger a normal permission"); - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 0, ownerKey, - blockingStubFull, ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1_000000); - } - - - @Test(enabled = true, description = "Sign normal transaction by active permission") - public void test03SignByActiveKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed - .sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - - List activePermissionKeys = new ArrayList<>(); - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(testKey002); - activePermissionKeys.add(normalKey001); - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(normalKey001) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - logger.info("** update owner permission to two address"); - logger.info("** trigger a normal permission"); - Assert.assertFalse(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 0, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - Assert.assertTrue(PublicMethedForMutiSign - .sendcoinWithPermissionId(fromAddress, 1_000000, ownerAddress, 2, ownerKey, - blockingStubFull, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - - @Test(enabled = true, description = "Sign permission transaction by active permission") - public void test04SignByActiveKeyForPermission() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - Integer[] ints = {ContractType.AccountPermissionUpdateContract_VALUE}; - final String operations = PublicMethedForMutiSign.getOperations(ints); - - PublicMethed.printAddress(ownerKey); - - List activePermissionKeys = new ArrayList<>(); - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(testKey002); - activePermissionKeys.add(normalKey001); - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," + "\"keys\":[" + "{\"address\":\"" - + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," + "{\"address\":\"" - + PublicMethed.getAddressString(normalKey001) + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, 2, - activePermissionKeys.toArray(new String[activePermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Sign permission transaction" - + " by address which is out of permission list") - public void test06SignByOtherKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1000000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(normalKey001); - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(SIGERROR, response.getCode()); - Assert.assertThat(response.getMessage().toStringUtf8(), - containsString("it is not contained of permission")); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Sign permission transaction " + "by empty permission list") - public void test07SignByEmptyObjectKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - String[] ownerPermissionKeys = new String[0]; - PublicMethed.printAddress(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerPermissionKeys); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(SIGERROR, response.getCode()); - Assert.assertEquals("validate signature error miss sig or contract", - response.getMessage().toStringUtf8()); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Sign permission transaction by empty address") - public void test08SignByEmptyKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - String[] ownerPermissionKeys = new String[1]; - PublicMethed.printAddress(ownerKey); - ownerPermissionKeys[0] = ""; - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - boolean ret = false; - try { - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys); - } catch (NumberFormatException e) { - logger.info("NumberFormatException !"); - ret = true; - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - - Assert.assertTrue(ret); - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - - } - - @Test(enabled = true, description = "Sign permission transaction by invalid address") - public void test07SignByStringKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - String emptyKey = "abc1222"; - - logger.info("** update active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + emptyKey + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed - .getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(emptyKey); - - boolean ret = false; - try { - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerKey.getBytes(), ownerKey, - blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - } catch (NullPointerException e) { - logger.info("NullPointerException !"); - ret = true; - } - Assert.assertTrue(ret); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @Test(enabled = true, description = "Set same permission") - public void test08RepeatUpdateSamePermission() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Sign permission transaction " - + "by active address and default permissionId") - public void test09SignListMoreThanPermissionKeys() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - PublicMethed.printAddress(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}" + "]}]}"; - - ownerPermissionKeys.add(testKey002); - ownerPermissionKeys.add(ownerKey); - - GrpcAPI.Return response = PublicMethedForMutiSign - .accountPermissionUpdateForResponse(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(SIGERROR, response.getCode()); - Assert.assertEquals( - "validate signature error Signature count " + "is 2 more than key counts of permission : 1", - response.getMessage().toStringUtf8()); - - Assert.assertEquals(1, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission() - .getKeysCount()); - - PublicMethedForMutiSign.printPermissionList( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList()); - - System.out.printf(PublicMethedForMutiSign.printPermission( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getOwnerPermission())); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign23.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign23.java deleted file mode 100644 index c2ec7fb39a3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign23.java +++ /dev/null @@ -1,1015 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.CoreMatchers.containsString; -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION; -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.NOT_ENOUGH_PERMISSION; -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.PERMISSION_ERROR; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign23 { - - private static final String AVAILABLE_OPERATION = - "7fff1fc0037e0000000000000000000000000000000000000000000000000000"; - private static final String DEFAULT_OPERATION = - "7fff1fc0033e0000000000000000000000000000000000000000000000000000"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Add sign for multi sign normal transaction") - public void test01MultiSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(1, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction, tmpKey02, 2, blockingStubFull); - - Transaction transaction2 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction1, witnessKey001, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Transaction transaction3 = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction4 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction, tmpKey02, 2, blockingStubFull); - Assert.assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction3,blockingStubFull)); - Assert.assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction4,blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - - @Test(enabled = true, description = "Add sign for multi sign permission transaction") - public void test02MultiSignPermissionTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee; - - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - Integer[] ints = {ContractType.AccountPermissionUpdateContract_VALUE}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + operations + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a permission transaction"); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - Transaction transaction = PublicMethedForMutiSign.accountPermissionUpdateWithoutSign( - accountPermissionJson, ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()])); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, ownerKey, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "" - + "Add sign for single sign normal transaction,get approve list") - public void test03SingleSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - Integer[] ints = {ContractType.TransferContract_VALUE}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionApprovedList:" + transactionApprovedList); - Assert.assertEquals(Base58.encode58Check(tmpAddr02), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - - } - - @Test(enabled = true, description = "Add sign for normal transaction " - + "with address not in permission list") - public void test06SignFailedTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + AVAILABLE_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, testKey002, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "Add sign for timeout normal transaction,get approve list") - public void test07TimeoutTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + AVAILABLE_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - try { - Thread.sleep(70000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign.getTransactionSignWeight( - transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionApprovedList:" + transactionApprovedList); - logger.info("Base58.encode58Check(test001Address)1:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(tmpAddr02), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - - } - - @Test(enabled = true, description = "Add sign for empty transaction,get approve list") - public void test08EmptyTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - - logger.info("** created an empty transaction"); - - AccountPermissionUpdateContract.Builder builder = - AccountPermissionUpdateContract.newBuilder(); - - AccountPermissionUpdateContract contract = builder.build(); - TransactionExtention transactionExtention = - blockingStubFull.accountPermissionUpdate(contract); - Transaction transaction = transactionExtention.getTransaction(); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, ownerKey, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore, balanceAfter); - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction, blockingStubFull); - logger.info("Before broadcast transactionApprovedList info :\n" + transactionApprovedList); - Assert.assertEquals("class java.lang.IndexOutOfBoundsException : Index: 0", - transactionApprovedList.getResult().getMessage()); - Assert.assertFalse(PublicMethedForMutiSign - .broadcastTransaction(transaction1, blockingStubFull)); - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - Assert.assertEquals("class java.lang.IndexOutOfBoundsException : Index: 0", - transactionApprovedList.getResult().getMessage()); - } - - @Test(enabled = true, description = "Add sign for fake transaction,get approve list") - public void test09ErrorTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + AVAILABLE_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":2}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(2, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - logger.info("** trigger a fake transaction"); - Transaction transaction = PublicMethedForMutiSign - .createFakeTransaction(ownerAddress, 1_000_000L, ownerAddress); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast permission TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(2, txWeight.getCurrentWeight()); - - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(tmpAddr02), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - @Test(enabled = true, description = "Add sign transaction with mix order") - public void test10MultiSignNormalTransactionWithMixOrder() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee + multiSignFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + DEFAULT_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(3, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - TransactionSignWeight txWeight = PublicMethedForMutiSign.getTransactionSignWeight( - transaction, blockingStubFull); - logger.info("Before Sign TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString( - transaction1.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast1 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(1, txWeight.getCurrentWeight()); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, ownerKey, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(2, txWeight.getCurrentWeight()); - - Transaction transaction3 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction2, witnessKey001, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction3.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction3, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(3, txWeight.getCurrentWeight()); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction3, blockingStubFull)); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - } - - @Test(enabled = true, description = "Add sign transaction with same address") - public void test11MultiSignNormalTransactionBySameAccount() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - logger.info("** update owner and active permission to two address"); - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + DEFAULT_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(3, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - TransactionSignWeight txWeight = - PublicMethedForMutiSign.getTransactionSignWeight(transaction, blockingStubFull); - logger.info("Before Sign TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast1 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(1, txWeight.getCurrentWeight()); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, ownerKey, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(2, txWeight.getCurrentWeight()); - - Transaction transaction3 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction2, ownerKey, 2, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction3.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction3, blockingStubFull); - logger.info("Before broadcast2 TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(PERMISSION_ERROR, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - Assert.assertThat(txWeight.getResult().getMessage(), - containsString("has signed twice!")); - - Assert.assertFalse(PublicMethedForMutiSign.broadcastTransaction( - transaction3, blockingStubFull)); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "Add sign transaction with null address") - public void test12MultiSignNormalTransactionByNullKey() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - ownerPermissionKeys.add(ownerKey); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":5,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"" + DEFAULT_OPERATION + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - - Assert.assertEquals(3, - PublicMethedForMutiSign.getActivePermissionKeyCount(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission()); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction.toByteArray())); - TransactionSignWeight txWeight = - PublicMethedForMutiSign.getTransactionSignWeight(transaction, blockingStubFull); - logger.info("Before Sign TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(NOT_ENOUGH_PERMISSION, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - - Transaction transaction1 = null; - boolean ret = false; - try { - transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, null, 2, blockingStubFull); - } catch (NullPointerException e) { - logger.info("java.lang.NullPointerException"); - ret = true; - } - Assert.assertTrue(ret); - - ret = false; - try { - transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, "", 2, blockingStubFull); - } catch (NumberFormatException e) { - logger.info("NumberFormatException: Zero length BigInteger"); - ret = true; - } catch (NullPointerException e) { - logger.info("NullPointerException"); - ret = true; - } - Assert.assertTrue(ret); - - ret = false; - try { - transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, "abcd1234", 2, blockingStubFull); - } catch (Exception e) { - logger.info("Exception!!"); - ret = true; - } - Assert.assertFalse(ret); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction1.toByteArray())); - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("Before broadcast TransactionSignWeight info :\n" + txWeight); - Assert.assertEquals(PERMISSION_ERROR, txWeight.getResult().getCode()); - Assert.assertEquals(0, txWeight.getCurrentWeight()); - Assert.assertThat(txWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign24.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign24.java deleted file mode 100644 index a96d5e165b1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign24.java +++ /dev/null @@ -1,280 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.tron.api.GrpcAPI.TransactionSignWeight.Result.response_code.ENOUGH_PERMISSION; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign24 { - - private static final String AVAILABLE_OPERATION - = "7fff1fc0037e0000000000000000000000000000000000000000000000000000"; - private static final String DEFAULT_OPERATION - = "7fff1fc0033e0000000000000000000000000000000000000000000000000000"; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] ownerAddress = ecKey1.getAddress(); - private String ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] normalAddr001 = ecKey2.getAddress(); - private String normalKey001 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey tmpEcKey01 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr01 = tmpEcKey01.getAddress(); - private String tmpKey01 = ByteArray.toHexString(tmpEcKey01.getPrivKeyBytes()); - private ECKey tmpEcKey02 = new ECKey(Utils.getRandom()); - private byte[] tmpAddr02 = tmpEcKey02.getAddress(); - private String tmpKey02 = ByteArray.toHexString(tmpEcKey02.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Broadcast multi sign normal transaction") - public void test01BroadcastMultiSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee * 2 + multiSignFee * 2; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - PublicMethed.printAddress(ownerKey); - PublicMethed.printAddress(tmpKey02); - - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - ownerPermissionKeys.add(ownerKey); - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(ownerKey); - - String accountPermissionJson = "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner1\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.clear(); - ownerPermissionKeys.add(tmpKey02); - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(witnessKey001); - activePermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, tmpKey02, 0, blockingStubFull); - - Transaction transaction2 = PublicMethedForMutiSign.addTransactionSignWithPermissionId( - transaction1, testKey002, 0, blockingStubFull); - - logger.info("transaction hex string is " + ByteArray.toHexString(transaction2.toByteArray())); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction2, blockingStubFull)); - - PublicMethedForMutiSign - .recoverAccountPermission(ownerKey, ownerPermissionKeys, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txWeight = PublicMethedForMutiSign.getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - PublicMethed - .unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - - } - - @Test(enabled = true, description = "Broadcast single owner sign normal transaction") - public void test03BroadcastSingleSignNormalTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey1.getAddress(); - ownerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - long needCoin = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, needCoin + 1_000_000, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - List ownerPermissionKeys = new ArrayList<>(); - List activePermissionKeys = new ArrayList<>(); - - PublicMethed.printAddress(ownerKey); - - ownerPermissionKeys.add(ownerKey); - activePermissionKeys.add(ownerKey); - - Integer[] ints = {ContractType.TransferContract_VALUE}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - String accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner1\"," - + "\"threshold\":1,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) + "\",\"weight\":3}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"" + operations + "\",\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(tmpKey02) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, - ownerAddress, ownerKey, blockingStubFull, - ownerPermissionKeys.toArray(new String[ownerPermissionKeys.size()]))); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerPermissionKeys.add(testKey002); - activePermissionKeys.add(tmpKey02); - - Assert.assertEquals(2, PublicMethedForMutiSign.getActivePermissionKeyCount( - PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList())); - - Assert.assertEquals(2, PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission().getKeysCount()); - - PublicMethedForMutiSign.printPermissionList(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getActivePermissionList()); - - System.out - .printf(PublicMethedForMutiSign.printPermission(PublicMethed.queryAccount(ownerAddress, - blockingStubFull).getOwnerPermission())); - - logger.info("** trigger a normal transaction"); - Transaction transaction = PublicMethedForMutiSign - .sendcoin2(fromAddress, 1000_000, ownerAddress, ownerKey, blockingStubFull); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, testKey002, 0, blockingStubFull); - - TransactionSignWeight txWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("TransactionSignWeight info : " + txWeight); - - Assert.assertTrue(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1000000); - - } - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(ownerAddress, ownerKey, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign26.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign26.java deleted file mode 100644 index bdcd997afe8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign26.java +++ /dev/null @@ -1,780 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign26 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidityInFullnode = null; - - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "Sendcoin,use acticve address to sign," - + "not meet the requirements.Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - logger.info("transactionSignWeight:" + transactionSignWeight); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList3 = test001AddressAccount3.getActivePermissionList(); - Permission ownerPermission3 = test001AddressAccount3.getOwnerPermission(); - Permission witnessPermission3 = test001AddressAccount3.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList3); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission3)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission3)); - - final Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, updateAccountPermissionFee); - logger.info("returnResult:"); - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("Permission denied")); - - - } - - @Test(enabled = true, description = "Sendcoin,use acticve address to sign," - + "meet the all requirements.Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign_1() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - GrpcAPI.TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction, blockingStubFull); - - logger.info("transactionApprovedList:" + transactionApprovedList); - Assert.assertEquals(0, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - final Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - } - - - @Test(enabled = true, description = "Sendcoin,use owner address to sign," - + "Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign_2() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[2]; - permissionKeyString[0] = dev001Key; - permissionKeyString[1] = sendAccountKey2; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address" - + "\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"" - + "active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = dev001Key; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString1)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - final Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - } - - @Test(enabled = true, description = "AccountPermissionUpdate transaction," - + "use owner address to sign,Delete the address,broadcastTransaction.") - public void testMultiUpdatepermissions_BeforeSign_3() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[2]; - permissionKeyString[0] = dev001Key; - permissionKeyString[1] = sendAccountKey2; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson3 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson3, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - final Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey2, 0, blockingStubFull); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address" - + "\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"" - + "active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = dev001Key; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString1)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - } - - - - - @Test(enabled = true, description = "Sendcoin,Delete the owner address," - + "use the address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_AfterSign() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - logger.info("1-----------------------"); - - final Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - - } - - @Test(enabled = true, description = "AccountPermissionUpdate transaction," - + "Delete the owner address,use the address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_AfterSign_4() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 3 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - String accountPermissionJson3 = - "{\"owner_permission\":{\"type\":0,\"permission_name" - + "\":\"owner\",\"threshold\":1,\"keys\":[{" - + "\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - final Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson3, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Assert - .assertFalse(PublicMethedForMutiSign.broadcastTransaction(transaction1, blockingStubFull)); - - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2 - balance3, 0); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign27.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign27.java deleted file mode 100644 index 5d25db9e159..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign27.java +++ /dev/null @@ -1,604 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign27 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "Then use permissionID not same in activelist address to sign," - + "not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_3() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use permissionID not same in activelist address to sign," - + "not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_4() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "Then use permissionID not same in activelist address to sign," - + "meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_6() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use not in permissionlist address to sign," - + "not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_7() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use in active address to sign,not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_8() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use in active address to sign, meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_9() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - final long balance = test001AddressAccount.getBalance(); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign28.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign28.java deleted file mode 100644 index dda33e99e0c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign28.java +++ /dev/null @@ -1,1134 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign28 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = - "Sendcoin permission id 2,use not in permissionlist address sign." - + "Then use in active address permission id 2 to sign ,broadcastTransaction.") - public void testMultiUpdatepermissions_10() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - - } - - @Test(enabled = true, description = - "Sendcoin permission id 2,use not in permissionlist address sign." - + "Then use in active address to sign,no right to sendcoin,broadcastTransaction.") - public void testMultiUpdatepermissions_11() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - - long balance2 = test001AddressAccount2.getBalance(); - logger.info("balance2:" + balance2); - - Assert.assertEquals(balance1, balance2); - - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use active address in permission id 3 sign." - + "Then use active address in permission id 2to sign.broadcastTransaction.") - public void testMultiUpdatepermissions_12() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "sum weight > threshold") - public void testMultiUpdatepermissions_13() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + multiSignFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - final long balance1 = test001AddressAccount1.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, multiSignFee + 1); - - - } - - @Test(enabled = true, description = "Sendcoin,use active address sign, meet all requirements." - + "Then use permissionId not same in active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_14() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("ENOUGH_PERMISSION")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use permissionId not same active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_15() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = - "Sendcoin,use not in permissionlist address sign," - + "Then use owner address to sign,meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_16() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = - "Sendcoin,use not in permissionlist address sign, meet all requirements." - + "Then use owner address to sign,,broadcastTransaction.") - public void testMultiUpdatepermissions_17() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use active address sign, meet all requirements." - + "Then use owner address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_18() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use active address sign, meet all requirements." - + "Then use owner address to sign with permission id 0,broadcastTransaction.") - public void testMultiUpdatepermissions_19() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2,use owner address sign." - + "Then use active address to sign, meet permission id.broadcastTransaction.") - public void testMultiUpdatepermissions_20() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - long balance = test001AddressAccount.getBalance(); - - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - final long balance1 = test001AddressAccount1.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin permission id 2" - + ",use not in permissionlist address sign." - + "Then use owner address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_21() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - final long balance = test001AddressAccount.getBalance(); - - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign29.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign29.java deleted file mode 100644 index ec67d890388..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign29.java +++ /dev/null @@ -1,656 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign29 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use permissionID same in active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_23() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("validate signature error Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin with permission id 0,use owner address sign," - + "Then use owner address to sign, sum weight > threshold,broadcastTransaction.") - public void testMultiUpdatepermissions_24() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\":" + "\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed - .getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, multiSignFee + 1); - - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use owner address to sign, not meet the requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_25() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("validate signature error Permission denied")); - - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign, not meet the requirements." - + "Then use owner address to sign with permission id 0,broadcastTransaction.") - public void testMultiUpdatepermissions_27() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @Test(enabled = true, description = "Sendcoin,use active address sign,meet all requirements." - + "Then use owner address to sign with permission id 0,broadcastTransaction.") - public void testMultiUpdatepermissions_28() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, dev001Key, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use active address to sign no permission id,broadcastTransaction.") - public void testMultiUpdatepermissions_29() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance, balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - @Test(enabled = true, description = "Sendcoin,use owner address sign, meet all requirements." - + "Then use active address to sign with permission id 2,broadcastTransaction.") - public void testMultiUpdatepermissions_30() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("but it is not contained of permission")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert.assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - /** - * constructor. - */ - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign30.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign30.java deleted file mode 100644 index 854c2b7c986..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign30.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign30 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = - "Sendcoin,use active address no right to sendcoin sign(weight< threshold)." - + "Then use the same address to sign(weight>=threshold),broadcastTransaction.") - public void testMultiUpdatepermissions_32() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}" - + ",{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey4, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey4, blockingStubFull); - - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("validate signature error Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - } - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign31.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign31.java deleted file mode 100644 index 7aa7403c631..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign31.java +++ /dev/null @@ -1,681 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign31 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - private ManagedChannel channelSolidity = null; - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = - "Sendcoin,use active address sign, meet all requirements,broadcast,Then use the same" - + " permissionID active address to sign, meet all requirements,broadcast.") - public void testMultiUpdatepermissions_34() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" - + "" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - logger.info("balance2:" + balance2); - - Assert.assertEquals(balance1 - balance2, 1L); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("DUP_TRANSACTION_ERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance3, balance2); - - - } - - - @Test(enabled = true, description = - "Sendcoin,use active address sign," - + "not meet the requirements broadcastTransaction.Then use the same" - + " permissionID active address to sign,broadcastTransaction.") - public void testMultiUpdatepermissions_35() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" - + "" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0100000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - logger.info("balance2:" + balance2); - Assert.assertEquals(balance1, balance2); - - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8().toLowerCase(), - containsString("validate signature error: permission denied".toLowerCase())); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - - logger.info("transaction1:" + transactionSignWeight1); - - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - logger.info("balance3:" + balance3); - Assert.assertEquals(balance3, balance2); - - - } - - @Test(enabled = true, description = - "Sendcoin,use owner address sign, broadcast,Then use other owner address to sign,broadcast.") - public void testMultiUpdatepermissions_36() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(returnResult1.getResult()); - - logger.info("returnResult1:" + returnResult1); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, 1); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult1:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("DUP_TRANSACTION_ERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2, balance3); - } - - @Test(enabled = true, description = - "Sendcoin permission id 3,use active address in permission id 2 sign," - + "Then use active address" - + " in permission id 3 to sign, meet all requirements.broadcastTransaction.") - public void testMultiUpdatepermissions_37() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("but it is not contained of permission")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("but it is not contained of permission")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1, balance2); - //Assert.assertTrue(returnResult1.getResult()); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 3, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance2, balance3); - - } - - @Test(enabled = true, description = - "Sendcoin,use active address sign meet all requirements,broadcast,Then use active address" - + "in wrong permission id to sign,not meet the requirements.broadcast.") - public void testMultiUpdatepermissions_38() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, 1); - - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance3, balance2); - - } - - @Test(enabled = true, description = - "Sendcoin,use active address sign, meet all requirements,Then use the other permissionID " - + "in active address to sign, meet all requirements.broadcastTransaction.") - public void testMultiUpdatepermissions_39() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 2; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - long balance1 = test001AddressAccount1.getBalance(); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 3, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey3, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, 1L); - - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 2, blockingStubFull); - - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - logger.info("transaction1:" + transactionSignWeight1); - - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance3, balance2); - - } - - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign33.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign33.java deleted file mode 100644 index 29c8c216d69..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign33.java +++ /dev/null @@ -1,168 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign33 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = "Active address fall back into only myself") - public void testMultiSignActiveAddress() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee; - - Assert.assertTrue( - PublicMethed.sendcoin(test001Address, amount, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" + ":\"" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson2 = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"" - + "owner\",\"threshold\":1,\"keys\":[{\"address\":\"" + "" + PublicMethed - .getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name" - + "\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"" - + ",\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\"," - + "\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - long balance2 = test001AddressAccount2.getBalance(); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign34.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign34.java deleted file mode 100644 index 5205a5b4265..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign34.java +++ /dev/null @@ -1,231 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign34 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - - @Test(enabled = true, description = "SR witness,sendcoin, use witnessPermission address sign.") - public void testMultiUpdatepermissions_42() { - Assert.assertTrue(PublicMethed - .sendcoin(witnessesKey, 1000000000, fromAddress, testKey002, - blockingStubFull)); - Account test001AddressAccount = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, witnessesKey, 1, testWitnesses, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, testWitnesses, blockingStubFull); - final TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance, balance1); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission for this, does not exist!")); - - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("permission isn't exit")); - - } - - @Test(enabled = true, description = "SR witness,sendcoin, use active address sign.") - public void testMultiUpdatepermissions_43() { - Assert.assertTrue(PublicMethed - .sendcoin(witnessesKey, 1000000000, fromAddress, testKey002, - blockingStubFull)); - Account test001AddressAccount = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, witnessesKey, 2, testWitnesses, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, testWitnesses, blockingStubFull); - final TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transaction:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission for this, does not exist!")); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Account test001AddressAccount1 = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance, balance1); - Assert - .assertThat(returnResult1.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult1.getMessage().toStringUtf8(), - containsString("permission isn't exit")); - - } - - - @Test(enabled = true, description = "SR witness,sendcoin, use owner address sign.") - public void testMultiUpdatepermissions_44() { - Assert.assertTrue(PublicMethed - .sendcoin(witnessesKey, 1000000000, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info("balance: " + balance); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, witnessesKey, 0, testWitnesses, - blockingStubFull); - final Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, testWitnesses, blockingStubFull); - Return returnResult1 = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult1:" + returnResult1); - Assert.assertTrue(returnResult1.getResult()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount1 = PublicMethed.queryAccount(witnessesKey, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1: " + balance1); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, 1); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign35.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign35.java deleted file mode 100644 index 68808226df9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign35.java +++ /dev/null @@ -1,299 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign35 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, description = "update active operation," - + " use active address meet all requirement") - public void testMultiUpdatepermissions_45() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[5]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":\"" - + "7fff1fc0037e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[5]; - permissionKeyString1[0] = sendAccountKey4; - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey4, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult:" + returnResult); - Assert.assertTrue(returnResult.getResult()); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - final long balance2 = test001AddressAccount2.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - Assert.assertEquals(balance1 - balance2, updateAccountPermissionFee); - - - } - - @Test(enabled = true, description = "update active operation," - + " use active address no right update sign, broadcast") - public void testMultiUpdatepermissions_46() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - final long balance = test001AddressAccount.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[5]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":\"" - + "7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - final long balance1 = test001AddressAccount1.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String[] permissionKeyString1 = new String[5]; - permissionKeyString1[0] = sendAccountKey4; - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey4, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight.getResult().getMessage(), - containsString("Permission denied")); - Return returnResult = PublicMethedForMutiSign - .broadcastTransaction1(transaction1, blockingStubFull); - logger.info("returnResult:" + returnResult); - - Assert - .assertThat(returnResult.getCode().toString(), containsString("SIGERROR")); - Assert - .assertThat(returnResult.getMessage().toStringUtf8(), - containsString("Permission denied")); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - final long balance2 = test001AddressAccount2.getBalance(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - Assert.assertEquals(balance1, balance2); - - - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign36.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign36.java deleted file mode 100644 index 1fb3bca6992..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign36.java +++ /dev/null @@ -1,549 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionApprovedList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign36 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "two owner address sign update permission transaction " - + "sum(weight)==threshold,get approve list") - public void getTransactionApprovedList_01() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[2]; - permissionKeyString[0] = dev001Key; - permissionKeyString[1] = sendAccountKey2; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Transaction transaction = PublicMethedForMutiSign - .accountPermissionUpdateWithoutSign(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, - permissionKeyString); - - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, dev001Key, 0, blockingStubFull); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey2, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction2, blockingStubFull); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - logger.info( - "transactionApprovedList:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test001Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(1).toByteArray())); - Assert.assertEquals(2, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(0, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - Account test001AddressAccount1 = PublicMethed - .queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - - } - - - @Test(enabled = true, description = - "sendcoin,use active address sign meet all requirement,delete " - + "the used active address," - + "and change active no right to sendcoin. get first transaction approve list") - public void getTransactionApprovedList_02() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = 2 * updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction, sendAccountKey2, 2, blockingStubFull); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson2, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - logger.info( - "transactionApprovedList:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - Account test001AddressAccount2 = PublicMethed.queryAccount(sendAccountKey2, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - - - } - - @Test(enabled = true, description = "sendcoin,use active address sign," - + "sum(weight)==threshold,get approve list") - public void getTransactionApprovedList_03() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(test005Address, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - Transaction transaction2 = PublicMethed - .addTransactionSign(transaction1, sendAccountKey3, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction2, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - logger.info( - "transactionApprovedList:" + Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(Base58.encode58Check(test003Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(1).toByteArray())); - Assert.assertEquals(2, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - @Test(enabled = true, description = "Multi-signature unfinished transaction,get approve list") - public void getTransactionApprovedList_06() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(test005Address, 1L, test001Address, 2, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - logger.info("test001Address:" + Base58.encode58Check(test001Address)); - - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(2, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - - @Test(enabled = true, description = "sendcoin transaction in owner permission," - + "but sign use active address," - + "get approve list") - public void getTransactionApprovedList_07() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1; - - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":2,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(test005Address, 1L, test001Address, 0, dev001Key, - blockingStubFull); - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, sendAccountKey2, blockingStubFull); - TransactionApprovedList transactionApprovedList = PublicMethed - .getTransactionApprovedList(transaction1, blockingStubFull); - - logger.info("transactionSignWeight:" + transactionApprovedList); - - Assert.assertEquals(1, transactionApprovedList.getApprovedListCount()); - Assert.assertEquals(Base58.encode58Check(test002Address), Base58 - .encode58Check(transactionApprovedList.getApprovedList(0).toByteArray())); - Assert.assertEquals(0, - transactionApprovedList.getTransaction().getTransaction().getRawData().getContract(0) - .getPermissionId()); - } - - - /** - * constructor. - */ - public Protocol.Transaction createFakeTransaction(byte[] toAddrss, Long amount, - byte[] fromAddress) { - - BalanceContract.TransferContract contract = BalanceContract.TransferContract.newBuilder() - .setOwnerAddress(ByteString.copyFrom(fromAddress)) - .setToAddress(ByteString.copyFrom(toAddrss)) - .setAmount(amount) - .build(); - Protocol.Transaction transaction = createTransaction(contract, ContractType.TransferContract); - - return transaction; - } - - private Transaction setReference(Transaction transaction, long blockNum, - byte[] blockHash) { - byte[] refBlockNum = ByteArray.fromLong(blockNum); - Transaction.raw rawData = transaction.getRawData().toBuilder() - .setRefBlockHash(ByteString.copyFrom(blockHash)) - .setRefBlockBytes(ByteString.copyFrom(refBlockNum)) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction setExpiration(Transaction transaction, long expiration) { - Transaction.raw rawData = transaction.getRawData().toBuilder().setExpiration(expiration) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction createTransaction(com.google.protobuf.Message message, - ContractType contractType) { - Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( - Transaction.Contract.newBuilder().setType(contractType).setParameter( - Any.pack(message)).build()); - - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) - .build(); - - long time = System.currentTimeMillis(); - AtomicLong count = new AtomicLong(); - long gtime = count.incrementAndGet() + time; - String ref = "" + gtime; - - transaction = setReference(transaction, gtime, ByteArray.fromString(ref)); - - transaction = setExpiration(transaction, gtime); - - return transaction; - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign37.java b/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign37.java deleted file mode 100644 index 2f6ebf69130..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/multisign/MultiSign37.java +++ /dev/null @@ -1,416 +0,0 @@ -package stest.tron.wallet.dailybuild.multisign; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionSignWeight; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MultiSign37 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private final String testWitnesses = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessesKey = PublicMethed.getFinalAddress(testWitnesses); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] test001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = - "Sendcoin with permission id 0,use owner address sign, weight permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - final Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - final Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("NOT_ENOUGH_PERMISSION")); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert - .assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Signature count is 2 more than key counts of permission : 1")); - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert - .assertThat(returnResult2.getMessage().toStringUtf8(), - containsString( - "Signature count is 2 more than key counts of permission : 1")); - Assert.assertEquals(balance1, balance3); - } - - - @Test(enabled = true, description = - "Sendcoin,use owner address sign, not meet all requirements.Then use " - + " active address to sign, not meet all requirements,broadcastTransaction.") - public void testMultiUpdatepermissions_48() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + 1000000; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - final Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - final Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert.assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("NOT_ENOUGH_PERMISSION")); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey3, 2, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert.assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("PERMISSION_ERROR")); - Assert.assertThat(transactionSignWeight1.getResult().getMessage(), - containsString("Permission denied")); - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Assert - .assertThat(returnResult2.getCode().toString(), containsString("SIGERROR")); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertThat(returnResult2.getMessage().toStringUtf8(), - containsString("Permission denied")); - Assert.assertEquals(balance1, balance3); - } - - @Test(enabled = true, description = - "Sendcoin,use two owner address sign,sum(weight)==threshold,broadcastTransaction.") - public void testMultiUpdatepermissions_49() { - ECKey ecKey = new ECKey(Utils.getRandom()); - test001Address = ecKey.getAddress(); - long amount = updateAccountPermissionFee + multiSignFee + 1000000; - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, amount, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - final Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - long balance = test001AddressAccount.getBalance(); - logger.info("balance:" + balance); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":2,\"keys\":[{\"address\":" - + "\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":" - + "\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - final Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - long balance1 = test001AddressAccount1.getBalance(); - logger.info("balance1:" + balance1); - - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - Assert.assertEquals(balance - balance1, updateAccountPermissionFee); - - Transaction transaction = PublicMethedForMutiSign - .sendcoinWithPermissionIdNotSign(fromAddress, 1L, test001Address, 0, dev001Key, - blockingStubFull); - - Transaction transaction1 = PublicMethed - .addTransactionSign(transaction, dev001Key, blockingStubFull); - TransactionSignWeight transactionSignWeight = PublicMethedForMutiSign - .getTransactionSignWeight(transaction1, blockingStubFull); - logger.info("transactionSignWeight:" + transactionSignWeight); - Assert - .assertThat(transactionSignWeight.getResult().getCode().toString(), - containsString("NOT_ENOUGH_PERMISSION")); - Transaction transaction2 = PublicMethedForMutiSign - .addTransactionSignWithPermissionId(transaction1, sendAccountKey2, 0, blockingStubFull); - TransactionSignWeight transactionSignWeight1 = PublicMethedForMutiSign - .getTransactionSignWeight(transaction2, blockingStubFull); - logger.info("transaction1:" + transactionSignWeight1); - Assert - .assertThat(transactionSignWeight1.getResult().getCode().toString(), - containsString("ENOUGH_PERMISSION")); - Return returnResult2 = PublicMethedForMutiSign - .broadcastTransaction1(transaction2, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("returnResult2:" + returnResult2); - Account test001AddressAccount3 = PublicMethed.queryAccount(test001Address, blockingStubFull); - long balance3 = test001AddressAccount3.getBalance(); - Assert.assertEquals(balance1 - balance3, multiSignFee + 1); - Assert.assertTrue(returnResult2.getResult()); - } - - /** - * constructor. - */ - - private Transaction setReference(Transaction transaction, long blockNum, - byte[] blockHash) { - byte[] refBlockNum = ByteArray.fromLong(blockNum); - Transaction.raw rawData = transaction.getRawData().toBuilder() - .setRefBlockHash(ByteString.copyFrom(blockHash)) - .setRefBlockBytes(ByteString.copyFrom(refBlockNum)) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction setExpiration(Transaction transaction, long expiration) { - Transaction.raw rawData = transaction.getRawData().toBuilder().setExpiration(expiration) - .build(); - return transaction.toBuilder().setRawData(rawData).build(); - } - - - /** - * constructor. - */ - - public Transaction createTransaction(com.google.protobuf.Message message, - ContractType contractType) { - Transaction.raw.Builder transactionBuilder = Transaction.raw.newBuilder().addContract( - Transaction.Contract.newBuilder().setType(contractType).setParameter( - Any.pack(message)).build()); - - Transaction transaction = Transaction.newBuilder().setRawData(transactionBuilder.build()) - .build(); - - long time = System.currentTimeMillis(); - AtomicLong count = new AtomicLong(); - long gtime = count.incrementAndGet() + time; - String ref = "" + gtime; - - transaction = setReference(transaction, gtime, ByteArray.fromString(ref)); - - transaction = setExpiration(transaction, gtime); - - return transaction; - } - - @AfterMethod - public void aftertest() { - PublicMethed.freedResource(test001Address, dev001Key, fromAddress, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java deleted file mode 100644 index c179d5b9821..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest.java +++ /dev/null @@ -1,192 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountPermissionUpdateTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1UpdatePermission() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 2 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId1(accountPermissionJson1, ownerAddress, ownerKey, - blockingStubFull, 0, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java deleted file mode 100644 index 68513fd3a58..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountPermissionUpdateTest002.java +++ /dev/null @@ -1,192 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountPermissionUpdateTest002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1UpdatePermission() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 2 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId1(accountPermissionJson1, ownerAddress, ownerKey, - blockingStubFull, 2, permissionKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java deleted file mode 100644 index a2d7790bf9d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest.java +++ /dev/null @@ -1,227 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - private String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static byte[] randomBytes(int length) { - // generate the random number - byte[] result = new byte[length]; - new Random().nextBytes(result); - result[0] = Wallet.getAddressPreFixByte(); - return result; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - //operations = "77ff1fc0037e0100000000000000000000000000000000000000000000000000"; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSignForAccount() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 10; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - final String updateName = Long.toString(System.currentTimeMillis()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - byte[] accountName = String.valueOf(System.currentTimeMillis()).getBytes(); - Assert.assertTrue(PublicMethedForMutiSign.createAccount1( - ownerAddress, newAddress, ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue( - PublicMethedForMutiSign.setAccountId1(accountName, - ownerAddress, ownerKey, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, ownerAddress, 0, ownerKey, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - ownerAddress, 1000000L, 0, 0, ownerKey, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - ownerAddress, 1000000L, 0, 1, ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - ownerAddress, 1000000L, 0, 2, ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiverWithPermissionId( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, null, 0, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, newAddress, 0, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccountWithPermissionId( - ownerAddress, updateName.getBytes(), ownerKey, blockingStubFull, 0, ownerKeyString)); - - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitnessWithPermissionId( - smallVoteMap, ownerAddress, ownerKey, blockingStubFull, 0, ownerKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, multiSignFee * 11 + 2000000 + 100); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java deleted file mode 100644 index ec26f326285..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAccountTest002.java +++ /dev/null @@ -1,217 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAccountTest002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static byte[] randomBytes(int length) { - // generate the random number - byte[] result = new byte[length]; - new Random().nextBytes(result); - result[0] = Wallet.getAddressPreFixByte(); - return result; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSignForAccount() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 10; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - final String updateName = Long.toString(System.currentTimeMillis()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - byte[] accountName = "11z2112310".getBytes(); - Assert.assertTrue(PublicMethedForMutiSign.createAccount1( - ownerAddress, newAddress, ownerKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.setAccountId1(accountName, - ownerAddress, ownerKey, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, ownerAddress, 2, ownerKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - ownerAddress, 1000000L, 0, 2, ownerKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - ownerAddress, 1000000L, 0, 1, ownerKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiverWithPermissionId( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, null, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, newAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccountWithPermissionId( - ownerAddress, updateName.getBytes(), ownerKey, blockingStubFull, 2, permissionKeyString)); - - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitnessWithPermissionId( - smallVoteMap, ownerAddress, ownerKey, blockingStubFull, 2, permissionKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, multiSignFee * 10 + 1000000 + 100); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java deleted file mode 100644 index 8b62df24b37..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest.java +++ /dev/null @@ -1,348 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAssetTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1CreateAssetissue() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - txid = PublicMethedForMutiSign - .createAssetIssueForTransactionId1(ownerAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, ownerKey, blockingStubFull, 0, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee + 1024_000000L); - - logger.info(" create asset end"); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign2TransferAssetissue() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(manager1Key); - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount(ownerAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign.transferAssetForTransactionId1(manager1Address, - assetAccountId1.toByteArray(), 10, ownerAddress, ownerKey, blockingStubFull, - 0, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign3ParticipateAssetissue() { - ecKey4 = new ECKey(Utils.getRandom()); - participateAddress = ecKey4.getAddress(); - participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(participateAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - ownerKeyString[0] = participateKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(participateKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, participateAddress, - participateKey, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - txid = PublicMethedForMutiSign.participateAssetIssueForTransactionId(ownerAddress, - assetAccountId1.toByteArray(), 10, participateAddress, participateKey, 0, - blockingStubFull, ownerKeyString); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee + 10); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign4updateAssetissue() { - url = "MutiSign001_update_url" + Long.toString(now); - ownerKeyString[0] = ownerKey; - description = "MutiSign001_update_description" + Long.toString(now); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign - .updateAssetForTransactionId(ownerAddress, description.getBytes(), url.getBytes(), 100L, - 100L, ownerKey, 0, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java deleted file mode 100644 index 2f829e1fcb7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignAssetTest002.java +++ /dev/null @@ -1,348 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignAssetTest002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress01 = PublicMethed.getFinalAddress(testKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1CreateAssetissue() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - String[] permissionKeyString1 = new String[1]; - permissionKeyString1[0] = ownerKey; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - txid = PublicMethedForMutiSign - .createAssetIssueForTransactionId1(ownerAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, ownerKey, blockingStubFull, 2, permissionKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee + 1024_000000L); - - logger.info(" create asset end"); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign2TransferAssetissue() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(manager1Key); - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount(ownerAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign.transferAssetForTransactionId1(manager1Address, - assetAccountId1.toByteArray(), 10, ownerAddress, ownerKey, blockingStubFull, - 2, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign3ParticipateAssetissue() { - ecKey4 = new ECKey(Utils.getRandom()); - participateAddress = ecKey4.getAddress(); - participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(participateAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - ownerKeyString[0] = participateKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(participateKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, participateAddress, - participateKey, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - txid = PublicMethedForMutiSign.participateAssetIssueForTransactionId(ownerAddress, - assetAccountId1.toByteArray(), 10, participateAddress, participateKey, 2, - blockingStubFull, permissionKeyString); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee + 10); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign4updateAssetissue() { - url = "MutiSign001_update_url" + Long.toString(now); - ownerKeyString[0] = ownerKey; - description = "MutiSign001_update_description" + Long.toString(now); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign - .updateAssetForTransactionId(ownerAddress, description.getBytes(), url.getBytes(), 100L, - 100L, ownerKey, 2, blockingStubFull, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java deleted file mode 100644 index cce4a0c4660..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignClearContractAbiTest.java +++ /dev/null @@ -1,311 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignClearContractAbiTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test1MutiSignForClearContractAbi() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Long maxFeeLimit = 1000000000L; - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, permissionKeyString); - logger.info("address:" + Base58.encode58Check(contractAddress)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, ownerAddress, ownerKey, - blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test2MutiSignForClearContractAbiForDefault() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Long maxFeeLimit = 1000000000L; - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, permissionKeyString); - logger.info("address:" + Base58.encode58Check(contractAddress)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, ownerAddress, ownerKey, - blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test3MutiSignForClearContractAbiForDefault() { - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String[] activeDefaultKeyString = new String[1]; - - activeDefaultKeyString[0] = ownerKey; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long maxFeeLimit = 1000000000L; - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, activeDefaultKeyString); - logger.info("address:" + Base58.encode58Check(contractAddress)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, ownerAddress, ownerKey, - blockingStubFull, 2, activeDefaultKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java deleted file mode 100644 index f8cf2b07a3d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest.java +++ /dev/null @@ -1,414 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignExchangeContractTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey3.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey4.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "MutiSign for create token") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(exchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "MutiSign for create exchange") - public void test2CreateExchange() { - ecKey3 = new ECKey(Utils.getRandom()); - manager1Address = ecKey3.getAddress(); - manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - ecKey4 = new ECKey(Utils.getRandom()); - manager2Address = ecKey4.getAddress(); - manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - final long needCoin = updateAccountPermissionFee + multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = exchange001Key; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(exchange001Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, exchange001Address, exchange001Key, - blockingStubFull, ownerKeyString); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate1( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1024_000_000L); - - } - - - @Test(enabled = true, description = "Mutisign for inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethedForMutiSign.injectExchange1( - exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "MutiSign for withdraw exchange") - public void test5WithdrawExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw1( - exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "MutiSign for transaction exchange") - public void test6TransactionExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction1(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull, 0, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java deleted file mode 100644 index 5edc03924e3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignExchangeContractTest002.java +++ /dev/null @@ -1,414 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignExchangeContractTest002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 1000000001L; - private static String name1 = "exchange001_1_" + Long.toString(now); - private static String name2 = "exchange001_2_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchange001Address = ecKey1.getAddress(); - String exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey2.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey3.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey4.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "MutiSign for create token") - public void test1CreateUsedAsset() { - ecKey1 = new ECKey(Utils.getRandom()); - exchange001Address = ecKey1.getAddress(); - exchange001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - secondExchange001Address = ecKey2.getAddress(); - secondExchange001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchange001Key); - PublicMethed.printAddress(secondExchange001Key); - - Assert.assertTrue(PublicMethed.sendcoin(exchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(exchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - Assert.assertTrue(PublicMethed.createAssetIssue(exchange001Address, name1, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, exchange001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "MutiSign for create exchange") - public void test2CreateExchange() { - ecKey3 = new ECKey(Utils.getRandom()); - manager1Address = ecKey3.getAddress(); - manager1Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - ecKey4 = new ECKey(Utils.getRandom()); - manager2Address = ecKey4.getAddress(); - manager2Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - final long needCoin = updateAccountPermissionFee + multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = exchange001Key; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(exchange001Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, exchange001Address, exchange001Key, - blockingStubFull, ownerKeyString); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - final Integer beforeCreateExchangeNum = listExchange.get().getExchangesCount(); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long token1BeforeBalance = 0L; - for (String name : firstAccount.getAssetMap().keySet()) { - token1BeforeBalance = firstAccount.getAssetMap().get(name); - } - Assert.assertTrue(PublicMethed.transferAsset(exchange001Address, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - Long token2BeforeBalance = secondTransferAssetToFirstAccountNum; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //logger.info("name1 is " + name1); - //logger.info("name2 is " + name2); - //logger.info("first balance is " + Long.toString(token1BeforeBalance)); - //logger.info("second balance is " + token2BeforeBalance.toString()); - //CreateExchange - Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate1( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, exchange001Address, - exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin + 1024_000_000L); - - } - - - @Test(enabled = true, description = "Mutisign for inject exchange") - public void test4InjectExchange() { - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer injectBalance = 100; - Assert.assertTrue( - PublicMethedForMutiSign.injectExchange1( - exchangeId, assetAccountId1.toByteArray(), injectBalance, - exchange001Address, exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(beforeToken1Balance - afterToken1Balance == injectBalance); - Assert.assertTrue(beforeToken2Balance - afterToken2Balance == injectBalance - * exchangeRate); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == injectBalance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == injectBalance * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - @Test(enabled = true, description = "MutiSign for withdraw exchange") - public void test5WithdrawExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer withdrawNum = 200; - Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw1( - exchangeId, assetAccountId1.toByteArray(), withdrawNum, - exchange001Address, exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - Assert.assertTrue(afterToken1Balance - beforeToken1Balance == withdrawNum); - Assert.assertTrue(afterToken2Balance - beforeToken2Balance == withdrawNum - * exchangeRate); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == -withdrawNum); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == -withdrawNum * exchangeRate); - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - - } - - @Test(enabled = true, description = "MutiSign for transaction exchange") - public void test6TransactionExchange() { - final long needCoin = multiSignFee; - Long balanceBefore = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - final Long beforeExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - final Long beforeExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("beforeExchangeToken1Balance" + beforeExchangeToken1Balance); - logger.info("beforeExchangeToken2Balance" + beforeExchangeToken2Balance); - - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long beforeToken1Balance = 0L; - Long beforeToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - beforeToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - - logger.info("before token 1 balance is " + Long.toString(beforeToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(beforeToken2Balance)); - Integer transactionNum = 50; - Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction1(exchangeId, assetAccountId1.toByteArray(), transactionNum, 1, - exchange001Address, exchange001Key, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(exchange001Address, blockingStubFull); - Long afterToken1Balance = 0L; - Long afterToken2Balance = 0L; - for (String id : firstAccount.getAssetV2Map().keySet()) { - if (assetAccountId1.toStringUtf8().equalsIgnoreCase(id)) { - afterToken1Balance = firstAccount.getAssetV2Map().get(id); - } - if (assetAccountId2.toStringUtf8().equalsIgnoreCase(id)) { - afterToken2Balance = firstAccount.getAssetV2Map().get(id); - } - } - logger.info("before token 1 balance is " + Long.toString(afterToken1Balance)); - logger.info("before token 2 balance is " + Long.toString(afterToken2Balance)); - - exchangeIdInfo = PublicMethed.getExchange(exchangeId.toString(), blockingStubFull); - Long afterExchangeToken1Balance = exchangeIdInfo.get().getFirstTokenBalance(); - Long afterExchangeToken2Balance = exchangeIdInfo.get().getSecondTokenBalance(); - logger.info("afterExchangeToken1Balance" + afterExchangeToken1Balance); - logger.info("afterExchangeToken2Balance" + afterExchangeToken2Balance); - Assert.assertTrue(afterExchangeToken1Balance - beforeExchangeToken1Balance - == beforeToken1Balance - afterToken1Balance); - Assert.assertTrue(afterExchangeToken2Balance - beforeExchangeToken2Balance - == beforeToken2Balance - afterToken2Balance); - - Long balanceAfter = PublicMethed.queryAccount(exchange001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, needCoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java deleted file mode 100644 index 13be09fc9b9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignMarketAssetTest.java +++ /dev/null @@ -1,217 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.MarketOrder; -import org.tron.protos.Protocol.MarketOrderList; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignMarketAssetTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - ECKey ecKey0 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey0.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey0.getPrivKeyBytes()); - - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(testAddress001, 20000_000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - Assert.assertTrue(PublicMethed.createAssetIssue(testAddress001, - "MarketAsset" + start, - 100_000000L, - 1,1, - start, end,1,"MarketAsset","MarketAsset.com",10000L,10000L,1L, 1L,testKey001, - blockingStubFull)); - Long balanceBefore = PublicMethed.queryAccount(testAddress001, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = testKey001; - ownerKeyString[1] = testKey002; - - // operation include MarketSellAssetContract(52) - Integer[] ints = {0, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 30, 31, - 32, 33, 41, 42, 43, 44, 45, 48, 49, 52, 53}; - String operations = PublicMethedForMutiSign.getOperations(ints); - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(testKey001) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, testAddress001, testKey001, - blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, description = "MutiSignForMarketSellAsset with active_permissions") - public void testMutiSignForMarketSellAsset001() { - // MarketSellAsset - ByteString assetAccountId = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetIssuedID(); - - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - Assert.assertTrue(PublicMethedForMutiSign - .marketSellAsset(testAddress001,assetAccountId.toByteArray(),10,"_".getBytes(),10,2, - permissionKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - MarketOrderList marketOrder = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get(); - Assert.assertEquals(marketOrderCountBefore + 1, marketOrder.getOrdersCount()); - } - - @Test(enabled = true, description = "MutiSignForMarketSellAsset with owner_permission") - public void testMutiSignForMarketSellAsset002() { - // MarketSellAsset - ByteString assetAccountId = PublicMethed - .queryAccount(testAddress001, blockingStubFull).getAssetIssuedID(); - - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - - Assert.assertTrue(PublicMethedForMutiSign - .marketSellAsset(testAddress001,assetAccountId.toByteArray(),10,"_".getBytes(),10,0, - ownerKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - MarketOrderList marketOrder = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get(); - Assert.assertEquals(marketOrderCountBefore + 1, marketOrder.getOrdersCount()); - } - - - @Test(enabled = true, dependsOnMethods = "testMutiSignForMarketSellAsset001", - description = "MutiSignForMarketOrderCancel with active_permissions") - public void testMutiSignForMarketOrderCancel001() { - // MarketOrderCancel - - ByteString orderId = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrders(0).getOrderId(); - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - - Assert.assertTrue(PublicMethedForMutiSign.marketCancelOrder(testAddress001, - orderId.toByteArray(),2,permissionKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(marketOrderCountBefore - 1, PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount()); - - } - - @Test(enabled = true, dependsOnMethods = "testMutiSignForMarketSellAsset002", - description = "MutiSignForMarketOrderCancel with owner_permission") - public void testMutiSignForMarketOrderCancel002() { - // MarketOrderCancel - - ByteString orderId = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrders(0).getOrderId(); - int marketOrderCountBefore = PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount(); - - - Assert.assertTrue(PublicMethedForMutiSign.marketCancelOrder(testAddress001, - orderId.toByteArray(),0,ownerKeyString,blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(marketOrderCountBefore - 1, PublicMethed - .getMarketOrderByAccount(testAddress001, blockingStubFull).get().getOrdersCount()); - - } - - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java deleted file mode 100644 index 73d5c0071f6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignProposalTest { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForProposal() { - long needcoin = updateAccountPermissionFee + multiSignFee * 5; - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, - fromAddress, testKey002, blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - ownerKeyString[1] = testKey002; - - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\"" - + ",\"threshold\":2,\"keys\":[{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\"," - + "\"weight\":1},{\"address\":\"" + PublicMethed.getAddressString(testKey002) - + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0037e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(manager1Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}]}]} "; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Create a proposal - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(witness001Address, witnessKey001, - proposalMap, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - witness001Address, witnessKey001, proposalId, - true, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - witness001Address, witnessKey001, proposalId, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java deleted file mode 100644 index 6724fe22d97..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignProposalTest002.java +++ /dev/null @@ -1,169 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignProposalTest002 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForProposal() { - long needcoin = updateAccountPermissionFee + multiSignFee * 3; - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, - fromAddress, testKey002, blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Create a proposal - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(witness001Address, witnessKey001, - proposalMap, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - witness001Address, witnessKey001, proposalId, - true, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - witness001Address, witnessKey001, proposalId, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue(balanceBefore - balanceAfter >= needcoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java deleted file mode 100644 index 2b1c4943504..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignSmartContractTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForSmartContract() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 0, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContract1(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, ownerAddress, ownerKey, blockingStubFull, 0, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.getTransactionById(txid, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue( - PublicMethedForMutiSign.updateSettingWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 0, blockingStubFull, ownerKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.updateEnergyLimitWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 0, blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java deleted file mode 100644 index 655518c4ab9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignSmartContractTest002.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignSmartContractTest002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForSmartContract() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 4; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - byte[] contractAddress = PublicMethedForMutiSign.deployContract1(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, 2, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContract1(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, ownerAddress, ownerKey, blockingStubFull, 2, permissionKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.getTransactionById(txid, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue( - PublicMethedForMutiSign.updateSettingWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.updateEnergyLimitWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java deleted file mode 100644 index 0958518d43d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/operationupdate/MutiSignUpdataBrokerageTest.java +++ /dev/null @@ -1,163 +0,0 @@ -package stest.tron.wallet.dailybuild.operationupdate; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class MutiSignUpdataBrokerageTest { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForUpdateBrokerage() { - long needcoin = updateAccountPermissionFee * 2 + multiSignFee * 5; - Assert.assertTrue(PublicMethed - .sendcoin(witness001Address, needcoin + 1000000L, fromAddress, testKey002, - blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - ownerKeyString[1] = testKey002; - - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\"" - + ",\"threshold\":2,\"keys\":[{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\"," + "\"weight\":1},{\"address\":\"" + PublicMethed - .getAddressString(testKey002) + "\",\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0300000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(manager1Key) - + "\",\"weight\":1}," + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) - + "\",\"weight\":1}]}]} "; - logger.info(accountPermissionJson); - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Update brokerage - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethedForMutiSign - .updateBrokerage(witness001Address, 70, witnessKey001, 2, permissionKeyString, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // wait a MaintenanceTimeInterval - accountPermissionJson = "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\"" - + ",\"threshold\":1,\"keys\":[{\"address\":\"" + PublicMethed - .getAddressString(witnessKey001) + "\"," + "\"weight\":1}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"7fff1fc0033e0300000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}]} "; - logger.info(accountPermissionJson); - PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit001.java deleted file mode 100644 index a2190cc24ac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit001.java +++ /dev/null @@ -1,145 +0,0 @@ -package stest.tron.wallet.dailybuild.originenergylimit; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractOriginEnergyLimit001 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress3 = ecKey1.getAddress(); - String testKeyForGrammarAddress3 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress3); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - //Origin_energy_limit001,028,029 - @Test(enabled = true, description = "Boundary value and update test") - public void testOrigin_energy_limit001() { - Assert.assertTrue(PublicMethed - .sendcoin(grammarAddress3, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/contractOriginEnergyLimit001.sol"; - String contractName = "findArgsContractTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String contractAddress = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, -1, "0", 0, - null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(contractAddress == null); - - String contractAddress1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 0, "0", 0, - null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - - Assert.assertTrue(contractAddress1 == null); - - byte[] contractAddress2 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 9223372036854775807L, "0", - 0, null, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertFalse(PublicMethed.updateEnergyLimit(contractAddress2, -1L, - testKeyForGrammarAddress3, grammarAddress3, blockingStubFull)); - SmartContract smartContract = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertTrue(smartContract.getOriginEnergyLimit() == 9223372036854775807L); - - Assert.assertFalse(PublicMethed.updateEnergyLimit(contractAddress2, 0L, - testKeyForGrammarAddress3, grammarAddress3, blockingStubFull)); - SmartContract smartContract1 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertTrue(smartContract1.getOriginEnergyLimit() == 9223372036854775807L); - - Assert.assertTrue(PublicMethed.updateEnergyLimit(contractAddress2, - 9223372036854775807L, testKeyForGrammarAddress3, - grammarAddress3, blockingStubFull)); - SmartContract smartContract2 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertTrue(smartContract2.getOriginEnergyLimit() == 9223372036854775807L); - - Assert.assertTrue(PublicMethed.updateEnergyLimit(contractAddress2, 'c', - testKeyForGrammarAddress3, grammarAddress3, blockingStubFull)); - SmartContract smartContract3 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertEquals(smartContract3.getOriginEnergyLimit(), 99); - - Assert.assertFalse(PublicMethed.updateEnergyLimit(contractAddress2, 1L, - testNetAccountKey, testNetAccountAddress, blockingStubFull)); - SmartContract smartContract4 = PublicMethed.getContract(contractAddress2, blockingStubFull); - Assert.assertEquals(smartContract4.getOriginEnergyLimit(), 99); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress3, testKeyForGrammarAddress3, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit004.java deleted file mode 100644 index c2ca4ff01a0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/originenergylimit/ContractOriginEnergyLimit004.java +++ /dev/null @@ -1,378 +0,0 @@ -package stest.tron.wallet.dailybuild.originenergylimit; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractOriginEnergyLimit004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - private long getAvailableFrozenEnergy(byte[] accountAddress) { - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(accountAddress, - blockingStubFull); - long energyLimit = resourceInfo.getEnergyLimit(); - long energyUsed = resourceInfo.getEnergyUsed(); - return energyLimit - energyUsed; - } - - private long getUserAvailableEnergy(byte[] userAddress) { - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(userAddress, - blockingStubFull); - Account info = PublicMethed.queryAccount(userAddress, blockingStubFull); - long balance = info.getBalance(); - long energyLimit = resourceInfo.getEnergyLimit(); - long userAvaliableFrozenEnergy = getAvailableFrozenEnergy(userAddress); - return balance / 100 + userAvaliableFrozenEnergy; - } - - private long getFeeLimit(String txid) { - Optional trsById = PublicMethed.getTransactionById(txid, blockingStubFull); - return trsById.get().getRawData().getFeeLimit(); - } - - private long getUserMax(byte[] userAddress, long feelimit) { - logger.info("User feeLimit: " + feelimit / 100); - logger.info("User UserAvaliableEnergy: " + getUserAvailableEnergy(userAddress)); - return Math.min(feelimit / 100, getUserAvailableEnergy(userAddress)); - } - - private long getOriginalEnergyLimit(byte[] contractAddress) { - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - return smartContract.getOriginEnergyLimit(); - } - - private long getConsumeUserResourcePercent(byte[] contractAddress) { - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - return smartContract.getConsumeUserResourcePercent(); - } - - private long getDevMax(byte[] devAddress, byte[] userAddress, long feeLimit, - byte[] contractAddress) { - long devMax = Math.min(getAvailableFrozenEnergy(devAddress), - getOriginalEnergyLimit(contractAddress)); - long p = getConsumeUserResourcePercent(contractAddress); - if (p != 0) { - logger.info("p: " + p); - devMax = Math.min(devMax, getUserMax(userAddress, feeLimit) * (100 - p) / p); - logger.info("Dev byUserPercent: " + getUserMax(userAddress, feeLimit) * (100 - p) / p); - } - logger.info("Dev AvaliableFrozenEnergy: " + getAvailableFrozenEnergy(devAddress)); - logger.info("Dev OriginalEnergyLimit: " + getOriginalEnergyLimit(contractAddress)); - return devMax; - } - - @Test(enabled = true, description = "Contract use Origin_energy_limit") - public void testOriginEnergyLimit() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 1000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // A2B1 - - //dev balance and Energy - long devTargetBalance = 10_000_000; - long devTargetEnergy = 70000; - - // deploy contract parameters - final long deployFeeLimit = maxFeeLimit; - final long consumeUserResourcePercent = 0; - final long originEnergyLimit = 1000; - - //dev balance and Energy - final long devTriggerTargetBalance = 0; - final long devTriggerTargetEnergy = 592; - - // user balance and Energy - final long userTargetBalance = 0; - final long userTargetEnergy = 2000L; - - // trigger contract parameter, maxFeeLimit 10000000 - final long triggerFeeLimit = maxFeeLimit; - final boolean expectRet = true; - - // count dev energy, balance - long devFreezeBalanceSun = PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, - devTargetEnergy, blockingStubFull); - - long devNeedBalance = devTargetBalance + devFreezeBalanceSun; - - logger.info("need balance:" + devNeedBalance); - - // get balance - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, devNeedBalance, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // get energy - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, devFreezeBalanceSun, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before deploy, dev energy limit is " + Long.toString(devEnergyLimitBefore)); - logger.info("before deploy, dev energy usage is " + Long.toString(devEnergyUsageBefore)); - logger.info("before deploy, dev balance is " + Long.toString(devBalanceBefore)); - - String filePath = "src/test/resources/soliditycode/contractOriginEnergyLimit004.sol"; - String contractName = "findArgsContractTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - deployFeeLimit, 0L, consumeUserResourcePercent, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after deploy, dev energy limit is " + Long.toString(devEnergyLimitAfter)); - logger.info("after deploy, dev energy usage is " + Long.toString(devEnergyUsageAfter)); - logger.info("after deploy, dev balance is " + Long.toString(devBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - - ByteString contractAddressString = infoById.get().getContractAddress(); - contractAddress = contractAddressString.toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - - Assert.assertTrue(smartContract.getAbi() != null); - - Assert.assertTrue(devEnergyLimitAfter > 0); - Assert.assertTrue(devEnergyUsageAfter > 0); - Assert.assertEquals(devBalanceBefore, devBalanceAfter); - - // count dev energy, balance - devFreezeBalanceSun = PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, - devTriggerTargetEnergy, blockingStubFull); - - devNeedBalance = devTriggerTargetBalance + devFreezeBalanceSun; - logger.info("dev need balance:" + devNeedBalance); - - // count user energy, balance - long userFreezeBalanceSun = PublicMethed.getFreezeBalanceCount(user001Address, user001Key, - userTargetEnergy, blockingStubFull); - - long userNeedBalance = userTargetBalance + userFreezeBalanceSun; - - logger.info("User need balance:" + userNeedBalance); - - // get balance - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, devNeedBalance, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, userNeedBalance, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // get energy - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, devFreezeBalanceSun, - 0, 1, dev001Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, userFreezeBalanceSun, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - devEnergyLimitBefore = accountResource.getEnergyLimit(); - devEnergyUsageBefore = accountResource.getEnergyUsed(); - devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before trigger, dev devEnergyLimitBefore is " - + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, dev devEnergyUsageBefore is " - + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, dev devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount( - user001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, user userEnergyLimitBefore is " - + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, user userEnergyUsageBefore is " - + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, user userBalanceBefore is " + Long.toString(userBalanceBefore)); - - logger.info("=================================="); - long userMax = getUserMax(user001Address, triggerFeeLimit); - long devMax = getDevMax(dev001Address, user001Address, triggerFeeLimit, contractAddress); - - logger.info("userMax: " + userMax); - logger.info("devMax: " + devMax); - logger.info("=================================="); - - String param = "\"" + 0 + "\""; - final String triggerTxid = PublicMethed - .triggerContract(contractAddress, "findArgsByIndexTest(uint256)", - param, false, 0, triggerFeeLimit, - user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - devEnergyLimitAfter = accountResource.getEnergyLimit(); - devEnergyUsageAfter = accountResource.getEnergyUsed(); - devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after trigger, dev devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, dev devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, dev devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("after trigger, user userEnergyLimitAfter is " - + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, user userEnergyUsageAfter is " - + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, user userBalanceAfter is " + Long.toString(userBalanceAfter)); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - boolean isSuccess = true; - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - logger.info("transaction failed with message: " + infoById.get().getResMessage()); - isSuccess = false; - } - - long fee = infoById.get().getFee(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long energyUsage = infoById.get().getReceipt().getEnergyUsage(); - long originEnergyUsage = infoById.get().getReceipt().getOriginEnergyUsage(); - long energyTotalUsage = infoById.get().getReceipt().getEnergyUsageTotal(); - long netUsage = infoById.get().getReceipt().getNetUsage(); - long netFee = infoById.get().getReceipt().getNetFee(); - - logger.info("fee: " + fee); - logger.info("energyFee: " + energyFee); - logger.info("energyUsage: " + energyUsage); - logger.info("originEnergyUsage: " + originEnergyUsage); - logger.info("energyTotalUsage: " + energyTotalUsage); - logger.info("netUsage: " + netUsage); - logger.info("netFee: " + netFee); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - long devExpectCost = energyTotalUsage * (100 - consumeUserPercent) / 100; - long userExpectCost = energyTotalUsage - devExpectCost; - final long totalCost = devExpectCost + userExpectCost; - - logger.info("devExpectCost: " + devExpectCost); - logger.info("userExpectCost: " + userExpectCost); - - Assert.assertTrue(devEnergyLimitAfter > 0); - Assert.assertEquals(devBalanceBefore, devBalanceAfter); - - // dev original is the dev max expense A2B1 - Assert.assertEquals(getOriginalEnergyLimit(contractAddress), devMax); - - // DEV is enough to pay - Assert.assertEquals(originEnergyUsage, devExpectCost); - // Assert.assertEquals(devEnergyUsageAfter,devExpectCost + devEnergyUsageBefore); - // User Energy is enough to pay"); - Assert.assertEquals(energyUsage, userExpectCost); - Assert.assertEquals(userBalanceBefore, userBalanceAfter); - Assert.assertEquals(userEnergyUsageAfter, userEnergyUsageBefore); - Assert.assertEquals(userBalanceBefore, userBalanceAfter); - Assert.assertEquals(totalCost, energyTotalUsage); - - if (expectRet) { - Assert.assertTrue(isSuccess); - } else { - Assert.assertFalse(isSuccess); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/transaction/TransactionPendingQuery001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/transaction/TransactionPendingQuery001.java deleted file mode 100644 index a0ec6441b33..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/transaction/TransactionPendingQuery001.java +++ /dev/null @@ -1,138 +0,0 @@ -package stest.tron.wallet.dailybuild.transaction; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.TransactionIdList; -import org.tron.api.GrpcAPI.TransactionList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; - - -@Slf4j - -public class TransactionPendingQuery001 { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddress = ecKey1.getAddress(); - final String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - String txid = null; - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - } - - @Test(enabled = true, description = "Test get pending size") - public void test01GetPendingSize() { - long pendingSizeInFullNode = 0; - int retryTimes = 100; - while (pendingSizeInFullNode == 0 && retryTimes-- > 0) { - PublicMethed.sendcoin(receiverAddress,1L,fromAddress,testKey002,blockingStubFull); - if (retryTimes % 5 == 0) { - pendingSizeInFullNode = blockingStubFull - .getPendingSize(EmptyMessage.newBuilder().build()).getNum(); - } - } - Assert.assertNotEquals(pendingSizeInFullNode,0); - } - - - @Test(enabled = true, description = "Test get pending transaction list") - public void test02GetPendingTransactionList() { - int retryTimes = 100; - TransactionIdList transactionList = blockingStubFull - .getTransactionListFromPending(EmptyMessage.newBuilder().build()); - while (transactionList.getTxIdCount() == 0 && retryTimes-- > 0) { - PublicMethed.sendcoin(receiverAddress,1L,fromAddress,testKey002,blockingStubFull); - if (retryTimes % 5 == 0) { - transactionList = blockingStubFull - .getTransactionListFromPending(EmptyMessage.newBuilder().build()); - } - } - Assert.assertNotEquals(transactionList.getTxIdCount(),0); - - txid = transactionList.getTxId(0); - - logger.info("txid:" + txid); - - } - - - @Test(enabled = true, description = "Test transaction from pending") - public void test03GetTransactionFromPending() { - Transaction transaction = PublicMethed.getTransactionFromPending(txid,blockingStubFull).get(); - Assert.assertEquals(ByteArray.toHexString(Sha256Hash - .hash(true, transaction.getRawData().toByteArray())),txid); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(receiverAddress, receiverKey, 1, receiverAddress, - blockingStubFull); - PublicMethed.freedResource(receiverAddress, receiverKey, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken001.java deleted file mode 100644 index 66ffddb0633..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken001.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken001 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - - @Test(enabled = true, description = "DeployContract with correct tokenValue and tokenId") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken001.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 5; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - final String triggerTxid = PublicMethed - .triggerContract(transferTokenContractAddress, "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken002.java deleted file mode 100644 index 83d4448645f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken002.java +++ /dev/null @@ -1,285 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken002 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TriggerContract with correct tokenValue and tokenId") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 3100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 300_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue( - dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken002.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed.getAssetIssueValue( - dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Assert.assertFalse(PublicMethed.transferAsset(transferTokenContractAddress, - assetAccountId.toByteArray(), 100L, dev001Address, dev001Key, blockingStubFull)); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() - + ", Count: " + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - - PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 10; - callValue = 0; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after user trigger Contract has AssetId: " + assetAccountId.toStringUtf8() - + ", Count: " + contractAssetCount); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken003.java deleted file mode 100644 index 4bc3cdab8cb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken003.java +++ /dev/null @@ -1,354 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class ContractTrcToken003 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountDev = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - } - - @Test(enabled = true, description = "DeployContract with exception condition") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //dev Create a new AssetIssue - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountDev = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The assetAccountDev token name: " + tokenName); - logger.info("The assetAccountDev token ID: " + assetAccountDev.toStringUtf8()); - - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - //user Create a new AssetIssue - Assert.assertTrue(PublicMethed - .createAssetIssue(user001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountUser = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getAssetIssuedID(); - logger.info("The assetAccountUser token name: " + tokenName); - logger.info("The assetAccountUser token ID: " + assetAccountUser.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountDev, blockingStubFull); - Long userAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountUser, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info( - "before dev has AssetId: " + assetAccountDev.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - logger.info( - "before dev has AssetId: " + assetAccountUser.toStringUtf8() + ", userAssetCountBefore: " - + userAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken003.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - // the tokenId is not exist - String fakeTokenId = Long.toString(Long.valueOf(assetAccountDev.toStringUtf8()) + 100); - Long fakeTokenValue = 100L; - - GrpcAPI.Return response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert - .assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // deployer didn't have any such token - fakeTokenId = assetAccountUser.toStringUtf8(); - fakeTokenValue = 100L; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : assetBalance must greater than 0.".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // deployer didn't have any Long.MAX_VALUE - fakeTokenId = Long.toString(Long.MAX_VALUE); - fakeTokenValue = 100L; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // the tokenValue is not enough - fakeTokenId = assetAccountDev.toStringUtf8(); - fakeTokenValue = devAssetCountBefore + 100; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, fakeTokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : assetBalance is not sufficient.".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenid is -1 - fakeTokenId = Long.toString(-1); - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenid is 100_0000L - fakeTokenId = Long.toString(100_0000L); - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenid is Long.MIN_VALUE - fakeTokenId = Long.toString(Long.MIN_VALUE); - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenid is 0 - fakeTokenId = Long.toString(0); - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - fakeTokenId, 100, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - ("contract validate error : invalid arguments " - + "with tokenValue = 100, tokenId = 0").toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenvalue is less than 0 - fakeTokenValue = -1L; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - assetAccountDev.toStringUtf8(), fakeTokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenvalue is long.min - fakeTokenValue = Long.MIN_VALUE; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, 0L, 0, 10000, - assetAccountDev.toStringUtf8(), fakeTokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - String tokenId = Long.toString(-1); - long tokenValue = 0; - long callValue = 10; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = 0; - callValue = 10; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = Long.toString(1000000); - tokenValue = 0; - callValue = 10; - - response = PublicMethed - .deployContractAndGetResponse(contractName, abi, code, "", maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountDev, blockingStubFull); - Long userAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountUser, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info( - "after dev has AssetId: " + assetAccountDev.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - logger.info( - "after user has AssetId: " + assetAccountDev.toStringUtf8() + ", userAssetCountAfter: " - + userAssetCountAfter); - - Assert.assertEquals(devAssetCountBefore, devAssetCountAfter); - Assert.assertEquals(userAssetCountBefore, userAssetCountAfter); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken005.java deleted file mode 100644 index cff6e0ddcae..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken005.java +++ /dev/null @@ -1,422 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken005 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - @Test(enabled = true, description = "TriggerContract with exception condition") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user001Address, 1_000_000L, fromAddress, testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken005.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info( - "before trigger, transferTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", Count is " + transferAssetBefore); - - Long userAssetId = PublicMethed - .getAssetIssueValue(user001Address, ByteString.copyFromUtf8(tokenId), blockingStubFull); - logger.info("before userAssetId has AssetId " + tokenId + ", Count is " + userAssetId); - - // not such tokenId - tokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 100000); - tokenValue = 10; - callValue = 5; - - GrpcAPI.Return response = PublicMethed - .triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, - tokenValue, user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert - .assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // not have this tokenId - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : Owner no asset!".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenId is Long.MAX_VALUE - tokenId = Long.toString(Long.MAX_VALUE); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert - .assertEquals("contract validate error : No asset !".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - Assert.assertTrue(PublicMethed - .transferAsset(user001Address, assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // tokenValue is not enough - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 100; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : assetBalance is not sufficient.".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenvalue is less than 0 - tokenId = assetAccountId.toStringUtf8(); - tokenValue = -1; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - tokenId = assetAccountId.toStringUtf8(); - tokenValue = Long.MIN_VALUE; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenValue must be >= 0".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - /*PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - // tokenId is 100_0000 - tokenId = Long.toString(100_0000); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenId is long.min - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - // tokenId is 0 - tokenId = Long.toString(0); - tokenValue = 10; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals( - "contract validate error : invalid arguments with tokenValue = 10, tokenId = 0" - .toLowerCase(), response.getMessage().toStringUtf8().toLowerCase()); - - /*PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = 0; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - - tokenId = Long.toString(-1); - tokenValue = 0; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - - tokenId = Long.toString(100_0000L); - tokenValue = 0; - callValue = 5; - - response = PublicMethed.triggerContractAndGetResponse(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, 1000000000L, tokenId, tokenValue, - user001Address, user001Key, blockingStubFull); - - Assert.assertFalse(response.getResult()); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, response.getCode()); - Assert.assertEquals("contract validate error : tokenId must be > 1000000".toLowerCase(), - response.getMessage().toStringUtf8().toLowerCase()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java deleted file mode 100644 index f39b96cdf00..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken011.java +++ /dev/null @@ -1,476 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken011 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with correct value, deploy transfer contract") - public void test01DeployTransferTokenContract001() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 15048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 14048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account getAssetIdFromThisAccount = PublicMethed - .queryAccount(dev001Address, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken011.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 200, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - /*Assert.assertFalse(PublicMethed.transferAsset(transferTokenContractAddress, - assetAccountId.toByteArray(), 100L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - } - - - @Test(enabled = true, description = "TransferToken with correct value, deploy receive contract") - public void test02DeployRevContract002() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken011.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - final String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with correct value, transfer to a contract") - public void test03TriggerContract003() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = assetAccountId.toStringUtf8(); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - TransactionInfo transactionInfo = infoById.get(); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(tokenId, msgId.toString()); - Assert.assertEquals(tokenValue, msgTokenValue); - Assert.assertEquals(callValue, msgCallValue); - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - - } - - @Test(enabled = true, description = "TransferToken with correct value, get contract tokenBalance") - public void test04TriggerTokenBalanceContract004() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before trigger, dev energy limit is " + devEnergyLimitBefore); - logger.info("before trigger, dev energy usage is " + devEnergyUsageBefore); - logger.info("before trigger, dev balance is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("before trigger, user energy limit is " + userEnergyLimitBefore); - logger.info("before trigger, user energy usage is " + userEnergyUsageBefore); - logger.info("before trigger, user balance is " + userBalanceBefore); - - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Long triggerResult = ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray()); - logger.info("the receivercontract token by trigger contract: " + triggerResult); - Long assetIssueCount = PublicMethed - .getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - Assert.assertTrue(assetIssueCount == triggerResult); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken012.java deleted file mode 100644 index 14ad0553a11..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken012.java +++ /dev/null @@ -1,373 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken012 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "deploy transfer contract with correct value") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 15048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 14048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken012.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 200, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - /*Assert.assertFalse(PublicMethed.transferAsset(transferTokenContractAddress, - assetAccountId.toByteArray(), 100L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - } - - - @Test(description = "TransferToken with correct value, transfer to a normal account") - public void test02TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - logger.info("before trigger, receiveTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = assetAccountId.toStringUtf8(); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - } - - @Test(description = "TransferToken with correct value, get account tokenBalance") - public void test03TriggerTokenBalanceContract() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("before trigger, dev energy limit is " + devEnergyLimitBefore); - logger.info("before trigger, dev energy usage is " + devEnergyUsageBefore); - logger.info("before trigger, dev balance is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, - blockingStubFull).getBalance(); - - logger.info("before trigger, user energy limit is " + userEnergyLimitBefore); - logger.info("before trigger, user energy usage is " + userEnergyUsageBefore); - logger.info("before trigger, user balance is " + userBalanceBefore); - - String param = "\"" + Base58.encode58Check(dev001Address) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - Long assetAccountCount = ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray()); - logger.info("the receivercontract token from contract: " + assetAccountCount); - Long assetIssueCount = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - Assert.assertEquals(assetIssueCount, assetAccountCount); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - // unfreeze resource - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken014.java deleted file mode 100644 index 1134d4bae4c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken014.java +++ /dev/null @@ -1,544 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken014 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with tokenId in exception condition," - + " deploy transfer contract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //dev Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, - 1, 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - //user Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(user001Address, tokenName, TotalSupply, - 1, 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountUser = PublicMethed.queryAccount( - user001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The assetAccountUser token name: " + tokenName); - logger.info("The assetAccountUser token ID: " + assetAccountUser.toStringUtf8()); - - assetAccountId = PublicMethed.queryAccount( - dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The assetAccountId token name: " + tokenName); - logger.info("The assetAccountId token ID: " + assetAccountId.toStringUtf8()); - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue( - dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken014.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with tokenId in exception condition," - + " deploy receiver contract") - public void test02DeployRevContract() { - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken014.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with tokenId in exception condition," - + " transfer to contract") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - Long devAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetBefore); - - - // transfer a not exist TokenId, to a contract - String tokenId = assetAccountUser.toStringUtf8(); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // transfer a not exist TokenId, to a normal account - tokenId = assetAccountUser.toStringUtf8(); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenValue is not enough - tokenId = assetAccountId.toStringUtf8(); - tokenValue = transferAssetBefore + 100; - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - - // tokenValue is not enough, transfer to a normal account - tokenId = assetAccountId.toStringUtf8(); - tokenValue = transferAssetBefore + 100; - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - // TokenId is long.max, to a contract - String fackTokenId = Long.toString(Long.MAX_VALUE); - Long fakeValue = 1L; - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - - // TokenId is not exist, to a contract - fackTokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 10000); - fakeValue = 1L; - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - // TokenId is long.max, to a normal account - fackTokenId = Long.toString(Long.MAX_VALUE); - fakeValue = 1L; - - param = "\"" + Base58.encode58Check(dev001Address) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - - // TokenId is not exist, to a normal account - fackTokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 10000); - fakeValue = 1L; - - param = "\"" + Base58.encode58Check(dev001Address) - + "\"," + fakeValue + ",\"" + fackTokenId + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, 0, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - // tokenValue is long.min, transfer to a contract - tokenId = assetAccountId.toStringUtf8(); - tokenValue = Long.MIN_VALUE; - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("endowment out of long range", - infoById.get().getResMessage().toStringUtf8()); - - // tokenValue is long.min, transfer to a normal account - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("endowment out of long range", - infoById.get().getResMessage().toStringUtf8()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Long devAssetAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetAfter); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - Assert.assertEquals(receiveAssetBefore, receiveAssetAfter); - Assert.assertEquals(devAssetBefore, devAssetAfter); - Assert.assertEquals(transferAssetBefore, transferAssetAfter); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken018.java deleted file mode 100644 index 07f96d21425..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken018.java +++ /dev/null @@ -1,286 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.SUCESS; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class ContractTrcToken018 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] receiveTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] tmpAddress = ecKey3.getAddress(); - private String tmp001Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Transfer token to an inactive account") - public void testDeployTransferTokenContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user001Address, 100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken023.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 0, - 10000, assetAccountId.toStringUtf8(), 200, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Delpoy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - /*Assert.assertFalse(PublicMethed - .transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, blockingStubFull), 0, - 1, ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .transferAsset(user001Address, assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info( - "before trigger, transferTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed - .getAssetIssueValue(tmpAddress, assetAccountId, blockingStubFull); - logger.info( - "before trigger, receiveTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", Count is " + receiveAssetBefore); - - String param = - "\"" + Base58.encode58Check(tmpAddress) + "\"," + assetAccountId.toStringUtf8() + ",\"1\""; - - final String triggerTxid = PublicMethed - .triggerContract(transferTokenContractAddress, "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, - user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(SUCESS, infoById.get().getResult()); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - logger.info("infoById.get().getResMessage().toStringUtf8(): " + infoById.get().getResMessage() - .toStringUtf8()); - /*Assert.assertEquals( - "transfer trc10 failed: Validate InternalTransfer error, no ToAccount. " - + "And not allowed to create account in smart contract.", - infoById.get().getResMessage().toStringUtf8());*/ - - Long transferAssetAfter = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info( - "after trigger, transferTokenContractAddress has AssetId " + assetAccountId.toStringUtf8() - + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed - .getAssetIssueValue(tmpAddress, assetAccountId, blockingStubFull); - logger.info( - "after trigger, receiveTokenAddress has AssetId " + assetAccountId.toStringUtf8() - + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter, Long.valueOf(receiveAssetBefore + 1)); - Assert.assertEquals(transferAssetBefore, Long.valueOf(transferAssetAfter - 1)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken023.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken023.java deleted file mode 100644 index c78a088dd3c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken023.java +++ /dev/null @@ -1,235 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken023 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] transferTokenContractAddress; - byte[] btestAddress; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "deploy contract for transfer token") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 4048000000L, fromAddress, testKey002, blockingStubFull)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - int i = randomInt(6666666, 9999999); - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath2 = "src/test/resources/soliditycode/contractTrcToken023.sol"; - String contractName2 = "tokenTest"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath2, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert - .assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 1000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert - .assertFalse(PublicMethed.sendcoin(btestAddress, 1000000000L, fromAddress, - testKey002, blockingStubFull));*/ - - // devAddress transfer token to userAddress - PublicMethed.transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), - 100, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "transfer token which from address does not have") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId,blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId,blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed.getAssetIssueValue(btestAddress, - assetAccountId, blockingStubFull); - - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = "\"" + Base58.encode58Check(btestAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", param, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java deleted file mode 100644 index cc6251d9720..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken026.java +++ /dev/null @@ -1,514 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken026 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] btestAddress; - byte[] ctestAddress; - byte[] transferTokenContractAddress; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy transferToken contract") - public void deploy01TransferTokenContract001() { - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken026.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - ctestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - - String contractName2 = "token"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, description = "Multistage call transferToken use right tokenID") - public void deploy02TransferTokenContract002() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - logger.info("beforeAssetIssueCAddress:" + beforeAssetIssueCAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - // 1.user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress + 1); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - Assert.assertTrue(afterAssetIssueCAddress == beforeAssetIssueCAddress - 1); - } - - @Test(enabled = true, description = "Multistage call transferToken use fake tokenID") - public void deploy03TransferTokenContract003() { - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - //3. user trigger A to transfer token to B - int i = randomInt(6666666, 9999999); - - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i)); - - String param1 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + tokenId1 - .toStringUtf8() - + "\""; - - final String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param1, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - final Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress1 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterEnergyUsed1:" + afterEnergyUsed1); - logger.info("afterNetUsed1:" + afterNetUsed1); - logger.info("afterFreeNetUsed1:" + afterFreeNetUsed1); - logger.info("afterAssetIssueCount1:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress1:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress1:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueCAddress1:" + afterAssetIssueCAddress1); - logger.info("afterBalanceContractAddress1:" + afterBalanceContractAddress1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertEquals(afterBalanceContractAddress, afterBalanceContractAddress1); - Assert.assertTrue(afterAssetIssueContractAddress == afterAssetIssueContractAddress1); - Assert.assertTrue(afterAssetIssueBAddress == afterAssetIssueBAddress1); - Assert.assertTrue(afterAssetIssueCAddress == afterAssetIssueCAddress1); - } - - @Test(enabled = true, description = "Multistage call transferToken token value not enough") - public void deploy04TransferTokenContract004() { - - final Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress1 = - PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress1); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress1); - - //4. user trigger A to transfer token to B - String param2 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",10000000,\"" + assetAccountId - .toStringUtf8() - + "\""; - - final String triggerTxid2 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param2, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress2 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress2:" + afterAssetIssueContractAddress2); - logger.info("afterAssetIssueBAddress2:" + afterAssetIssueBAddress2); - logger.info("afterAssetIssueCAddress2:" + afterAssetIssueCAddress2); - logger.info("afterBalanceContractAddress2:" + afterBalanceContractAddress2); - - Assert.assertEquals(afterBalanceContractAddress1, afterBalanceContractAddress2); - Assert.assertTrue(afterAssetIssueContractAddress1 == afterAssetIssueContractAddress2); - Assert.assertTrue(afterAssetIssueBAddress1 == afterAssetIssueBAddress2); - Assert.assertTrue(afterAssetIssueCAddress1 == afterAssetIssueCAddress2); - } - - @Test(enabled = true, description = "Multistage call transferToken calltoken ID not exist") - public void deploy05TransferTokenContract005() { - - final Long afterAssetIssueContractAddress2 = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress2 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - //5. user trigger A to transfer token to B - String param3 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId - .toStringUtf8() - + "\""; - int i = randomInt(6666666, 9999999); - - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i)); - final String triggerTxid3 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param3, false, 0, 1000000000L, tokenId1 - .toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(triggerTxid3 == null); - - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress3 = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress3 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount3:" + afterAssetIssueDevAddress3); - logger.info("afterAssetIssueDevAddress3:" + afterAssetIssueContractAddress3); - logger.info("afterAssetIssueBAddress3:" + afterAssetIssueBAddress3); - logger.info("afterAssetIssueCAddress3:" + afterAssetIssueCAddress3); - logger.info("afterBalanceContractAddress3:" + afterBalanceContractAddress3); - - Assert.assertEquals(afterBalanceContractAddress2, afterBalanceContractAddress3); - Assert.assertTrue(afterAssetIssueContractAddress2 == afterAssetIssueContractAddress3); - Assert.assertTrue(afterAssetIssueBAddress2 == afterAssetIssueBAddress3); - Assert.assertTrue(afterAssetIssueCAddress2 == afterAssetIssueCAddress3); - } - - @Test(enabled = true, description = "Multistage call transferToken calltoken value not enough") - public void deploy06TransferTokenContract006() { - - final Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress3 = - PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - //6. user trigger A to transfer token to B - String param4 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid4 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param4, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), 100000000, dev001Address, dev001Key, blockingStubFull); - Assert.assertTrue(triggerTxid4 == null); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterAssetIssueContractAddress4 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress4 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress4:" + afterAssetIssueContractAddress4); - logger.info("afterAssetIssueBAddress4:" + afterAssetIssueBAddress4); - logger.info("afterAssetIssueCAddress4:" + afterAssetIssueCAddress4); - logger.info("afterBalanceContractAddress4:" + afterBalanceContractAddress4); - - Assert.assertEquals(afterBalanceContractAddress3, afterBalanceContractAddress4); - Assert.assertTrue(afterAssetIssueContractAddress3 == afterAssetIssueContractAddress4); - Assert.assertTrue(afterAssetIssueBAddress3 == afterAssetIssueBAddress4); - Assert.assertTrue(afterAssetIssueCAddress3 == afterAssetIssueCAddress4); - } - - @Test(enabled = true, description = "Multistage call transferToken use right tokenID,tokenvalue") - public void deploy07TransferTokenContract007() { - final Long afterAssetIssueDevAddress4 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress4 = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress4 = - PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - //2. user trigger A to transfer token to B - String param5 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid5 = PublicMethed.triggerContract(transferTokenContractAddress, - "testInCall(address,address,address,uint256,trcToken)", - param5, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterAssetIssueContractAddress5 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress5 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress5 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress5 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress5:" + afterAssetIssueContractAddress5); - logger.info("afterAssetIssueBAddress5:" + afterAssetIssueBAddress5); - logger.info("afterAssetIssueCAddress5:" + afterAssetIssueCAddress5); - logger.info("afterBalanceContractAddress5:" + afterBalanceContractAddress5); - - Optional infoById5 = PublicMethed - .getTransactionInfoById(triggerTxid5, blockingStubFull); - Assert.assertTrue(infoById5.get().getResultValue() == 0); - Assert.assertEquals(afterBalanceContractAddress4, afterBalanceContractAddress5); - Assert.assertTrue(afterAssetIssueContractAddress4 + 2 == afterAssetIssueContractAddress5); - Assert.assertTrue(afterAssetIssueBAddress4 == afterAssetIssueBAddress5); - Assert.assertTrue(afterAssetIssueCAddress4 - 1 == afterAssetIssueCAddress5); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken027.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken027.java deleted file mode 100644 index 63fc4690a95..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken027.java +++ /dev/null @@ -1,490 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken027 { - - - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] btestAddress; - byte[] ctestAddress; - byte[] transferTokenContractAddress; - int i1 = randomInt(6666666, 9999999); - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i1)); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - /** - * constructor. - */ - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy transferToken contract") - public void deploy01TransferTokenContract() { - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String tokenName = "testAI_" + randomInt(10000, 90000); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken027.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - String contractName1 = "C"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - ctestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - - - String contractName2 = "token"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 1000000000L, - fromAddress, testKey002, blockingStubFull));*/ - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken use right tokenID") - public void deploy02TransferTokenContract() { - - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - logger.info("beforeAssetIssueCAddress:" + beforeAssetIssueCAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - // 1.user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueCAddress:" + afterAssetIssueCAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress + 1); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - Assert.assertTrue(afterAssetIssueCAddress == beforeAssetIssueCAddress - 1); - - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken use fake tokenID") - public void deploy03TransferTokenContract() { - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - String param1 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + tokenId1.toStringUtf8() + "\""; - - final String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param1, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress1 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("afterAssetIssueCount1:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress1:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress1:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueCAddress1:" + afterAssetIssueCAddress1); - logger.info("afterBalanceContractAddress1:" + afterBalanceContractAddress1); - - - Assert.assertEquals(afterBalanceContractAddress, afterBalanceContractAddress1); - Assert.assertTrue(afterAssetIssueContractAddress == afterAssetIssueContractAddress1); - Assert.assertTrue(afterAssetIssueBAddress == afterAssetIssueBAddress1); - Assert.assertTrue(afterAssetIssueCAddress == afterAssetIssueCAddress1); - } - - - @Test(enabled = true, description = "Multistage delegatecall transferToken token value" - + " not enough") - public void deploy04TransferTokenContract() { - - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress1 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress1 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - String param2 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",10000000,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid2 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param2, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress2 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount2:" + afterAssetIssueDevAddress2); - logger.info("afterAssetIssueDevAddress2:" + afterAssetIssueContractAddress2); - logger.info("afterAssetIssueBAddress2:" + afterAssetIssueBAddress2); - logger.info("afterAssetIssueCAddress2:" + afterAssetIssueCAddress2); - logger.info("afterBalanceContractAddress2:" + afterBalanceContractAddress2); - - Assert.assertEquals(afterBalanceContractAddress1, afterBalanceContractAddress2); - Assert.assertTrue(afterAssetIssueContractAddress1 == afterAssetIssueContractAddress2); - Assert.assertTrue(afterAssetIssueBAddress1 == afterAssetIssueBAddress2); - Assert.assertTrue(afterAssetIssueCAddress1 == afterAssetIssueCAddress2); - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken calltoken ID" - + " not exist") - public void deploy05TransferTokenContract() { - - Long afterAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress2 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress2 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress2 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - - String param3 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid3 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param3, false, 0, 1000000000L, tokenId1.toStringUtf8(), - 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(triggerTxid3 == null); - - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress3 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount3:" + afterAssetIssueDevAddress3); - logger.info("afterAssetIssueDevAddress3:" + afterAssetIssueContractAddress3); - logger.info("afterAssetIssueBAddress3:" + afterAssetIssueBAddress3); - logger.info("afterAssetIssueCAddress3:" + afterAssetIssueCAddress3); - logger.info("afterBalanceContractAddress3:" + afterBalanceContractAddress3); - - Assert.assertEquals(afterBalanceContractAddress2, afterBalanceContractAddress3); - Assert.assertTrue(afterAssetIssueContractAddress2 == afterAssetIssueContractAddress3); - Assert.assertTrue(afterAssetIssueBAddress2 == afterAssetIssueBAddress3); - Assert.assertTrue(afterAssetIssueCAddress2 == afterAssetIssueCAddress3); - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken calltoken value " - + "not enough") - public void deploy06TransferTokenContract() { - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress3 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress3 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress3 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - String param4 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid4 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param4, false, 0, 1000000000L, assetAccountId.toStringUtf8(), - 100000000, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(triggerTxid4 == null); - Long afterAssetIssueDevAddress4 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress4 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress4 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - Long afterUserBalance4 = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("afterAssetIssueCount4:" + afterAssetIssueDevAddress4); - logger.info("afterAssetIssueDevAddress4:" + afterAssetIssueContractAddress4); - logger.info("afterAssetIssueBAddress4:" + afterAssetIssueBAddress4); - logger.info("afterAssetIssueCAddress4:" + afterAssetIssueCAddress4); - logger.info("afterBalanceContractAddress4:" + afterBalanceContractAddress4); - logger.info("afterUserBalance4:" + afterUserBalance4); - - Assert.assertEquals(afterBalanceContractAddress3, afterBalanceContractAddress4); - Assert.assertTrue(afterAssetIssueContractAddress3 == afterAssetIssueContractAddress4); - Assert.assertTrue(afterAssetIssueBAddress3 == afterAssetIssueBAddress4); - Assert.assertTrue(afterAssetIssueCAddress3 == afterAssetIssueCAddress4); - } - - @Test(enabled = true, description = "Multistage delegatecall transferToken use right tokenID," - + "tokenvalue") - public void deploy07TransferTokenContract() { - final Long afterAssetIssueDevAddress4 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long afterAssetIssueContractAddress4 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueBAddress4 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueCAddress4 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - final Long afterBalanceContractAddress4 = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - String param5 = - "\"" + Base58.encode58Check(btestAddress) + "\",\"" + Base58.encode58Check(ctestAddress) - + "\",\"" + Base58.encode58Check(transferTokenContractAddress) - + "\",1,\"" + assetAccountId.toStringUtf8() + "\""; - - final String triggerTxid5 = PublicMethed.triggerContract(transferTokenContractAddress, - "testIndelegateCall(address,address,address,uint256,trcToken)", - param5, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById5 = PublicMethed - .getTransactionInfoById(triggerTxid5, blockingStubFull); - Assert.assertTrue(infoById5.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress5 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress5 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress5 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueCAddress5 = PublicMethed - .getAssetIssueValue(ctestAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress5 = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount5:" + afterAssetIssueDevAddress5); - logger.info("afterAssetIssueDevAddress5:" + afterAssetIssueContractAddress5); - logger.info("afterAssetIssueBAddress5:" + afterAssetIssueBAddress5); - logger.info("afterAssetIssueCAddress5:" + afterAssetIssueCAddress5); - logger.info("afterBalanceContractAddress5:" + afterBalanceContractAddress5); - - Assert.assertEquals(afterBalanceContractAddress4, afterBalanceContractAddress5); - Assert.assertTrue(afterAssetIssueContractAddress4 + 2 == afterAssetIssueContractAddress5); - Assert.assertTrue(afterAssetIssueBAddress4 == afterAssetIssueBAddress5); - Assert.assertTrue(afterAssetIssueCAddress4 - 1 == afterAssetIssueCAddress5); - Assert.assertTrue(afterAssetIssueDevAddress4 - 1 == afterAssetIssueDevAddress5); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken028.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken028.java deleted file mode 100644 index 06ddba41e0e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken028.java +++ /dev/null @@ -1,189 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken028 { - - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - int i1 = randomInt(6666666, 9999999); - ByteString tokenId1 = ByteString.copyFromUtf8(String.valueOf(i1)); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy tokenBalanceWithSameName contract") - public void deploy01TransferTokenContract() { - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 3, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String tokenName = "testAI_" + randomInt(10000, 90000); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken028.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - - @Test(enabled = true, description = "Trigger tokenBalanceWithSameName") - public void deploy02TransferTokenContract() { - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed.getAssetIssueValue( - transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - String param = - "\"" + tokenId1 - .toStringUtf8() - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "tokenBalanceWithSameName(trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - Long afterUserBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - logger.info("afterUserBalance:" + afterUserBalance); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - - String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "getA()", - "#", false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(triggerTxid1, blockingStubFull); - Long returnnumber1 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(returnnumber1 == 9); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken029.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken029.java deleted file mode 100644 index 5dc1e876212..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken029.java +++ /dev/null @@ -1,174 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken029 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy transferTokenwithSameName contract") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.printAddress(dev001Key); - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken029.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, - 1000000000L, fromAddress, testKey002, blockingStubFull));*/ - } - - /** - * constructor. - */ - - @Test(enabled = true, description = "Trigger transferTokenwithSameName") - public void deploy02TransferTokenContract() { - - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - // user trigger A to transfer token to B - ByteString assetAccountDev = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - ByteString fakeTokenId = ByteString - .copyFromUtf8(Long.toString(Long.valueOf(assetAccountDev.toStringUtf8()) + 100)); - String param = "\"" + fakeTokenId.toStringUtf8() + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenWithSameName(trcToken,uint256)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueCount:" + afterAssetIssueContractAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken030.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken030.java deleted file mode 100644 index c35993a0207..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken030.java +++ /dev/null @@ -1,187 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken030 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Deploy suicide contract") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - - - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken030.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger suicide contract,toaddress is other") - public void deploy02TransferTokenContract() { - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - final Long beforeUserBalance = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(user001Address) - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "kill(address)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - final Long afterUserBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Assert.assertTrue(afterBalanceContractAddress == 0); - Assert.assertTrue(beforeAssetIssueUserAddress + beforeAssetIssueContractAddress - == afterAssetIssueUserAddress); - Assert.assertTrue(beforeUserBalance + beforeBalanceContractAddress - == afterUserBalance); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken031.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken031.java deleted file mode 100644 index 4622e1f4897..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken031.java +++ /dev/null @@ -1,171 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken031 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Deploy suicide contract") - public void deploy01TransferTokenContract() { - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("assetId: " + assetAccountId); - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken031.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(transferTokenContractAddress); - - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, - 1000000000L, fromAddress, testKey002, blockingStubFull));*/ - } - - @Test(enabled = true, description = "Trigger suicide contract,toaddress is myself") - public void deploy02TransferTokenContract() { - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = - "\"" + Base58.encode58Check(transferTokenContractAddress) - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "kill(address)", param, false, 0, 1000000000L, - "0", 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - - Assert.assertTrue(afterBalanceContractAddress == 0); - Assert.assertTrue(afterAssetIssueContractAddress == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken034.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken034.java deleted file mode 100644 index f9e5ed01772..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken034.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken034 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info( - "dev001Address:" + Base58.encode58Check(dev001Address)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info( - "user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - - @Test(enabled = true, description = "Deploy after transfertoken execute require contract") - public void deploy01TransferTokenContract() { - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken034.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 100000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 50, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, description = "Trigger after transfertoken execute require contract") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - - String param = - "\"" + Base58.encode58Check(user001Address) + "\",1,\"" + assetAccountId - .toStringUtf8() - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "failTransferTokenRevert(address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - - Assert.assertEquals(beforeAssetIssueDevAddress, afterAssetIssueDevAddress); - Assert.assertEquals(beforeAssetIssueUserAddress, afterAssetIssueUserAddress); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken035.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken035.java deleted file mode 100644 index e3568c6873c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken035.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken035 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] transferTokenContractAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Deploy after transfertoken execute assert contract") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 9999000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "dev001Address:" + Base58.encode58Check(dev001Address)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - String filePath = "src/test/resources/soliditycode/contractTrcToken035.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 100000000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 50, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger after transfertoken execute assert contract") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - - String param = - "\"" + Base58.encode58Check(user001Address) + "\",1,\"" + assetAccountId - .toStringUtf8() - + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "failTransferTokenError(address,uint256,trcToken)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - - Assert.assertEquals(beforeAssetIssueDevAddress, afterAssetIssueDevAddress); - Assert.assertEquals(beforeAssetIssueUserAddress, afterAssetIssueUserAddress); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken036.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken036.java deleted file mode 100644 index 400e51cae3a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken036.java +++ /dev/null @@ -1,527 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken036 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] transferTokenContractAddress; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - int originEnergyLimit = 50000; - byte[] transferTokenWithPureTestAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = false, description = "Deploy contract") - public void deploy01TransferTokenContract() { - - Assert - .assertTrue(PublicMethed.sendcoin(dev001Address, 9999000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "dev001Address:" + Base58.encode58Check(dev001Address)); - Assert - .assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info( - "user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - // String filePath = "src/test/resources/soliditycode/contractTrcToken036.sol"; - // String contractName = "IllegalDecorate"; - // HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - // String code = retMap.get("byteCode").toString(); - // String abi = retMap.get("abI").toString(); - // transferTokenContractAddress = PublicMethed - // .deployContract(contractName, abi, code, "", maxFeeLimit, - // 0L, 0, originEnergyLimit, "0", - // 0, null, dev001Key, dev001Address, - // blockingStubFull); - - - // - // // devAddress transfer token to userAddress - // PublicMethed - // .transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), 100, - // dev001Address, - // dev001Key, - // blockingStubFull); - // Assert - // .assertTrue(PublicMethed.sendcoin(transferTokenContractAddress, 100, fromAddress, - // testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Trigger transferTokenWithPure contract") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - logger.info("user001AddressAddressBalance:" + user001AddressAddressBalance); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenWithPure(address,uint256)", - param, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - logger.info("afterContractAddressBalance:" + afteruser001AddressAddressBalance); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(beforeAssetIssueDevAddress - 10 == afterAssetIssueDevAddress); - Assert.assertTrue(beforeAssetIssueUserAddress + 10 == afterAssetIssueUserAddress); - Assert.assertTrue(user001AddressAddressBalance + 10 == afteruser001AddressAddressBalance); - - String filePath = "src/test/resources/soliditycode/contractTrcToken036.sol"; - String contractName1 = "IllegalDecorate1"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - transferTokenWithPureTestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // devAddress transfer token to userAddress - PublicMethed - .transferAsset(transferTokenWithPureTestAddress, assetAccountId.toByteArray(), 100, - dev001Address, - dev001Key, - blockingStubFull); - Assert - .assertTrue(PublicMethed.sendcoin(transferTokenWithPureTestAddress, 100, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Trigger transferTokenWithConstant contract") - public void deploy03TransferTokenContract() { - Account info1; - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeEnergyUsed1 = resourceInfo1.getEnergyUsed(); - Long beforeNetUsed1 = resourceInfo1.getNetUsed(); - Long beforeFreeNetUsed1 = resourceInfo1.getFreeNetUsed(); - Long beforeAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance1 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance1); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed1); - logger.info("beforeNetUsed:" + beforeNetUsed1); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed1); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress1); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress1); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress1); - logger.info("user001AddressAddressBalance:" + user001AddressAddressBalance1); - - // user trigger A to transfer token to B - String param1 = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - final String triggerTxid1 = PublicMethed.triggerContract(transferTokenWithPureTestAddress, - "transferTokenWithConstant(address,uint256)", - param1, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance1 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress1); - logger.info("afterContractAddressBalance:" + afteruser001AddressAddressBalance1); - - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertEquals(beforeBalance1, afterBalance1); - Assert.assertEquals(beforeAssetIssueDevAddress1, afterAssetIssueDevAddress1); - Assert.assertEquals(beforeAssetIssueUserAddress1, afterAssetIssueUserAddress1); - Assert.assertEquals(user001AddressAddressBalance1, afteruser001AddressAddressBalance1); - } - - @Test(enabled = false, description = "Trigger transferTokenWithView contract") - public void deploy04TransferTokenContract() { - String filePath2 = "src/test/resources/soliditycode/contractTrcToken036.sol"; - String contractName2 = "IllegalDecorate2"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - byte[] transferTokenWithViewAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // devAddress transfer token to userAddress - PublicMethed - .transferAsset(transferTokenWithViewAddress, assetAccountId.toByteArray(), 100, - dev001Address, - dev001Key, - blockingStubFull); - Assert - .assertTrue(PublicMethed.sendcoin(transferTokenWithViewAddress, 100, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info2; - AccountResourceMessage resourceInfo2 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info2 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance2 = info2.getBalance(); - Long beforeEnergyUsed2 = resourceInfo2.getEnergyUsed(); - Long beforeNetUsed2 = resourceInfo2.getNetUsed(); - Long beforeFreeNetUsed2 = resourceInfo2.getFreeNetUsed(); - Long beforeAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress2 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenWithViewAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance2 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeAssetIssueContractAddress2:" + beforeAssetIssueContractAddress2); - logger.info("beforeAssetIssueDevAddress2:" + beforeAssetIssueDevAddress2); - logger.info("beforeAssetIssueUserAddress2:" + beforeAssetIssueUserAddress2); - logger.info("user001AddressAddressBalance2:" + user001AddressAddressBalance2); - - // user trigger A to transfer token to B - String param2 = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - String triggerTxid2 = PublicMethed.triggerContract(transferTokenWithViewAddress, - "transferTokenWithView(address,uint256)", - param2, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - - Account infoafter2 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter2 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance2 = infoafter2.getBalance(); - Long afterEnergyUsed2 = resourceInfoafter2.getEnergyUsed(); - Long afterAssetIssueDevAddress2 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed2 = resourceInfoafter2.getNetUsed(); - Long afterFreeNetUsed2 = resourceInfoafter2.getFreeNetUsed(); - Long afterAssetIssueContractAddress2 = PublicMethed - .getAssetIssueValue(transferTokenWithViewAddress, - assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress2 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance2 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - logger.info("afterAssetIssueDevAddress2:" + afterAssetIssueDevAddress2); - logger.info("afterAssetIssueContractAddress2:" + afterAssetIssueContractAddress2); - logger.info("afterAssetIssueUserAddress2:" + afterAssetIssueUserAddress2); - logger.info("afteruser001AddressAddressBalance2:" + afteruser001AddressAddressBalance2); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - - Assert.assertEquals(beforeAssetIssueDevAddress2, afterAssetIssueDevAddress2); - Assert.assertEquals(beforeAssetIssueUserAddress2, afterAssetIssueUserAddress2); - Assert.assertEquals(user001AddressAddressBalance2, afteruser001AddressAddressBalance2); - } - - @Test(enabled = false, description = "Trigger transferTokenWithNoPayable contract") - public void deploy05TransferTokenContract() { - String filePath = "src/test/resources/soliditycode/contractTrcToken036.sol"; - String contractName3 = "IllegalDecorate3"; - HashMap retMap3 = PublicMethed.getBycodeAbi(filePath, contractName3); - - String code3 = retMap3.get("byteCode").toString(); - String abi3 = retMap3.get("abI").toString(); - byte[] transferTokenWithOutPayableTestAddress = PublicMethed - .deployContract(contractName3, abi3, code3, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed - .transferAsset(transferTokenWithOutPayableTestAddress, assetAccountId.toByteArray(), 100, - dev001Address, - dev001Key, - blockingStubFull); - Assert - .assertTrue(PublicMethed.sendcoin(transferTokenWithOutPayableTestAddress, 100, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info3; - AccountResourceMessage resourceInfo3 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info3 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance3 = info3.getBalance(); - Long beforeEnergyUsed3 = resourceInfo3.getEnergyUsed(); - Long beforeNetUsed3 = resourceInfo3.getNetUsed(); - Long beforeFreeNetUsed3 = resourceInfo3.getFreeNetUsed(); - Long beforeAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueUserAddress3 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue( - transferTokenWithOutPayableTestAddress, - assetAccountId, - blockingStubFull); - Long user001AddressAddressBalance3 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance3); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed3); - logger.info("beforeNetUsed:" + beforeNetUsed3); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed3); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueContractAddress3); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress3); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress3); - logger.info("user001AddressAddressBalance:" + user001AddressAddressBalance3); - - String param3 = - "\"" + Base58.encode58Check(user001Address) + "\",\"1\""; - - String triggerTxid3 = PublicMethed.triggerContract(transferTokenWithOutPayableTestAddress, - "transferTokenWithOutPayable(address,uint256)", - param3, false, 10, 1000000000L, assetAccountId - .toStringUtf8(), - 10, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter3 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter3 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance3 = infoafter3.getBalance(); - Long afterEnergyUsed3 = resourceInfoafter3.getEnergyUsed(); - Long afterAssetIssueDevAddress3 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, - blockingStubFull); - Long afterNetUsed3 = resourceInfoafter3.getNetUsed(); - Long afterFreeNetUsed3 = resourceInfoafter3.getFreeNetUsed(); - Long afterAssetIssueContractAddress3 = PublicMethed - .getAssetIssueValue( - transferTokenWithOutPayableTestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress3 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afteruser001AddressAddressBalance3 = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(triggerTxid3, blockingStubFull); - Assert.assertTrue(infoById3.get().getResultValue() == 1); - - Assert.assertEquals(beforeAssetIssueDevAddress3, afterAssetIssueDevAddress3); - Assert.assertEquals(beforeAssetIssueUserAddress3, afterAssetIssueUserAddress3); - Assert.assertEquals(user001AddressAddressBalance3, afteruser001AddressAddressBalance3); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, - null, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, - null, blockingStubFull); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken037.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken037.java deleted file mode 100644 index 14c395b2f2f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken037.java +++ /dev/null @@ -1,205 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken037 { - - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Multi-level call transferToken tokenBalance") - public void deploy01TransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info("dev001Address:" + Base58.encode58Check(dev001Address)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - - String filePath = "src/test/resources/soliditycode/contractTrcToken037.sol"; - String contractName = "receiveTrc10"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 0, originEnergyLimit, "0", 0, - null, dev001Key, dev001Address, blockingStubFull); - - String contractName1 = "transferTrc10"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = - "\"" + Base58.encode58Check(btestAddress) + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "receive(address)", - param, false, 0, 1000000000L, assetAccountId.toStringUtf8(), - 10, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueDevAddress == beforeAssetIssueDevAddress - 10); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress + 10); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken038.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken038.java deleted file mode 100644 index af4cc453903..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken038.java +++ /dev/null @@ -1,209 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken038 { - - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Multi-level call transferToken assert tokenBalance ") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - logger.info("dev001Address:" + Base58.encode58Check(dev001Address)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 3, 1, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertFalse(assetAccountId.toStringUtf8().equals("")); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - - String filePath = "src/test/resources/soliditycode/contractTrcToken038.sol"; - String contractName2 = "transferTrc10"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - final byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - - String contractName = "receiveTrc10"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] btestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 1000000000L, - fromAddress, testKey002, blockingStubFull)); - Assert.assertFalse(PublicMethed.sendcoin(btestAddress, 1000000000L, - fromAddress, testKey002, blockingStubFull));*/ - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long beforeBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeBalanceContractAddress:" + beforeBalanceContractAddress); - - String param = - "\"" + Base58.encode58Check(btestAddress) + "\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "receive(address)", - param, false, 0, 1000000000L, assetAccountId.toStringUtf8(), - 1, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - - Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, blockingStubFull); - - Long afterBalanceContractAddress = PublicMethed.queryAccount(transferTokenContractAddress, - blockingStubFull).getBalance(); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - - Assert.assertEquals(afterBalanceContractAddress, beforeBalanceContractAddress); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, null, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java deleted file mode 100644 index 9f18bb1afb7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken039.java +++ /dev/null @@ -1,345 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken039 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - byte[] proxyTestAddress; - byte[] atestAddress; - byte[] btestAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "Deploy Proxy contract") - public void deploy01TransferTokenContract() { - Assert - .assertTrue(PublicMethed.sendcoin(dev001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info("dev001Address:" + Base58.encode58Check(dev001Address)); - Assert - .assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info("user001Address:" + Base58.encode58Check(user001Address)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - int originEnergyLimit = 50000; - - String filePath = "src/test/resources/soliditycode/contractTrcToken039.sol"; - String contractName = "Proxy"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - proxyTestAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 1000L, 0, originEnergyLimit, assetAccountId.toStringUtf8(), - 1000, null, dev001Key, dev001Address, - blockingStubFull); - - String contractName1 = "A"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - atestAddress = PublicMethed - .deployContract(contractName1, abi1, code1, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName2 = "B"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath, contractName2); - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - btestAddress = PublicMethed - .deployContract(contractName2, abi2, code2, "", maxFeeLimit, - 0L, 0, originEnergyLimit, "0", - 0, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true, dependsOnMethods = "deploy01TransferTokenContract", - description = "Trigger Proxy contract use AddressA") - public void deploy02TransferTokenContract() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - - Long beforeAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long beforeAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - Long beforeAssetIssueAAddress = PublicMethed - .getAssetIssueValue(atestAddress, assetAccountId, - blockingStubFull); - Long beforeBalanceContractAddress = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long beforeUserBalance = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("beforeBalance:" + beforeBalance); - - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueBAddress:" + beforeAssetIssueBAddress); - - logger.info("beforeAssetIssueDevAddress:" + beforeAssetIssueDevAddress); - logger.info("beforeAssetIssueUserAddress:" + beforeAssetIssueUserAddress); - - String param = - "\"" + Base58.encode58Check(atestAddress) + "\""; - String param1 = - "\"" + "1" + "\",\"" + Base58.encode58Check(user001Address) + "\",\"" + assetAccountId - .toStringUtf8() - + "\""; - - String triggerTxid = PublicMethed.triggerContract(proxyTestAddress, - "upgradeTo(address)", - param, false, 0, 1000000000L, "0", - 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - final String triggerTxid1 = PublicMethed.triggerContract(proxyTestAddress, - "trans(uint256,address,trcToken)", - param1, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), - 1, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long afterAssetIssueDevAddress = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueBAddress = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueAAddress = PublicMethed - .getAssetIssueValue(atestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueUserAddress = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterBalanceContractAddress = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long afterUserBalance = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("afterAssetIssueCount:" + afterAssetIssueDevAddress); - logger.info("afterAssetIssueDevAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueBAddress:" + afterAssetIssueBAddress); - logger.info("afterAssetIssueUserAddress:" + afterAssetIssueUserAddress); - logger.info("afterBalanceContractAddress:" + afterBalanceContractAddress); - logger.info("afterUserBalance:" + afterUserBalance); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterAssetIssueUserAddress == beforeAssetIssueUserAddress); - Assert.assertTrue(afterBalanceContractAddress == beforeBalanceContractAddress - 1); - Assert.assertTrue(afterAssetIssueContractAddress == beforeAssetIssueContractAddress + 1); - Assert.assertTrue(afterAssetIssueDevAddress == beforeAssetIssueDevAddress - 1); - Assert.assertTrue(afterUserBalance == beforeUserBalance + 1); - Assert.assertTrue(afterAssetIssueUserAddress == afterAssetIssueUserAddress); - Assert.assertTrue(afterAssetIssueBAddress == beforeAssetIssueBAddress); - } - - @Test(enabled = true,dependsOnMethods = "deploy02TransferTokenContract", - description = "Trigger Proxy contract use AddressB") - public void deploy03TransferTokenContract() { - Account info1; - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - info1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance1 = info1.getBalance(); - Long beforeAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - - Long beforeAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long beforeAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - - Long beforeBalanceContractAddress1 = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long beforeUserBalance1 = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - logger.info("beforeBalance1:" + beforeBalance1); - logger.info("beforeAssetIssueContractAddress1:" + beforeAssetIssueContractAddress1); - logger.info("beforeAssetIssueBAddress1:" + beforeAssetIssueBAddress1); - - logger.info("beforeAssetIssueDevAddress1:" + beforeAssetIssueDevAddress1); - logger.info("beforeAssetIssueUserAddress1:" + beforeAssetIssueUserAddress1); - logger.info("beforeBalanceContractAddress1:" + beforeBalanceContractAddress1); - logger.info("beforeUserBalance1:" + beforeUserBalance1); - String param3 = - "\"" + Base58.encode58Check(btestAddress) + "\""; - String param2 = - "\"" + "1" + "\",\"" + Base58.encode58Check(user001Address) + "\",\"" + assetAccountId - .toStringUtf8() - + "\""; - - String triggerTxid2 = PublicMethed.triggerContract(proxyTestAddress, - "upgradeTo(address)", param3, false, 0, 1000000000L, - assetAccountId.toStringUtf8(), 1, dev001Address, dev001Key, blockingStubFull); - String triggerTxid3 = PublicMethed.triggerContract(proxyTestAddress, - "trans(uint256,address,trcToken)", - param2, false, 0, 1000000000L, assetAccountId - .toStringUtf8(), - 1, dev001Address, dev001Key, - blockingStubFull); - Account infoafter1 = PublicMethed.queryAccount(dev001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterAssetIssueDevAddress1 = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - Long afterAssetIssueContractAddress1 = PublicMethed - .getAssetIssueValue(proxyTestAddress, assetAccountId, - blockingStubFull); - Long afterAssetIssueBAddress1 = PublicMethed - .getAssetIssueValue(btestAddress, assetAccountId, - blockingStubFull); - - Long afterAssetIssueUserAddress1 = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long afterBalanceContractAddress1 = PublicMethed.queryAccount(proxyTestAddress, - blockingStubFull).getBalance(); - Long afterUserBalance1 = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("afterBalance1:" + afterBalance1); - logger.info("afterAssetIssueCount1:" + afterAssetIssueDevAddress1); - logger.info("afterAssetIssueDevAddress1:" + afterAssetIssueContractAddress1); - logger.info("afterAssetIssueBAddress1:" + afterAssetIssueBAddress1); - logger.info("afterAssetIssueUserAddress1:" + afterAssetIssueUserAddress1); - logger.info("afterBalanceContractAddress1:" + afterBalanceContractAddress1); - logger.info("afterUserBalance1:" + afterUserBalance1); - - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid3, blockingStubFull); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - Assert.assertTrue(afterAssetIssueUserAddress1 == beforeAssetIssueUserAddress1); - Assert.assertTrue(afterBalanceContractAddress1 == beforeBalanceContractAddress1 - 1); - Assert.assertTrue(afterAssetIssueContractAddress1 == beforeAssetIssueContractAddress1 + 1); - Assert.assertTrue(afterAssetIssueDevAddress1 == beforeAssetIssueDevAddress1 - 1); - Assert.assertTrue(afterUserBalance1 == beforeUserBalance1 + 1); - Assert.assertTrue(afterAssetIssueUserAddress1 == afterAssetIssueUserAddress1); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken041.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken041.java deleted file mode 100644 index 9281c03d8cc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken041.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken041 { - - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true, description = "Trigger contract msg.tokenId add 1,msg.tokenValue add 1") - public void deployTransferTokenContract() { - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // freeze balance - PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull); - - PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - final ByteString fakeTokenId = ByteString - .copyFromUtf8(Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 100)); - - // deploy transferTokenContract - String filePath = "src/test/resources/soliditycode/contractTrcToken041.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(dev001Address) + "\",\"" + fakeTokenId - .toStringUtf8() - + "\",\"105\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, fakeTokenId.toStringUtf8(), - 10000000L, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - Assert.assertTrue(afterEnergyUsed == 0L); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken043.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken043.java deleted file mode 100644 index c07017f0ce5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken043.java +++ /dev/null @@ -1,466 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken043 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] user002Address = ecKey3.getAddress(); - private String user002Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - @Test(enabled = true, description = "TransferToken with invalid tokenId, deploy transferContract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user002Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken043.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with invalid tokenId, deploy receive contract") - public void test02DeployRevContract() { - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken043.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with invalid tokenId, transferToken") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user002Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - // tokenId is 100_0000 - String tokenId = Long.toString(100_0000); - Long tokenValue = Long.valueOf(1); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Triger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenId is -1 - tokenId = Long.toString(-1); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - //Assert.assertEquals("validateForSmartContract failure, not valid token id", - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenId is long.min - tokenId = Long.toString(Long.MIN_VALUE); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - // tokenId is 0, contract not have trx - tokenId = Long.toString(0); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - Assert.assertFalse(PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(user002Address, 5000000, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //tokenId is 0, transfer contract has trx, transfer to normal account - tokenId = Long.toString(0); - tokenValue = Long.valueOf(1); - callValue = Long.valueOf(1); - - param = "\"" + Base58.encode58Check(dev001Address) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user002Address, user002Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - // tokenid bigger than long.max, trigger to a contract - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestIDOverBigInteger(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user002Address, user002Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter, receiveAssetBefore); - Assert.assertEquals(transferAssetBefore, transferAssetAfter); - - // unfreeze resource - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user002Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken048.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken048.java deleted file mode 100644 index ef74ef6e0c3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken048.java +++ /dev/null @@ -1,193 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken048 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken msg.value msg,tokenvalue is negative number") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - final ByteString fakeassetAccountId = ByteString - .copyFromUtf8(Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 100)); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken048.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, "0", - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "testMsgTokenValue()", - "#", false, 0, 100000000L, fakeassetAccountId.toStringUtf8(), - -1000, user001Address, user001Key, blockingStubFull); - - String triggerTxid1 = PublicMethed.triggerContract(transferTokenContractAddress, - "testMsgValue()", - "#", false, -1000, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken049.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken049.java deleted file mode 100644 index 0ee8fe250c5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken049.java +++ /dev/null @@ -1,228 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken049 { - - - private static final long TotalSupply = 10000000L; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - /** - * constructor. - */ - - public ByteString createAssetissue(byte[] devAddress, String devKey, String tokenName) { - - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - - logger.info("The token name: " + tokenName); - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(devAddress, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, devKey, blockingStubFull)); - - ByteString assetAccountId = PublicMethed.queryAccount(devAddress, blockingStubFull) - .getAssetIssuedID(); - logger.info("The tokenID: " + assetAccountId); - - return assetAccountId; - } - - @Test(enabled = true, description = "TransferToken to myself") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String tokenName = "testAI_" + randomInt(10000, 90000); - ByteString tokenId = createAssetissue(user001Address, user001Key, tokenName); - - PublicMethed.transferAsset(dev001Address, tokenId.toByteArray(), 101, user001Address, - user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken049.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, tokenId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - byte[] transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - - Long beforeBalance = PublicMethed - .queryAccount(user001Address, blockingStubFull).getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = - PublicMethed.getAssetIssueValue(user001Address, tokenId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, tokenId, blockingStubFull); - final Long beforeAssetIssueDev = PublicMethed.getAssetIssueValue(dev001Address, tokenId, - blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(dev001Address) + "\",\"" + tokenId - .toStringUtf8() - + "\",\"1\""; - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = - PublicMethed.getAssetIssueValue(user001Address, tokenId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, tokenId, blockingStubFull); - final Long afterAssetIssueDev = PublicMethed.getAssetIssueValue(dev001Address, tokenId, - blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(beforeBalance, afterBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertTrue(beforeAssetIssueContractAddress == afterAssetIssueContractAddress); - - Assert.assertTrue(beforeAssetIssueDev == afterAssetIssueDev); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken050.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken050.java deleted file mode 100644 index f428d2932a7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken050.java +++ /dev/null @@ -1,203 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken050 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken to contract address ") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken050.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] transferTokenContractAddress; - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, - blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, - assetAccountId, - blockingStubFull); - final Long beforeAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDev:" + beforeAssetIssueDev); - - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(transferTokenContractAddress) + "\",\"" + assetAccountId - .toStringUtf8() - + "\",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - final Long afterAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueDev:" + afterAssetIssueDev); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertTrue(beforeAssetIssueContractAddress == afterAssetIssueContractAddress); - Assert.assertEquals(beforeAssetIssueDev, afterAssetIssueDev); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken051.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken051.java deleted file mode 100644 index 5abad4b440d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken051.java +++ /dev/null @@ -1,203 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken051 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken to contract developer tokenID is 0") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 6048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken051.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] transferTokenContractAddress; - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDev:" + beforeAssetIssueDev); - - String fakeassetAccountId = Long.toString(0L); - - String param = "\"" + Base58.encode58Check(dev001Address) - + "\"," + fakeassetAccountId + ",\"1\""; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertFalse(infoById.get().getResultValue() == 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueDev:" + afterAssetIssueDev); - - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - Assert.assertEquals(beforeAssetIssueDev, afterAssetIssueDev); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken052.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken052.java deleted file mode 100644 index b0b5efc8f20..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken052.java +++ /dev/null @@ -1,207 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken052 { - - private static final long TotalSupply = 10000000L; - private static final long now = System.currentTimeMillis(); - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - - @Test(enabled = true, description = "TransferToken to contract address tokenID is 0") - public void deployTransferTokenContract() { - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 6048000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, - 10000L, 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - // deploy transferTokenContract - String filePath = "./src/test/resources/soliditycode/contractTrcToken052.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, assetAccountId.toStringUtf8(), - 0, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - /*Assert.assertFalse(PublicMethed.sendcoin(transferTokenContractAddress, 2048000000, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull);*/ - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - info = PublicMethed.queryAccount(user001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long beforeAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long beforeAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long beforeAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long beforetransferTokenContractAddressBalance = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - final Long beforeDevBalance = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getBalance(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("beforeAssetIssueCount:" + beforeAssetIssueCount); - logger.info("beforeAssetIssueContractAddress:" + beforeAssetIssueContractAddress); - logger.info("beforeAssetIssueDev:" + beforeAssetIssueDev); - String fakeassetAccountId = Long.toString(0L); - - String param = "\"" + Base58.encode58Check(transferTokenContractAddress) - + "\"," + fakeassetAccountId + ",\"1\""; - // user trigger A to transfer token to B - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, "0", - 0, user001Address, user001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Account infoafter = PublicMethed.queryAccount(user001Address, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(user001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterAssetIssueCount = PublicMethed - .getAssetIssueValue(user001Address, assetAccountId, blockingStubFull); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long afterAssetIssueContractAddress = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - Long afterAssetIssueDev = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - final Long aftertransferTokenContractAddressBalance = PublicMethed - .queryAccount(transferTokenContractAddress, blockingStubFull).getBalance(); - final Long afterDevBalance = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getBalance(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("afterAssetIssueCount:" + afterAssetIssueCount); - logger.info("afterAssetIssueContractAddress:" + afterAssetIssueContractAddress); - logger.info("afterAssetIssueDev:" + afterAssetIssueDev); - - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals( - beforetransferTokenContractAddressBalance, aftertransferTokenContractAddressBalance); - Assert.assertEquals(beforeDevBalance, afterDevBalance); - Assert.assertEquals(beforeAssetIssueCount, afterAssetIssueCount); - Assert.assertEquals(beforeAssetIssueContractAddress, afterAssetIssueContractAddress); - Assert.assertEquals(beforeAssetIssueDev, afterAssetIssueDev); - - } - - /** - * constructor. - */ - - - @AfterClass - public void shutdown() throws InterruptedException { - - PublicMethed.unFreezeBalance(dev001Address, dev001Key, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(user001Address, user001Key, 1, user001Address, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken054.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken054.java deleted file mode 100644 index 9ad9496fae4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken054.java +++ /dev/null @@ -1,272 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken054 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Trigger transferToken with 0 tokenValue") - public void testTriggerTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - //String contractName = "transferTokenContract"; - - String filePath = "./src/test/resources/soliditycode/contractTrcToken054.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - tokenId = assetAccountId.toStringUtf8(); - tokenValue = 0; - callValue = 5; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info( - "the value: " + PublicMethed.getStrings(infoById.get().getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken055.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken055.java deleted file mode 100644 index 36ce5677f1d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken055.java +++ /dev/null @@ -1,277 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken055 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Trigger TransferToken with long.max tokenId," - + " and 0tokenValue") - public void triggerTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountBefore: " + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken055.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + userEnergyLimitBefore); - logger.info("before trigger, userEnergyUsageBefore is " + userEnergyUsageBefore); - logger.info("before trigger, userBalanceBefore is " + userBalanceBefore); - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - tokenId = Long.toString(Long.MAX_VALUE); - tokenValue = 0; - callValue = 5; - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + userEnergyLimitAfter); - logger.info("after trigger, userEnergyUsageAfter is " + userEnergyUsageAfter); - logger.info("after trigger, userBalanceAfter is " + userBalanceAfter); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info( - "the value: " + PublicMethed.getStrings(infoById.get().getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(infoById.get().getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken060.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken060.java deleted file mode 100644 index 4884706c2bf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken060.java +++ /dev/null @@ -1,232 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken060 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "DeployContract with 0 tokenValue") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken060.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 0; - long callValue = 5; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + devEnergyLimitBefore); - logger.info("before trigger, devEnergyUsageBefore is " + devEnergyUsageBefore); - logger.info("before trigger, devBalanceBefore is " + devBalanceBefore); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - final String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + devEnergyLimitAfter); - logger.info("after trigger, devEnergyUsageAfter is " + devEnergyUsageAfter); - logger.info("after trigger, devBalanceAfter is " + devBalanceAfter); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray())); - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken061.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken061.java deleted file mode 100644 index c13556767f7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken061.java +++ /dev/null @@ -1,218 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken061 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "DeployContract with 0 tokenValue and long.max tokenId") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken061.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = Long.toString(Long.MAX_VALUE); - long tokenValue = 0; - long callValue = 10; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray())); - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken064.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken064.java deleted file mode 100644 index a7bce360148..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken064.java +++ /dev/null @@ -1,450 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken064 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private static ByteString assetAccountUser = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue and " - + "tokenId in exception condition, deploy transfer contract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(user001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, user001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountUser = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getAssetIssuedID(); - logger.info("The assetAccountUser token name: " + tokenName); - logger.info("The assetAccountUser token ID: " + assetAccountUser.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken064.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue and " - + "tokenId in exception condition, deploy receiver contract") - public void test02DeployRevContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - // before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balance is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken064.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - // after deploy, check account resource - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue and " - + "tokenId in exception condition, trigger contract") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - Long callValue = Long.valueOf(0); - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\""; - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValue0IdBigInteger(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getResMessage().toStringUtf8()); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - //Assert.assertEquals("BigInteger out of long range", - infoById.get().getResMessage().toStringUtf8()); - - //transfer to a normal account - param = "\"" + Base58.encode58Check(dev001Address) + "\""; - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValue0IdBigInteger(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - //Assert.assertEquals("BigInteger out of long range", - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - String tokenId = Long.toString(Long.MIN_VALUE); - Long tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(100_0000); - tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(-1); - tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(0); - tokenValue = Long.valueOf(0); - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - callValue = Long.valueOf(0); - - param = "\"" + Base58.encode58Check(resultContractAddress) + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValueMaxLong(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //transfer to a normal account - param = "\"" + Base58.encode58Check(dev001Address) + "\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTestValueMaxLong(address)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter, receiveAssetBefore); - Assert.assertEquals(transferAssetBefore, transferAssetAfter); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken066.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken066.java deleted file mode 100644 index 5fef9eca4ac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken066.java +++ /dev/null @@ -1,333 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken066 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, deploy transferContract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + energyLimit); - logger.info("before energyUsage is " + energyUsage); - logger.info("before balanceBefore is " + balanceBefore); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken066.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + energyLimit); - logger.info("after energyUsage is " + energyUsage); - logger.info("after balanceAfter is " + balanceAfter); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, deploy receive contract") - public void test02DeployRevContract() { - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken066.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, trigger transferContract") - public void test03TriggerContract() { - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Long transferAssetBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = assetAccountId.toStringUtf8(); - Long tokenValue = Long.valueOf(0); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - TransactionInfo transactionInfo = infoById.get(); - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - logger.info("the value: " + retList); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(tokenId, msgId.toString()); - Assert.assertEquals(tokenValue, msgTokenValue); - Assert.assertEquals(callValue, msgCallValue); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, get contract tokenBalance") - public void test04TriggerTokenBalanceContract() { - - - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("the receivercontract token: " + ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray())); - Long assetIssueCount = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - - Assert.assertTrue(assetIssueCount == ByteArray - .toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken067.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken067.java deleted file mode 100644 index 67d9f896944..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken067.java +++ /dev/null @@ -1,339 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken067 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - private byte[] resultContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, deploy transfer contract") - public void test01DeployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 5048_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 4048_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken067.sol"; - String contractName = "transferTokenContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - assetAccountId.toStringUtf8(), 100, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, deploy receive contract") - public void test02DeployRevContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken067.sol"; - String contractName = "Result"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String recieveTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000, assetAccountId.toStringUtf8(), - 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(recieveTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (recieveTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy receive failed with message: " + infoById.get().getResMessage()); - } - - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - resultContractAddress = infoById.get().getContractAddress().toByteArray(); - - SmartContract smartContract = PublicMethed - .getContract(resultContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(100), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(100), contractAssetCount); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, trigger transfer contract") - public void test03TriggerContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long receiveAssetBefore = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("before trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + receiveAssetBefore); - - String tokenId = Long.toString(Long.MAX_VALUE); - Long tokenValue = Long.valueOf(0); - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(resultContractAddress) - + "\",\"" + tokenValue + "\"," + tokenId; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "transferTokenTest(address,uint256,trcToken)", param, false, callValue, - 1000000000L, assetAccountId.toStringUtf8(), 2, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info( - "the value: " + PublicMethed.getStrings(transactionInfo.getLogList().get(0).getData() - .toByteArray())); - - List retList = PublicMethed.getStrings(transactionInfo.getLogList().get(0) - .getData().toByteArray()); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(tokenId, msgId.toString()); - Assert.assertEquals(tokenValue, msgTokenValue); - Assert.assertEquals(callValue, msgCallValue); - - Long transferAssetAfter = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", transferAssetAfter is " + transferAssetAfter); - - Long receiveAssetAfter = PublicMethed.getAssetIssueValue(resultContractAddress, - assetAccountId, blockingStubFull); - logger.info("after trigger, resultContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", receiveAssetAfter is " + receiveAssetAfter); - - Assert.assertEquals(receiveAssetAfter - receiveAssetBefore, - transferAssetBefore + 2L - transferAssetAfter); - } - - @Test(enabled = true, description = "TransferToken with 0 tokenValue, " - + "and not existed tokenId, get tokenBalance") - public void test04TriggerTokenBalanceContract() { - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 1000_000_000L, - 0, 1, user001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String param = "\"" + Base58.encode58Check(resultContractAddress) + "\",\"" - + assetAccountId.toStringUtf8() + "\""; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(triggerTxid, - blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("the receivercontract token: " + ByteArray - .toLong(infoById.get().getContractResult(0).toByteArray())); - Long assetIssueCount = PublicMethed.getAssetIssueValue(resultContractAddress, assetAccountId, - blockingStubFull); - logger.info("the receivercontract token(getaccount): " + assetIssueCount); - Assert.assertTrue(assetIssueCount == ByteArray - .toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken073.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken073.java deleted file mode 100644 index 1d8024559e7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken073.java +++ /dev/null @@ -1,260 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken073 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "TokenBalance with correct tokenValue and tokenId") - public void testTokenBalanceContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 11000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 300000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken073.sol"; - String contractName = "Dest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 5; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long devAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetBefore); - - tokenId = assetAccountId.toStringUtf8(); - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + infoById.get().getLogList().get(0).getTopicsList()); - - Long msgTokenBalance = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(1).toByteArray()); - Long msgId = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(2).toByteArray()); - Long msgTokenValue = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(3).toByteArray()); - - logger.info("msgTokenBalance: " + msgTokenBalance); - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - - Assert.assertEquals(msgTokenBalance, devAssetBefore); - - tokenId = Long.toString(Long.valueOf(assetAccountId.toStringUtf8()) + 1000); - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + infoById.get().getLogList().get(0).getTopicsList()); - - msgTokenBalance = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(1).toByteArray()); - msgId = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(2).toByteArray()); - msgTokenValue = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(3).toByteArray()); - - logger.info("msgTokenBalance: " + msgTokenBalance); - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - - Assert.assertEquals(Long.valueOf(0), msgTokenBalance); - - tokenId = Long.toString(Long.MAX_VALUE); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - logger.info("The msg value: " + infoById.get().getLogList().get(0).getTopicsList()); - - msgTokenBalance = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(1).toByteArray()); - msgId = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(2).toByteArray()); - msgTokenValue = ByteArray - .toLong(infoById.get().getLogList().get(0).getTopicsList().get(3).toByteArray()); - - logger.info("msgTokenBalance: " + msgTokenBalance); - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - - Assert.assertEquals(Long.valueOf(0), msgTokenBalance); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken075.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken075.java deleted file mode 100644 index 849f752489d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken075.java +++ /dev/null @@ -1,268 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken075 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "TokenBalance with exception condition") - public void testTokenBalanceContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 11000_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed - .queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken075.sol"; - String contractName = "Dest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 5; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - Long devAssetBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("before trigger, dev001Address has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + devAssetBefore); - - tokenId = Long.toString(100_0000); - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(0); - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(-1); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - tokenId = Long.toString(Long.MIN_VALUE); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getToken(trcToken)", tokenId, false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenLongMin()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getTokenLongMax()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert.assertEquals(FAILED, infoById.get().getResult()); - //Assert.assertEquals("BigInteger out of long range", - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken076.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken076.java deleted file mode 100644 index 51f7fc1b2db..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken076.java +++ /dev/null @@ -1,138 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken076 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "Origin test ") - public void testDeployTransferTokenContract() { - PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken076.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - - PublicMethed.triggerContract(contractAddress, - "test()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed.triggerContract(contractAddress, - "getResult1()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - logger.info("infoById:" + infoById); - Long returnnumber = ByteArray.toLong(ByteArray.fromHexString(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber == 1); - - txid = PublicMethed.triggerContract(contractAddress, - "getResult2()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - logger.info("-------------------------"); - - logger.info("infoById:" + infoById); - Long returnnumber2 = ByteArray.toLong(ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - - Assert.assertTrue(returnnumber2 == 1); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken077.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken077.java deleted file mode 100644 index f5cfcdab3b6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken077.java +++ /dev/null @@ -1,184 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken077 { - - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] grammarAddress = ecKey1.getAddress(); - String testKeyForGrammarAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForGrammarAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = false) - public void testAddress001() { - PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken077.sol"; - String contractName = "trcToken077"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - Optional deployInfo = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - contractAddress = deployInfo.get().getContractAddress().toByteArray(); - logger.info("Deploy energy is " + deployInfo.get().getReceipt().getEnergyUsageTotal()); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "addressTest()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - logger.info("Trigger energy is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - } - - @Test(enabled = true, description = "The value of address is not at the beginning of 41") - public void testAddress002() { - PublicMethed - .sendcoin(grammarAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String contractName = "trcToken077"; - - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600" - + "080fd5b5060b0806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080" - + "fd5b50d28015602757600080fd5b5060043610605c577c01000000000000000000000000000000000000000" - + "0000000000000000060003504636241c1d881146061575b600080fd5b60676079565b604080519182525190" - + "81900360200190f35b60405130908190529056fea165627a7a723058207b9b52e71420f2fa4cb55ffd55641" - + "355ec84e09d6d4545c629dde7cc01d74a100029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"addressTest\",\"outputs\":[{\"name" - + "\":\"addressValue\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonp" - + "ayable\",\"type\":\"function\"}]"; - - String deploytxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testKeyForGrammarAddress, - grammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional deployById = PublicMethed - .getTransactionInfoById(deploytxid, blockingStubFull); - contractAddress = deployById.get().getContractAddress().toByteArray(); - logger.info("infoById:" + deployById); - - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "addressTest()", "#", false, - 0, maxFeeLimit, grammarAddress, testKeyForGrammarAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - - Assert.assertNotNull(infoById); - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - Assert.assertEquals(exceptedResult, ByteArray.toHexString(contractAddress)); - - } - - - /** - * constructor. - */ - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(grammarAddress, testKeyForGrammarAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken078.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken078.java deleted file mode 100644 index 84ace997b17..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken078.java +++ /dev/null @@ -1,275 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class ContractTrcToken078 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] internalTxsAddress = ecKey1.getAddress(); - String testKeyForinternalTxsAddress = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String priKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - /** - * constructor. - */ - - public static String byte2HexStr(byte[] b, int offset, int length) { - String stmp = ""; - StringBuilder sb = new StringBuilder(""); - for (int n = offset; n < offset + length && n < b.length; n++) { - stmp = Integer.toHexString(b[n] & 0xFF); - sb.append((stmp.length() == 1) ? "0" + stmp : stmp); - } - return sb.toString().toUpperCase().trim(); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKeyForinternalTxsAddress); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - } - - @Test(enabled = true, description = "Origin test call") - public void testOriginCall001() { - PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - contractAddress = infoById.get().getContractAddress().toByteArray(); - - String filePath1 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName1 = "calledContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName1); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - byte[] contractAddress1; - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - - String filePath2 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName2 = "c"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - byte[] contractAddress2 = infoById.get().getContractAddress().toByteArray(); - logger.info("infoById : " + infoById); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - - String txid2 = ""; - txid2 = PublicMethed.triggerContract(contractAddress, - "sendToB2(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - logger.info("Trigger InfobyId: " + infoById2); - Account info1 = PublicMethed.queryAccount(internalTxsAddress, blockingStubFull); - AccountResourceMessage resourceInfo1 = PublicMethed.getAccountResource(internalTxsAddress, - blockingStubFull); - logger.info("getEnergyUsed " + resourceInfo1.getEnergyUsed()); - logger.info("getEnergyLimit " + resourceInfo1.getEnergyLimit()); - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - - } - - @Test(enabled = true, description = "Origin test delegatecall") - public void testOriginDelegatecall001() { - PublicMethed - .sendcoin(internalTxsAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - contractAddress = infoById.get().getContractAddress().toByteArray(); - - String filePath1 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName1 = "calledContract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath1, contractName1); - - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName1, abi1, code1, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - byte[] contractAddress1; - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - - String filePath2 = "./src/test/resources/soliditycode/contractTrcToken078.sol"; - String contractName2 = "c"; - HashMap retMap2 = PublicMethed.getBycodeAbi(filePath2, contractName2); - - String code2 = retMap2.get("byteCode").toString(); - String abi2 = retMap2.get("abI").toString(); - txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName2, abi2, code2, "", maxFeeLimit, - 1000000L, 100, null, testKeyForinternalTxsAddress, - internalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById : " + infoById); - byte[] contractAddress2 = infoById.get().getContractAddress().toByteArray(); - - String initParmes = "\"" + Base58.encode58Check(contractAddress1) - + "\",\"" + Base58.encode58Check(contractAddress2) + "\""; - - String txid2 = ""; - txid2 = PublicMethed.triggerContract(contractAddress, - "sendToB(address,address)", initParmes, false, - 0, maxFeeLimit, internalTxsAddress, testKeyForinternalTxsAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid2, blockingStubFull); - logger.info("infoById : " + infoById2); - - Assert.assertTrue(infoById2.get().getResultValue() == 0); - - - } - - private List getStrings(byte[] data) { - int index = 0; - List ret = new ArrayList<>(); - while (index < data.length) { - ret.add(byte2HexStr(data, index, 32)); - index += 32; - } - return ret; - } - - /** - * constructor. - */ - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(internalTxsAddress, testKeyForinternalTxsAddress, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken079.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken079.java deleted file mode 100644 index 46c5948b69b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken079.java +++ /dev/null @@ -1,220 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken079 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Trigger transferToken with 0 tokenValue and tokenId") - public void triggerTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 70000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken079.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 200; - long callValue = 0; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, callValue, 0, 10000, - tokenId, tokenValue, null, dev001Key, - dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(200), Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(200), contractAssetCount); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.transferAsset(user001Address, - assetAccountId.toByteArray(), 10L, dev001Address, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - PublicMethed - .sendcoin(transferTokenContractAddress, 5000000, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - tokenId = Long.toString(0); - tokenValue = 0; - callValue = 5; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "msgTokenValueAndTokenIdTest()", "#", false, callValue, - 1000000000L, tokenId, tokenValue, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (triggerTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - logger.info("the value: " + retList); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, user001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken080.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken080.java deleted file mode 100644 index c77fd323690..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken080.java +++ /dev/null @@ -1,195 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTrcToken080 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "DeployContract with 0 tokenValue and tokenId") - public void deployTransferTokenContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(dev001Address, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, 100000L, - 1L, 1L, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - Long devAssetCountBefore = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken080.sol"; - String contractName = "tokenTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 100; - long callValue = 10; - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, - null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (transferTokenTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(transferTokenContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long devAssetCountAfter = PublicMethed.getAssetIssueValue(dev001Address, - assetAccountId, blockingStubFull); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Long contractAssetCount = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), - Long.valueOf(devAssetCountBefore - devAssetCountAfter)); - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - // get and verify the msg.value and msg.id - Long transferAssetBefore = PublicMethed.getAssetIssueValue(transferTokenContractAddress, - assetAccountId, blockingStubFull); - logger.info("before trigger, transferTokenContractAddress has AssetId " - + assetAccountId.toStringUtf8() + ", Count is " + transferAssetBefore); - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "getResultInCon()", "#", false, 0, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - List retList = PublicMethed.getStrings(infoById.get() - .getContractResult(0).toByteArray()); - logger.info("The msg value: " + retList); - - Long msgId = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Long msgTokenValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - Long msgCallValue = ByteArray.toLong(ByteArray.fromHexString(retList.get(2))); - - logger.info("msgId: " + msgId); - logger.info("msgTokenValue: " + msgTokenValue); - logger.info("msgCallValue: " + msgCallValue); - - Assert.assertEquals(msgId.toString(), tokenId); - Assert.assertEquals(Long.valueOf(msgTokenValue), Long.valueOf(tokenValue)); - Assert.assertEquals(Long.valueOf(msgCallValue), Long.valueOf(callValue)); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken081.java b/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken081.java deleted file mode 100644 index 8312b886b10..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/trctoken/ContractTrcToken081.java +++ /dev/null @@ -1,239 +0,0 @@ -package stest.tron.wallet.dailybuild.trctoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class ContractTrcToken081 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] tokenReceiver = null; - private byte[] tokenSender = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "./src/test/resources/soliditycode/contractTrcToken081.sol"; - String contractName = "TokenReceiver"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - - tokenReceiver = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, dev001Key, dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed - .getContract(tokenReceiver, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - - contractName = "TokenSender"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - tokenSender = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, 10000L, assetAccountId.toStringUtf8(), - 10L, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(tokenSender, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long contractAssetCount = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId before: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Long devAssetCountAfterDeploy = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after deploy tokenSender AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfter: " + devAssetCountAfterDeploy); - Assert.assertTrue(10 == devAssetCountBefore - devAssetCountAfterDeploy); - Assert.assertTrue(10 == contractAssetCount); - - } - - - @Test(enabled = true, description = "transfer 1 trc10 to contract by assembly") - public void transferTokenToContract() { - Long senderAssetCountBefore = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("before trigger tokenSender has AssetId before: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountBefore); - - Long receiverAssetCountBefore = PublicMethed - .getAssetIssueValue(tokenReceiver, assetAccountId, blockingStubFull); - logger.info("before trigger tokenReceiver AssetId: " + assetAccountId.toStringUtf8() - + ", Count: " + receiverAssetCountBefore); - String args = "\"" + Base58.encode58Check(tokenReceiver) + "\""; - logger.info("args: " + args); - String triggerTxid = PublicMethed - .triggerContract(tokenSender, "sendTRC10(address)", args, false, 0, 1000000000L, - assetAccountId.toStringUtf8(), 0, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = - PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - Long senderAssetCountAfter = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId After trigger: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountAfter); - - Long receiverAssetCountAfterTrigger = PublicMethed - .getAssetIssueValue(tokenReceiver, assetAccountId, blockingStubFull); - logger.info("after trigger AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + receiverAssetCountAfterTrigger); - Assert.assertTrue(1 == senderAssetCountBefore - senderAssetCountAfter); - Assert.assertTrue(1 == receiverAssetCountAfterTrigger - receiverAssetCountBefore); - - } - - @Test(enabled = true, description = "transfer 1 trc10 to normal address by assembly") - public void transferTokenToNormalAddress() { - long senderAssetCountBefore = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId After trigger: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountBefore); - - long devAssetCountBeforeTrigger = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after trigger AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfterTrigger: " + devAssetCountBeforeTrigger); - - String args = "\"" + Base58.encode58Check(dev001Address) + "\""; - logger.info("args: " + args); - String triggerTxid = PublicMethed - .triggerContract(tokenSender, "sendTRC10(address)", args, false, 0, 1000000000L, - assetAccountId.toStringUtf8(), 0, dev001Address, dev001Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = - PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - long senderAssetCountAfter = PublicMethed - .getAssetIssueValue(tokenSender, assetAccountId, blockingStubFull); - logger.info("tokenSender has AssetId After trigger: " + assetAccountId.toStringUtf8() - + ", Count: " + senderAssetCountAfter); - - long devAssetCountAfterTrigger = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - logger.info("after trigger AssetId: " + assetAccountId.toStringUtf8() - + ", devAssetCountAfterTrigger: " + devAssetCountAfterTrigger); - Assert.assertTrue(1 == senderAssetCountBefore - senderAssetCountAfter); - Assert.assertTrue(1 == devAssetCountAfterTrigger - devAssetCountBeforeTrigger); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck001.java deleted file mode 100644 index 814c9e38bd2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck001.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.addressStrictCheck; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class AddressStrictCheck001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Open experimental check address ") - public void test01CheckAddressNew() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/addressCheckNew.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "00000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - - num = "10000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("AAAAA:" + transactionExtention.toString()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck002.java deleted file mode 100644 index e64b30b47f1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/addressStrictCheck/AddressStrictCheck002.java +++ /dev/null @@ -1,142 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.addressStrictCheck; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class AddressStrictCheck002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Close experimental check address") - public void test01AddressOld() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/addressCheckOld.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String txid = ""; - String num = "00000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - logger.info(infoById.toString()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - - num = "10000000000000000000004108362A6DB594586C035758ECA382A49FDF13EF61"; - txid = PublicMethed.triggerContract(contractAddress, - "checkAddress(address)", num, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, infoById.get().getResultValue()); - logger.info(infoById.toString()); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "checkAddress2(address)", num, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract001.java deleted file mode 100644 index f1b846be342..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract001.java +++ /dev/null @@ -1,368 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 16 signatures test pure multivalidatesign") - public void test01Correct16signatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertEquals( - "class org.tron.core.vm.program.Program$OutOfTimeException " - + ": CPU timeout for 'ISZERO' operation executing", - transactionExtention.getResult().getMessage().toStringUtf8()); - } else { - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "14 signatures with 1st incorrect signatures test" - + " pure multivalidatesign") - public void test02Incorrect1stSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01111111111111000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "13 signatures with 1st incorrect address test" - + " pure multivalidatesign") - public void test03Incorrect1stAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 13; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01111111111110000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with 15th incorrect signatures" - + " test pure multivalidatesign") - public void test04Incorrect15thSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 14) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh123770807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111111111111010000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "15 signatures with 10th-15th incorrect address" - + " test pure multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 15; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 9; i < 14; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111111100000100000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with 2nd/16th incorrect signatures" - + " test pure multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 15) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("10111111111111100000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with 6th/9th/11th/13nd incorrect address" - + " test pure multivalidatesign") - public void test07IncorrectAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(5, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(12, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111011010101110000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures with Incorrect hash" - + " test pure multivalidatesign") - public void test08IncorrectHash() { - String txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract002.java deleted file mode 100644 index c0bb3e908a4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract002.java +++ /dev/null @@ -1,675 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 16 signatures test multivalidatesign") - public void test01Correct16signatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "14 signatures with 1st incorrect signatures" - + " test multivalidatesign") - public void test02Incorrect1stSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111111111000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "13 signatures with 1st incorrect address" - + " test multivalidatesign") - public void test03Incorrect1stAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 13; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111111110000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with 15th incorrect signatures" - + " test multivalidatesign") - public void test04Incorrect15thSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 14) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh123770807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("11111111111111010000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "15 signatures with 10th-15th incorrect address" - + " test multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 15; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 9; i < 14; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111111100000100000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with 2nd、16th incorrect signatures" - + " test multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 15) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("10111111111111100000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with 6th/9th/11th/13nd incorrect address" - + " test multivalidatesign") - public void test07IncorrectAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(5, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(12, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111011010101110000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with Incorrect hash test multivalidatesign") - public void test08IncorrectHash() { - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract003.java deleted file mode 100644 index 4c1d12e6569..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract003.java +++ /dev/null @@ -1,302 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "13 signatures and 12 address test pure multivalidatesign") - public void test01With25SignaturesAnd24Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 12; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "7 signatures and 8 address test pure multivalidatesign") - public void test02With15SignaturesAnd16Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 7; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "150 signatures and 1 address test pure multivalidatesign") - public void test03With150SignaturesAnd1Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 150; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "1 signatures and 160 address test pure multivalidatesign") - public void test04With1SignaturesAnd160Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 160; i++) { - ECKey key = new ECKey(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "16 signatures and 17 address test pure multivalidatesign") - public void test05With32SignaturesAnd33Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "17 signatures and 16 address test pure multivalidatesign") - public void test06With33SignaturesAnd32Address() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - private String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract004.java deleted file mode 100644 index f1a3eafa181..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract004.java +++ /dev/null @@ -1,534 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "10 signatures and 9 address test multivalidatesign") - public void test01With25SignaturesAnd24Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 9; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "14 signatures and 15 address test multivalidatesign") - public void test02With15SignaturesAnd16Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "40 signatures and 1 address test multivalidatesign") - public void test03With40SignaturesAnd1Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 40; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "1 signatures and 50 address test multivalidatesign") - public void test04With1SignaturesAnd50Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 50; i++) { - ECKey key = new ECKey(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures and 17 address test multivalidatesign") - public void test05With32SignaturesAnd33Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.add(StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "17 signatures and 16 address test multivalidatesign") - public void test06With33SignaturesAnd32Address() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.add(Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - private String parametersString(List parameters) { - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - return input; - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract005.java deleted file mode 100644 index 5277eb725f4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract005.java +++ /dev/null @@ -1,233 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class batchValidateSignContract005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Hash is empty test multivalidatesign") - public void test01HashIsEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "Address is empty test multivalidatesign") - public void test02AddressIsEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "Signatures is empty test multivalidatesign") - public void test03SignaturesIsEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "Signatures and addresses are empty test multivalidatesign") - public void test04SignaturesAndAddressesAreEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "All empty test multivalidatesign") - public void test05AllEmpty() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract006.java deleted file mode 100644 index bbc541830c7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract006.java +++ /dev/null @@ -1,426 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j - -public class batchValidateSignContract006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Hash is empty test multivalidatesign") - public void test01HashIsEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Address is empty test multivalidatesign") - public void test02AddressIsEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Signatures is empty test multivalidatesign") - public void test03SignaturesIsEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Signatures and addresses are empty test multivalidatesign") - public void test04SignaturesAndAddressesAreEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "All empty test multivalidatesign") - public void test05AllEmpty() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - List parameters = Arrays.asList("0x" + "", signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContract(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract007.java deleted file mode 100644 index b252c7170f6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract007.java +++ /dev/null @@ -1,196 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Constructor test multivalidatesign") - public void test01Constructor() { - String txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 2000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "src/test/resources/soliditycode/batchvalidatesign007.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String data = PublicMethed.parametersString(parameters); - String constructorStr = "constructor(bytes32,bytes[],address[])"; - txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Long fee1 = infoById.get().getFee(); - Long netUsed1 = infoById.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - contractAddress = infoById.get().getContractAddress().toByteArray(); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testConstructorPure()", "", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - - txid = PublicMethed - .triggerContract(contractAddress, "testConstructor()", "", false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById2.get().getResultValue() == 0) { - Assert.assertEquals("11111111111111110000000000000000", - PublicMethed.bytes32ToString(infoById2.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById2.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById2.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee2 = infoById2.get().getFee(); - Long netUsed2 = infoById2.get().getReceipt().getNetUsage(); - Long energyUsed2 = infoById2.get().getReceipt().getEnergyUsage(); - Long netFee2 = infoById2.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById2.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee2:" + fee2); - logger.info("netUsed2:" + netUsed2); - logger.info("energyUsed2:" + energyUsed2); - logger.info("netFee2:" + netFee2); - logger.info("energyUsageTotal2:" + energyUsageTotal2); - - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee1 + fee2 == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed1 + energyUsed2 >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed1 + netUsed2 >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed1 + netUsed2 >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract008.java deleted file mode 100644 index 9f9b8b30512..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract008.java +++ /dev/null @@ -1,146 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract008 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Incorrect address hex test pure multivalidatesign") - public void test01IncorrectAddressHex() { - String input = "7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e00000000000000" - + "000000000000000000000000000000000000000000000000600000000000000000000000000000000000000" - + "0000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000" - + "000200000000000000000000000000000000000000000000000000000000000000400000000000000000000" - + "0000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000" - + "0000000000000000000041ad7ca8100cf0ce028b83ac719c8458655a6605317abfd071b91f5cc14d53e87a2" - + "99fe0cdf6a8567074e9be3944affba33b1e15d14b7cb9003ec2c87cb1a56405000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000417ce31e565fb99451f87db65e75f46672e8a8f7b29e6589e60fd11e076550d0a66d0b05" - + "e4b4d7d40bd34140f13dc3632d3ce0f25e4cf75840238b6fe2346c94fa01000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000020000000000000000000000410d6b1de9e84c1d7a9a5b43d93dbe4a5aae79b18900000000000" - + "00000000000123456"; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, true, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - Assert.assertEquals("", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("REVERT opcode executed", - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "Empty address and signatures hex" - + " test pure multivalidatesign") - public void test02EmptyAddressAndSignaturesHex() { - String input = "da586d881362c0c38eb31b556ce0f7c2837a3ebb60080e8e665a6b92c7541837b95064ba000000" - + "000000000000000000000000000000000000000000000000000000006000000000000000000000000000000" - + "000000000000000000000000000000001200000000000000000000000000000000000000000000000000000" - + "000000000001000000000000000000000000000000000000000000000000000000000000002000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000001000000000000000000000000000000000000000" - + "0000000000000000000000000"; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, true, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - Assert.assertEquals("", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("REVERT opcode executed", - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract009.java deleted file mode 100644 index fb9a8325914..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract009.java +++ /dev/null @@ -1,225 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract009 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Incorrect address hex test multivalidatesign") - public void test02IncorrectAddressHex() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String input = "7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e00000000000000" - + "000000000000000000000000000000000000000000000000600000000000000000000000000000000000000" - + "0000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000" - + "000200000000000000000000000000000000000000000000000000000000000000400000000000000000000" - + "0000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000" - + "0000000000000000000041ad7ca8100cf0ce028b83ac719c8458655a6605317abfd071b91f5cc14d53e87a2" - + "99fe0cdf6a8567074e9be3944affba33b1e15d14b7cb9003ec2c87cb1a56405000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000417ce31e565fb99451f87db65e75f46672e8a8f7b29e6589e60fd11e076550d0a66d0b05" - + "e4b4d7d40bd34140f13dc3632d3ce0f25e4cf75840238b6fe2346c94fa01000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "0000000000020000000000000000000000410d6b1de9e84c1d7a9a5b43d93dbe4a5aae79b18900000000000" - + "00000000000123456"; - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, true, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertTrue( - infoById.get().getResMessage().toStringUtf8().contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Empty address and signatures hex test multivalidatesign") - public void test03EmptyAddressAndSignaturesHex() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String input = "da586d881362c0c38eb31b556ce0f7c2837a3ebb60080e8e665a6b92c7541837b95064ba000000" - + "000000000000000000000000000000000000000000000000000000006000000000000000000000000000000" - + "000000000000000000000000000000001200000000000000000000000000000000000000000000000000000" - + "000000000001000000000000000000000000000000000000000000000000000000000000002000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000001000000000000000000000000000000000000000" - + "0000000000000000000000000"; - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, true, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertTrue( - infoById.get().getResMessage().toStringUtf8().contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract010.java deleted file mode 100644 index 663be1160c7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract010.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract010 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 50 signatures test multivalidatesign") - public void test01Correct50Signatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 50; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "2 signatures with 1st incorrect signatures" - + " test multivalidatesign") - public void test02Incorrect1stSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 2; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "3 signatures with 1st incorrect address" - + " test multivalidatesign") - public void test03Incorrect1stAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 3; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("01100000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "9 signatures with 7th incorrect signatures" - + " test multivalidatesign") - public void test04Incorrect15thSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 9; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(6, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("11111101100000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "5 signatures with 2th-4th incorrect address" - + " test multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 5; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 1; i < 4; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("10001000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "150 signatures with 2nd/32nd incorrect signatures" - + " test multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 150; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 31) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "88 signatures with 9th/11th/28th/32nd incorrect address" - + " test multivalidatesign") - public void test07IncorrectAddress() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 88; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(27, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(31, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - @Test(enabled = true, description = "105 signatures with Incorrect hash test multivalidatesign") - public void test08IncorrectHash() { - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 105; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPure(bytes32,bytes[],address[])", - input, false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - if (transactionExtention.getResult().getCode().toString().equals("CONTRACT_EXE_ERROR")) { - Assert.assertTrue(transactionExtention.getResult().getMessage().toStringUtf8().contains( - "class org.tron.core.vm.program.Program$OutOfTimeException : CPU timeout for")); - } else { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract011.java deleted file mode 100644 index 1697784e7e3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract011.java +++ /dev/null @@ -1,695 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract011 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String txid = ""; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign001.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Correct 17 signatures test multivalidatesign") - public void test01Correct33Signatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 17; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "14 signatures with 1st incorrect signatures" - + " test multivalidatesign") - public void test02Incorrect1stSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 14; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111111111000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "8 signatures with 1st incorrect address" - + " test multivalidatesign") - public void test03Incorrect1stAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 8; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(0, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("01111111000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "6 signatures with 3th incorrect signatures" - + " test multivalidatesign") - public void test04Incorrect15thSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 6; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(2, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11011100000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "11 signatures with 7th-9th incorrect address" - + " test multivalidatesign") - public void test05Incorrect15thTo30thAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 11; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - for (int i = 6; i < 9; i++) { - addresses.set(i, StringUtil.encode58Check(new ECKey().getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("11111100011000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "40 signatures with 2nd、32nd incorrect signatures" - + " test multivalidatesign") - public void test06Incorrect2ndAnd32ndIncorrectSignatures() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 40; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - if (i == 1 || i == 31) { - signatures.add( - Hex.toHexString(key.sign("dgjjsldgjljvjjfdshkh1hgsk0807779".getBytes()).toByteArray())); - } else { - signatures.add(Hex.toHexString(sign)); - } - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "44 signatures with 9th/11th/28th/32nd incorrect address" - + " test multivalidatesign") - public void test07IncorrectAddress() { - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 44; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - addresses.set(8, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(10, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(27, StringUtil.encode58Check(new ECKey().getAddress())); - addresses.set(31, StringUtil.encode58Check(new ECKey().getAddress())); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "16 signatures with Incorrect hash test multivalidatesign") - public void test08IncorrectHash() { - String incorrecttxid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays - .asList("0x" + Hex.toHexString(Hash.sha3(incorrecttxid.getBytes())), signatures, addresses); - String input = PublicMethed.parametersString(parameters); - txid = PublicMethed - .triggerContractBoth(contractAddress, "testArray(bytes32,bytes[],address[])", input, false, - 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - if (infoById.get().getResultValue() == 0) { - Assert.assertEquals("00000000000000000000000000000000", - PublicMethed.bytes32ToString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - } else { - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8().contains("CPU timeout for") - || "Already Time Out".equals(infoById.get().getResMessage().toStringUtf8())); - Assert.assertTrue(afterBalance == 0); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract012.java deleted file mode 100644 index c35abd39f78..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/batchValidateSignContract/batchValidateSignContract012.java +++ /dev/null @@ -1,172 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.batchValidateSignContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class batchValidateSignContract012 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/batchvalidatesign005.sol"; - String contractName = "Demo"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger precompile multivalisign function with correct data") - public void test01TriggerPrecompileMultivalisignWithCorrectData() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String argsStr = PublicMethed.parametersString(parameters); - - String input = AbiUtil.parseParameters("batchvalidatesign(bytes32,bytes[],address[])", argsStr); - String method = "testArray2(bytes)"; - txid = PublicMethed.triggerContractBoth(contractAddress, method, - AbiUtil.parseParameters(method, Arrays.asList(input)), true, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - PublicMethed.getTransactionById(txid, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - logger.info( - "infoById:" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .equals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0101010101010101010101010101010100000000000000000000000000000000")); - } - - @Test(enabled = true, description = "Trigger precompile multivalidatesign function with incor" - + "rect data") - public void test02TriggerPrecompileMultivalisignWithIncorrectData() { - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = Hash.sha3(txid.getBytes()); - for (int i = 0; i < 16; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - byte[] sign = new ECKey().sign(Hash.sha3("sdifhsdfihyw888w7".getBytes())).toByteArray(); - signatures.set(0, Hex.toHexString(sign)); - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String argsStr = PublicMethed.parametersString(parameters); - - String input = AbiUtil.parseParameters("batchvalidatesign(bytes32,bytes[],address[])", argsStr); - String method = "testArray2(bytes)"; - txid = PublicMethed.triggerContractBoth(contractAddress, method, - AbiUtil.parseParameters(method, Arrays.asList(input)), true, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull, blockingStubFull1); - PublicMethed.getTransactionById(txid, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - logger.info( - "infoById:" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .equals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0001010101010101010101010101010100000000000000000000000000000000")); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi001.java deleted file mode 100644 index aeb7f5d6e85..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi001.java +++ /dev/null @@ -1,301 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress1, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Clear a contract created by other account") - public void testClearAbi001() { - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractAddress, contractExcAddress1, contractExcKey1, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("is not the owner of the contract")); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - @Test(enabled = true, description = "Clear a contract with ABI created by itself") - public void testClearAbi002() { - - String contractName = "testConstantContract"; - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - String txid1 = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - } - - - @Test(enabled = true, description = "Clear a contract without ABI") - public void testClearAbi003() { - - String contractName = "testConstantContract"; - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - @Test(enabled = true, description = "Clear a account address") - public void testClearAbi004() { - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - } - - - @Test(enabled = true, description = "Clear a uninitialized account") - public void testClearAbi005() { - - ECKey ecKeyN = new ECKey(Utils.getRandom()); - byte[] contractExcAddressN = ecKeyN.getAddress(); - String contractExcKeyN = ByteArray.toHexString(ecKeyN.getPrivKeyBytes()); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddressN, contractExcAddress, contractExcKey, - blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - } - - @Test(enabled = true, description = "Clear a not meet the rules address") - public void testClearAbi006() { - byte[] fakeAddress = "412B5D".getBytes(); - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(fakeAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - byte[] fakeAddress1 = "412B5D3405B2D26767C9C09886D53DEAFF6EB718AC111".getBytes(); - - TransactionExtention transactionExtention1 = PublicMethed - .clearContractAbiForExtention(fakeAddress1, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention1.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention1.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - PublicMethed.freedResource(contractExcAddress1, contractExcKey1, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi002.java deleted file mode 100644 index b949713f0ab..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi002.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract with ABI created by itself") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi003.java deleted file mode 100644 index 3daf89fc406..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi003.java +++ /dev/null @@ -1,148 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract without ABI") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi004.java deleted file mode 100644 index efa7f20f6d8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi004.java +++ /dev/null @@ -1,115 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a account address") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi005.java deleted file mode 100644 index 0af7a1bf2f1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi005.java +++ /dev/null @@ -1,197 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract created by create2 (without ABI)") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi005.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(returnAddressBytes, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("is not the owner of the contract")); - - smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - } - - - /** - * testClearAbitestClearAbi constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi006.java deleted file mode 100644 index 25e85fe9e73..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi006.java +++ /dev/null @@ -1,114 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a uninitialized account") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(contractExcAddress1, contractExcAddress, contractExcKey, - blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi007.java deleted file mode 100644 index 02bf0babc42..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi007.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a not meet the rules address") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - byte[] fakeAddress = "412B5D".getBytes(); - TransactionExtention transactionExtention = PublicMethed - .clearContractAbiForExtention(fakeAddress, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - byte[] fakeAddress1 = "412B5D3405B2D26767C9C09886D53DEAFF6EB718AC111".getBytes(); - - TransactionExtention transactionExtention1 = PublicMethed - .clearContractAbiForExtention(fakeAddress1, contractExcAddress, contractExcKey, - blockingStubFull); - Assert - .assertThat(transactionExtention1.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention1.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : Contract not exists")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi008.java deleted file mode 100644 index c12802bab0a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/ClearAbi008.java +++ /dev/null @@ -1,162 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ClearAbi008 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Clear a contract with ABI created by itself," - + "clear a contract by itself again") - public void testClearAbi() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - String txid1 = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(infoById1.get().getResultValue() == 0); - - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/NoAbi009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/NoAbi009.java deleted file mode 100644 index fc6e57905ae..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/clearabi/NoAbi009.java +++ /dev/null @@ -1,356 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.clearabi; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContractDataWrapper; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class NoAbi009 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress1 = ecKey2.getAddress(); - String contractExcKey1 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress1, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "clearabi contract with event") - public void testNoAbi001() { - String filePath = "src/test/resources/soliditycode/NoAbi001.sol"; - String contractName = "testNoABiContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - // getcontract - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - System.out.println("smartContract:" + smartContract.toString()); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - // getcontractinfo - SmartContractDataWrapper contractInfo = PublicMethed - .getContractInfo(contractAddress, blockingStubFull); - System.out.println("contractInfo.toString():" + contractInfo.toString()); - Assert.assertTrue(contractInfo.getSmartContract().getAbi().toString().isEmpty()); - Assert.assertTrue(contractInfo.getSmartContract().getName().equalsIgnoreCase(contractName)); - Assert.assertTrue(contractInfo.getRuntimecode().size() > 0); - Assert.assertFalse(contractInfo.getSmartContract().getBytecode().toString().isEmpty()); - - // triggerconstantcontract fullnode - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testTrigger()", "#", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(3, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // triggercontract - txid = PublicMethed - .triggerContract(contractAddress, "testTrigger()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Long returnNumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(3 == returnNumber); - List retList = PublicMethed - .getStrings(infoById.get().getLogList().get(0).getData().toByteArray()); - logger.info("retList:" + retList.toString()); - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(1)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - Assert.assertEquals(WalletClient.encode58Check(contractExcAddress),addressFinal); - Long actualNum = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Assert.assertEquals(returnNumber,actualNum); - - // triggerconstantcontract solidity - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(contractAddress, "testTrigger()", "#", - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(4, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "create2 contract with event") - public void testNoAbi002() { - String filePath = "./src/test/resources/soliditycode/NoAbi002.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, contractExcKey1, - contractExcAddress1, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - byte[] factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - contractName = "testNoABiContract"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String testNoABiContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - String param = "\"" + testNoABiContractCode + "\"," + salt; - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, Long.valueOf(0), - 1000000000L, "0", 0, contractExcAddress1, contractExcKey1, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - byte[] testNoABiContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - // getcontract - smartContract = PublicMethed.getContract(testNoABiContractAddress, blockingStubFull); - System.out.println("smartContract:" + smartContract.toString()); - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - // Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - // getcontractinfo - SmartContractDataWrapper contractInfo = PublicMethed - .getContractInfo(testNoABiContractAddress, blockingStubFull); - System.out.println("contractInfo.toString():" + contractInfo.toString()); - Assert.assertTrue(contractInfo.getSmartContract().getAbi().toString().isEmpty()); - // Assert.assertTrue(contractInfo.getSmartContract().getName().equalsIgnoreCase(contractName)); - Assert.assertTrue(contractInfo.getRuntimecode().size() > 0); - Assert.assertFalse(contractInfo.getSmartContract().getBytecode().toString().isEmpty()); - - // triggerconstantcontract fullnode - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(testNoABiContractAddress, "plusOne()", "#", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(1, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // triggercontract - String txid = PublicMethed - .triggerContract(testNoABiContractAddress, "plusOne()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Long returnNumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnNumber); - retList = PublicMethed - .getStrings(infoById.get().getLogList().get(0).getData().toByteArray()); - logger.info("retList:" + retList.toString()); - tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(1)), 12, tmpAddress, 0, 20); - addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - Assert.assertEquals(WalletClient.encode58Check(contractExcAddress),addressFinal); - Long actualNum = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - Assert.assertEquals(returnNumber,actualNum); - - // triggerconstantcontract solidity - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(testNoABiContractAddress, "plusOne()", "#", - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - logger.info("Code = " + transactionExtention.getResult().getCode()); - logger.info("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals(2, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - PublicMethed.freedResource(contractExcAddress1, contractExcKey1, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test001.java deleted file mode 100644 index ce88b68644b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test001.java +++ /dev/null @@ -1,558 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] factoryContractAddress = null; - private byte[] factoryContractAddress2 = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract generated by new solidity") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 command with test bytecode using factory. ") - public void test02TriggerCreate2ToDeployTestContract() { - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // different contract address with different bytecode, same salt and address - Assert.assertNotEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(testContractAddress)); - } - - @Test(enabled = true, description = "Trigger create2 command with factory bytecode") - public void test02TriggerCreate2ToDeployFactory2Contract() { - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - factoryContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed - .getContract(factoryContractAddress2, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 command with test bytecode using factory2") - public void test03TriggerCreate2ToDeployTestContract2() { - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress2, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - // Istanbul change create2 algorithm - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = true, description = "Trigger create2 command without meta data hash in bytecode") - public void test04TriggerCreate2ToDeployTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - String msgSender = Base58.encode58Check(ByteArray.fromHexString(retList.get(2))); - Assert.assertNotEquals(msgSender, Base58.encode58Check(user001Address)); - } - - @Test(enabled = true, description = "Trigger create2 command with 0 extended bytecode") - public void test05TriggerCreate2ToDeployTestContract() { - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe0000000000000000000000000000000000000000000000000000000000000000000000"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - } - - @Test(enabled = true, description = "Trigger Test contact") - public void test04TriggerTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test002.java deleted file mode 100644 index a708e96c3aa..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test002.java +++ /dev/null @@ -1,324 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - //PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 command without meta data hash in bytecode") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - String msgSender = Base58.encode58Check(ByteArray.fromHexString(retList.get(2))); - Assert.assertNotEquals(msgSender, Base58.encode58Check(user001Address)); - } - - - @Test(enabled = false, description = "Trigger Test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test003.java deleted file mode 100644 index bc536e7caf4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test003.java +++ /dev/null @@ -1,489 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 command with invalid bytecode") - public void test02TriggerCreate2WithInvalidBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f5fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fea165627a7a72305820f3e3c0646a8c8d521fe819f10a592327469f611f0d9e8206697f7f" - + "3436ff3c7d0029"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with empty bytecode") - public void test03TriggerCreate2WithEmptyBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = ""; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with \"6080\" bytecode") - public void test04TriggerCreate2WithShortBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "6080"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with \"00000000000\" bytecode") - public void test05TriggerCreate2WithZeroBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "000000000000000000000000000000"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - @Test(enabled = true, description = "Trigger create2 command with NULL bytecode") - public void test06TriggerCreate2WithNullBytecode() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = null; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - boolean ret = false; - - try { - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - } catch (org.bouncycastle.util.encoders.DecoderException e) { - logger.info("Expected org.bouncycastle.util.encoders.DecoderException!"); - ret = true; - } - Assert.assertTrue(ret); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test004.java deleted file mode 100644 index 17e87b7d289..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test004.java +++ /dev/null @@ -1,470 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] factoryContractAddress2 = null; - private byte[] testContractAddress = null; - private byte[] testContractAddress2 = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore));*/ - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 command with factory bytecode") - public void test02TriggerCreate2ToDeployFactory2Contract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 150000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore));*/ - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - factoryContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed - .getContract(factoryContractAddress2, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger create2 command with test bytecode using factory") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore));*/ - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // different contract address with different bytecode, same salt and address - Assert.assertNotEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(testContractAddress)); - } - - @Test(enabled = false, description = "Trigger create2 command with test bytecode using factory2") - public void test04TriggerCreate2ToDeployTestContract2() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - /*AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore));*/ - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress2, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - /*accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter));*/ - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("Not enough energy for 'SWAP1' operation executing")); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test005.java deleted file mode 100644 index 9ec661328e6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test005.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 command with 0 extended bytecode") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testContractCode = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801" - + "561002a57600080fd5b5060c9806100396000396000f3fe6080604052348015600f57600080fd5b50d38015" - + "601b57600080fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000" - + "00000000000000000000000000000600035046368e5c0668114606b578063e5aa3d58146083575b600080fd" - + "5b60716089565b60408051918252519081900360200190f35b60716097565b6000805460010190819055905" - + "65b6000548156fe0000000000000000000000000000000000000000000000000000000000000000000000"; - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test006.java deleted file mode 100644 index fdd0504c242..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test006.java +++ /dev/null @@ -1,1014 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test006 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 with salt empty") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String param = "\"" + testContractCode + "\"," + null; - boolean ret = false; - try { - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - @Test(enabled = true, description = "Trigger create2 with salt 0") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 0L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt -1") - public void test04TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = -1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt 100") - public void test05TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 100L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - // Istanbul change create2 algorithm - @Test(enabled = false, description = "Trigger create2 with salt f * 64") - public void test06TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String saltHexString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(saltHexString, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt efffe") - public void test07TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "EFFFE"; - final String expectedSalt = "0EFFFE0000000000000000000000000000000000000000000000000000000000"; - - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger create2 with salt affffa") - public void test08TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "AFFFFA"; - final String expectedSalt = "AFFFFA0000000000000000000000000000000000000000000000000000000000"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - @Test(enabled = true, description = "Trigger test contract") - public void test09TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test007.java deleted file mode 100644 index 135a76a7560..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test007.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 with salt -1") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = -1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test008.java deleted file mode 100644 index b278ff2ccac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test008.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test008 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 with salt 100") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 100L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test009.java deleted file mode 100644 index fc3132c2d72..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test009.java +++ /dev/null @@ -1,365 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract generated by new solidity") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 function to deploy test contract") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - String[] parameter = {Base58.encode58Check(user001Address), testContractCode, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - - Assert.assertEquals(Base58.encode58Check(testContractAddress), PublicMethed.create2(parameter)); - - } - - - @Test(enabled = false, description = "Trigger Test contact") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test010.java deleted file mode 100644 index cd32b9c983d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test010.java +++ /dev/null @@ -1,210 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test010 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "TransferToken with correct value, deploy transfer contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 with salt empty") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String param = "\"" + testContractCode + "\"," + null; - boolean ret = false; - try { - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - } catch (NullPointerException e) { - logger.info("Expected NullPointerException!"); - ret = true; - } - Assert.assertTrue(ret); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test011.java deleted file mode 100644 index 93a149c6298..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test011.java +++ /dev/null @@ -1,369 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "FactoryBytes"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 with salt f * 64") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - String saltHexString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(saltHexString, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger test contract") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test012.java deleted file mode 100644 index f4a906c3af3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test012.java +++ /dev/null @@ -1,396 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test012 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - private byte[] testContractAddress2 = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 command with test bytecode and salt 1") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger create2 command with test bytecode and salt 2") - public void test03TriggerCreate2ToDeployTestContract2() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 80000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 2L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(salt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // contract address are different with different salt - Assert.assertNotEquals(Base58.encode58Check(testContractAddress), - Base58.encode58Check(testContractAddress2)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test013.java deleted file mode 100644 index d1b1ebba816..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test013.java +++ /dev/null @@ -1,436 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test013 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger factory contract to deploy test contract") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger factory contract to deploy test contract again " - + "with same code, salt and address") - public void test03TriggerCreate2ToDeployTestContractAgain() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("Not enough energy for 'SWAP1' operation executing")); - } - - @Test(enabled = false, description = "Trigger test1 contract") - public void test04TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test014.java deleted file mode 100644 index 127eac0aad9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test014.java +++ /dev/null @@ -1,641 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test014 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - private byte[] testContractAddress2 = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "Trigger factory contract with Test " - + "bytecode and salt using user account") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger factory contract to deploy test contract again " - + "with same code, salt and address") - public void test02TriggerCreate2ToDeployTestContractAgain() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert - .assertThat(infoById.get().getResMessage().toStringUtf8(), - containsString("REVERT opcode executed")); - } - - // Istanbul change create2 algorithm - @Test(enabled = false, description = "Same code, salt and address," - + " create contract using develop account") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, dev001Address, dev001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress2 = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress2, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - // contract address are different - Assert.assertNotEquals(Base58.encode58Check(testContractAddress), - Base58.encode58Check(testContractAddress2)); - } - - @Test(enabled = true, description = "Trigger test1 contract") - public void test04TriggerTest1Contract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - } - - // Istanbul change create2 algorithm - @Test(enabled = false, description = "Trigger test2 contract") - public void test05TriggerTest2Contract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress2, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test015.java deleted file mode 100644 index c61b9befe1b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test015.java +++ /dev/null @@ -1,499 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test015 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] callerContractAddress = null; - private byte[] callContractAddress = null; - private byte[] delegateCallContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy caller contract") - public void test01DeployCallerContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2CallContract.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - callerContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(callerContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test02DeployFactoryContract() { - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger callCreate2 function in caller contract " - + "with factory contract address") - public void test03TriggerCreate2ToDeployTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + Base58.encode58Check(factoryContractAddress) - + "\",\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(callerContractAddress, - "callCreate2(address,bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), - 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - callContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(callContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // call type make the caller contract to be the owner of - // test contract (the contract address in transaction info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger delegateCallCreate2 function in caller contract " - + "with factory contract address") - public void test04TriggerCreate2ToDeployTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + Base58.encode58Check(factoryContractAddress) - + "\",\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(callerContractAddress, - "delegateCallCreate2(address,bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - delegateCallContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed - .getContract(delegateCallContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // delegatecall type make the caller contract to be the owner of test contract (contract info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // call type make the caller contract to be the owner of test contract - // (the contract address in transaction info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Trigger test contract") - public void test09TriggerTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(callContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test016.java deleted file mode 100644 index 055f55a982f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test016.java +++ /dev/null @@ -1,422 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test016 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] callerContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy caller contract") - public void test01DeployCallerContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2CallContract.sol"; - String contractName = "callerContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - callerContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(callerContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test02DeployFactoryContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger delegateCallCreate2 function in caller contract " - + "with factory contract address") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - Long salt = 1L; - - String param = "\"" + Base58.encode58Check(factoryContractAddress) - + "\",\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(callerContractAddress, - "delegateCallCreate2(address,bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // delegatecall type make the caller contract to be the owner of test contract (contract info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // call type make the caller contract to be the owner of test contract - // (the contract address in transaction info) - Assert.assertEquals(Base58.encode58Check(callerContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger test contract") - public void test04TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test017.java deleted file mode 100644 index 6346c900d21..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test017.java +++ /dev/null @@ -1,405 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test017 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "FactoryBytes"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Trigger create2 with salt efffe") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "EFFFE"; - final String expectedSalt = "0EFFFE0000000000000000000000000000000000000000000000000000000000"; - - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = false, description = "Trigger create2 with salt affffa") - public void test03TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - - final String saltHexString = "AFFFFA"; - final String expectedSalt = "AFFFFA0000000000000000000000000000000000000000000000000000000000"; - logger.info("saltHexString: " + saltHexString); - - String param = "\"" + testContractCode + "\",\"" + saltHexString + "\""; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,bytes32)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - // The first - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("addressHex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("addressFinal: " + addressFinal); - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String actualSalt = retList.get(1); - logger.info("actualSalt: " + actualSalt); - - byte[] tmpSenderAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(2)), 12, tmpSenderAddress, 0, 20); - String senderAddressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("senderAddressHex: " + senderAddressHex); - String senderAddressFinal = Base58.encode58Check(ByteArray.fromHexString(senderAddressHex)); - logger.info("senderAddressFinal: " + senderAddressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - Assert.assertEquals(expectedSalt, actualSalt); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test018.java deleted file mode 100644 index 858d167c80d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test018.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test018 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - private byte[] witnessAddress001 = PublicMethed.getFinalAddress(witnessKey001); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(witnessKey001); - } - - @Test(enabled = false, description = "Deploy factory contract generated by new solidity") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(witnessAddress001, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = false, description = "Trigger create2 function to deploy test contract " - + "using Witness account") - public void test02TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 9000_000_000_000L, 0, 1, - ByteString.copyFrom(witnessAddress001), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = new Random().nextLong(); - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, witnessAddress001, witnessKey001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - - @Test(enabled = false, description = "Trigger Test contact") - public void test03TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(witnessAddress001, witnessKey001, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(witnessAddress001), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - final String triggerTxid = PublicMethed.triggerContract(testContractAddress, - "plusOne()", "#", false, callValue, - 1000000000L, "0", 0, witnessAddress001, witnessKey001, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(witnessAddress001, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(witnessAddress001, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - Long ret = ByteArray.toLong(ByteArray.fromHexString(retList.get(0))); - - logger.info("ret: " + ret); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " + infoById.get().getResMessage()); - } - - SmartContract smartContract = PublicMethed.getContract(infoById.get().getContractAddress() - .toByteArray(), blockingStubFull); - - long consumeUserPercent = smartContract.getConsumeUserResourcePercent(); - logger.info("ConsumeURPercent: " + consumeUserPercent); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - witnessAddress001, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - witnessAddress001, blockingStubFull); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test019.java deleted file mode 100644 index d903550be89..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test019.java +++ /dev/null @@ -1,297 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test019 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "seted Value of Contract that created by create2," - + " should not be stored after contact suicided ande create2 again") - public void testTriggerContract() { - String sendcoin = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, testNetAccountAddress, - testNetAccountKey, - blockingStubFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById0 = null; - infoById0 = PublicMethed.getTransactionInfoById(sendcoin, blockingStubFull); - logger.info("infoById0 " + infoById0.get()); - Assert.assertEquals(ByteArray.toHexString(infoById0.get().getContractResult(0).toByteArray()), - ""); - Assert.assertEquals(infoById0.get().getResult().getNumber(), 0); - Optional ById = PublicMethed.getTransactionById(sendcoin, blockingStubFull); - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), - SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - String filePath = "src/test/resources/soliditycode/create2contractn2.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "set()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(5 == returnnumber); - - String param1 = "\"" + Base58.encode58Check(returnAddressBytes) + "\""; - - txid = PublicMethed - .triggerContract(returnAddressBytes, - "testSuicideNonexistentTarget(address)", param1, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals("suicide", ByteArray - .toStr(infoById2.get().getInternalTransactions(0).getNote().toByteArray())); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : No contract or not a valid smart contract")); - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - byte[] returnAddressBytes1 = infoById3.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress1 = Base58.encode58Check(returnAddressBytes1); - Assert.assertEquals(returnAddress1, returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes1, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test020.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test020.java deleted file mode 100644 index 5329174e028..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test020.java +++ /dev/null @@ -1,896 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test020 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : trcToken") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 500000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1000001; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,trcToken)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : uint8") - public void testTriggerContract1() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1000031; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy1(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : address") - public void testTriggerContract2() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractExcAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy2(bytes,address)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - @Test(enabled = true, description = "Deploy Factory contract, create2 with salt type : string") - public void testTriggerContract3() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractExcAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - @Test(enabled = true, description = "TriggerContract a constant function created by create2" - + "can not create2 twice if salt type is string") - public void testTriggerContract4() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract1"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(2 == returnnumber); - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById2.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - - @Test(enabled = true, description = "TriggerContract a constant function created by create2" - + "can not create2 twice if salt type is string") - public void testTriggerContract5() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract2"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(3 == returnnumber); - num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(testNetAccountAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById2.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - - @Test(enabled = true, description = "TriggerContract a constant function created by create2" - + "can not create2 twice if salt type is string") - public void testTriggerContract6() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract3"; - String filePath = "src/test/resources/soliditycode/create2contract22.sol"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(4 == returnnumber); - String fakeAddress = "FFFFFFF"; - - num = "\"" + code1 + "\"" + ",\"" + fakeAddress + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, - "deploy3(bytes,string)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById2 = null; - infoById2 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertTrue(infoById2.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById2.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test021.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test021.java deleted file mode 100644 index fafbd5244fe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test021.java +++ /dev/null @@ -1,372 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test021 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "Asset008_" + Long.toString(now); - private static final long totalSupply = now; - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] bytes; - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - ByteString assetAccountId = null; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] resourceOnwerAddress = ecKey2.getAddress(); - String resourceOnwerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] contractExcAddress = ecKey3.getAddress(); - private String contractExcKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - PublicMethed.printAddress(resourceOnwerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = true, description = "resource delegate with create2 contract, and suicide ") - public void test1TriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(resourceOnwerAddress, 1000000000L + 1024000000L, testNetAccountAddress, - testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Create 3 the same name token. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(resourceOnwerAddress, - name, totalSupply, 1, 1, start, end, 1, description, url, - 2000L, 2000L, 1L, 1L, resourceOnwerKey, blockingStubFull)); - String filePath = "src/test/resources/soliditycode/create2contractn.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - - Long beforeExcAccountBalance = PublicMethed - .queryAccount(resourceOnwerAddress, blockingStubFull).getBalance(); - // create2 TestContract - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - - bytes = returnAddressBytes; - - - // freezeBalanceForReceiver to create2 contract Address, transaction Failed - - Assert.assertFalse(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 5000000L, 0, 0, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - Assert.assertFalse(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 5000000L, 0, 1, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - Long afterExcAccountBalance = PublicMethed.queryAccount(resourceOnwerAddress, blockingStubFull) - .getBalance(); - Assert.assertTrue(PublicMethed.getAccountResource(bytes, blockingStubFull).getNetLimit() == 0); - Assert - .assertTrue(PublicMethed.getAccountResource(bytes, blockingStubFull).getEnergyLimit() == 0); - logger.info("afterExcAccountBalance: " + afterExcAccountBalance); - logger.info("beforeExcAccountBalance:" + beforeExcAccountBalance); - - Assert.assertTrue(afterExcAccountBalance - beforeExcAccountBalance == 0); - - - // create2 Address Suicide - String param2 = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - String txidn = PublicMethed - .triggerContract(bytes, - "testSuicideNonexistentTarget(address)", param2, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - // active create2 Address to normal Address - Assert.assertTrue(PublicMethed - .sendcoin(bytes, 1000000L, contractExcAddress, contractExcKey, blockingStubFull)); - //Trigger contract to transfer trx and token. - Account getAssetIdFromAccount = PublicMethed - .queryAccount(resourceOnwerAddress, blockingStubFull); - assetAccountId = getAssetIdFromAccount.getAssetIssuedID(); - Long contractBeforeBalance = PublicMethed.queryAccount(bytes, blockingStubFull).getBalance(); - - Assert.assertTrue( - PublicMethed.transferAsset(bytes, assetAccountId.toByteArray(), 100, resourceOnwerAddress, - resourceOnwerKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account account1 = PublicMethed.queryAccount(bytes, blockingStubFull); - int typeValue1 = account1.getTypeValue(); - Assert.assertEquals(0, typeValue1); - - // freezeBalanceForReceiver to "create2" contract Address, transaction SUCCESS - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 1000000L, 0, 0, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(resourceOnwerAddress, 1000000L, 0, 1, - ByteString.copyFrom(bytes), resourceOnwerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - beforeExcAccountBalance = PublicMethed.queryAccount(resourceOnwerAddress, blockingStubFull) - .getBalance(); - - Assert.assertTrue(PublicMethed.unFreezeBalance(resourceOnwerAddress, resourceOnwerKey, - 0, bytes, blockingStubFull)); - Assert.assertTrue(PublicMethed.unFreezeBalance(resourceOnwerAddress, resourceOnwerKey, - 1, bytes, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterUnfreezeBalance = PublicMethed.queryAccount(resourceOnwerAddress, blockingStubFull) - .getBalance(); - Assert.assertTrue(afterUnfreezeBalance == beforeExcAccountBalance + 1000000L * 2); - - - // create2 TestContract to turn AccountType To create2 Contract Address - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - // triggercontract Create2 address, function normal - txid = PublicMethed - .triggerContract(returnAddressBytes, - "i()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - Account account = PublicMethed.queryAccount(returnAddressBytes, blockingStubFull); - int typeValue = account.getTypeValue(); - Assert.assertEquals(2, typeValue); - Assert.assertEquals(account.getBalance(), 1000000); - } - - @Test(enabled = true, description = "Create2 contract can transfer trx and token.") - public void test2TriggerContract() { - Account accountbefore = PublicMethed.queryAccount(bytes, blockingStubFull); - int typeValue = accountbefore.getTypeValue(); - Assert.assertEquals(2, typeValue); - long accountbeforeBalance = accountbefore.getBalance(); - Assert.assertEquals(accountbeforeBalance, 1000000); - Account contractExcAddressbefore = PublicMethed - .queryAccount(contractExcAddress, blockingStubFull); - long contractExcAddressbeforeBalance = contractExcAddressbefore.getBalance(); - - String num = "1"; - - String txid = PublicMethed - .triggerContract(bytes, - "testTransfer(uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(transactionInfoById.get().getResultValue() == 0); - Long fee1 = transactionInfoById.get().getFee(); - - Account accountafter = PublicMethed.queryAccount(bytes, blockingStubFull); - long accountafterBalance = accountafter.getBalance(); - Assert.assertTrue(accountbeforeBalance - 1 == accountafterBalance); - - Account contractExcAddressafter = PublicMethed - .queryAccount(contractExcAddress, blockingStubFull); - long contractExcAddressafterBalance = contractExcAddressafter.getBalance(); - Assert.assertTrue(contractExcAddressbeforeBalance + 1 - fee1 == contractExcAddressafterBalance); - - num = "1" + ",\"" + assetAccountId.toStringUtf8() + "\""; - Long returnAddressBytesAccountCountBefore = PublicMethed - .getAssetIssueValue(bytes, assetAccountId, blockingStubFull); - Long contractExcAddressAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - String txid1 = PublicMethed - .triggerContract(bytes, - "testTransferToken(uint256,trcToken)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - Assert.assertTrue(transactionInfoById1.get().getResultValue() == 0); - Long returnAddressBytesAccountCountAfter = PublicMethed - .getAssetIssueValue(bytes, assetAccountId, blockingStubFull); - - Long contractExcAddressAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Assert.assertTrue( - returnAddressBytesAccountCountBefore - 1 == returnAddressBytesAccountCountAfter); - Assert.assertTrue( - contractExcAddressAccountCountBefore + 1 == contractExcAddressAccountCountAfter); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test023.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test023.java deleted file mode 100644 index b390698eb60..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test023.java +++ /dev/null @@ -1,282 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test023 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test023.sol"; - String contractName = "factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "contract A new B contract,A suicide,contract B still exist") - public void test02TriggerTestContract() { - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "testCreate()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(exceptedResult)); - logger.info("B Address : " + addressFinal); - - //B Address is created by A, Trigger contract B - triggerTxid = PublicMethed.triggerContract(ByteArray.fromHexString(exceptedResult), - "test()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(ByteArray.toLong(infoById.get().getContractResult(0).toByteArray()), 1); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - - triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "kill()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - String note = ByteArray - .toStr(infoById.get().getInternalTransactions(0).getNote().toByteArray()); - - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("suicide", note); - - triggerTxid = PublicMethed.triggerContract(ByteArray.fromHexString(exceptedResult), - "test()", "#", false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test024.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test024.java deleted file mode 100644 index 8c42a4362ec..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test024.java +++ /dev/null @@ -1,277 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test024 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test024.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "create2 not allowed create2 twice in function") - public void test02TriggerTestContract() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/Create2Test024.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 4L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(exceptedResult)); - logger.info("create2 Address : " + addressFinal); - - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(infoById.get().getResultValue(), 0); - - triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy2(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - devEnergyLimitAfter = accountResource.getEnergyLimit(); - devEnergyUsageAfter = accountResource.getEnergyUsed(); - devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - userEnergyLimitAfter = accountResource.getEnergyLimit(); - userEnergyUsageAfter = accountResource.getEnergyUsed(); - userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals(infoById.get().getResult().toString(), "FAILED"); - Assert.assertThat(ByteArray.toStr(infoById.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test025.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test025.java deleted file mode 100644 index be459a86a81..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/create2/Create2Test025.java +++ /dev/null @@ -1,263 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.create2; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Create2Test025 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] testContractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = false, description = "Deploy factory contract") - public void test01DeployFactoryContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test025.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - code += "05"; - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "create2 bytecode with parm") - public void test02TriggerTestContract() { - //Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - // PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - // blockingStubFull), 0, 1, - // ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/Create2Test025.sol"; - String contractName = "TestContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - testContractCode += "0000000000000000000000000000000000000000000000000000000000000005"; - Long salt = 4L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = null; - triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "create2(bytes,uint256)", param, false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - String txid = PublicMethed.triggerContract(testContractAddress, - "getNum()", "#", false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - Optional infoById2 = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - TransactionInfo transactionInfo2 = infoById2.get(); - final int Num = ByteArray.toInt(transactionInfo2.getContractResult(0).toByteArray()); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - userEnergyLimitAfter = accountResource.getEnergyLimit(); - userEnergyUsageAfter = accountResource.getEnergyUsed(); - userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - logger.info("NUM :" + Num); - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(5, Num); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest001.java deleted file mode 100644 index ecc505fa210..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest001.java +++ /dev/null @@ -1,689 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - private String testContractAddress2 = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = false, description = "Get the extcodehash of a normal address") - public void test02GetNormalAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(dev001Address) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("transaction failed with message: " - + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - } - - @Test(enabled = true, description = "Get a contract extcodehash") - public void test03GetContactCodeHash() { - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(extCodeHashContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - @Test(enabled = true, description = "Get a not exist account extcodehash") - public void test04GetNotExistAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Active the account and get extcodehash again") - public void test05ActiveAccountGetCodeHash() { - - Assert.assertTrue(PublicMethed.sendcoin(testAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - - } - - @Test(enabled = true, description = "Get a not deployed create2 extcodehash") - public void test06GetCreate2CodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - final String abi = retMap.get("abI").toString(); - - Long salt = 100L; - String[] parameter = {Base58.encode58Check(user001Address), code, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - testContractAddress2 = PublicMethed.create2(parameter); - - Long callValue = Long.valueOf(0); - - String param = "\"" - + Base58.encode58Check(WalletClient.decodeFromBase58Check(testContractAddress2)) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - /*PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull);*/ - } - - @Test(enabled = true, description = "Get the EXTCODEHASH of an account created " - + "in the current transaction") - public void test07DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashConstruct.sol"; - String contractName = "CounterConstruct"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getTopics(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest002.java deleted file mode 100644 index 9fbe6334872..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest002.java +++ /dev/null @@ -1,246 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest002 { - - private final boolean AllTest = false; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = AllTest, description = "Get a contract extcodehash") - public void test02GetContactCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(extCodeHashContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest003.java deleted file mode 100644 index e6f29b2eaf0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest003.java +++ /dev/null @@ -1,336 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest003 { - - private final boolean AllTest = false; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = AllTest, description = "Get a not exist account extcodehash") - public void test02GetNotExistAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = AllTest, description = "Active the account and get extcodehash again") - public void test03ActiveAccountGetCodeHash() { - - Assert.assertTrue(PublicMethed.sendcoin(testAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest004.java deleted file mode 100644 index 8e64990fe57..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest004.java +++ /dev/null @@ -1,256 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import static org.tron.common.crypto.Hash.sha3; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest004 { - - private final boolean AllTest = false; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private String testContractAddress = null; - - private String expectedCodeHash = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - final String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - Long salt = 100L; - String[] parameter = {Base58.encode58Check(user001Address), code, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - testContractAddress = PublicMethed.create2(parameter); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = AllTest, description = "Get a not deployed create2 extcodehash") - public void test02GetCreate2CodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = - "\"" + Base58.encode58Check(WalletClient.decodeFromBase58Check(testContractAddress)) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest005.java deleted file mode 100644 index 060b9b8e999..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest005.java +++ /dev/null @@ -1,713 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.runtime.vm.DataWord; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String contractCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - - String fakeAddress = ""; - - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - fakeAddress = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - - logger.info("realAddress: " + fakeAddress); - fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Get codehash of a real contract by uint") - public void test02GetContractCodeHash() { - - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String testAddress = ByteArray.toHexString(extCodeHashContractAddress); - logger.info("realAddress: " + testAddress); - byte[] fullHexAddr = new DataWord(testAddress).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - contractCodeHash = retList.get(0); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a fake address by uint") - public void test03GetInvalidAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = "41660757B2543F4849D3F42B90F58DE1C14C7E0038"; - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a normal account by uint") - public void test04GetNormalAddressCodeHash() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = ByteArray.toHexString(user001Address); - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a empty address by uint") - public void test05GetEmptyAddressCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = ""; - - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a fffffff*64 address by uint") - public void test06GetFakeAddressCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String fakeAddress = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; - - logger.info("realAddress: " + fakeAddress); - byte[] fullHexAddr = new DataWord(fakeAddress).getData(); - logger.info("fullHexAddr ++= " + Hex.toHexString(fullHexAddr)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - } - - @Test(enabled = true, description = "Get codehash of a real contract plus 2**160 by uint") - public void test07GetContractAddress96CodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - BigInteger bigIntAddr = new DataWord(extCodeHashContractAddress).sValue(); - String bigIntAddrChange = BigInteger.valueOf(2).pow(160).add(bigIntAddr).toString(16); - byte[] fullHexAddr = new DataWord(bigIntAddrChange).getData(); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByUint(uint256)", Hex.toHexString(fullHexAddr), true, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - // expect the code hash same - Assert.assertEquals(contractCodeHash, retList.get(0)); - - SmartContract smartContract = PublicMethed - .getContract(extCodeHashContractAddress, blockingStubFull); - logger.info(smartContract.getBytecode().toStringUtf8()); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest006.java deleted file mode 100644 index a0723bbe817..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest006.java +++ /dev/null @@ -1,185 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest006 { - - private final boolean AllTest = false; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] testAddress = ecKey3.getAddress(); - private String testKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Get the EXTCODEHASH of an account created " - + "in the current transaction") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashConstruct.sol"; - String contractName = "CounterConstruct"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getTopics(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest007.java deleted file mode 100644 index ddf712a08e8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest007.java +++ /dev/null @@ -1,617 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] testAddressOld = null; - private byte[] testAddressNew = null; - private byte[] testAddress2 = null; - private byte[] extCodeHashContractAddress = null; - - private String expectedCodeHash = null; - private String expectedCodeHashOld = null; - - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy testNoPayable contract using old solidity") - public void test01DeployTestContractOld() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String contractName = "testExtHashContract"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a576000" - + "80fd5b5060ef806100396000396000f30060806040526004361060485763ffffffff7c010000000000000000" - + "0000000000000000000000000000000000000000600035041663c518aa0f8114604d578063e5aa3d58146089" - + "575b600080fd5b348015605857600080fd5b50d38015606457600080fd5b50d28015607057600080fd5b5060" - + "7760b3565b60408051918252519081900360200190f35b348015609457600080fd5b50d3801560a057600080" - + "fd5b50d2801560ac57600080fd5b50607760bd565b6001600081905590565b600054815600a165627a7a7230" - + "5820766b4e2fca9081689cd89419411d2cbc5588a17a5c9fa900fd9cfe4b0d9652be0029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testNoPayable\"," - + "\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true," - + "\"inputs\":[],\"name\":\"i\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}]," - + "\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]"; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - testAddressOld = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(testAddressOld, - blockingStubFull); - } - - @Test(enabled = true, description = "Deploy testNoPayable contract using new solidity") - public void test02DeployTestContractNew() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String contractName = "testConstantContract"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a5760" - + "0080fd5b5060c5806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b576000" - + "80fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000000000000" - + "000000000000000000006000350463c518aa0f8114606b578063e5aa3d58146083575b600080fd5b607160" - + "89565b60408051918252519081900360200190f35b60716093565b6001600081905590565b6000548156fe" - + "a165627a7a723058205c5aadfbd06ea264db7b73e7b7f3c36ac64a9d520ba46b4bc7f1dc56252f17ac0029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"" - + "name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable" - + "\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":" - + "[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"" - + "type\":\"function\"}]"; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - testAddressNew = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(testAddressNew, - blockingStubFull); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test03DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "Get contract code hash with old solidity") - public void test04GetTestOldCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddressOld) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - expectedCodeHashOld = retList.get(0); - Assert.assertEquals( - "B4AB5B9FF1A4FF7793E60EBFF0C769443AF66D0A6F9455AF145432CE8BA78175", expectedCodeHashOld); - Assert.assertFalse(retList.isEmpty()); - } - - @Test(enabled = true, description = "Get contract code hash with new solidity") - public void test05GetTestNewCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddressNew) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertNotEquals(retList.get(0), expectedCodeHashOld); - expectedCodeHash = retList.get(0); - Assert.assertEquals( - "34DB53BD1F7214367E8D6B2A7A6FBBF0E3B7DDB4939ECADE4CDEF6749C27A2DA", expectedCodeHash); - } - - @Test(enabled = true, description = "Deploy contract using new solidity again") - public void test06DeployTest2Contract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String contractName = "testConstantContract"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a5760" - + "0080fd5b5060c5806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b576000" - + "80fd5b50d28015602757600080fd5b50600436106066577c01000000000000000000000000000000000000" - + "000000000000000000006000350463c518aa0f8114606b578063e5aa3d58146083575b600080fd5b607160" - + "89565b60408051918252519081900360200190f35b60716093565b6001600081905590565b6000548156fe" - + "a165627a7a723058205c5aadfbd06ea264db7b73e7b7f3c36ac64a9d520ba46b4bc7f1dc56252f17ac0029"; - String abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"" - + "name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable" - + "\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":" - + "[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"" - + "type\":\"function\"}]"; - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - testAddress2 = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(testAddress2, - blockingStubFull); - } - - @Test(enabled = true, description = "Get contract code hash with test2") - public void test07GetTest2CodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress2) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - Assert.assertFalse(retList.isEmpty()); - - Assert.assertEquals(expectedCodeHash, retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest008.java deleted file mode 100644 index 87ac6cddfd3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest008.java +++ /dev/null @@ -1,512 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest008 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "Get code hash of create2 empty contract") - public void test02GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String[] parameter = {Base58.encode58Check(user001Address), testContractCode, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + PublicMethed.create2(parameter) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test03DeployFactoryContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 function to deploy test contract") - public void test04TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Get code hash of test contract") - public void test05GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest009.java deleted file mode 100644 index 71b3b7b9274..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest009.java +++ /dev/null @@ -1,512 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash.sol"; - String contractName = "TestExtCodeHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - @Test(enabled = true, description = "Get code hash of create2 empty contract") - public void test02GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String[] parameter = {Base58.encode58Check(user001Address), testContractCode, salt.toString()}; - logger.info(PublicMethed.create2(parameter)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + PublicMethed.create2(parameter) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - @Test(enabled = true, description = "Deploy factory contract") - public void test03DeployFactoryContract() { - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - factoryContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(factoryContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Trigger create2 function to deploy test contract") - public void test04TriggerCreate2ToDeployTestContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String filePath = "./src/test/resources/soliditycode/create2contract.sol"; - String contractName = "TestConstract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - final String triggerTxid = PublicMethed.triggerContract(factoryContractAddress, - "deploy(bytes,uint256)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - - logger.info("actualSalt: " + actualSalt); - - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - - testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - SmartContract smartContract = PublicMethed.getContract(testContractAddress, blockingStubFull); - - // contract created by create2, doesn't have ABI - Assert.assertEquals(0, smartContract.getAbi().getEntrysCount()); - - // the contract owner of contract created by create2 is the factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(smartContract.getOriginAddress().toByteArray())); - - // the contract address in transaction info, - // contract address of create2 contract is factory contract - Assert.assertEquals(Base58.encode58Check(factoryContractAddress), - Base58.encode58Check(infoById.get().getContractAddress().toByteArray())); - } - - @Test(enabled = true, description = "Get code hash of test contract") - public void test05GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", param, false, callValue, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertNotEquals("C5D2460186F7233C927E7DB2DCC703C0E500B653CA82273B7BFAD8045D85A470", - retList.get(0)); - Assert.assertNotEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - dev001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - user001Address, blockingStubFull); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest010.java deleted file mode 100644 index a9271034372..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest010.java +++ /dev/null @@ -1,370 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest010 { - - final boolean AllTest = false; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] factoryContractAddress = null; - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = AllTest, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/ExtCodeHashTest010.sol"; - String contractName = "Counter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - } - - - @Test(enabled = AllTest, description = "The EXTCODEHASH of an account that selfdestructed in the " - + "current transaction. but later been revert") - public void test02GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashRevert()", "#", false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - - @Test(enabled = AllTest, description = "The EXTCODEHASH of an account that create in the current " - + "transaction. but later been revert") - public void test03GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashCreate()", "#", false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - @Test(enabled = AllTest, description = "The EXTCODEHASH of an account that selfdestructed in the" - + " current transaction.") - public void test04GetTestContractCodeHash() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long devEnergyLimitBefore = accountResource.getEnergyLimit(); - long devEnergyUsageBefore = accountResource.getEnergyUsed(); - long devBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("before trigger, devEnergyLimitBefore is " + Long.toString(devEnergyLimitBefore)); - logger.info("before trigger, devEnergyUsageBefore is " + Long.toString(devEnergyUsageBefore)); - logger.info("before trigger, devBalanceBefore is " + Long.toString(devBalanceBefore)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitBefore = accountResource.getEnergyLimit(); - long userEnergyUsageBefore = accountResource.getEnergyUsed(); - long userBalanceBefore = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("before trigger, userEnergyLimitBefore is " + Long.toString(userEnergyLimitBefore)); - logger.info("before trigger, userEnergyUsageBefore is " + Long.toString(userEnergyUsageBefore)); - logger.info("before trigger, userBalanceBefore is " + Long.toString(userBalanceBefore)); - - String param = "\"" + Base58.encode58Check(extCodeHashContractAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashSuicide(address)", param, false, 0L, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - long devEnergyLimitAfter = accountResource.getEnergyLimit(); - long devEnergyUsageAfter = accountResource.getEnergyUsed(); - long devBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull).getBalance(); - - logger.info("after trigger, devEnergyLimitAfter is " + Long.toString(devEnergyLimitAfter)); - logger.info("after trigger, devEnergyUsageAfter is " + Long.toString(devEnergyUsageAfter)); - logger.info("after trigger, devBalanceAfter is " + Long.toString(devBalanceAfter)); - - accountResource = PublicMethed.getAccountResource(user001Address, blockingStubFull); - long userEnergyLimitAfter = accountResource.getEnergyLimit(); - long userEnergyUsageAfter = accountResource.getEnergyUsed(); - long userBalanceAfter = PublicMethed.queryAccount(user001Address, blockingStubFull) - .getBalance(); - - logger.info("after trigger, userEnergyLimitAfter is " + Long.toString(userEnergyLimitAfter)); - logger.info("after trigger, userEnergyUsageAfter is " + Long.toString(userEnergyUsageAfter)); - logger.info("after trigger, userBalanceAfter is " + Long.toString(userBalanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info("the value: " + retList); - - Assert.assertFalse(retList.isEmpty()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - retList.get(0)); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest011.java deleted file mode 100644 index 20b5267d13f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/extCodeHash/ExtCodeHashTest011.java +++ /dev/null @@ -1,369 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.extCodeHash; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.Hash; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashTest011 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] extCodeHashContractAddress = null; - private byte[] testContractAddress = null; - - private String expectedCodeHash = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr()", "#", false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - Assert.assertTrue(infoById.get().getResultValue() != 0); - Assert - .assertThat(ByteArray - .toStr(infoById.get().getResMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract1() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter1"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr()", "#", false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - - Assert.assertEquals(retList.get(1), - retList.get(0)); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract2() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter2"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", num, false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - Assert.assertEquals(retList.get(1), - retList.get(0)); - } - - - @Test(enabled = true, description = "Deploy extcodehash contract") - public void test01DeployExtCodeHashContract3() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHash11.sol"; - String contractName = "Counter2"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - expectedCodeHash = ByteArray.toHexString(Hash.sha3(Hex.decode(code))); - logger.info("expectedCodeHash: " + expectedCodeHash); - - String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - extCodeHashContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - transferTokenTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "getCodeHashByAddr(address)", num, false, 0, - 1000000000L, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - List retList = PublicMethed - .getStrings(transactionInfo.getContractResult(0).toByteArray()); - - logger.info( - "the value: " + retList); - Assert.assertEquals(retList.get(1), - retList.get(0)); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(user001Address, user001Key, fromAddress, blockingStubFull); - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, dev001Address, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand001.java deleted file mode 100644 index 736fa1b5202..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand001.java +++ /dev/null @@ -1,340 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.isContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class isContractCommand001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - } - - - @Test(enabled = true, description = "Correct contract address test") - public void test01CorrectContractAddress() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testIsContractCommand(address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testIsContractView(address)", num, - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Account address test") - public void test02AccountAddress() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testIsContractCommand(address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testIsContractView(address)", num, - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Nonexistent account address test") - public void test03NonexistentAddress() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, "testIsContractCommand(address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testIsContractView(address)", num, - false, 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Constructor return test") - public void test04ConstructorReturn() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = PublicMethed - .triggerContract(contractAddress, "testConstructor()", "", false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testConstructorView()", "", false, 0, - 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand002.java deleted file mode 100644 index 327092c74e8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand002.java +++ /dev/null @@ -1,190 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.isContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class isContractCommand002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] selfdestructContractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - byte[] selfdestructContractExcAddress = ecKey1.getAddress(); - String selfdestructContractKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - PublicMethed.printAddress(selfdestructContractKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "Selfdestruct contract test isContract Command") - public void test01SelfdestructContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "\"" + Base58.encode58Check(contractAddress) + "\""; - Assert.assertTrue(PublicMethed - .sendcoin(selfdestructContractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, - blockingStubFull)); - - selfdestructContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, selfdestructContractKey, - selfdestructContractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed.triggerContract(selfdestructContractAddress, - "testIsContractCommand(address)", num, false, - 0, maxFeeLimit, selfdestructContractExcAddress, selfdestructContractKey, blockingStubFull); - Optional infoById1 = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, ByteArray.toInt(infoById1.get().getContractResult(0).toByteArray())); - logger.info(infoById1.toString()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(selfdestructContractAddress, - "testIsContractView(address)", num, false, - 0, 0, "0", 0, selfdestructContractExcAddress, selfdestructContractKey, - blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - String txid1 = ""; - txid1 = PublicMethed.triggerContract(contractAddress, - "selfdestructContract(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - logger.info(infoById1.toString()); - - txid1 = PublicMethed.triggerContract(selfdestructContractAddress, - "testIsContractCommand(address)", num, false, - 0, maxFeeLimit, selfdestructContractExcAddress, selfdestructContractKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - Assert.assertEquals(0, ByteArray.toInt(infoById1.get().getContractResult(0).toByteArray())); - logger.info(infoById1.toString()); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(selfdestructContractAddress, - "testIsContractView(address)", num, false, - 0, 0, "0", 0, selfdestructContractExcAddress, selfdestructContractKey, - blockingStubFull); - logger.info("transactionExtention:" + transactionExtention.toString()); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "No constructor test isContract Command") - public void test02NoConstructorContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract002.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(info.get().toString()); - Assert.assertEquals(0, info.get().getResultValue()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand003.java deleted file mode 100644 index ee33144338f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/isContract/isContractCommand003.java +++ /dev/null @@ -1,252 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.isContract; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class isContractCommand003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - byte[] selfdestructContractExcAddress = ecKey1.getAddress(); - String selfdestructContractKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - PublicMethed.printAddress(selfdestructContractKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, description = "Incorrect address hex test isContract Command") - public void test01IncorrectHashContract() { - PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String input = "ac5a3e290000000000000000000000123456789123456789"; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testIsContractCommand(address)", input, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8() - .contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testIsContractView(address)", input, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - @Test(enabled = true, description = "Empty addresses hash test isContract Command") - public void test02EmptyAddressHashContract() { - PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmIsContract001.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String input = "ac5a3e29"; - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "testIsContractCommand(address)", input, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertTrue(infoById.get().getResMessage().toStringUtf8() - .contains("REVERT opcode executed")); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testIsContractView(address)", input, true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed.sendcoin(testNetAccountAddress, balance, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java deleted file mode 100644 index 355c8cd30af..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/AltbnTest001.java +++ /dev/null @@ -1,161 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.istanbul; - -import static org.tron.protos.Protocol.Transaction.Result.contractResult.OUT_OF_TIME; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AltbnTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/altbn.sol"; - String contractName = "AltBn128"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - @Test(enabled = true, description = "bn256add energyCost reduced from 500 to 150") - public void bn256addTest001() { - - String methodStr = "callBn256Add(bytes32,bytes32,bytes32,bytes32)"; - String data = "" - + "\"0000000000000000000000000000000000000000000000000000000000000001\"," - + "\"0000000000000000000000000000000000000000000000000000000000000002\"," - + "\"0000000000000000000000000000000000000000000000000000000000000001\"," - + "\"0000000000000000000000000000000000000000000000000000000000000002\""; - - logger.info("data: " + data); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, data, false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - - long energyCost = option.getReceipt().getEnergyUsageTotal(); - logger.info("energyCost: " + energyCost); - - Assert.assertEquals(0,option.getResultValue()); - } - - @Test(enabled = true, description = "bn256add energyCost reduced from 40000 to 6000") - public void bn256ScalarMulTest001() { - String methodStr = "callBn256ScalarMul(bytes32,bytes32,bytes32)"; - String data = "" - + "\"0000000000000000000000000000000000000000000000000000000000000001\"," - + "\"0000000000000000000000000000000000000000000000000000000000000002\"," - + "\"0000000000000000000000000000000000000000000000000000000000000001\""; - - logger.info("data: " + data); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, data, false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - - long energyCost = option.getReceipt().getEnergyUsageTotal(); - logger.info("energyCost: " + energyCost); - - Assert.assertEquals(0,option.getResultValue()); - Assert.assertTrue(energyCost < 40000L); - Assert.assertTrue(energyCost > 6000L); - } - - @Test(enabled = true, description = "bn256add energyCost reduced from ( 80000 * pairNum + 100000)" - + "to ( 34000 * pairNum + 45000) ") - public void bn256paringTest001() { - String methodStr = "callBn256Pairing(bytes)"; - String data = "" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000180" - + "1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59" - + "3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41" - + "209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf7" - + "04bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a41678" - + "2bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d" - + "120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550" - + "111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c" - + "2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411" - + "198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2" - + "1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed" - + "090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b" - + "12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"; - - logger.info("data: " + data); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, data, true, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - - long energyCost = option.getReceipt().getEnergyUsageTotal(); - logger.info("energyCost: " + energyCost); - if (option.getResultValue() == 1) { - Assert.assertEquals(option.getReceipt().getResult(), OUT_OF_TIME); - return; - } - - Assert.assertEquals(0,option.getResultValue()); - Assert.assertTrue(energyCost < 80000L * 2 + 100000L); - Assert.assertTrue(energyCost > 34000L * 2 + 45000L); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java deleted file mode 100644 index f9770923984..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/ChainidAndSelfBalance001.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.istanbul; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BlockExtention; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class ChainidAndSelfBalance001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/chainid001.sol"; - String contractName = "IstanbulTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 123456789L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - @Test(enabled = true, description = "chainId should be block zero`s Hash") - public void chainidTest001() { - String methodStr = "getId()"; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, "#", - false, 0, maxFeeLimit, "0", 0, testAddress001, testKey001, blockingStubFull); - - String chainIdHex = ByteArray.toHexString(returns.getConstantResult(0).toByteArray()); - - BlockExtention blockZero = PublicMethed.getBlock2(0, blockingStubFull); - String tem = ByteArray.toHexString(blockZero.getBlockid().toByteArray()).substring(56); - String blockZeroId = "00000000000000000000000000000000000000000000000000000000" + tem; - - Assert.assertEquals(chainIdHex, blockZeroId); - } - - /* - * New command selfBalance for solidity compiler, - * optimize address.balance when contract`s balance - */ - - @Test(enabled = true, description = "selfBalance of addres(this).balance") - public void getBalanceTest001() { - - String methodStr = "getBalance()"; - String argsStr = ""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Long contractBalance = PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance(); - - Assert.assertEquals(contractBalance, getBalance); - - } - - - @Test(enabled = true, description = "selfBalance of contractAddress") - public void getBalanceTest002() { - - String methodStr = "getBalance(address)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Long contractBalance = PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance(); - - Assert.assertEquals(contractBalance, getBalance); - - } - - @Test(enabled = true, description = "selfBalance of normal Address") - public void getBalanceTest003() { - String methodStr = "getBalance(address)"; - String argsStr = "\"" + Base58.encode58Check(testFoundationAddress) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Long accountBalance = PublicMethed - .queryAccount(testFoundationAddress, blockingStubFull).getBalance(); - - Assert.assertEquals(accountBalance, getBalance); - - } - - @Test(enabled = true, description = "selfBalance of unActive Address") - public void getBalanceTest004() { - String methodStr = "getBalance(address)"; - - byte[] unActiveAddress = new ECKey(Utils.getRandom()).getAddress(); - - String argsStr = "\"" + Base58.encode58Check(unActiveAddress) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - Long getBalance = ByteArray.toLong(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(0, getBalance.longValue()); - - } - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java deleted file mode 100644 index 9f6d87cf3af..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/istanbul/Create2IstanbulTest001.java +++ /dev/null @@ -1,105 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.istanbul; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class Create2IstanbulTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/create2Istanbul.sol"; - String contractName = "create2Istanbul"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - /** - * Create2 Algorithm Changed - * Before: according to msg.sender`s Address, salt, bytecode to get create2 Address - * After : according to contract`s Address, salt, bytecode to get create2 Address - * The calculated Create2 address should be same as get(bytes1,bytes,uint256) - */ - - @Test(enabled = true, description = "create2 Algorithm Change") - public void create2IstanbulTest001() { - String filePath = "src/test/resources/soliditycode/create2Istanbul.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - - String methodStr = "deploy(bytes,uint256)"; - String argStr = "\"" + code + "\"," + "1"; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argStr, false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo option = PublicMethed - .getTransactionInfoById(txid, blockingStubFull).get(); - String returnHex = ByteArray.toHexString(option.getContractResult(0).toByteArray()); - - Assert.assertEquals(0,option.getResultValue()); - - String methodStr2 = "get(bytes1,bytes,uint256)"; - String argStr2 = "\"41\",\"" + code + "\"," + 1; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr2, argStr2, - false, 0, - maxFeeLimit, "0", 0, testAddress001, testKey001, blockingStubFull); - String getHex = ByteArray.toHexString(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(returnHex,getHex); - - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbiEncodeTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbiEncodeTest.java deleted file mode 100644 index 6b8b21a29c5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbiEncodeTest.java +++ /dev/null @@ -1,269 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AbiEncodeTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/abiencode.sol"; - String contractName = "AbiEncode"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - logger.info("abi:" + abi); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test02TriggerContract() { - String methodStr = "h(int256[2][])"; - String argStr = "00000000000000000000000000000000000000000000000000000000000000200000000000000" - + "000000000000000000000000000000000000000000000000003000000000000000000000000000000000000" - + "000000000000000000000000000300000000000000000000000000000000000000000000000000000000000" - + "000040000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000006300000000000000000000000000000000000000000" - + "000000000000000000000060000000000000000000000000000000000000000000000000000000000000008"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000002000000000000000000" - + "00000000000000000000000000000000000000000000100000000000000000000000000000000000000" - + "00000000000000000000000000200000000000000000000000000000000000000000000000000000000" - + "00000000300000000000000000000000000000000000000000000000000000000000000030000000000" - + "00000000000000000000000000000000000000000000000000000400000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000630000000000000000000000000000000000000000000000000000000000000006000" - + "0000000000000000000000000000000000000000000000000000000000008", - contractResult); - - String methodStr1 = "i(int256[2][2])"; - String argStr1 = "0000000000000000000000000000000000000000000000000000000000000005000000000000" - + "000000000000000000000000000000000000000000000000000700000000000000000000000000000000000" - + "000000000000000000000000003e80000000000000000000000000000000000000000000000000000000000" - + "000065"; - String txid1 = PublicMethed.triggerContract(contractAddress, methodStr1, argStr1, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000002000000000000000000" - + "00000000000000000000000000000000000000000000080000000000000000000000000000000000000" - + "00000000000000000000000000050000000000000000000000000000000000000000000000000000000" - + "00000000700000000000000000000000000000000000000000000000000000000000003e80000000000" - + "000000000000000000000000000000000000000000000000000065", - contractResult1); - } - - @Test(enabled = true, description = "Trigger contract with negative number") - public void test03TriggerContract() { - String methodStr = "h(int256[2][])"; - String argStr = "00000000000000000000000000000000000000000000000000000000000000200000000000000" - + "000000000000000000000000000000000000000000000000003ffffffffffffffffffffffffffffffffffff" - + "ffffffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000000" - + "000090000000000000000000000000000000000000000000000000000000000000042ffffffffffffffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffbe00000000000000000000000000000000000000000" - + "000000000000000000000b1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa8"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000002000000000000000000" - + "00000000000000000000000000000000000000000000100000000000000000000000000000000000000" - + "00000000000000000000000000200000000000000000000000000000000000000000000000000000000" - + "000000003ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000" - + "00000000000000000000000000000000000000000000000000000900000000000000000000000000000" - + "00000000000000000000000000000000042ffffffffffffffffffffffffffffffffffffffffffffffff" - + "ffffffffffffffbe00000000000000000000000000000000000000000000000000000000000000b1fff" - + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa8", - contractResult); - - String methodStr1 = "i(int256[2][2])"; - String argStr1 = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff000000000000" - + "000000000000000000000000000000000000000000000000000900000000000000000000000000000000000" - + "00000000000000000000000000042ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "ffffbe"; - String txid1 = PublicMethed.triggerContract(contractAddress, methodStr1, argStr1, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - Assert.assertEquals( - "00000000000000000000000000000000000000000000000000000000000000200000000000000000" - + "000000000000000000000000000000000000000000000080ffffffffffffffffffffffffffffffffff" - + "ffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000" - + "0000000000090000000000000000000000000000000000000000000000000000000000000042ffffff" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffbe", - contractResult1); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java deleted file mode 100644 index 63aaa9ae313..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AbstractTest.java +++ /dev/null @@ -1,78 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AbstractTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "compile abstract contract 001") - public void test01CompileAbstractContract001() { - String filePath = "./src/test/resources/soliditycode/abstract001.sol"; - String contractName = "abstract001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - Assert.assertTrue(abi.length() > 0); - Assert.assertTrue(code.length() == 0); - } - - @Test(enabled = true, description = "compile abstract contract 002") - public void test02CompileAbstractContract002() { - String filePath = "./src/test/resources/soliditycode/abstract002.sol"; - String contractName = "abstract002"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - Assert.assertTrue(abi.length() > 0); - Assert.assertTrue(code.length() == 0); - } - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java deleted file mode 100644 index d537f06ebd6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AddressChange.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AddressChange { - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] contractAddressOld = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/getAddressChange.sol"; - String contractName = "getAddressChange"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_getAddressChange"); - code = Configuration.getByPath("testng.conf") - .getString("code.code_getAddressChange"); - contractName = "getAddressChangeOldVersion"; - contractAddressOld = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get external function address") - public void test01GetExternalAddress() { - String txid = ""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testaddress1()", "#", false, 0, 0, - "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - byte[] b1 = new byte[21]; - b1[0] = 0x41; - System.arraycopy(result, 12, b1, 1, 20); - Assert.assertEquals(Base58.encode58Check(contractAddress), Base58.encode58Check(b1)); - } - - @Test(enabled = true, description = "get external function address, solidity version < 0.6.0") - public void test02GetExternalAddressOldVersion() { - String txid = ""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressOld, "testaddress1()", "#", false, 0, 0, - "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - byte[] b1 = new byte[21]; - b1[0] = 0x41; - System.arraycopy(result, 12, b1, 1, 20); - Assert.assertEquals(Base58.encode58Check(contractAddressOld), Base58.encode58Check(b1)); - } - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - PublicMethed - .freedResource(contractAddressOld, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AssignToExternalTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AssignToExternalTest.java deleted file mode 100644 index 990d8f44c59..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/AssignToExternalTest.java +++ /dev/null @@ -1,249 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class AssignToExternalTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/AssignToExternal.sol"; - String contractName = "AssignToExternal"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test02TriggerContract() { - String methodStr = "f(uint256)"; - String argStr = "2"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - int contractResult = - ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(3, contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test03TriggerContract() { - String methodStr = "StringSet(string)"; - String argStr = "\"test\""; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "7465737400000000000000000000000000000000000000000000000000000000", contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test04TriggerContract() { - String methodStr = "ByteSet(bytes32)"; - String argStr = "00000000000000000000000000000000000000000000000000000000000003e9"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - int contractResult = - ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(1001, contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test05TriggerContract() { - String methodStr = "UintArraySet(uint256[2])"; - String argStr = "00000000000000000000000000000000000000000000000000000000000003e9" - + "00000000000000000000000000000000000000000000000000000000000003e9"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals("00000000000000000000000000000000000000000000000000000000000003e9" - + "00000000000000000000000000000000000000000000000000000000000003e9", contractResult); - } - - @Test(enabled = true, description = "Trigger contract with ") - public void test06TriggerContract() { - String methodStr = "AddSet(address)"; - String argStr = "\"TYVT8YJYis13NdrzdE7yVuwVxjsaRy2UsM\""; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals("000000000000000000000000f70b0a56acf4b0af44723c329ff113a677b5f589", - contractResult); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java deleted file mode 100644 index febc9cbe63c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/BlockhashTest.java +++ /dev/null @@ -1,170 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class BlockhashTest { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/BlockHash.sol"; - String contractName = "TestBlockHash"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "BlockHash should not be change after command OR") - public void test01BlockHashWithOR() { - String methodStr = "testOR1(bytes32)"; - String argStr = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - String ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before OR should equals to blockHash after OR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - - methodStr = "testOR2(bytes32)"; - txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before OR should equals to blockHash after OR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - } - - @Test(enabled = true, description = "BlockHash should not be change after command AND") - public void test02BlockHashWithAND() { - String methodStr = "testAND1(bytes32)"; - String argStr = "0000000000000000000000000000000000000000000000000000000000000000"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - String ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before AND should equals to blockHash after AND - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - - methodStr = "testAND2(bytes32)"; - txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before AND should equals to blockHash after AND - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - } - - @Test(enabled = true, description = "BlockHash should not be change after command XOR") - public void test03BlockHashWithXOR() { - String methodStr = "testXOR1(bytes32)"; - String argStr = "00000000000000000000000000000000ffffffffffffffffffffffffffffffff"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - String ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before XOR should equals to blockHash after XOR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - - methodStr = "testXOR2(bytes32)"; - txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - ContractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - // 3 bytes32 - Assert.assertEquals(192, ContractResult.length()); - // blockHash before XOR should equals to blockHash after XOR - Assert.assertEquals(ContractResult.substring(0,64),ContractResult.substring(128)); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallValueGasPureTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallValueGasPureTest.java deleted file mode 100644 index 52f1eb6b80a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallValueGasPureTest.java +++ /dev/null @@ -1,136 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CallValueGasPureTest { - - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] testAddress001 = ecKey1.getAddress(); - private String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testKey001); - } - - @Test(enabled = true, description = "call.value.gas be pure") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(testAddress001, 1000_000_000L, foundationAddress001, foundationKey001, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(foundationAddress001, 100_000_000L, 0, 0, - ByteString.copyFrom(testAddress001), foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(testAddress001, blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(testKey001, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/callValueGasPure.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 0, - 10000, "0", 0, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String param = "\"" + Base58.encode58Check(testAddress001) + "\""; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "check(address)", - param, false, 0, 1000000000L, "0", 0, testAddress001, - testKey001, blockingStubFull); - - Assert.assertNotNull(extention); - Assert.assertTrue(extention.hasResult()); - Assert.assertTrue(extention.getResult().getResult()); - - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(testKey001, blockingStubFull).getBalance(); - PublicMethed - .sendcoin(foundationAddress001, balance, testAddress001, testKey001, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallvalueTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallvalueTest.java deleted file mode 100644 index 296f8a36b44..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/CallvalueTest.java +++ /dev/null @@ -1,205 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CallvalueTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 3147483647L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/callvalue.sol"; - String contractName = "Callvalue"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract") - public void test02TriggerContract() { - String methodStr = "check()"; - // 15 - String triggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, "", true, - 15, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - logger.info("contractResult:" + contractResult); - Assert.assertEquals(Long.parseLong(contractResult, 16), 15); - - // 0 - String triggerTxid1 = PublicMethed.triggerContract(contractAddress, methodStr, "", true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - logger.info("contractResult1:" + contractResult1); - Assert.assertEquals(Long.parseLong(contractResult1, 16), 0); - - // Integer.MAX_VALUE - String triggerTxid2 = PublicMethed.triggerContract(contractAddress, methodStr, "", true, - Integer.MAX_VALUE, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - if (infoById2.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById2.get().getResMessage()); - } - logger.info("infoById2" + infoById2); - String contractResult2 = - ByteArray.toHexString(infoById2.get().getContractResult(0).toByteArray()); - logger.info("contractResult2:" + contractResult2); - Assert.assertEquals(Long.parseLong(contractResult2, 16), Integer.MAX_VALUE); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage001.java deleted file mode 100644 index bd6ad18c451..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage001.java +++ /dev/null @@ -1,255 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ConstantCallStorage001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerconstantContract trigger modidy storage date") - public void testConstantCallStorage001() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/constantCallStorage001.sol"; - String contractName = "NotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - //Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "setnum()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(138, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - logger.info("transactionExtention: " + transactionExtention); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "num()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(123, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = false, description = "TriggerconstantContract storage date by another contract ") - public void testConstantCallStorage002() { - - String filePath = "src/test/resources/soliditycode/constantCallStorage001.sol"; - String contractName = "UseNotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress002 = PublicMethed - .deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress002, blockingStubFull); - //Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress002, - "setnumuseproxy(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertEquals(138, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "num()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(123, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - } - - - @Test(enabled = false, description = "TriggerconstantContract storage date by another contract " - + "view function, use 0.5.* version solidity complier") - public void testConstantCallStorage003() { - String filePath = "src/test/resources/soliditycode/constantCallStorage002.sol"; - String contractName = "UseNotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress002 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress002, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress002, - "setnumuseproxy(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertFalse(transactionExtention.getResult().getResult()); - Assert.assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("Not enough energy")); - } - - - @Test(enabled = false, description = "TriggerconstantContract storage date by another contract " - + "view function, use 0.4.* version solidity complier") - public void testConstantCallStorage004() { - String filePath = "src/test/resources/soliditycode/constantCallStorage002.sol"; - String contractName = "UseNotView"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress002 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress002, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress002, - "setnumuseproxy(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertEquals(138, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "num()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertTrue(transactionExtention.getResult().getResult()); - Assert.assertEquals(123, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage002.java deleted file mode 100644 index 6e838b17bb4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage002.java +++ /dev/null @@ -1,421 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ConstantCallStorage002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerconstantContract trigger modidy storage date with " - + "difference date type") - public void testConstantCallStorage001() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/constantCallStorage001.sol"; - String contractName = "viewCall"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - // modify bool type - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeBool(bool)", "true", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getBool()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(0, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // modify NegativeInt type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeNegativeInt(int256)", "-2", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(-2, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getNegativeInt()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(-32482989, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // modify address type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeAddress(address)", "\"" + WalletClient.encode58Check(contractAddress) + "\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - String ContractResult = - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - String tmpAddress = - Base58.encode58Check(ByteArray.fromHexString("41" + ContractResult.substring(24))); - Assert.assertEquals(WalletClient.encode58Check(contractAddress), tmpAddress); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getAddress()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000dcad3a6d3569df655070ded06cb7a1b2ccd1d3af", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify byte32s type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeBytes32(bytes32)", "\"0xdCad3a6d3569DF655070DEd1\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("dcad3a6d3569df655070ded10000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getBytes32()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000dcad3a6d3569df655070ded0", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify bytes type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeBytes(bytes)", "\"0x05\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0500000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getBytes()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify string type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeString(string)", "\"321test\"", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("321test", - ByteArray.toStr(transactionExtention - .getConstantResult(0).substring(64, 64 + 7).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getString()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("123qwe", - ByteArray.toStr(transactionExtention - .getConstantResult(0).substring(64, 64 + 6).toByteArray())); - - // modify enum type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeActionChoices(uint8)", "3", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(3, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getActionChoices()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // modify Int64NegativeArray type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeInt64NegativeArray(int64[])", - "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getInt64NegativeArray()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - // modify Int32Array[2][] type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeInt32Array(int32[2][])", - "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000006" - + "0000000000000000000000000000000000000000000000000000000000000007" - + "0000000000000000000000000000000000000000000000000000000000000008" - + "0000000000000000000000000000000000000000000000000000000000000009" - + "000000000000000000000000000000000000000000000000000000000000000a", - true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000006" - + "0000000000000000000000000000000000000000000000000000000000000007" - + "0000000000000000000000000000000000000000000000000000000000000008" - + "0000000000000000000000000000000000000000000000000000000000000009" - + "000000000000000000000000000000000000000000000000000000000000000a", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getInt32Array()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000005" - + "0000000000000000000000000000000000000000000000000000000000000006", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - // modify Int256Array[2][2] type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "changeInt256Array(int256[2][2])", - - "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004", - true, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000004", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "getInt256Array()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals( - "000000000000000000000000000000000000000000000000000000000000000b" - + "0000000000000000000000000000000000000000000000000000000000000016" - + "0000000000000000000000000000000000000000000000000000000000000021" - + "000000000000000000000000000000000000000000000000000000000000002c", - ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray())); - - // modify mapping type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "setMapping(uint256)", "55", - false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(55, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "mapa(address)", "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(34, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage0425.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage0425.java deleted file mode 100644 index 44e1fe2635f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/ConstantCallStorage0425.java +++ /dev/null @@ -1,462 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ConstantCallStorage0425 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Deploy contract without abi") - public void test01DeployContract() { - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/constantCallStorage0425.sol"; - String contractName = "constantCall"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, "[]", code, "", - maxFeeLimit, 0L, 0, 1000000000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = false, description = "Trigger contract constant function without ABI") - public void test02TriggerContract() { - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "changeBool(bool)", "true", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getLog(0).getData().toByteArray())); - - String triggerTxid2 = PublicMethed - .triggerContract(contractAddress, "getBool()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - Assert.assertEquals(0, infoById1.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById1.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, ByteArray.toInt(infoById1.get().getLog(0).getData().toByteArray())); - } - - @Test(enabled = false, description = "TriggerConstantContract bool constant function") - public void test03TriggerConstantContract() { - // bool - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeBool(bool)", "false", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getBool()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // int - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt(int256)", "30", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(30, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(32482989, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // negative int - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeNegativeInt(int256)", "-111", - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(-111, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getNegativeInt()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(-32482989, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // uint - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeUint(uint256)", "1024", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(1024, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getUint()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert - .assertEquals(23487823, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - // address - String param = "\"" + Base58.encode58Check(dev001Address) + "\""; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeAddress(address)", param, - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - byte[] tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals(Base58.encode58Check(dev001Address), - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getAddress()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals("TW63BNR5M7LuH1fjXS7Smyza3PZXfHAAs2", - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - - // bytes32 - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeBytes32(bytes32)", - "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a", - true, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getBytes32()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // bytes - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeBytes(bytes)", "\"0x06\"", - false, - 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000020000000000000000000" - + "000000000000000000000000000000000000000000000106000000000000000000000000000000000000" - + "00000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getBytes()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000020000000000000000000" - + "000000000000000000000000000000000000000000000900000000000000000000000000000000000000" - + "00000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // string - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeString(string)", - "\"1q2w\"", - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000043171327700000000000000" - + "000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getString()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000063132337177650000000000" - + "000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // enum - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeActionChoices(uint8)", - "1", - false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getActionChoices()", "", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000003", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // int64[] include negative number - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt64NegativeArray(int64[])", - "0000000000000000000000000000000000000000000000000000000000000020000000000000000" - + "00000000000000000000000000000000000000000000000040000000000000000000000000000000" - + "00000000000000000000000000000000b00000000000000000000000000000000000000000000000" - + "00000000000000063000000000000000000000000000000000000000000000000000000000000004" - + "1000000000000000000000000000000000000000000000000000000000000005a", - true, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000040000000000000000000000" - + "00000000000000000000000000000000000000000b000000000000000000000000000000000000000000" - + "000000000000000000006300000000000000000000000000000000000000000000000000000000000000" - + "41000000000000000000000000000000000000000000000000000000000000005a", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt64NegativeArray()", "", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000030000000000000000000000" - + "00000000000000000000000000000000000000005b000000000000000000000000000000000000000000" - + "000000000000000000000200000000000000000000000000000000000000000000000000000000000001" - + "4d", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // int32[2][] - String argsStr = - "0000000000000000000000000000000000000000000000000000000000000020000000000000000" - + "00000000000000000000000000000000000000000000000030000000000000000000000000000000" - + "00000000000000000000000000000000d00000000000000000000000000000000000000000000000" - + "00000000000000058fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - + "70000000000000000000000000000000000000000000000000000000000000022000000000000000" - + "0000000000000000000000000000000000000000000000063fffffffffffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffc8"; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt32Array(int32[2][])", - argsStr, true, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(argsStr, - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt32Array()", "", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000002000" - + "000000000000000000000000000000000000000000000000000000000000030000000000000000000000" - + "000000000000000000000000000000000000000001000000000000000000000000000000000000000000" - + "000000000000000000000200000000000000000000000000000000000000000000000000000000000000" - + "030000000000000000000000000000000000000000000000000000000000000004000000000000000000" - + "000000000000000000000000000000000000000000000500000000000000000000000000000000000000" - + "00000000000000000000000006", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // int256[2][2] - String argsStr1 = - "0000000000000000000000000000000000000000000000000000000000000013000000000000000" - + "00000000000000000000000000000000000000000000000440000000000000000000000000000000" - + "000000000000000000000000000000037fffffffffffffffffffffffffffffffffffffffffffffff" - + "fffffffffffffffde"; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "changeInt256Array(int256[2][2])", - argsStr1, true, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(argsStr1, - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getInt256Array()", "", false, - 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000b00" - + "000000000000000000000000000000000000000000000000000000000000160000000000000000000000" - + "000000000000000000000000000000000000000021000000000000000000000000000000000000000000" - + "000000000000000000002c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - // modify mapping type - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "setMapping(uint256)", "39", - false, - 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(39, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "mapa(address)", "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"", false, - 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(88, - ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer.java deleted file mode 100644 index 5633f0ff936..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer.java +++ /dev/null @@ -1,539 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class EthGrammer { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - byte[] contractC = null; - byte[] contractD = null; - byte[] create2Address; - String create2Str; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/EthGrammer.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractC = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractC, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - contractName = "D"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractD = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(contractD, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "test get base fee value = commit.No 11 energy fee") - public void test01baseFee() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "baseFee()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long basefee = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("basefee: " + basefee); - long energyfee; - Protocol.ChainParameters chainParameters = blockingStubFull - .getChainParameters(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - String key = ""; - boolean flag = false; - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - key = getChainParameters.get().getChainParameter(i).getKey(); - if ("getEnergyFee".equals(key)) { - energyfee = getChainParameters.get().getChainParameter(i).getValue(); - logger.info("energyfee: " + energyfee); - Assert.assertEquals(basefee, energyfee); - flag = true; - } - } - Assert.assertTrue(flag); - } - - @Test(enabled = true, description = "test get gas price value = commit.No 11 energy fee") - public void test02GasPrice() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "gasPrice()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "get create2 address, test get base fee ") - public void test03BaseFeeFromCreate2() { - String methedStr = "deploy(uint256)"; - String argsStr = "1"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(create2Address, - "baseFeeOnly()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long basefee = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("basefee: " + basefee); - long energyfee; - Protocol.ChainParameters chainParameters = blockingStubFull - .getChainParameters(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - String key = ""; - boolean flag = false; - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - key = getChainParameters.get().getChainParameter(i).getKey(); - if ("getEnergyFee".equals(key)) { - energyfee = getChainParameters.get().getChainParameter(i).getValue(); - logger.info("energyfee: " + energyfee); - Assert.assertEquals(basefee, energyfee); - flag = true; - } - } - Assert.assertTrue(flag); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(create2Address, - "gasPriceOnly()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long gasprice = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("gasprice: " + gasprice); - Assert.assertEquals(basefee, gasprice); - } - - @Test(enabled = true, description = "call can use 63/64 energy in new contract") - public void test04CallEnergy() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - String methedStr = "testCall(address,address)"; - String argsStr = "\"" + Base58.encode58Check(contractD) + "\"," + "\"" - + Base58.encode58Check(transferToAddress) + "\""; - String txid = PublicMethed.triggerContract(contractC, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - logger.info("testAccount: " + testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - @Test(enabled = true, description = "create2 address call can use 63/64 energy in new contract") - public void test05Create2AddressCallEnergy() { - String methedStr = "deploy(uint256)"; - String argsStr = "2"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - methedStr = "testCall(address,address)"; - argsStr = "\"" + Base58.encode58Check(contractD) + "\"," + "\"" - + Base58.encode58Check(transferToAddress) + "\""; - txid = PublicMethed.triggerContract(create2Address, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - Assert.assertEquals("", testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - @Test(enabled = true, description = "create2 address delegatecall " - + "can use 63/64 energy in new contract") - public void test06Create2AddressDelegateCallEnergy() { - String methedStr = "deploy(uint256)"; - String argsStr = "5"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - methedStr = "testDelegateCall(address,address)"; - argsStr = "\"" + Base58.encode58Check(contractD) + "\"," + "\"" - + Base58.encode58Check(transferToAddress) + "\""; - txid = PublicMethed.triggerContract(create2Address, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - Assert.assertEquals("", testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - @Test(enabled = true, description = "create2 address this.function " - + "can use 63/64 energy in new contract") - public void test07Create2AddressCallFunctionEnergy() { - String methedStr = "deploy(uint256)"; - String argsStr = "6"; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - String create2Str = - "41" + ByteArray.toHexString(info.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("hex create2 address: " + create2Str); - create2Address = ByteArray.fromHexString(create2Str); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] transferToAddress = ecKey1.getAddress(); - String transferToKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(transferToKey); - - Long temMaxLimitFee = 200000000L; - methedStr = "testCallFunctionInContract(address)"; - argsStr = "\"" + Base58.encode58Check(transferToAddress) + "\""; - txid = PublicMethed.triggerContract(create2Address, methedStr, argsStr, - false, 0, temMaxLimitFee, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Protocol.Account testAccount = - PublicMethed.queryAccountByAddress(transferToAddress, blockingStubFull); - Assert.assertEquals("", testAccount.toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - Assert.assertTrue(info.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(info.get().getReceipt().getEnergyFee() < temMaxLimitFee); - } - - // - @Test(enabled = true, description = "test get Ripemd160 input is 123") - public void test08getRipemd160() { - String args = "\"123\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("e3431a8e0adbf96fd140103dc6f63a3f8fa343ab000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input is empty") - public void test09getRipemd160() { - String args = "\"\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("9c1185a5c5e9fc54612808977ee8f548b2258d31000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input length is greater than 256") - public void test10getRipemd160() { - String args = "\"111111111111ddddddddddddd0x0000000000000000000000008b56a0602cc81fb0" - + "b99bce992b3198c0bab181ac111111111111ddddddddddddd0x0000000000000000000000008b56" - + "a0602cc81fb0b99bce992b3198c0bab181ac%^$#0000008b56a0602cc81fb0b99bce99" - + "2b3198c0bab181ac%^$#0000008b56a0602cc81fb0b99bce992b3198c0bab181ac%^$#\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("173c283ebcbad0e1c623a5c0f6813cb663338369000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input is string " - + "and do not convert to bytes") - public void test11getRipemd160Str() { - String args = "\"data\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160Str(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("cd43325b85172ca28e96785d0cb4832fd62cdf43000000000000000000000000", result); - } - - @Test(enabled = true, description = "test get Ripemd160 input is string and " - + "do not convert to bytes") - public void test12getRipemd160Str() { - String args = "\"000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "getRipemd160Str(string)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("efe2df697b79b5eb73a577251ce3911078811fa4000000000000000000000000", result); - } - - @Test(enabled = true, description = "test blake2f") - public void test13getBlak2f() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractC, - "callF()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String result = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals("ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac" - + "4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923", - result); - - } - - @Test(enabled = true, description = "when call create2, stack depth will be checked" - + "if stack depth is greater than 64, then create command will revert" - + "but run environment can not compute so much, so the actual result is time out") - public void test14FixCreate2StackDepth() { - String methedStr = "fixCreate2StackDepth(uint256)"; - String argsStr = "123"; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info("transactionExtention: " + transactionExtention.toString()); - String message = ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()); - Assert.assertTrue(message.contains("CPU timeout")); - /*int interCount = transactionExtention.getInternalTransactionsCount(); - int createCount = 0; - for(int i=0;i= 15 && createCount <= 64);*/ - } - - @Test(enabled = true, description = "when call create, stack depth will be checked." - + "if stack depth is greater than 64, then create command will revert" - + "but run environment can not compute so much, so the actual result is time out") - public void test15FixCreateStackDepth() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - "fixCreateStackDepth()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String message = ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()); - logger.info("transactionExtention: " + transactionExtention.toString()); - Assert.assertTrue(message.contains("CPU timeout")); - /*int interCount = transactionExtention.getInternalTransactionsCount(); - int createCount = 0; - for(int i=0;i= 15 && createCount <= 64);*/ - - } - - @Test(enabled = false, description = "test max Energy Limit For trigger Constant contract") - public void test16MaxEnergyLimitForConstant() { - String methedStr = "transfer(address)"; - String argsStr = "\"" + Base58.encode58Check(testNetAccountAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("transactionExtention: " + transactionExtention.toString()); - } - - @Test(enabled = true, description = "commit NO.47 value can be 1e17 if commit No.63 opened") - public void test17Commit47Value() { - HashMap proposalMap = new HashMap(); - proposalMap.put(47L, 100000000000000000L); - org.testng.Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer02.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer02.java deleted file mode 100644 index 10b47c7793f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/EthGrammer02.java +++ /dev/null @@ -1,556 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class EthGrammer02 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractD = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - int salt = 11; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/EthGrammer02.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractD = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractD, - blockingStubFull); - Assert.assertEquals(1, smartContract.getVersion()); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode ef") - public void test16forbiddenBytecodeStartWithEf() { - String code = "60ef60005360016000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", - abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode ef00") - public void test17forbiddenBytecodeStartWithEf() { - String code = "60ef60005360026000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", - abi, code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode ef0000") - public void test18forbiddenBytecodeStartWithEf() { - String code = "60ef60005360036000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", abi, - code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can not deploy contract with bytecode" - + " ef00000000000000000000000000000000000000000000000000000000000000") - public void test19forbiddenBytecodeStartWithEf() { - String code = "60ef60005360206000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", abi, - code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.INVALID_CODE, - info.get().getReceipt().getResult()); - Assert.assertEquals("invalid code: must not begin with 0xef".toLowerCase(), - ByteArray.toStr(info.get().getResMessage().toByteArray()).toLowerCase()); - } - - @Test(enabled = true, description = "can deploy contract with bytecode fe") - public void test20forbiddenBytecodeStartWithEf() { - String code = "60fe60005360016000f3"; - String abi = "[{\"inputs\":[],\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - String txid = PublicMethed.deployContractAndGetTransactionInfoById("test", abi, - code, "", maxFeeLimit, 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("info: " + info.get().toString()); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode ef") - public void test21forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360016000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode ef00") - public void test22forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360026000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode ef0000") - public void test23forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360036000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create with bytecode " - + "ef00000000000000000000000000000000000000000000000000000000000000") - public void test24forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60ef60005360206000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can deploy contract by create with bytecode fe") - public void test25forbiddenBytecodeStartWithEf() { - String methedStr = "createDeployEf(bytes)"; - String argsStr = "\"0x60fe60005360016000f3\""; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode ef") - public void test26forbiddenBytecodeStartWithEf() { - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360016000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode ef00") - public void test27forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360026000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode ef0000") - public void test28forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360036000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not deploy contract by create2 with bytecode " - + "ef00000000000000000000000000000000000000000000000000000000000000") - public void test29forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60ef60005360206000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can deploy contract by create2 with bytecode fe") - public void test30forbiddenBytecodeStartWithEf() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60fe60005360016000f3\"," + salt; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - } - - @Test(enabled = true, description = "can not sendcoin to contract") - public void test31forbiddenSendTrxToContract() { - Assert.assertFalse(PublicMethed - .sendcoin(contractD, 100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - } - - @Test(enabled = true, description = "db key can use high 16 bytes," - + "0x6162630000000000000000000000000000000000000000000000000000000000") - public void test32DbKeyUseHigh16Bytes() { - String slot = "0x6162630000000000000000000000000000000000000000000000000000000000"; - long value = 121; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot high 16bytes all f," - + "0xffffffffffffffffffffffffffffffff00000000000000000000000000000000") - public void test33DbKeyUseHigh16Bytes() { - String slot = "0xffffffffffffffffffffffffffffffff00000000000000000000000000000000"; - long value = 122; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot high 16bytes 1," - + " 0x0000000000000000000000000000000100000000000000000000000000000000") - public void test34DbKeyUseHigh16Bytes() { - String slot = "0x0000000000000000000000000000000100000000000000000000000000000000"; - long value = 123; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot high 16bytes all 0,low 16bytes 1." - + " 0x0000000000000000000000000000000000000000000000000000000000000001") - public void test35DbKeyUseHigh16Bytes() { - String slot = "0x0000000000000000000000000000000000000000000000000000000000000001"; - long value = 124; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot all 0," - + " 0x0000000000000000000000000000000000000000000000000000000000000000") - public void test36DbKeyUseHigh16BytesAllBytes0() { - String slot = "0x0000000000000000000000000000000000000000000000000000000000000000"; - long value = 125; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "slot all f," - + " 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff") - public void test37DbKeyUseHigh16BytesAllBytesF() { - String slot = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; - long value = 126; - String methedStr = "setSlot(bytes,uint256)"; - String argsStr = "\"" + slot + "\"," + value; - String txid = PublicMethed.triggerContract(contractD, methedStr, argsStr, - false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = - PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, info.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - info.get().getReceipt().getResult()); - - methedStr = "getSlot(bytes)"; - argsStr = "\"" + slot + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + result); - Assert.assertEquals(value, result); - } - - @Test(enabled = true, description = "TransactionExtention has logs and internal_transactions") - public void test38ConstantLogEven() { - salt++; - String methedStr = "create2DeployEf(bytes,uint256)"; - String argsStr = "\"0x60fe60005360016000f3\"," + salt; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractD, - methedStr, argsStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, transactionExtention.getLogsCount()); - Assert.assertEquals(1, transactionExtention.getInternalTransactionsCount()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FixbugTest086.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FixbugTest086.java deleted file mode 100644 index cd31d1f6826..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FixbugTest086.java +++ /dev/null @@ -1,147 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class FixbugTest086 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = - "src/test/resources/soliditycode/abstractContractWithMapParamsConstructor.sol"; - String contractName = "Cat"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "abstract With Map Params") - public void test01ContractWithMapParams() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "getMapValue()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(20, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - } - - - @Test(enabled = true, description = " super skip unimplemented in abstract contract") - public void test02SkipUnimplemented() { - String filePath = - "src/test/resources/soliditycode/super_skip_unimplemented_in_abstract_contract.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "f()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(42, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FunctionArray2Storage086.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FunctionArray2Storage086.java deleted file mode 100644 index 9977fc94cc8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/FunctionArray2Storage086.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class FunctionArray2Storage086 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/function_type_array_to_storage.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "function array test view to default") - public void test01View2Default() { - String triggerTxid = - PublicMethed.triggerContract(mapKeyContract, "testViewToDefault()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(12, - ByteArray.toInt(transactionInfo.get().getContractResult(0).substring(0, 32).toByteArray())); - Assert.assertEquals(22, - ByteArray.toInt(transactionInfo.get().getContractResult(0) - .substring(32, 64).toByteArray())); - } - - @Test(enabled = true, description = "function array pure to default") - public void test02Pure2Default() { - String triggerTxid = - PublicMethed.triggerContract(mapKeyContract, "testPureToDefault()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(13, - ByteArray.toInt(transactionInfo.get().getContractResult(0).substring(0, 32).toByteArray())); - Assert.assertEquals(23, - ByteArray.toInt(transactionInfo.get().getContractResult(0) - .substring(32, 64).toByteArray())); - - } - - @Test(enabled = true, description = "function array pure to view ") - public void test03Pure2View() { - String triggerTxid = - PublicMethed.triggerContract(mapKeyContract, "testPureToView()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(13, - ByteArray.toInt(transactionInfo.get().getContractResult(0).substring(0, 32).toByteArray())); - Assert.assertEquals(23, - ByteArray.toInt(transactionInfo.get().getContractResult(0) - .substring(32, 64).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java deleted file mode 100644 index 2f7950ed5d9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/LengthTest.java +++ /dev/null @@ -1,285 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class LengthTest { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 10000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - String filePath = "src/test/resources/soliditycode/arrayLength001.sol"; - String contractName = "arrayLength"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "push() increase Array length") - public void arrayLengthTest001() { - - String methodStr = "arrayPush()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "push(value) increase Array length") - public void arrayLengthTest002() { - - String methodStr = "arrayPushValue()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0100000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "pop() decrease Array length") - public void arrayLengthTest003() { - - String methodStr = "arrayPop()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "push() return no value") - public void arrayLengthTest004() { - - String methodStr = "arrayPushReturn()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "push(value) return value") - public void arrayLengthTest005() { - - String methodStr = "arrayPushValueReturn()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "pop() return no value") - public void arrayLengthTest006() { - - String methodStr = "arrayPopReturn()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "bytes push() return value") - public void arrayLengthTest007() { - - String methodStr = "bytesPush()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "bytes push(value) return no value") - public void arrayLengthTest008() { - - String methodStr = "bytesPushValue()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "bytes pop() return no value") - public void arrayLengthTest009() { - - String methodStr = "bytesPop()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - - @Test(enabled = true, description = "array length change before v0.5.15") - public void arrayLengthV0515() { - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_arrayLenth_0.5.15"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_arrayLength_0.5.15"); - String contractName = "arrayLength"; - byte[] v0515Address = PublicMethed.deployContract(contractName,abi,code,"",maxFeeLimit,0,100, - null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String Txid = PublicMethed.triggerContract(v0515Address,"ChangeSize()","",false,0,maxFeeLimit, - testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(Txid, blockingStubFull); - - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0100000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingFixTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingFixTest.java deleted file mode 100644 index 4527a8d63bf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingFixTest.java +++ /dev/null @@ -1,186 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MappingFixTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - // after solidity version 0.5.4. - // Tron Solidity compiler is no longer compatible with Ethereum - // Tron handles 41 Address in contract, and Ethereum do not - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/SolidityMappingFix.sol"; - String contractName = "Tests"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - @Test(enabled = true, description = "Trigger contract,set balances[msg.sender]") - public void test02TriggerContract() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String methodStr = "update(uint256)"; - String argStr = "123"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - TransactionInfo transactionInfo = infoById.get(); - logger.info("infoById" + infoById); - - String ContractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - String tmpAddress = - Base58.encode58Check(ByteArray.fromHexString("41" + ContractResult.substring(24))); - Assert.assertEquals(WalletClient.encode58Check(dev001Address), tmpAddress); - - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - methodStr = "balances(address)"; - argStr = "\"" + WalletClient.encode58Check(dev001Address) + "\""; - TransactionExtention return1 = PublicMethed - .triggerContractForExtention(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, "0", 0L, dev001Address, dev001Key, blockingStubFull); - logger.info("return1: " + return1); - logger.info(Hex.toHexString(return1.getConstantResult(0).toByteArray())); - int ContractRestult = ByteArray.toInt(return1.getConstantResult(0).toByteArray()); - - Assert.assertEquals(123, ContractRestult); - - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingPopingTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingPopingTest.java deleted file mode 100644 index 6d80a266d5e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/MappingPopingTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MappingPopingTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/TestMappings_array_pop.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract ") - public void test02TriggerContract() { - String methodStr = "n1(uint256,uint256)"; - String argStr = "1,1001"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - } - - @Test(enabled = true, description = "Trigger contract ") - public void test03TriggerContract() { - String methodStr = "p()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NegativeArrayTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NegativeArrayTest.java deleted file mode 100644 index 13e676401ea..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NegativeArrayTest.java +++ /dev/null @@ -1,259 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class NegativeArrayTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/negativeArray.sol"; - String contractName = "NegativeArray"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @Test(enabled = true, description = "Trigger contract") - public void test02TriggerContract() { - // get[2] - String methodStr = "get(uint256)"; - String argStr = "2"; - String triggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById.get().getResMessage()); - } - logger.info("infoById" + infoById); - String contractResult = - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()); - logger.info("contractResult:" + contractResult); - Assert.assertEquals(new BigInteger(contractResult, 16).intValue(), -3); - - // get[1] - String argStr1 = "1"; - String triggerTxid1 = PublicMethed.triggerContract(contractAddress, methodStr, argStr1, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = PublicMethed - .getTransactionInfoById(triggerTxid1, blockingStubFull); - if (infoById1.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById1.get().getResMessage()); - } - logger.info("infoById1" + infoById1); - String contractResult1 = - ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()); - logger.info("contractResult1:" + contractResult1); - Assert.assertEquals(new BigInteger(contractResult1, 16).intValue(), 2); - - // change array value - String triggerTxid2 = PublicMethed.triggerContract(contractAddress, "set()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(triggerTxid2, blockingStubFull); - if (infoById2.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById2.get().getResMessage()); - } - logger.info("infoById2" + infoById2); - String log1 = - ByteArray.toHexString(infoById2.get().getLog(0).getData().toByteArray()); - logger.info("log1:" + log1); - Assert.assertEquals(new BigInteger(log1, 16).intValue(), -1); - String log2 = ByteArray.toHexString(infoById2.get().getLog(1).getData().toByteArray()); - logger.info("log2:" + log2); - Assert.assertEquals(new BigInteger(log2, 16).intValue(), 3); - String log3 = - ByteArray.toHexString(infoById2.get().getLog(2).getData().toByteArray()); - logger.info("log3:" + log3); - Assert.assertEquals(new BigInteger(log3, 16).intValue(), -8); - - // get[2] - String triggerTxid3 = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById3 = PublicMethed - .getTransactionInfoById(triggerTxid3, blockingStubFull); - if (infoById3.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById3.get().getResMessage()); - } - logger.info("infoById3" + infoById3); - String contractResult3 = - ByteArray.toHexString(infoById3.get().getContractResult(0).toByteArray()); - logger.info("contractResult3:" + contractResult3); - Assert.assertEquals(new BigInteger(contractResult3, 16).intValue(), -8); - - // get[1] - String triggerTxid4 = PublicMethed.triggerContract(contractAddress, methodStr, argStr1, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById4 = PublicMethed - .getTransactionInfoById(triggerTxid4, blockingStubFull); - if (infoById4.get().getResultValue() != 0) { - Assert.fail("trigger contract failed with message: " + infoById4.get().getResMessage()); - } - logger.info("infoById4" + infoById4); - String contractResult4 = - ByteArray.toHexString(infoById4.get().getContractResult(0).toByteArray()); - logger.info("contractResult4:" + contractResult4); - Assert.assertEquals(new BigInteger(contractResult4, 16).intValue(), 3); - - // get[3] - String triggerTxid5 = PublicMethed.triggerContract(contractAddress, methodStr, "3", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById5 = PublicMethed - .getTransactionInfoById(triggerTxid5, blockingStubFull); - logger.info("infoById5" + infoById5); - Assert.assertEquals(1, infoById5.get().getResultValue()); - Assert.assertEquals("REVERT opcode executed", infoById5.get() - .getResMessage().toStringUtf8()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc068.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc068.java deleted file mode 100644 index 527dfcfdd9f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc068.java +++ /dev/null @@ -1,269 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class NewFeatureForSolc068 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] getSelectorContract = null; - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature068.sol"; - String contractName = "testMapKey"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "map with enum key") - public void test01MapWithEnumKey() { - String txid = PublicMethed.triggerContract(mapKeyContract, - "setEnumValue(uint256)", "1", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getEnumValue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - @Test(enabled = true, description = "map with contract key") - public void test02MapWithContractKey() { - - String txid = PublicMethed.triggerContract(mapKeyContract, - "setContractValue()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getContractValue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(2, trueRes); - } - - @Test(enabled = true, description = "get function selector during compile period") - public void test03GetSelectorDuringCompile() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getfunctionSelector()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("trueRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.startsWith("48593bae")); - } - - @Test(enabled = true, description = "test storage variable init before been used") - public void test04StorageValInit() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "testStorage()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = PublicMethed - .getContractStringMsg(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("test", trueRes); - } - - @Test(enabled = true, description = "test immutable variable inited when declared") - public void test05ImmutableInit() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getOwner()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(ByteArray.toHexString(PublicMethed - .getFinalAddress(contractExcKey)).substring(2), trueRes.substring(24)); - - } - - @Test(enabled = true, description = "test immutable variable inited in construct") - public void test06ImmutableInit() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getImmutableVal()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(5, trueRes); - } - - @Test(enabled = true, description = "get interface id," - + "interface id is result of all function selector's XOR ") - public void test07GetInterfaceId() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getInterfaceId()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - String trueRes = ByteArray.toHexString(ByteArray.subArray(result, 0, 4)); - String trueRes1 = ByteArray.toHexString(ByteArray.subArray(result, 32, 36)); - - logger.info("truerRes: " + trueRes + " truerRes1: " + trueRes1 - + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("a9ab72bd", trueRes); - Assert.assertEquals(trueRes, trueRes1); - - } - - @Test(enabled = true, description = "abstract contract can have vitrual modifier with empty body") - public void test08VirtualModifier() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "requireOwner()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - int trueRes = ByteArray.toInt(result); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(6, trueRes); - - } - - @Test(enabled = true, description = "uint256 max and mine") - public void test09Uint256MaxMine() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getUint256MinAndMax()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - String trueRes = ByteArray.toHexString(ByteArray.subArray(result, 0, 32)); - String trueRes1 = ByteArray.toHexString(ByteArray.subArray(result, 32, 64)); - logger.info("truerRes: " + trueRes + "truerRes1: " + trueRes1 - + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - trueRes); - Assert.assertEquals("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", - trueRes1); - - } - - @Test(enabled = true, description = "solidity 0.6.12 test Reference " - + "variable can be marked by calldata") - public void test10CalldataModifier() { - String hexAdd = ByteArray.toHexString(PublicMethed.getFinalAddress(contractExcKey)); - String args = "\"0x" + hexAdd + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "calldataModifier(bytes)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - String trueRes = ByteArray.toHexString(result); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.contains(hexAdd)); - } - - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc076.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc076.java deleted file mode 100644 index 3e55337e60c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc076.java +++ /dev/null @@ -1,133 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class NewFeatureForSolc076 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature076.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "call method outside contract") - public void test01CallOutsideMethod() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getOutsideMethod()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - @Test(enabled = true, description = "get abstract contract and interface name") - public void test02GetTypeName() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getAbstractName()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toStr(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.contains("abvd")); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getInterfaceName()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - trueRes = ByteArray.toStr(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertTrue(trueRes.contains("qwer")); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc080.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc080.java deleted file mode 100644 index 39820c4f24c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc080.java +++ /dev/null @@ -1,313 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class NewFeatureForSolc080 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature080.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 5000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "math sub without unchecked, transaction revert") - public void test01MathSubNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "subNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - } - - @Test(enabled = true, description = "math sub with uncheck,transaction success") - public void test02SubWithUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "subWithUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(255, trueRes); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertTrue(transactionExtention.getEnergyUsed() > 300); - - } - - @Test(enabled = true, description = "math add overflow without unchecked, transaction revert") - public void test03MathAddNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "addNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - } - - @Test(enabled = true, description = "math divide zero without unchecked, transaction revert") - public void test04DivideZeroNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "divideZeroNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - } - - @Test(enabled = true, description = "assert fail without unchecked, transaction revert") - public void test05AssertFailNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "assertFailNoUncheck()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "array out of index without unchecked, transaction revert") - public void test06AssertFailNoUncheck() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "arrayOutofIndex()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals("REVERT opcode executed", - transactionExtention.getResult().getMessage().toStringUtf8()); - Assert.assertEquals("FAILED", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "type convert") - public void test07TypeConvert() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "typeConvert()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(65535, trueRes); - Assert.assertEquals(true, - transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "power multi by default turn: right to left") - public void test08PowerMultiRightToLeft() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "powerMultiRightToLeft()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(2, trueRes); - Assert.assertEquals(true, - transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "power multi: left to right ") - public void test09PowerMultiLeftToRight() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "powerMultiLeftToRight()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(64, trueRes); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "power multi with 2 params ") - public void test10PowerMultiWith2Params() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "powerMultiWith2Params()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(8, trueRes); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "get block chain id ") - public void test11GetBlockChainId() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getBlockChainId()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - String chainId = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("chainId: " + chainId); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - @Test(enabled = true, description = "get normal account address hashcode ") - public void test12GetAccountHashCode() { - String argStr = "\"" + Base58.encode58Check(contractExcAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getAddressCodehash(address)", argStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info(transactionExtention.toString()); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("0000000: " + trueRes); - } - - @Test(enabled = true, description = "get contract address hashcode ") - public void test13GetContractAddressHashCode() { - String argStr = "\"" + Base58.encode58Check(mapKeyContract) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getAddressCodehash(address)", argStr, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - logger.info(transactionExtention.toString()); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("0000000: " + trueRes); - } - - @Test(enabled = true, description = "transfer trx to tx.origin address with payable") - public void test14TransferToTxoriginAddress() { - Protocol.Account info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance: " + beforeBalance); - - String methodStr = "transferToTxorigin(uint64)"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, "1000000", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long afterBalance = info.getBalance(); - logger.info("afterBalance: " + afterBalance); - Assert.assertTrue(beforeBalance == afterBalance + 1000000); - } - - @Test(enabled = true, description = "transfer trx to literal address with payable") - public void test15TransferToLiteralAddress() { - Protocol.Account info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance: " + beforeBalance); - - String methodStr = "transferToLiteralAddress(uint64)"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, "1000000", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - Long afterBalance = info.getBalance(); - logger.info("afterBalance: " + afterBalance); - Assert.assertTrue(beforeBalance == afterBalance + 1000000); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc0811.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc0811.java deleted file mode 100644 index 375323c0d66..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc0811.java +++ /dev/null @@ -1,240 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class NewFeatureForSolc0811 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature0811.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Get enum.min or enum.max") - public void test001GetEnumMinOrMax() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getEnumMin()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - int result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(0, result); - - - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getEnumMax()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(3, result); - - } - - - @Test(enabled = true,description = "User defined type of data") - public void test002SupportUserDefinedTypeOfData() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getUserDefinedValue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - int result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(45, result); - } - - - @Test(enabled = true,description = "Get assembly address") - public void test003GetAssemblyAddress() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "testGetAddress()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertTrue(ByteArray.toHexString(transactionExtention.getConstantResult(0) - .toByteArray()).contains(ByteArray.toHexString(mapKeyContract).substring(2))); - } - - - @Test(enabled = true,description = "Get assembly selector") - public void test004GetAssemblySelector() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "testGetSelector()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - long result = ByteArray.toLong(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(3781905051L, result); - } - - - @Test(enabled = true,description = "Get ABI-Encode calldata") - public void test005GetAbiEncodedCalldata() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "fSignatureFromLiteralCall()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000084" - + "33d8581000000000000000000000000000000000000000000000000000000000" - + "0000000100000000000000000000000000000000000000000000000000000000" - + "0000004000000000000000000000000000000000000000000000000000000000" - + "0000000331323300000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - - @Test(enabled = true,description = "Support constructor read immutable value") - public void test006SupportConstructorReadImmutableValue() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "readX()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - int result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(33, result); - - - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "readI()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - result = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(33, result); - - - } - - - @Test(enabled = true,description = "Fix immutable symbol bug") - public void test007FixImmutableSymbol() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "fixBugTest()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - - Assert.assertEquals("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc086.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc086.java deleted file mode 100644 index 30544ef8e64..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolc086.java +++ /dev/null @@ -1,305 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - - -@Slf4j -public class NewFeatureForSolc086 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/NewFeature086.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 500000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - - @Test(enabled = true, description = "catch assert fail") - public void test01TrtCatchAssertFail() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "catchAssertFail()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(1, trueRes); - - } - - @Test(enabled = true, description = "catch under flow") - public void test02CatchUnderFlow() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "catchUnderFlow()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(17, trueRes); - - } - - @Test(enabled = true, description = "catch divide zero") - public void test03CatchDivideZero() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "catchDivideZero()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - Assert.assertEquals(18, trueRes); - } - - @Test(enabled = true, description = "get address code length") - public void test04GetAddressCodeLength() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "getAddressCodeLength()", - "#", false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertTrue(transactionInfo.get().getFee() < 40000); - } - - @Test(enabled = true, description = "fix kecca256 bug: differt length return same code") - public void test05Kecca256BugFix() { - String args = "\"abcd123\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "keccak256Bug(string)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(0, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - logger.info(transactionInfo.toString()); - } - - @Test(enabled = true, description = "revert error type with params") - public void test06RevertErrorType() { - String args = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\",1000000000"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "transfer(address,uint256)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(1, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("cf479181", - ByteArray.toHexString(transactionInfo.get() - .getContractResult(0).substring(0, 4).toByteArray())); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0) - .substring(4, 36).toByteArray())); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000003b9aca00", - ByteArray.toHexString(transactionInfo.get().getContractResult(0) - .substring(36, 68).toByteArray())); - - } - - @Test(enabled = true, description = "revert error type no params") - public void test07RevertErrorType() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "withdraw()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(1, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.REVERT, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("82b42900", - ByteArray.toHexString(transactionInfo.get().getContractResult(0) - .substring(0, 4).toByteArray())); - } - - @Test(enabled = true, description = "test bytes concat") - public void test08bytesConcat() { - String args = "\"0x1234\",\"p2\",\"0x48e2f56f2c57e3532146eef2587a2a72\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "bytesConcat(bytes,string,bytes16)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals(36, trueRes); - } - - @Test(enabled = true, description = "test emit event") - public void test09EmitEvent() { - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "testEmitEvent()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals(6, - ByteArray.toInt(transactionInfo.get().getLog(0).getData().toByteArray())); - } - - - @Test(enabled = true, description = "test bytes convert to byteN overflow") - public void test10Bytes2ByteN() { - String args = "\"0x12345678\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "bytes2BytesN(bytes)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("1234560000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "test bytes convert to byteN underflow") - public void test11Bytes2ByteN() { - String args = "\"0x1234\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, "bytes2BytesN(bytes)", - args, false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(transactionInfo.toString()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertEquals("1234000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "get contract address by different function") - public void test12GetConcatAddress() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "getContractAddress()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - String res1 = ByteArray.toHexString(transactionExtention.getConstantResult(0) - .substring(0, 32).toByteArray()); - String res2 = ByteArray.toHexString(transactionExtention.getConstantResult(0) - .substring(32, 64).toByteArray()); - Assert.assertEquals(res1, res2); - } - - @Test(enabled = true, description = "test bytes concat with empty string") - public void test13bytesConcatWithEmptyStr() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "bytesConcatWithEmptyStr()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertEquals(true, transactionExtention.getResult().getResult()); - Assert.assertEquals("SUCESS", - transactionExtention.getTransaction().getRet(0).getRet().toString()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolidity062.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolidity062.java deleted file mode 100644 index addf73f5112..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/NewFeatureForSolidity062.java +++ /dev/null @@ -1,306 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; -import static org.tron.protos.Protocol.TransactionInfo.code.SUCESS; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class NewFeatureForSolidity062 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] getSelectorContract = null; - byte[] gasValueContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ExternalSelector.sol"; - String contractName = "TestGasValue"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - gasValueContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 10000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - - @Test(enabled = true, description = "get selector from contract or interface's external function") - public void test01GetFunctionSelector() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(gasValueContract, - "getContractSelectorNoParam()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String truerRes = ByteArray.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(truerRes.startsWith("6c4959fa")); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(gasValueContract, - "getContractSelectorWithParam()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - truerRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(truerRes.startsWith("fbb94ff8")); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(gasValueContract, - "getInterfaceSelectorNoParam()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - truerRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertTrue(truerRes.startsWith("034899bc")); - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 0, value: 1}()") - public void test02Call0GasAnd1Value() { - - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "0,1", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000159", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - byte[] internalReceiver = infoById.get().getInternalTransactions(0) - .getTransferToAddress().toByteArray(); - - long balanceReceiver = PublicMethed.queryAccount(internalReceiver, blockingStubFull) - .getBalance(); - logger.info("transfer to address: " + Base58.encode58Check(internalReceiver) - + "\n balance:" + balanceReceiver); - Assert.assertEquals(1, balanceReceiver); - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 0, value: 0}()") - public void test03Call0GasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "0,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertEquals("REVERT opcode executed", - infoById.get().getResMessage().toStringUtf8()); - - } - - @Test(enabled = true, description = "inline assembly allow true and false") - public void test04AssembleTrueFalse() { - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(gasValueContract, - "testAssemblyTrue()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int truerRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, truerRes); - - transactionExtention = PublicMethed.triggerConstantContractForExtention(gasValueContract, - "testAssemblyFalse()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - int falseRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("res: " + falseRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(0, falseRes); - - } - - @Test(enabled = true, description = "test new create2") - public void test05NewCreate2() { - - String txid = PublicMethed.triggerContract(gasValueContract, - "testCreate2()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - byte[] internalReceiver = infoById.get() - .getInternalTransactions(0).getTransferToAddress().toByteArray(); - - long balanceReceiver = PublicMethed.queryAccount(internalReceiver, blockingStubFull) - .getBalance(); - logger.info("transfer to address: " + Base58.encode58Check(internalReceiver) - + "\n balance:" + balanceReceiver); - Assert.assertEquals(1000000, balanceReceiver); - - } - - @Test(enabled = true, description = "test Interface Succeed") - public void test06InterfaceSucceed() { - - String filePath = "src/test/resources/soliditycode/ExternalSelector.sol"; - String contractName = "implementContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] implementContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 10000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(implementContract, - "getSelector()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int truerRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(66, truerRes); - } - - @Test(enabled = true, description = "call in contract external function like " - + "c.f{gas: 0, value: 1}()") - public void test07CallThis0GasAnd1Value() { - - String txid = PublicMethed.triggerContract(gasValueContract, - "callThisNoGasAnd1Value()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 440000, value: 0}()") - public void test08CallWithGasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "440000,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(SUCESS, infoById.get().getResult()); - - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 1, value: 0}()") - public void test09CallWith1GasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "1,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 0, value: > balance}()") - public void test10CallWith0GasAndBigValue() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "0,9223372036854775800", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(FAILED, infoById.get().getResult()); - } - - @Test(enabled = true, description = "call external function like " - + "c.f{gas: 9223372036854775800, value: 0}()") - public void test11CallWithBigGasAnd0Value() { - String txid = PublicMethed.triggerContract(gasValueContract, - "callWithGasAndValue(uint256,uint256)", "9223372036854775800,0", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(SUCESS, infoById.get().getResult()); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java deleted file mode 100644 index 65515d6db51..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/Opcode.java +++ /dev/null @@ -1,509 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - - -@Slf4j -public class Opcode { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/opCode.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbiNoOptimize(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - - @Test(enabled = true, description = "test opcode smod, used for int") - public void test01Smod() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "sssmod()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals(1, trueRes); - } - - @Test(enabled = true, description = "test opcode extcodecopy return contract bytecode") - public void test02Extcodecopy() { - String base58 = Base58.encode58Check(mapKeyContract); - String txid = PublicMethed.triggerContract(mapKeyContract, - "eextcodecopy(address)", "\"" + base58 + "\"", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertTrue(ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()).length() > 0); - - } - - @Test(enabled = true, description = "test opcode coinbase," - + "block.coinbase is sr address which produced the block") - public void test03Coinbase() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "cccoinbase()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertTrue(trueRes.startsWith("00000000000000000000000" - + "0bafb56091591790e00aa05eaddcc7dc1474b5d4b") - || trueRes.startsWith("0000000000000000000000000be88a918d74d0dfd71dc84bd4abf036d0562991")); - - } - - @Test(enabled = true, description = "test opcode difficulty,block.difficulty is always 0") - public void test04Difficulty() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "ddifficulty()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(0, trueRes); - - } - - @Test(enabled = true, description = "test opcode gaslimit,block.gaslimit is always 0") - public void test05Gaslimit() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "gggaslimit()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(0, trueRes); - - } - - @Test(enabled = true, description = "test opcode pc,return current position, " - + "ppppc() can refer to opCode.sol") - public void test06Pc() { - String code = "608060405260838060116000396000f3fe608060405234" - + "8015600f57600080fd5b506004361060285760003560e01c806" - + "36d3a027714602d575b600080fd5b60336045565b6040805191825251" - + "9081900360200190f35b60005890509056fea264697" - + "0667358221220fe03cbd3d2aae7454565f203b9abd76ce74cf0ac" - + "a079b151cf6b8e2bfda2d5c464736f6c634300060c0033"; - String abi = "[\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"name\": \"ppppc\",\n" - + "\t\t\"outputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"internalType\": \"uint256\",\n" - + "\t\t\t\t\"name\": \"a\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"stateMutability\": \"nonpayable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t}\n" - + "]"; - byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(temContract, - "ppppc()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(72, trueRes); - - } - - @Test(enabled = true, description = "test opcode msize,return size of memory, " - + "msize cannot be used if optimize is open, mmmsize() can refer to opCode.sol") - public void test07Msize() { - String code = "608060405260b5806100126000396000f3fe6080604052348015600f5760" - + "0080fd5b506004361060285760003560e01c8063bf1a725d14602d575b600080fd5b60" - + "336047565b604051603e9190605c565b60405180910390f35b600059905090565b6056" - + "816075565b82525050565b6000602082019050606f6000830184604f565b9291505056" - + "5b600081905091905056fea26469706673582212202252652aad4bca9a4aa9db179e03" - + "f7b3bf439f47152e31f45d8587b710bce79664736f6c63430008060033"; - String abi = "[\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"name\": \"mmmsize\",\n" - + "\t\t\"outputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"internalType\": \"uint256\",\n" - + "\t\t\t\t\"name\": \"a\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"stateMutability\": \"nonpayable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t}\n" - + "]"; - byte[] temContract = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(temContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(temContract, - "mmmsize()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(96, trueRes); - - } - - - @Test(enabled = true, description = "test opcode swap14-16,solidity cannot use optimize") - public void test08Swap() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "ssswap()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(1, trueRes); - - } - - @Test(enabled = true, description = "test opcode push13-30 but exclude push20 and push29," - + "solidity cannot use optimize") - public void test08Pushx() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "pppushx()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - String trueRes = ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + trueRes + " message:" + transaction.getRet(0).getRet()); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertTrue(trueRes.contains("000000000000000000000000000000000000001" - + "1223344556677889900112233")); - } - - @Test(enabled = true, description = "test opcode callcode,difference with delegatecall " - + "is caller and callvalue,the bytecode is compiled with solidity 0.4.22, " - + "can refer to opCode.sol for code") - public void test09Callcode() { - String code = "60806040526103b4806100136000396000f3006080604052600436106100565763" - + "ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634" - + "cb335db811461005b578063ae02d91d14610081578063ea856db2146100a5575b600080fd5b61007f" - + "73ffffffffffffffffffffffffffffffffffffffff600435166024356100c9565b005b61007f73ffff" - + "ffffffffffffffffffffffffffffffffffff600435166024356101b6565b61007f73ffffffffffffff" - + "ffffffffffffffffffffffffff600435166024356102a3565b604080516024808201849052825180830" - + "39091018152604490910182526020810180517bffffffffffffffffffffffffffffffffffffffffffff" - + "ffffffffffff167f66c99139000000000000000000000000000000000000000000000000000000001781529" - + "151815173ffffffffffffffffffffffffffffffffffffffff861693600a93929182919080838360005b8" - + "3811015610170578181015183820152602001610158565b50505050905090810190601f16801561019d5" - + "780820380516001836020036101000a031916815260200191505b5091505060006040518083038185875" - + "af1505050505050565b60408051602480820184905282518083039091018152604490910182526020810" - + "180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167f66c99139000000000" - + "000000000000000000000000000000000000000000000001781529151815173fffffffffffffffffffff" - + "fffffffffffffffffff861693600a93929182919080838360005b8381101561025d57818101518382015" - + "2602001610245565b50505050905090810190601f16801561028a5780820380516001836020036101000" - + "a031916815260200191505b5091505060006040518083038185875af2505050505050565b60408051602" - + "480820184905282518083039091018152604490910182526020810180517bfffffffffffffffffffffff" - + "fffffffffffffffffffffffffffffffff167f66c991390000000000000000000000000000000000000000" - + "00000000000000001781529151815173ffffffffffffffffffffffffffffffffffffffff8616938291808" - + "38360005b8381101561034457818101518382015260200161032c565b50505050905090810190601f1680" - + "156103715780820380516001836020036101000a031916815260200191505b50915050600060405180830" - + "381855af450505050505600a165627a7a72305820210d132d0c4006264ef113f342556c616d9e69acc20" - + "bfa80cf440a4eac170de80029"; - String abi = "[\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"callCAddress\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"testInCall\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"callCAddress\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"testInCallcode\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"callCAddress\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"testIndelegateCall\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t}\n" - + "]"; - byte[] contractA = PublicMethed.deployContract("A", abi, code, "", maxFeeLimit, - 1000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(contractA, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - code = "608060405260d2806100126000396000f300608060405260043610603e5763ffffffff7c0" - + "10000000000000000000000000000000000000000000000000000000060003504166366c99" - + "13981146043575b600080fd5b604c600435604e565b005b6040805173fffffffffffffffff" - + "fffffffffffffffffffffff3316815234602082015280820183905290517fac74fdf75f0e5" - + "a43f870f7135801b44f404be82b1dcad73423c542b840d1d64b9181900360600190a150560" - + "0a165627a7a72305820c460a35f70e363777be22b3a4ace5f95533de626073ab4e06d9bf3bbb2cffceb0029"; - abi = "[\n" - + "\t{\n" - + "\t\t\"constant\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"name\": \"amount\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"trans\",\n" - + "\t\t\"outputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"function\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"inputs\": [],\n" - + "\t\t\"payable\": true,\n" - + "\t\t\"stateMutability\": \"payable\",\n" - + "\t\t\"type\": \"constructor\"\n" - + "\t},\n" - + "\t{\n" - + "\t\t\"anonymous\": false,\n" - + "\t\t\"inputs\": [\n" - + "\t\t\t{\n" - + "\t\t\t\t\"indexed\": false,\n" - + "\t\t\t\t\"name\": \"\",\n" - + "\t\t\t\t\"type\": \"address\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"indexed\": false,\n" - + "\t\t\t\t\"name\": \"\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t},\n" - + "\t\t\t{\n" - + "\t\t\t\t\"indexed\": false,\n" - + "\t\t\t\t\"name\": \"\",\n" - + "\t\t\t\t\"type\": \"uint256\"\n" - + "\t\t\t}\n" - + "\t\t],\n" - + "\t\t\"name\": \"clog\",\n" - + "\t\t\"type\": \"event\"\n" - + "\t}\n" - + "]"; - byte[] contractC = PublicMethed.deployContract("C", abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(contractC, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String base58C = Base58.encode58Check(contractC); - - String txid = PublicMethed.triggerContract(contractA, - "testInCall(address,uint256)", "\"" + base58C + "\",1", false, - 1, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - String logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); - System.out.println("000000: " + logRes); - String b = "41" + logRes.substring(24, 64); - String c = logRes.substring(64, 128); - String x = ByteArray.toHexString(contractA); - Assert.assertEquals(b, x); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); - - txid = PublicMethed.triggerContract(contractA, - "testIndelegateCall(address,uint256)", "\"" + base58C + "\",1", false, - 2, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); - System.out.println("000000: " + logRes); - b = "41" + logRes.substring(24, 64); - c = logRes.substring(64, 128); - x = ByteArray.toHexString(contractExcAddress); - Assert.assertEquals(b, x); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000002", c); - - - txid = PublicMethed.triggerContract(contractA, - "testInCallcode(address,uint256)", "\"" + base58C + "\",1", false, - 3, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("txid: " + txid + "\n" + infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - logRes = ByteArray.toHexString(infoById.get().getLog(0).getData().toByteArray()); - System.out.println("000000: " + logRes); - b = "41" + logRes.substring(24, 64); - c = logRes.substring(64, 128); - x = ByteArray.toHexString(contractA); - Assert.assertEquals(b, x); - Assert.assertEquals("000000000000000000000000000000000000000000000000000000000000000a", c); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverridePrivateFunction.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverridePrivateFunction.java deleted file mode 100644 index 14473535bb8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverridePrivateFunction.java +++ /dev/null @@ -1,106 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class OverridePrivateFunction { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] gasValueContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - - @Test(enabled = false, description = "test override private function") - public void test01OverridePrivateFunction() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/overridePrivateFunction.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - gasValueContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(gasValueContract, - "testOverridePrivate()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Protocol.Transaction transaction = transactionExtention.getTransaction(); - int truerRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("truerRes: " + truerRes + " message:" + transaction.getRet(0).getRet()); - logger.info("transactionExtention: " + transactionExtention); - Assert.assertEquals(2, truerRes); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java deleted file mode 100644 index 8219070fd5c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/OverrideTest001.java +++ /dev/null @@ -1,455 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class OverrideTest001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy 0.5.15 about override(Base1,Base2)") - public void test01OverrideContract515() { - String contractName = "override001"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_override001"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_override001"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Deploy 0.6.0 about not need override") - public void test02NotNeedOverride() { - String filePath = "./src/test/resources/soliditycode/override002.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 about override(Base1,Base2)") - public void test03OverrideMultipleFunctionsWithTheSameName() { - String filePath = "./src/test/resources/soliditycode/override003.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 about override modifier") - public void test04OverrideModifier060() { - String filePath = "./src/test/resources/soliditycode/override004.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "7", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1,infoById.get().getResultValue()); - Assert.assertTrue(infoById.get().getContractResult(0).toStringUtf8().contains("x must >= 6")); - - txid = PublicMethed.triggerContract(contractAddress, "setValue2(uint256)", "6", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "8", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(8, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.5.15 about override modifier") - public void test05OverrideModifier515() { - String contractName = "C"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_override002"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_override002"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "7", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(1,infoById.get().getResultValue()); - Assert.assertTrue(infoById.get().getContractResult(0).toStringUtf8().contains("x must >= 6")); - - txid = PublicMethed.triggerContract(contractAddress, "setValue2(uint256)", "6", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "8", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(8, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 public override external function") - public void test06PublicOverrideExternalFunction060() { - String filePath = "./src/test/resources/soliditycode/override005.sol"; - String contractName = "Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "stopped()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i2()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(-32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "ui()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(23487823, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "origin()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - byte[] tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals("TW63BNR5M7LuH1fjXS7Smyza3PZXfHAAs2", - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "b32()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "choice()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000003", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.5.15 public override external function") - public void test07PublicOverrideExternalFunction515() { - String contractName = "Test"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_override003"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_override003"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "stopped()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(0, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "i2()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(-32482989, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "ui()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(23487823, ByteArray.toInt(transactionExtention.getConstantResult(0) - .toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "origin()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - byte[] tmpAddress = new byte[20]; - System - .arraycopy(transactionExtention.getConstantResult(0).toByteArray(), 12, tmpAddress, 0, 20); - Assert.assertEquals("TW63BNR5M7LuH1fjXS7Smyza3PZXfHAAs2", - Base58.encode58Check(ByteArray.fromHexString("41" + ByteArray.toHexString(tmpAddress)))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "b32()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "choice()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000003", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java deleted file mode 100644 index 65785e99283..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/PayableTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class PayableTest { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - String filePath = "src/test/resources/soliditycode/payable001.sol"; - String contractName = "PayableTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "payable(address) transfer") - public void tryCatchTest001() { - - Account account = PublicMethed - .queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull); - Long balanceBefore = account.getBalance(); - - String methodStr = "receiveMoneyTransfer(address,uint256)"; - String argStr = "\"TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Long balanceAfter = PublicMethed.queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull).getBalance(); - Assert.assertEquals(balanceBefore + 3,balanceAfter.longValue()); - } - - @Test(enabled = true, description = "payable(address) send") - public void tryCatchTest002() { - - Account account = PublicMethed - .queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull); - Long balanceBefore = account.getBalance(); - - String methodStr = "receiveMoneySend(address,uint256)"; - String argStr = "\"TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Long balanceAfter = PublicMethed.queryAccount(PublicMethed.decode58Check( - "TBXSw8fM4jpQkGc6zZjsVABFpVN7UvXPdV"), blockingStubFull).getBalance(); - Assert.assertEquals(balanceBefore + 3,balanceAfter.longValue()); - } - - @Test(enabled = true, description = "payable(address(contract)) transfer") - public void tryCatchTest003() { - - String filePath = "src/test/resources/soliditycode/payable001.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] AContract = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Account account = PublicMethed - .queryAccount(AContract, blockingStubFull); - Long balanceBefore = account.getBalance(); - - String methodStr = "receiveMoneyTransferWithContract(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(AContract) + "\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Long balanceAfter = PublicMethed.queryAccount(AContract, blockingStubFull).getBalance(); - Assert.assertEquals(balanceBefore + 3,balanceAfter.longValue()); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java deleted file mode 100644 index d969f7a707e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SelectorTest.java +++ /dev/null @@ -1,104 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class SelectorTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/selector.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - final String aContractAddress = ByteArray.toHexString(contractAddress); - - contractName = "testSelector"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - abi = retMap.get("abI").toString(); - code = retMap.get("byteCode").toString(); - code = PublicMethed.replaceCode(code, aContractAddress.substring(1)); - logger.info("code:" + code); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Get the selector of public or external library functions " - + "through member variables") - public void test01GetSelector() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getselector2()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - logger.info("result: " + ByteArray - .toHexString(transactionExtention.getConstantResult(0).toByteArray())); - Assert.assertEquals("f8b2cb4f", PublicMethed.removeAll0sAtTheEndOfHexStr(ByteArray - .toHexString(transactionExtention.getConstantResult(0).toByteArray()).substring(0, 64))); - Assert.assertEquals("b4cef28d", PublicMethed.removeAll0sAtTheEndOfHexStr(ByteArray - .toHexString(transactionExtention.getConstantResult(0).toByteArray()).substring(64))); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SlotAndOffsetNewGrammer.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SlotAndOffsetNewGrammer.java deleted file mode 100644 index b38ec456fca..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/SlotAndOffsetNewGrammer.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class SlotAndOffsetNewGrammer { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - /** - * trigger contract and assert. - */ - public void assertResult(byte[] contractAddress) { - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, "getA()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - String res = "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000000"; - System.out.println(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(res, - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - - txid = PublicMethed.triggerContract(contractAddress, "getE()", "", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - res = "0000000000000000000000000000000000000000000000000000000000000004" - + "0000000000000000000000000000000000000000000000000000000000000000"; - System.out.println(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(res, - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Deploy 0.6.x new grammer") - public void testSlotAndOffsetOldVersion() { - String contractName = "A"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_slotAndOffset_06x"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_slotAndOffset_06x"); - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - assertResult(contractAddress); - - } - - @Test(enabled = true, description = "Deploy 0.7.0 new grammer") - public void testSlotAndOffsetNew() { - String filePath = "./src/test/resources/soliditycode/slotAndOffsetNewGrammer.sol"; - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - assertResult(contractAddress); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java deleted file mode 100644 index 765fa4c3c99..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/StringSplitTest.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StringSplitTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/stringSplit.sol"; - String contractName = "testStringSplit"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get s1 n1") - public void test01GetS1N1() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS1()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s12,./", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS1N1()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s12,./", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - - @Test(enabled = true, description = "get s2 n2") - public void test01GetS2N2() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS2()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s123?\\'.", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS2N2()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("s123?\'.", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - - @Test(enabled = true, description = "get s3 n3") - public void test01GetS3N3() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS3()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS3N3()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - - @Test(enabled = true, description = "get s4 n4") - public void test01GetS4N4() { - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS4()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "getS4N4()", "#", false, 0, - 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - Assert.assertEquals("AB", - PublicMethed.hexStringToString(PublicMethed.removeAll0sAtTheEndOfHexStr( - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())) - .substring(128))); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/TvmVote.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/TvmVote.java deleted file mode 100644 index 9d450b0392f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/TvmVote.java +++ /dev/null @@ -1,334 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.SmartContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class TvmVote { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final String witnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey); - byte[] mapKeyContract = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - int freezeCount = 100000000; - int voteCount = 1; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 300100_000_000L, - testNetAccountAddress, testNetAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/tvmVote.sol"; - String contractName = "TestVote"; - - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - mapKeyContract = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed.getContract(mapKeyContract, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "query reward balance") - public void test01QueryRewardBalance() { - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryRewardBalance()", "#", true, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - long trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info("result: " + trueRes); - Assert.assertEquals(0, trueRes); - - GrpcAPI.BytesMessage bytesMessage = GrpcAPI.BytesMessage.newBuilder().setValue(ByteString - .copyFrom(mapKeyContract)) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - org.testng.Assert.assertEquals(trueRes, reward); - } - - - @Test(enabled = true, description = "freeze balance and vote witness") - public void test02VoteWitness() { - String methodStr = "freeze(address,uint256,uint256)"; - String receiverAdd = Base58.encode58Check(mapKeyContract); - String args = "\"" + receiverAdd + "\"," + freezeCount + ",1"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, - methodStr, args, false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Protocol.InternalTransaction internal = transactionInfo.get().getInternalTransactions(0); - String note = internal.getNote().toStringUtf8(); - Assert.assertEquals("freezeForEnergy", note); - Assert.assertEquals(freezeCount, internal.getCallValueInfo(0).getCallValue()); - - String witness58Add = Base58.encode58Check(witnessAddress); - args = "[\"" + witness58Add + "\"],[" + voteCount + "]"; - logger.info("vote args: " + args); - methodStr = "voteWitness(address[],uint256[])"; - triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, args, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - internal = transactionInfo.get().getInternalTransactions(0); - note = internal.getNote().toStringUtf8(); - Assert.assertEquals("voteWitness", note); - Assert.assertTrue(internal.getExtra().length() > 1); - - Protocol.Account info = PublicMethed.queryAccount(mapKeyContract, blockingStubFull); - int voteCount = info.getVotesCount(); - logger.info("voteCount: " + voteCount); - Assert.assertEquals(1, voteCount); - } - - @Test(enabled = true, description = "query contract address is Sr Candidate or not") - public void test03IsSrCandidate() { - String args = "\"" + Base58.encode58Check(mapKeyContract) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "isWitness(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(0, 0); - } - - @Test(enabled = true, description = "query sr address is Sr Candidate or not") - public void test04IsSrCandidate() { - String args = "\"" + Base58.encode58Check(witnessAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "isWitness(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(1, 1); - } - - @Test(enabled = true, description = "query zero address is Sr Candidate or not") - public void test05IsSrCandidate() { - String args = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "isWitness(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(0, 0); - } - - @Test(enabled = true, description = "query sr's total vote count") - public void test06querySrTotalVoteCount() { - String args = "\"" + Base58.encode58Check(witnessAddress) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryTotalVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(0, trueRes); - } - - @Test(enabled = true, description = "query contract's total vote count") - public void test07queryContractTotalVoteCount() { - String args = "\"" + Base58.encode58Check(mapKeyContract) + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryTotalVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(freezeCount / 1000000, trueRes); - } - - @Test(enabled = true, description = "query vote count") - public void test08queryVoteCount() { - String from = Base58.encode58Check(mapKeyContract); - String to = Base58.encode58Check(witnessAddress); - String args = "\"" + from + "\",\"" + to + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryVoteCount(address,address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(voteCount, trueRes); - } - - @Test(enabled = true, description = "query contract used vote count") - public void test09queryUsedVoteCount() { - String from = Base58.encode58Check(mapKeyContract); - String args = "\"" + from + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryUsedVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertEquals(voteCount, trueRes); - } - - @Test(enabled = true, description = "query witnesses received vote count") - public void test10queryReceivedVoteCount() { - String witness = Base58.encode58Check(witnessAddress); - String args = "\"" + witness + "\""; - GrpcAPI.TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(mapKeyContract, - "queryReceivedVoteCount(address)", args, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - int trueRes = ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray()); - logger.info(trueRes + ""); - Assert.assertTrue(trueRes > 0); - Optional list = PublicMethed.listWitnesses(blockingStubFull); - long receiveCount = 0; - String temAdd; - for (int i = 0; i < list.get().getWitnessesCount(); i++) { - temAdd = Base58.encode58Check(list.get().getWitnesses(i).getAddress().toByteArray()); - if (witness.equals(temAdd)) { - receiveCount = list.get().getWitnesses(i).getVoteCount(); - break; - } - } - Assert.assertEquals(trueRes, receiveCount); - } - - @Test(enabled = true, description = "withdraw reward") - public void test11WithdrawReward() { - String methodStr = "withdrawReward()"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Protocol.InternalTransaction internal = transactionInfo.get().getInternalTransactions(0); - String note = internal.getNote().toStringUtf8(); - Assert.assertEquals("withdrawReward", note); - Assert.assertEquals(1, internal.getCallValueInfoCount()); - Assert.assertEquals("", internal.getCallValueInfo(0).toString()); - } - - @Test(enabled = true, description = "unfreeze energy") - public void test12Unfreeze() { - String methodStr = "unfreeze(address,uint256)"; - String args = "\"" + Base58.encode58Check(mapKeyContract) + "\",1"; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, args, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - Protocol.InternalTransaction internal = transactionInfo.get().getInternalTransactions(0); - String note = internal.getNote().toStringUtf8(); - Assert.assertEquals("unfreezeForEnergy", note); - Assert.assertEquals(freezeCount, internal.getCallValueInfo(0).getCallValue()); - } - - @Test(enabled = true, description = "kill me") - public void test13Suicide() { - String methodStr = "killme(address)"; - String args = "\"" + Base58.encode58Check(witnessAddress) + "\""; - String triggerTxid = PublicMethed.triggerContract(mapKeyContract, methodStr, args, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional transactionInfo = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(Protocol.Transaction.Result.contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContractOuterClass.SmartContract smartContract = PublicMethed - .getContract(mapKeyContract, blockingStubFull); - Assert.assertEquals("", smartContract.getAbi().toString()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(contractExcAddress, contractExcKey, - testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java deleted file mode 100644 index c23787ffc5a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/VirtualTest001.java +++ /dev/null @@ -1,207 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class VirtualTest001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy 0.5.15 about virtual") - public void test01OverrideContract515() { - String contractName = "Z"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_virtual001"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_virtual001"); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setBool(bool)", "true", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setString(string)", "\"1q2w\"", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "z()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "3171327700000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Deploy 0.6.0 about virtual") - public void test02OverrideContract060() { - String filePath = "./src/test/resources/soliditycode/virtual001.sol"; - String contractName = "Z"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed.getTransactionInfoById(txid, - blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - txid = PublicMethed.triggerContract(contractAddress, "setValue(uint256)", "5", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setBool(bool)", "true", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - txid = PublicMethed.triggerContract(contractAddress, "setString(string)", "\"1q2w\"", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "x()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(5, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "y()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals(1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "z()", "#", - false, 0, 0, "0", 0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals("SUCCESS", transactionExtention.getResult().getCode().toString()); - Assert - .assertEquals("0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000004" - + "3171327700000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionExtention.getConstantResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java deleted file mode 100644 index c462d208263..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/assemblyTest.java +++ /dev/null @@ -1,118 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class assemblyTest { - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/assemblyTest.sol"; - String contractName = "assemblyTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get assembly references fuction number, type: uint") - public void test01AssemblyReferencesUint() { - String methodStr = "getZuint()"; - String argStr = ""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit,"0",0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals(1,ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - methodStr = "getZuint2()"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - int ContractResult = ByteArray.toInt(infoById.get() - .getContractResult(0).toByteArray()); - Assert.assertEquals(1,ContractResult); - - - } - - @Test(enabled = true, description = "get assembly references fuction number, type: boolen") - public void test02AssemblyReferencesBoolen() { - String methodStr = "getZbool()"; - String argStr = ""; - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit,"0",0, dev001Address, dev001Key, blockingStubFull); - Assert.assertEquals(1,ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - - methodStr = "getZbool2()"; - String txid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0,infoById.get().getResultValue()); - int ContractResult = ByteArray.toInt(infoById.get() - .getContractResult(0).toByteArray()); - Assert.assertEquals(1,ContractResult); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/calldataTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/calldataTest.java deleted file mode 100644 index d11e2338ddc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/calldataTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class calldataTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/calldata.sol"; - String contractName = "C"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/constructorDefaultsTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/constructorDefaultsTest.java deleted file mode 100644 index 093e4a38324..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/constructorDefaultsTest.java +++ /dev/null @@ -1,105 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class constructorDefaultsTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(dev001Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Constructor default test") - public void Test01ConstructorDefault() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 200000000L, fromAddress, testKey002, blockingStubFull)); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - String filePath = "./src/test/resources/soliditycode/ConstructorDefaults.sol"; - String contractName = "testIsContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(bool)"; - String data = "0"; - String txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - byte[] contractaddress = null; - Optional info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(info.toString()); - Assert.assertTrue(info.get().getResultValue() == 0); - data = "false"; - txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(info.toString()); - Assert.assertTrue(info.get().getResultValue() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java deleted file mode 100644 index 4230379af5a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/enumAndStructTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class enumAndStructTest { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - String filePath = "src/test/resources/soliditycode/enumAndStruct.sol"; - String contractName = "enumAndStructTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "get Enum and Struct") - public void EnumAndStructTest001() { - - - String methodStr = "getvalue()"; - String argStr = ""; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testFoundationAddress, testFoundationKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals(1, - ByteArray.toInt(transactionInfo.get().getContractResult(0).toByteArray())); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java deleted file mode 100644 index bfa8ebf1561..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackOldVersion.java +++ /dev/null @@ -1,156 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class fallbackOldVersion { - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddressCall = null; - byte[] contractAddressTest0 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_fallbackOldVersionTest"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_fallbackOldVersionTest"); - String contractName = "Test0"; - contractAddressTest0 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_fallbackOldversionCall"); - code = Configuration.getByPath("testng.conf") - .getString("code.code_fallbackOldVersionCall"); - contractName = "Call"; - contractAddressCall = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "test fallback") - public void test01FallbakTest() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance:" + beforeBalance); - String txid = ""; - String method = "call(address)"; - long value = 10000; - String para = "\"" + Base58.encode58Check(contractAddressTest0) + "\""; - txid = PublicMethed.triggerContract(contractAddressCall, method, para, false, value, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - logger.info("fee:" + fee); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - logger.info("afterBalance:" + afterBalance); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee + value == beforeBalance); - - txid = PublicMethed.triggerContract(contractAddressCall, method, para, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - //@AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddressCall, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTest0, contractExcKey, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java deleted file mode 100644 index 63bd60a0d1c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/fallbackReceive.java +++ /dev/null @@ -1,376 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class fallbackReceive { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddressCaller = null; - byte[] contractAddressTest0 = null; - byte[] contractAddressTest1 = null; - byte[] contractAddressTest2 = null; - byte[] contractAddressTestPayable = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/fallbackUpgrade.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddressCaller = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, - null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "Test0"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTest0 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "Test1"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTest1 = PublicMethed - .deployContractFallback(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "Test2"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTest2 = PublicMethed - .deployContractFallback(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - contractName = "TestPayable"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddressTestPayable = PublicMethed - .deployContractFallback(contractName, abi, code, "", maxFeeLimit, 0L, - 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "contract test0 has no fallback method") - public void test001NoFallback() { - String txid = ""; - String method = "hello()"; - txid = PublicMethed.triggerContract(contractAddressTest0, - method, "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - } - - @Test(enabled = true, description = "contract test0 has no fallback method") - public void test002NoFallback() { - String txid = ""; - String method = "callTest0(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest0) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - } - - @Test(enabled = true, description = "contract test01 has fallback method") - public void test011Fallback() { - String txid = ""; - String method = "callTest1(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest1) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - List logList = infoById.get().getLogList(); - if (!Objects.isNull(logList)) { - for (Protocol.TransactionInfo.Log log : logList) { - //logger.info("LOG data info:" + tmp); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(log.getData().toByteArray())); - } - } - } - - @Test(enabled = true, description = "contract test01 has fallback method") - public void test012Fallback() { - String txid = ""; - String method = "callTest2(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest1) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("REVERT", infoById.get().getReceipt().getResult().toString()); - } - - @Test(enabled = true, description = "contract test01 has fallback method") - public void test013Fallback() { - String txid = ""; - txid = PublicMethed.triggerContract(contractAddressTest1, - "hello()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - - txid = PublicMethed.triggerContract(contractAddressTest1, - "hello2()", "#", false, - 100000, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("result:" + infoById.get().getReceipt().getResult()); - Assert.assertEquals("REVERT", infoById.get().getReceipt().getResult().toString()); - } - - @Test(enabled = true, description = "contract test02 has fallback payable method") - public void test021FallbackPayable() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance:" + beforeBalance); - String txid = ""; - long value = 10000; - txid = PublicMethed.triggerContract(contractAddressTest2, "hello()", "#", false, value, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("result:" + infoById.get().getReceipt().getResult()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Long fee = infoById.get().getFee(); - logger.info("fee:" + fee); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - logger.info("afterBalance:" + afterBalance); - Assert.assertTrue(afterBalance + fee + value == beforeBalance); - - String method = "callTest2(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTest2) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, method, para, false, value, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("callTest2 result:" + infoById.get().getReceipt().getResult()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - fee = infoById.get().getFee(); - logger.info("callTest2 fee:" + fee); - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance2 = infoafter.getBalance(); - logger.info("callTest2 afterBalance:" + afterBalance); - Assert.assertTrue(afterBalance2 + fee + value == afterBalance); - } - - @Test(enabled = true, description = "contract TestPayable has fallback and receive") - public void test041FallbackReceive() { - String txid = ""; - String method = "callTestPayable1(address)"; - String para = "\"" + Base58.encode58Check(contractAddressTestPayable) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("getResult: " + infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - Assert.assertEquals("receive", - PublicMethed.getContractStringMsg(infoById.get().getLog(1).getData().toByteArray())); - } - - @Test(enabled = true, description = "contract TestPayable has fallback and receive") - public void test042FallbackReceive() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - String txid = ""; - Long beforeBalance = info.getBalance(); - logger.info("beforeBalance:" + beforeBalance); - String method = "callTest2(address)"; - long value = 10000; - String para = "\"" + Base58.encode58Check(contractAddressTestPayable) + "\""; - txid = PublicMethed.triggerContract(contractAddressCaller, - method, para, false, - value, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - - Long fee = infoById.get().getFee(); - logger.info("fee:" + fee); - Protocol.Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - logger.info("afterBalance:" + afterBalance); - Assert.assertTrue(afterBalance + fee + value == beforeBalance); - } - - @Test(enabled = true, description = "contract TestPayable has fallback and receive") - public void test05FallbackReceive() { - String txid = ""; - long value = 10000; - txid = PublicMethed.triggerContract(contractAddressTestPayable, - "method()", "#", false, - value, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("fallback", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - - Protocol.Account infoafter = PublicMethed - .queryAccount(contractAddressTestPayable, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractAddressTestPayable, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - logger.info("contract balance:" + afterBalance.longValue()); - Assert.assertEquals(11000, afterBalance.longValue()); - - txid = PublicMethed.triggerContract(contractAddressTestPayable, - "#", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.get().getResult().toString()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals("receive", - PublicMethed.getContractStringMsg(infoById.get().getLog(0).getData().toByteArray())); - - } - - //@AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddressTest0, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTest1, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTest2, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressTestPayable, contractExcKey, testNetAccountAddress, - blockingStubFull); - PublicMethed - .freedResource(contractAddressCaller, contractExcKey, testNetAccountAddress, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/mappingGetterTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/mappingGetterTest.java deleted file mode 100644 index c1bb682a801..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/mappingGetterTest.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class mappingGetterTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/mappingGetter.sol"; - String contractName = "mappingGetter"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java deleted file mode 100644 index 82ff090f2e2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/stateVariableShadowing.java +++ /dev/null @@ -1,140 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class stateVariableShadowing { - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed - .sendcoin(contractExcAddress, 1000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/stateVariableShadowing.sol"; - String contractName = "stateVariableShadowing"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Verify that the compilation is successful") - public void test01VerifyCompile() { - Protocol.Account info; - GrpcAPI.AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - ArrayList methods = new ArrayList(); - methods.add("setValue2(uint256)"); - methods.add("setValue3(uint256)"); - for (String tmp : methods) { - System.out.println(tmp); - txid = PublicMethed.triggerContract(contractAddress, - tmp, "100", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(100, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - } - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/typeNameTest.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/typeNameTest.java deleted file mode 100644 index 57aca964fad..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/newGrammar/typeNameTest.java +++ /dev/null @@ -1,174 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.newGrammar; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class typeNameTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy contract") - public void test01DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/typeName.sol"; - String contractName = "TypeName"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Key, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - - @Test(enabled = true, description = "Trigger testTypeName function") - public void test02TriggerTestTypeNameFunction() { - final String txid = PublicMethed.triggerContract(contractAddress, - "testTypeName()", "#", false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("infoById:" + infoById.get()); - Assert.assertTrue(infoById.get().getContractResult(0).toStringUtf8() - .contains("TypeName")); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - PublicMethed.sendcoin(fromAddress, balance, dev001Address, dev001Key, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand001.java deleted file mode 100644 index 11ebe1e45ea..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand001.java +++ /dev/null @@ -1,253 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = true, description = "Trigger old ShiftLeft ShiftRight") - public void test1OldInstruction() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TvmOldCommand001.sol"; - String contractName = "binaryRightContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed.triggerContract(contractAddress, - "binaryMoveR(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed.triggerContract(contractAddress, - "binaryLiftR(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - - } - - @Test(enabled = true, description = "Trigger new ShiftLeft ShiftRight ShiftRightSigned") - public void test2NewInstruction() { - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1" + "," + "5"; - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(10, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(2, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand002.java deleted file mode 100644 index 03e15dce8ce..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand002.java +++ /dev/null @@ -1,265 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = true, description = "OLd compiler compile shift instruction") - public void test1Oldcompile() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "TestBitwiseShift"; - String code = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a5" - + "7600080fd5b506101478061003a6000396000f3006080604052600436106100565763ffffffff7c0100" - + "000000000000000000000000000000000000000000000000000000600035041663614eb4da811461005" - + "b578063b5675d6d146100a2578063baf27c0c146100d7575b600080fd5b34801561006757600080fd5b" - + "50d3801561007457600080fd5b50d2801561008157600080fd5b5061009060043560243561010c565b6" - + "0408051918252519081900360200190f35b3480156100ae57600080fd5b50d380156100bb57600080fd" - + "5b50d280156100c857600080fd5b50610090600435602435610111565b3480156100e357600080fd5b5" - + "0d380156100f057600080fd5b50d280156100fd57600080fd5b50610090600435602435610116565b90" - + "1b90565b901d90565b901c905600a165627a7a723058200d5cc53ffdc6db62c4d7414d8b7d95c98218e" - + "50b4c1ea5961d527de1439733450029"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"num\",\"type\":\"uint256\"}," - + "{\"name\":\"input\",\"type\":\"uint256\"}],\"name\":\"shlTest\",\"outputs\":" - + "[{\"name\":\"out\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":" - + "\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":" - + "\"num\",\"type\":\"uint256\"},{\"name\":\"input\",\"type\":\"uint256\"}],\"name" - + "\":\"sarTest\",\"outputs\":[{\"name\":\"out\",\"type\":\"bytes32\"}],\"payable" - + "\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant" - + "\":false,\"inputs\":[{\"name\":\"num\",\"type\":\"uint256\"},{\"name\":\"input\"" - + ",\"type\":\"uint256\"}],\"name\":\"shrTest\",\"outputs\":[{\"name\":\"out\",\"" - + "type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"" - + "type\":\"function\"}]"; - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1" + "," + "5"; - - txid = PublicMethed - .triggerContract(contractAddress, "sarTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed - .triggerContract(contractAddress, "shlTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - txid = PublicMethed - .triggerContract(contractAddress, "shrTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - @Test(enabled = true, description = "New compiler compile shift instruction") - public void test2Newcompile() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1" + "," + "5"; - - txid = PublicMethed - .triggerContract(contractAddress, "sarTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - txid = PublicMethed - .triggerContract(contractAddress, "shlTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - txid = PublicMethed - .triggerContract(contractAddress, "shrTest(uint256,uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand003.java deleted file mode 100644 index 66da905e03e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand003.java +++ /dev/null @@ -1,332 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft with displacement number too short ") - public void test1ShiftLeft() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - logger.info("param:" + param); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0001fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRight with displacement number too short ") - public void test2ShiftRight() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - logger.info("param:" + param); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("00007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned " - + "with displacement number too short ") - public void test3ShiftRightSigned() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - logger.info("param:" + param); - String txid = ""; - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("00007fffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand004.java deleted file mode 100644 index b382ae75a56..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand004.java +++ /dev/null @@ -1,1040 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x00") - public void test1ShiftLeft() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x01") - public void test2ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x01")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000002")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0xff") - public void test3ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x0100") - public void test4ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x0101") - public void test5ShiftLeft() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x00") - public void test6ShiftLeft() { - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void test7ShiftLeft() { - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void test8ShiftLeft() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xff")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void test9ShiftLeft() { - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void testShiftLeft10() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void testShiftLeft11() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftLeft,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftLeft12() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shlTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand005.java deleted file mode 100644 index 8030a54490f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand005.java +++ /dev/null @@ -1,1049 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x00") - public void test1ShiftRight() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x01") - public void test2ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void test3ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - String originNumber = String.valueOf(ByteArray.toLong(ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000"))); - String valueNumber = String.valueOf(ByteArray.toLong((ByteArray - .fromHexString("0x01")))); - String num = valueNumber + "," + originNumber; - - logger.info("returnnumber:" + originNumber); - logger.info("returnnumber1:" + valueNumber); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x4000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0xff") - public void test4ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0100") - public void test5ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0101") - public void test6ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x00") - public void test7ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void test8ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void test9ShiftRight() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xff")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void testShiftRight10() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void testShiftRight11() { - - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRight,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftRight12() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "shrTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand006.java deleted file mode 100644 index 1991fc5a52f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/shiftcommand/ShiftCommand006.java +++ /dev/null @@ -1,1539 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.shiftcommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.DataWord; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ShiftCommand006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x00") - public void test1ShiftRightSigned() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ShiftCommand001.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x00")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000001 and Displacement number" - + "is 0x01") - public void test2ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void test3ShiftRightSigned() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x01")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xc000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0xff") - public void test4ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0100") - public void test5ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x8000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x0101") - public void test6ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x8000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x00") - public void test7ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x00")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x01") - public void test8ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x01")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void test9ShiftRightSigned() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xff")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void testShiftRightSigned10() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x0100")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x0000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0x01") - public void testShiftRightSigned11() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x01")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x4000000000000000000000000000000000000000000000000000000000000000 and Displacement number" - + "is 0xfe") - public void testShiftRightSigned12() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x4000000000000000000000000000000000000000000000000000000000000000")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xfe")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xf8") - public void testShiftRightSigned13() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0xf8")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x000000000000000000000000000000000000000000000000000000000000007f")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xfe") - public void testShiftRightSigned14() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xfe")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0xff") - public void testShiftRightSigned15() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0xff")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0100") - public void testShiftRightSigned16() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0100")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(uint256,uint256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftRightSigned17() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray - .fromHexString("0x0101")) - .getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - String param = Hex.toHexString(paramBytes); - - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber14 = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - @Test(enabled = true, description = "Trigger new ShiftRightSigned,value is " - + "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff and Displacement number" - + "is 0x0101") - public void testShiftRightSigned18() { - - String filePath = "src/test/resources/soliditycode/TvmNewCommand043.sol"; - String contractName = "TestBitwiseShift"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - byte[] originNumber = new DataWord( - ByteArray - .fromHexString("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")) - .getData(); - byte[] valueNumber = new DataWord( - ByteArray.fromHexString("0x0101")).getData(); - byte[] paramBytes = new byte[originNumber.length + valueNumber.length]; - System.arraycopy(valueNumber, 0, paramBytes, 0, valueNumber.length); - System.arraycopy(originNumber, 0, paramBytes, valueNumber.length, originNumber.length); - - String param = Hex.toHexString(paramBytes); - txid = PublicMethed.triggerContract(contractAddress, - "sarTest(int256,int256)", param, true, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - String returnString = (ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray())); - logger.info("returnString:" + returnString); - Assert.assertEquals(ByteArray.toLong(ByteArray - .fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000")), - ByteArray.toLong(ByteArray - .fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java deleted file mode 100644 index a0b1f62289f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/ContractTestSendCoin001.java +++ /dev/null @@ -1,624 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import static org.hamcrest.core.StringContains.containsString; -import static org.tron.api.GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR; -import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS_VALUE; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractTestSendCoin001 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 1000L; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] transferTokenContractAddress = null; - - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Sendcoin and transferAsset to contractAddresss ," - + "then selfdestruct") - public void testSendCoinAndTransferAssetContract001() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(dev001Address, dev001Key, 130000L, blockingStubFull), 0, - 1, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 10_000_000L, 0, 0, - ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed - .createAssetIssue(dev001Address, tokenName, TotalSupply, 1, 10000, start, end, 1, - description, url, 100000L, 100000L, 1L, 1L, dev001Key, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "src/test/resources/soliditycode/contractTrcToken031.sol"; - String contractName = "token"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 100; - long callValue = 5; - - final String deployContractTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployContractTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - if (deployContractTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(transferTokenContractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - Return ret = PublicMethed - .transferAssetForReturn(transferTokenContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - Long contractAssetCount = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(tokenValue), contractAssetCount); - - Return ret1 = PublicMethed - .sendcoinForReturn(transferTokenContractAddress, 1_000_000L, fromAddress, testKey002, - blockingStubFull); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer TRX to a smartContract.", - ret1.getMessage().toStringUtf8()); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - String txid = PublicMethed - .triggerContract(transferTokenContractAddress, "kill(address)", num, false, 0, maxFeeLimit, - dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long contractAssetCountBefore = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - long contractBefore = PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull) - .getBalance(); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Assert.assertTrue(PublicMethed - .transferAsset(transferTokenContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .sendcoin(transferTokenContractAddress, 1_000_000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAssetCountAfter = PublicMethed - .getAssetIssueValue(transferTokenContractAddress, assetAccountId, blockingStubFull); - long contractAfetr = PublicMethed.queryAccount(transferTokenContractAddress, blockingStubFull) - .getBalance(); - - Assert.assertTrue(contractAssetCountBefore + 100L == contractAssetCountAfter); - Assert.assertTrue(contractBefore + 1_000_000L == contractAfetr); - - } - - - @Test(enabled = true, description = "Use create to generate a contract address " - + "Sendcoin and transferAsset to contractAddresss ,then selfdestruct,") - public void testSendCoinAndTransferAssetContract002() { - - assetAccountId = PublicMethed.queryAccount(dev001Address, blockingStubFull).getAssetIssuedID(); - - logger.info("The token name: " + tokenName); - logger.info("The token ID: " + assetAccountId.toStringUtf8()); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountBefore = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - logger.info("before AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountBefore: " - + devAssetCountBefore); - - String filePath = "src/test/resources/soliditycode/contractTransferToken001.sol"; - - String contractName = "A"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String tokenId = assetAccountId.toStringUtf8(); - long tokenValue = 100; - long callValue = 5; - - final String deployContractTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callValue, 0, 10000, tokenId, tokenValue, null, dev001Key, dev001Address, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployContractTxid, blockingStubFull); - - transferTokenContractAddress = infoById.get().getContractAddress().toByteArray(); - - accountResource = PublicMethed.getAccountResource(dev001Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - Long devAssetCountAfter = PublicMethed - .getAssetIssueValue(dev001Address, assetAccountId, blockingStubFull); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - logger.info("after AssetId: " + assetAccountId.toStringUtf8() + ", devAssetCountAfter: " - + devAssetCountAfter); - - String txid = PublicMethed - .triggerContract(transferTokenContractAddress, "newB()", "#", false, 0, maxFeeLimit, - dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - byte[] a = infoById.get().getContractResult(0).toByteArray(); - byte[] b = subByte(a, 11, 1); - byte[] c = subByte(a, 0, 11); - byte[] e = "41".getBytes(); - byte[] d = subByte(a, 12, 20); - - logger.info("a:" + ByteArray.toHexString(a)); - - logger.info("b:" + ByteArray.toHexString(b)); - logger.info("c:" + ByteArray.toHexString(c)); - - logger.info("d:" + ByteArray.toHexString(d)); - - logger.info("41" + ByteArray.toHexString(d)); - String exceptedResult = "41" + ByteArray.toHexString(d); - String realResult = ByteArray.toHexString(b); - Assert.assertEquals(realResult, "00"); - Assert.assertNotEquals(realResult, "41"); - - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(exceptedResult)); - logger.info("create Address : " + addressFinal); - byte[] testContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - Return ret = PublicMethed - .transferAssetForReturn(testContractAddress, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - Long contractAssetCount = PublicMethed - .getAssetIssueValue(testContractAddress, assetAccountId, blockingStubFull); - logger.info("Contract has AssetId: " + assetAccountId.toStringUtf8() + ", Count: " - + contractAssetCount); - - Assert.assertEquals(Long.valueOf(0L), contractAssetCount); - - Return ret1 = PublicMethed - .sendcoinForReturn(testContractAddress, 1_000_000L, fromAddress, testKey002, - blockingStubFull); - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer TRX to a smartContract.", - ret1.getMessage().toStringUtf8()); - - String num = "\"" + Base58.encode58Check(dev001Address) + "\""; - - txid = PublicMethed - .triggerContract(testContractAddress, "kill(address)", num, false, 0, maxFeeLimit, - dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long contractAssetCountBefore = PublicMethed - .getAssetIssueValue(testContractAddress, assetAccountId, blockingStubFull); - long contractBefore = PublicMethed.queryAccount(testContractAddress, blockingStubFull) - .getBalance(); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - Assert.assertTrue(PublicMethed - .transferAsset(testContractAddress, assetAccountId.toByteArray(), 100L, dev001Address, - dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .sendcoin(testContractAddress, 1_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAssetCountAfter = PublicMethed - .getAssetIssueValue(testContractAddress, assetAccountId, blockingStubFull); - long contractAfetr = PublicMethed.queryAccount(testContractAddress, blockingStubFull) - .getBalance(); - - Assert.assertTrue(contractAssetCountBefore + 100L == contractAssetCountAfter); - Assert.assertTrue(contractBefore + 1_000_000L == contractAfetr); - } - - - @Test(enabled = true, description = "Use create2 to generate a contract address " - + "Sendcoin and transferAsset to contractAddresss ,then selfdestruct") - public void testSendCoinAndTransferAssetContract003() { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String sendcoin = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 1000000000L, fromAddress, testKey002, - blockingStubFull); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById0 = null; - infoById0 = PublicMethed.getTransactionInfoById(sendcoin, blockingStubFull); - logger.info("infoById0 " + infoById0.get()); - Assert.assertEquals(ByteArray.toHexString(infoById0.get().getContractResult(0).toByteArray()), - ""); - Assert.assertEquals(infoById0.get().getResult().getNumber(), 0); - Optional ById = PublicMethed.getTransactionById(sendcoin, blockingStubFull); - Assert.assertEquals(ById.get().getRet(0).getContractRet().getNumber(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRetValue(), SUCCESS_VALUE); - Assert.assertEquals(ById.get().getRet(0).getContractRet(), contractResult.SUCCESS); - String filePath = "src/test/resources/soliditycode/create2contractn2.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", num, false, 0, maxFeeLimit, "0", - 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - - Return ret = PublicMethed - .transferAssetForReturn(returnAddressBytes, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - - Return ret1 = PublicMethed - .transferAssetForReturn(returnAddressBytes, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret1.getMessage().toStringUtf8()); - - txid = PublicMethed - .triggerContract(returnAddressBytes, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - txid = PublicMethed - .triggerContract(returnAddressBytes, "set()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - txid = PublicMethed - .triggerContract(returnAddressBytes, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(5 == returnnumber); - - String param1 = "\"" + Base58.encode58Check(returnAddressBytes) + "\""; - - txid = PublicMethed - .triggerContract(returnAddressBytes, "testSuicideNonexistentTarget(address)", param1, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById2 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals("suicide", - ByteArray.toStr(infoById2.get().getInternalTransactions(0).getNote().toByteArray())); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(returnAddressBytes, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_VALIDATE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Contract validate error : No contract or not a valid smart contract")); - - Assert.assertTrue(PublicMethed - .transferAsset(returnAddressBytes, assetAccountId.toByteArray(), 100L, dev001Address, - dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed - .sendcoin(returnAddressBytes, 1_000_000L, fromAddress, testKey002, blockingStubFull)); - - txid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", num, false, 0, maxFeeLimit, "0", - 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById3 = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - byte[] returnAddressBytes1 = infoById3.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress1 = Base58.encode58Check(returnAddressBytes1); - Assert.assertEquals(returnAddress1, returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes1, "i()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - ret = PublicMethed - .transferAssetForReturn(returnAddressBytes1, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret.getMessage().toStringUtf8()); - - ret1 = PublicMethed - .transferAssetForReturn(returnAddressBytes1, assetAccountId.toByteArray(), 100L, - dev001Address, dev001Key, blockingStubFull); - - Assert.assertEquals(CONTRACT_VALIDATE_ERROR, ret1.getCode()); - Assert.assertEquals("Contract validate error : Cannot transfer asset to smartContract.", - ret1.getMessage().toStringUtf8()); - - } - - - public byte[] subByte(byte[] b, int off, int length) { - byte[] b1 = new byte[length]; - System.arraycopy(b, off, b1, 0, length); - return b1; - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TestResourceReceiver.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TestResourceReceiver.java deleted file mode 100644 index 518e49aad24..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TestResourceReceiver.java +++ /dev/null @@ -1,189 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestResourceReceiver { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = false, description = "Suicide existent Target") - public void test1SuicideExistentTarget() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 3000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(testNetAccountAddress, - 1000000, 0, 1, - ByteString.copyFrom(contractAddress), testNetAccountKey, blockingStubFull)); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] existentAddress = ecKey2.getAddress(); - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Account contractafter = PublicMethed.queryAccount(contractAddress, blockingStubFull1); - long contractBalance = contractafter.getBalance(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(contractBalance, 0); - txid = PublicMethed.triggerContract(contractAddress, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Assert.assertNull(txid); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - PublicMethed.unFreezeBalance(testNetAccountAddress, testNetAccountKey, 1, - contractAddress, blockingStubFull); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed001.java deleted file mode 100644 index cd62ed8edb6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed001.java +++ /dev/null @@ -1,920 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import static org.tron.protos.Protocol.TransactionInfo.code.FAILED; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.vm.EnergyCost; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Transfer trx insufficient balance") - public void test001TransferTrxInsufficientBalance() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 2000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "2000001"; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxInsufficientBalance(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Transfer balance enough") - public void test002TransferEnough() { - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 3000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxInsufficientBalance(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - logger.info("infoById" + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee - 1 == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - - @Test(enabled = true, description = "Transfer trx nonexistent target") - public void test003TransferTrxNonexistentTarget() { - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(1, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(2, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertEquals(energyUsageTotal2 + EnergyCost.getNewAcctCall(), - energyUsageTotal); - - } - - - @Test(enabled = true, description = "Transfer trx to myself") - public void test004TransferTrxSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxSelf(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult()); - Assert.assertEquals("transfer trx failed: Cannot transfer TRX to yourself.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Transfer trx nonexistent target and insufficient balance") - public void test005TransferTrxNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "10000000" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull1); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Transfer trx to myself and insufficient balance") - public void test006TransferTrxSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - String txid = ""; - String num = "1000000000"; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxSelf(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - @Test(enabled = true, description = "PreCompiled transfertoken with value," - + " long.max < value or long.min > value") - public void test007TransferTrckenPreCompiled() { - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = ""; - String num = "1"; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenCompiledLongMax1()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - beforeBalance = info.getBalance(); - beforeEnergyUsed = resourceInfo.getEnergyUsed(); - beforeNetUsed = resourceInfo.getNetUsed(); - beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenCompiledLongMin1()", "#", false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - beforeBalance = info.getBalance(); - beforeEnergyUsed = resourceInfo.getEnergyUsed(); - beforeNetUsed = resourceInfo.getNetUsed(); - beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertEquals(FAILED, infoById.get().getResult()); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals("REVERT opcode executed", infoById.get().getResMessage().toStringUtf8()); - - } - - @Test(enabled = false, description = "PreCompiled tokenbalance") - public void test008TransferTrctoken() { - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ByteString assetAccountId = null; - final long TotalSupply = 10000000L; - long now = System.currentTimeMillis(); - String tokenName = "testAssetIssue_" + Long.toString(now); - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.transferAsset(contractAddress, - assetAccountId.toByteArray(), 100L, contractExcAddress, contractExcKey, - blockingStubFull)); - - Long returnAddressBytesAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("returnAddressBytesAccountCountBefore : " + returnAddressBytesAccountCountBefore); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = - "\"" + Base58.encode58Check(contractAddress) + "\"," + "\"" + assetAccountId.toStringUtf8() - + "\""; - //String num = "\""+Base58.encode58Check(contractAddress) +"\","+ "\"" + -1 + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenTest(address,uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals(100, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - - } - - @Test(enabled = true, description = "PreCompiled address(0x1) query tokenbalance") - public void test009TransferTrctoken() { - //address: 410000000000000000000000000000000000000001 - String addressx = "T9yD14Nj9j7xAB4dbGeiX9h8unkKLxmGkn"; - byte[] addressxx = WalletClient.decodeFromBase58Check(addressx); - - Assert.assertTrue(PublicMethed - .sendcoin(addressxx, 1000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - - ByteString assetAccountId = null; - final long TotalSupply = 10000000L; - long now = System.currentTimeMillis(); - String tokenName = "testAssetIssue_" + Long.toString(now); - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - - Assert.assertTrue(PublicMethed.transferAsset(addressxx, - assetAccountId.toByteArray(), 100L, contractExcAddress, contractExcKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long returnAddressBytesAccountCountBefore = PublicMethed - .getAssetIssueValue(addressxx, assetAccountId, blockingStubFull); - logger.info("returnAddressBytesAccountCountBefore : " + returnAddressBytesAccountCountBefore); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - //String num = "\""+Base58.encode58Check(contractAddress) - // +"\","+ "\"" + assetAccountId.toStringUtf8() + "\""; - String num = "\"" + assetAccountId.toStringUtf8() + "\""; - //String num = "\""+Base58.encode58Check(contractAddress) +"\","+ "\"" + -1 + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenCompiledTokenId(uint256)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(energyUsageTotal < maxFeeLimit / 10); - Assert.assertEquals(100, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "transferTrx to nonexistent target ,but revert") - public void test010TransferRevert() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTrxrevert(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(1, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal > EnergyCost.getNewAcctCall()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed002.java deleted file mode 100644 index f3691a62b15..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed002.java +++ /dev/null @@ -1,582 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.vm.EnergyCost; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "Send balance not enough") - public void test1SendNotEnough() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 3000000L, 100, null, - contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "3000001"; - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxInsufficientBalance(uint256)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - @Test(enabled = true, description = "Send balance enough") - public void test2SendEnough() { - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 3000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxInsufficientBalance(uint256)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee - 1 == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - } - - - @Test(enabled = true, description = "Send trx nonexistent target") - public void test3SendTrxNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(1, nonexistentAddressAccount.getBalance()); - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertNotEquals(energyUsageTotal2, - energyUsageTotal + EnergyCost.getNewAcctCall()); - - nonexistentAddressAccount = PublicMethed.queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(2, nonexistentAddressAccount.getBalance()); - - } - - - @Test(enabled = true, description = "Send trx self") - public void test4SendTrxSelf() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - String num = "1"; - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxSelf(uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult()); - Assert.assertEquals("transfer trx failed: Cannot transfer TRX to yourself.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "Send trx nonexistent target and balance not enough") - public void test5SendTrxNonexistentTarget() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - - String num = "100000000" + ",\"" + Base58.encode58Check(contractExcAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxNonexistentTarget(uint256,address)", num, - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - } - - - @Test(enabled = true, description = "Send trx self and balance not enough") - public void test6SendTrxSelf() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - String txid = ""; - - String num = "1000000000"; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxSelf(uint256)", num, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - @Test(enabled = true, description = "Send trx nonexistent target, but revert") - public void test7SendTrxNonexistentTargetRevert() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed - .triggerContract(contractAddress, "testSendTrxRevert(uint256,address)", num, false, 0, - maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0, nonexistentAddressAccount.getBalance()); - Assert.assertEquals(1, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal > EnergyCost.getNewAcctCall()); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed003.java deleted file mode 100644 index 5aa9255e54a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed003.java +++ /dev/null @@ -1,817 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.vm.EnergyCost; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed003 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - - @Test(enabled = true, description = "TransferToken enough tokenBalance") - public void test1TransferTokenEnough() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 100L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Assert.assertTrue(PublicMethed.transferAsset(contractAddress, - // assetAccountId.toByteArray(), 100L, contractExcAddress, contractExcKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenInsufficientBalance(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(testNetAccountCountBefore + 1 == testNetAccountCountAfter); - Assert.assertTrue(contractAccountCountBefore - 1 == contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - @Test(enabled = true, description = "TransferToken insufficient tokenBalance") - public void test2TransferTokenNotEnough() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1000" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenInsufficientBalance(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - logger.info("infoById:" + infoById); - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - } - - - @Test(enabled = true, description = "TransferToken to nonexistent target") - public void test3TransferTokenNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String num = - "\"1" + "\",\"" + Base58.encode58Check(nonexistentAddress) + "\",\"" + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 1, contractAccountCountAfter.longValue()); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.longValue()); - - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - - infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - afterBalance = infoafter.getBalance(); - afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - afterNetUsed = resourceInfoafter.getNetUsed(); - afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 2, contractAccountCountAfter.longValue()); - - Assert.assertEquals(energyUsageTotal, - energyUsageTotal2 + EnergyCost.getNewAcctCall()); - - nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(2L, nonexistentAddressAccount.longValue()); - } - - - @Test(enabled = true, description = "TransferToken to myself") - public void test4TransferTokenSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenSelf(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.TRANSFER_FAILED, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "transfer trc10 failed: Cannot transfer asset to yourself.", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - - } - - - @Test(enabled = true, description = "TransferToken notexist tokenID ") - public void test5TransferTokenNotexist() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String fakeassetAccountId = Long.toString(0L); - - String num = "1" + ",\"" + fakeassetAccountId + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenInsufficientBalance(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - - } - - - @Test(enabled = true, description = "TransferToken to nonexistent target and " - + "insufficient tokenBalance") - public void test7TransferTokenNonexistentTarget() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String num = - "\"100000000000" + "\",\"" + Base58.encode58Check(nonexistentAddress) + "\",\"" - + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertEquals(afterBalance + fee, beforeBalance.longValue()); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccount.longValue()); - - - } - - - @Test(enabled = true, description = "TransferToken to myself and insufficient tokenBalance") - public void test8TransferTokenSelf() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "1000000000000000" + ",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenSelf(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertTrue(infoById.get().getResultValue() == 1); - Assert.assertEquals(contractResult.REVERT, infoById.get().getReceipt().getResult()); - Assert.assertEquals( - "REVERT opcode executed", - ByteArray.toStr(infoById.get().getResMessage().toByteArray())); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - - Assert.assertNotEquals(10000000, energyUsageTotal); - - } - - @Test(enabled = true, description = "TransferToken to nonexistent target, but revert") - public void test9TransferTokenNonexistentTargetRevert() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - String num = - "\"1" + "\",\"" + Base58.encode58Check(nonexistentAddress) + "\",\"" + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testTransferTokenRevert(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(1, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore, contractAccountCountAfter); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal > EnergyCost.getNewAcctCall()); - - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccount.longValue()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed004.java deleted file mode 100644 index 9c9fea1af32..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed004.java +++ /dev/null @@ -1,576 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] contractAddress2 = null; - byte[] contractAddress3 = null; - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static ByteString assetAccountId2 = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress3 = ecKey3.getAddress(); - String contractExcKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - long energyUsageTotal = 0; - long energyUsageTotal2 = 0; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - - } - - @Test(enabled = true, description = "Suicide nonexistent target") - public void test1SuicideNonexistentTarget() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContractFallbackReceive(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100,1000L, assetAccountId.toStringUtf8(), 1000L, - null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - final Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - final Long netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(0L, contractAccountCountAfter.longValue()); - Assert.assertNotEquals(10000000, energyUsageTotal); - String assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - Assert.assertEquals(0, assetIssueId.length()); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(1000000L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1000L, nonexistentAddressAccountTokenBalance.longValue()); - } - - @Test(enabled = true, description = "Suicide existent target") - public void test2SuicideExistentTarget() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress2 = PublicMethed.deployContractFallbackReceive(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100,1000L, assetAccountId.toStringUtf8(), - 1000L,null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - - Assert.assertTrue(PublicMethed - .sendcoin(nonexistentAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress2, - "testSuicideNonexistentTarget(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - final Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - final Long netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal2 = infoById.get().getReceipt().getEnergyUsageTotal(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal2); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Account contractafter = PublicMethed.queryAccount(contractAddress2, blockingStubFull1); - long contractBalance = contractafter.getBalance(); - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertEquals(contractBalance, 0); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(0L, contractAccountCountAfter.longValue()); - Assert.assertEquals(energyUsageTotal, energyUsageTotal2); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(3000000L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(2000L, nonexistentAddressAccountTokenBalance.longValue()); - - } - - @Test(enabled = true, description = "Suicide nonexistent target, but revert") - public void test3SuicideNonexistentTargetRevert() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress3 = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000000L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Assert.assertTrue(PublicMethed - //.sendcoin(contractAddress, 1000000L, testNetAccountAddress, testNetAccountKey, - // blockingStubFull)); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress1 = ecKey2.getAddress(); - - String txid = ""; - String num = "\"" + Base58.encode58Check(nonexistentAddress1) + "\""; - - txid = PublicMethed.triggerContract(contractAddress3, - "testSuicideRevert(address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infobyid : --- " + infoById); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - final Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - final Long netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertTrue(energyUsageTotal < 1000000000L); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(nonexistentAddress1, blockingStubFull1); - Assert.assertEquals(1000000L, nonexistentAddressAccount.getBalance()); - } - - @Test(enabled = true, description = "transfer to a suicide contract address same token") - public void test4transferToSuicideContractSameToken() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final byte[] contractAddress4 = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 1000L,null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Account info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String txid = ""; - String num = "1" + ",\"" + Base58.encode58Check(contractAddress) + "\""; - - txid = PublicMethed.triggerContract(contractAddress4, - "testTransferTrxNonexistentTarget(uint256,address)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("infoById:" + infoById); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, infoById.get().getReceipt().getResult()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(contractAddress, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.getBalance()); - - num = - "\"1" + "\",\"" + Base58.encode58Check(contractAddress) + "\",\"" + assetAccountId - .toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress4, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1L, contractAccountCountAfter.longValue()); - } - - @Test(enabled = true, description = "transfer to a suicide contract address different token") - public void test5transferToSuicideContractDifferentToken() { - // create different token - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress3, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey3, blockingStubFull)); - assetAccountId2 = PublicMethed.queryAccount(contractExcAddress3, blockingStubFull) - .getAssetIssuedID(); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - String filePath = "src/test/resources/soliditycode/TransferFailed001.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final byte[] contractAddress4 = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 1000000L, 100, 1000000000L, - assetAccountId2.toStringUtf8(), 1000L,null, contractExcKey3, - contractExcAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress3, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey3, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Account nonexistentAddressAccount = PublicMethed - .queryAccount(contractAddress, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.getBalance()); - - String num = - "\"1" + "\",\"" + Base58.encode58Check(contractAddress) + "\",\"" + assetAccountId2 - .toStringUtf8() + "\""; - String txid = PublicMethed.triggerContract(contractAddress4, - "testTransferTokenNonexistentTarget(uint256,address,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress3, contractExcKey3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Long contractAccountCountTokenBalance = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1L, contractAccountCountTokenBalance.longValue()); - Long contractAccountCountTokenBalance2 = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId2, blockingStubFull); - Assert.assertEquals(1L, contractAccountCountTokenBalance2.longValue()); - - String assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - Assert.assertEquals(0, assetIssueId.length()); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed005.java deleted file mode 100644 index 5971122a9c8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed005.java +++ /dev/null @@ -1,493 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final Long maxFeeLimit = Configuration.getByPath("testng.cong") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress = null; - byte[] contractAddress1 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress = ecKey1.getAddress(); - String accountExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(accountExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - - filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - contractName = "Caller"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - contractAddress1 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - } - } - - @Test(enabled = false, description = "Deploy contract for trigger") - public void deployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - String txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertEquals(0, infoById.get().getResultValue()); - - filePath = "src/test/resources/soliditycode/TransferFailed005.sol"; - contractName = "Caller"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - contractAddress1 = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100L, null, accountExcKey, - accountExcAddress, blockingStubFull); - txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - logger.info("caller address : " + Base58.encode58Check(contractAddress1)); - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = true, description = "TransferFailed for function call_value ") - public void triggerContract01() { - Account info = null; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(accountExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 1000100L, accountExcAddress, accountExcKey, blockingStubFull)); - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress1, 1, accountExcAddress, accountExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - long paramValue = 1; - - // transfer trx to self`s account - String param = "\"" + paramValue + "\",\"" + Base58.encode58Check(contractAddress) + "\""; - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - Assert.assertEquals("TRANSFER_FAILED", infoById.get().getReceipt().getResult().toString()); - Assert.assertEquals("transfer trx failed: Cannot transfer TRX to yourself.", - infoById.get().getResMessage().toStringUtf8()); - Assert.assertEquals(100L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(0L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - // transfer trx to unactivate account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress2 = ecKey2.getAddress(); - param = "\"" + paramValue + "\",\"" + Base58.encode58Check(accountExcAddress2) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - - Assert.assertEquals(99L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(0L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - // transfer trx to caller, value enough , function success contractResult(call_value) successed - param = "\"" + paramValue + "\",\"" + Base58.encode58Check(contractAddress1) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getReceipt().getResult() + ""); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(1, contractResult); - - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(98L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - // transfer trx to caller, value not enough, function success - // but contractResult(call_value) failed - param = "\"" + 100 + "\",\"" + Base58.encode58Check(contractAddress1) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCallTrxInsufficientBalance(uint256,address)", param, - false, 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - //contractResult`s first boolean value - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(0, contractResult); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertEquals(infoById.get().getResult().toString(), "SUCESS"); - Assert.assertEquals(98L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - - } - - @Test(enabled = true, description = "TransferFailed for create") - public void triggerContract02() { - final Long contractBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Account info = null; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(accountExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 1000100L, accountExcAddress, accountExcKey, blockingStubFull)); - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress1, 1, accountExcAddress, accountExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - long paramValue = 1; - String param = "\"" + paramValue + "\""; - - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCreateTrxInsufficientBalance(uint256)", param, false, - 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getReceipt().getResult() + ""); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertEquals(contractBalance - 1, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - param = "\"" + (contractBalance + 1) + "\""; - triggerTxid = PublicMethed - .triggerContract(contractAddress, "testCreateTrxInsufficientBalance(uint256)", param, false, - 0L, maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - logger.info("callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull).getBalance()); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals(infoById.get().getResMessage().toStringUtf8(), "REVERT opcode executed"); - Assert.assertEquals(contractBalance - 1, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - - } - - @Test(enabled = true, description = "TransferFailed for create2") - public void triggerContract03() { - final Long contractBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(accountExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - //Assert.assertTrue(PublicMethed - // .sendcoin(contractAddress, 15L, accountExcAddress, accountExcKey, blockingStubFull)); - logger.info("contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - - String filePath = "./src/test/resources/soliditycode/TransferFailed007.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", param, false, 0L, maxFeeLimit, - accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Long afterBalance = 0L; - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - logger.info("contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(contractBalance - 10L, afterBalance.longValue()); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - triggerTxid = PublicMethed - .triggerContract(contractAddress, "deploy2(bytes,uint256)", param, false, 0L, maxFeeLimit, - accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - logger.info("contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1, infoById.get().getResultValue()); - Assert.assertEquals("FAILED", infoById.get().getResult().toString()); - Assert.assertEquals(contractBalance - 10L, afterBalance.longValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - } - - @Test(enabled = true, description = "Triggerconstant a transfer function") - public void triggerContract04() { - Account account = PublicMethed.queryAccount(accountExcAddress, blockingStubFull); - Account contractAccount = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - final Long AccountBeforeBalance = account.getBalance(); - final Long contractAccountBalance = contractAccount.getBalance(); - - TransactionExtention return1 = PublicMethed.triggerConstantContractForExtention(contractAddress, - "testTransferTrxInsufficientBalance(uint256)", "1", false, 0L, 1000000000, "0", 0L, - accountExcAddress, accountExcKey, blockingStubFull); - Assert.assertEquals(response_code.SUCCESS, return1.getResult().getCode()); - /*Assert.assertEquals( - "class org.tron.core.vm.program.Program$StaticCallModificationException " - + ": Attempt to call a state modifying opcode inside STATICCALL", - return1.getResult().getMessage().toStringUtf8());*/ - - logger.info("return1: " + return1); - - account = PublicMethed.queryAccount(accountExcAddress, blockingStubFull); - contractAccount = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(AccountBeforeBalance.longValue(), account.getBalance()); - Assert.assertEquals(contractAccountBalance.longValue(), contractAccount.getBalance()); - } - - /** - * constructor. - */ - @AfterClass - - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(accountExcAddress, accountExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed006.java deleted file mode 100644 index c75f2b312af..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed006.java +++ /dev/null @@ -1,229 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final Long maxFeeLimit = Configuration.getByPath("testng.cong") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress = null; - byte[] contractAddress1 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress = ecKey1.getAddress(); - String accountExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(accountExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = false, description = "Deploy contract for trigger") - public void deployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed006.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertEquals(0, infoById.get().getResultValue()); - - filePath = "src/test/resources/soliditycode/TransferFailed006.sol"; - contractName = "Caller"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - - txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress1 = infoById.get().getContractAddress().toByteArray(); - logger.info("caller address : " + Base58.encode58Check(contractAddress1)); - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = false, description = "TransferFailed for create") - public void triggerContract() { - Account info = null; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(accountExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 1000100L, accountExcAddress, accountExcKey, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress1, 1, accountExcAddress, accountExcKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - logger.info( - "callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull) - .getBalance()); - long paramValue = 1000000; - String param = "\"" + paramValue + "\""; - - String triggerTxid = PublicMethed.triggerContract(contractAddress, - "testCreateTrxInsufficientBalance(uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - logger.info(infoById.get().getReceipt().getResult() + ""); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - logger.info( - "callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull) - .getBalance()); - Assert.assertEquals(infoById.get().getResultValue(), 0); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertEquals(100L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - triggerTxid = PublicMethed.triggerContract(contractAddress, - "testCreateTrxInsufficientBalance(uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(triggerTxid, blockingStubFull); - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - logger.info( - "callerAddress balance before: " + PublicMethed - .queryAccount(contractAddress1, blockingStubFull) - .getBalance()); - - Assert.assertEquals(infoById.get().getResultValue(), 1); - Assert.assertEquals(infoById.get().getResMessage().toStringUtf8(), "REVERT opcode executed"); - Assert.assertEquals(100L, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance()); - Assert.assertEquals(1L, - PublicMethed.queryAccount(contractAddress1, blockingStubFull).getBalance()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - - } - - /** - * constructor. - */ - @AfterClass - - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(accountExcAddress, accountExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed007.java deleted file mode 100644 index 886bc8683ee..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed007.java +++ /dev/null @@ -1,201 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - private final Long maxFeeLimit = Configuration.getByPath("testng.cong") - .getLong("defaultParameter.maxFeeLimit"); - byte[] contractAddress = null; - byte[] contractAddress1 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountExcAddress = ecKey1.getAddress(); - String accountExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(accountExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - } - - @Test(enabled = false, description = "Deploy contract for trigger") - public void deployContract() { - Assert.assertTrue(PublicMethed - .sendcoin(accountExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/TransferFailed007.sol"; - String contractName = "EnergyOfTransferFailedTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid1 = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, 0L, 100L, - null, accountExcKey, accountExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid1, blockingStubFull); - contractAddress = infoById.get().getContractAddress().toByteArray(); - Assert.assertEquals(0, infoById.get().getResultValue()); - } - - @Test(enabled = false, description = "TransferFailed for create2") - public void triggerContract() { - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(accountExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(accountExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - Assert.assertTrue(PublicMethed - .sendcoin(contractAddress, 15L, accountExcAddress, accountExcKey, blockingStubFull)); - logger.info( - "contractAddress balance before: " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - - String filePath = "./src/test/resources/soliditycode/TransferFailed007.sol"; - String contractName = "Caller"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String testContractCode = retMap.get("byteCode").toString(); - Long salt = 1L; - - String param = "\"" + testContractCode + "\"," + salt; - - String triggerTxid = PublicMethed.triggerContract(contractAddress, - "deploy(bytes,uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - long afterBalance = 0L; - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - logger.info( - "contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(5L, afterBalance); - Assert.assertFalse(infoById.get().getInternalTransactions(0).getRejected()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - triggerTxid = PublicMethed.triggerContract(contractAddress, - "deploy(bytes,uint256)", param, false, 0L, - maxFeeLimit, accountExcAddress, accountExcKey, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - fee = infoById.get().getFee(); - netUsed = infoById.get().getReceipt().getNetUsage(); - energyUsed = infoById.get().getReceipt().getEnergyUsage(); - netFee = infoById.get().getReceipt().getNetFee(); - energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - afterBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - logger.info( - "contractAddress balance after : " + PublicMethed - .queryAccount(contractAddress, blockingStubFull) - .getBalance()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - Assert.assertEquals(5L, afterBalance); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() < 10000000); - - } - - /** - * constructor. - */ - @AfterClass - - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(accountExcAddress, accountExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed008.java deleted file mode 100644 index 1d118bedd8b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/transferfailed/TransferFailed008.java +++ /dev/null @@ -1,485 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.transferfailed; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TransferFailed008 { - - private static final long now = System.currentTimeMillis(); - private static final long TotalSupply = 10000000L; - private static ByteString assetAccountId = null; - private static ByteString assetAccountId2 = null; - private static String tokenName = "testAssetIssue_" + Long.toString(now); - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - byte[] contractAddress = null; - byte[] contractAddress2 = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress3 = ecKey3.getAddress(); - String contractExcKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey, blockingStubFull)); - - assetAccountId = PublicMethed.queryAccount(contractExcAddress, blockingStubFull) - .getAssetIssuedID(); - System.out.println("assetAccountId:" + assetAccountId.toStringUtf8()); - - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - } - - - @Test(enabled = false, description = "TransferToken to old contractAddress") - public void test1TransferToOldContractAddress() { - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestB"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 1000L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAccountTokenBalance = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1000L, contractAccountTokenBalance.longValue()); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - // TUtbvvfggwQLrDZCNqYpfieCvCaKgKk5k9 selfdestruct contractAddress - // TQ1sSomxqmgqKiGqL3Lt8iybHt28FvUTwN exist accountAddress have token - // TWvKUjxH37F9BoeBrdD1hhWf7Es4CDTsRP exist contractAddress haven't token - // TKK8PhmACsJVX9T7Jkwr2QuWmhB8LjvwUW exist accountAddress haven't token - // v4.1.2 contract address ----Manual input - String oldContractAddress = "TV1ExzvFmSTMj67sxnzHrkZmjpsG5QWSne"; - String num = - "\"" + oldContractAddress + "\",\"1\",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "transferTokenTest(address,uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 1, contractAccountCountAfter.longValue()); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - Long oldContractAddressAccount = PublicMethed.getAssetIssueValue( - PublicMethed.decode58Check(oldContractAddress), assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, oldContractAddressAccount.longValue()); - } - - @Test(enabled = true, description = "TransferToken to new contract") - public void test1TransferToNewContract() { - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestB"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 1000000000L, - assetAccountId.toStringUtf8(), 1000L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long contractAccountTokenBalance = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - Assert.assertEquals(1000L, contractAccountTokenBalance.longValue()); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - String txid = ""; - String num = "\"1" + "\",\"" + assetAccountId.toStringUtf8() + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "createContractTest(uint256,trcToken)", num, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("infoById:" + infoById); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull1); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull1); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertEquals(testNetAccountCountBefore, testNetAccountCountAfter); - Assert.assertEquals(contractAccountCountBefore - 1, contractAccountCountAfter.longValue()); - - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Assert.assertNotEquals(10000000, energyUsageTotal); - - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressA = ByteArray.fromHexString(addressHex); - logger.info("contractAddressA: " + Base58.encode58Check(contractAddressA)); - Long nonexistentAddressAccount = PublicMethed - .getAssetIssueValue(contractAddressA, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccount.longValue()); - } - - @Test(enabled = true, description = "TransferToken nonexistent target in constructor") - public void test2TransferToNonexistentTargetInConstructor() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(address,uint256,trcToken)"; - String argsStr = - "\"" + Base58.encode58Check(nonexistentAddress) + "\",\"1\",\"" + assetAccountId - .toStringUtf8() + "\""; - - String deplTxid = PublicMethed.deployContractWithConstantParame(contractName, abi, code, - constructorStr, argsStr, "", maxFeeLimit, 1000000L, 100,1000L, - assetAccountId.toStringUtf8(), 1000L, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - contractAddress = info.get().getContractAddress().toByteArray(); - - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress, assetAccountId, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(testNetAccountCountBefore.longValue() - 1000L, - testNetAccountCountAfter.longValue()); - Assert.assertEquals(999L, contractAccountCountAfter.longValue()); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccountTokenBalance.longValue()); - } - - @Test(enabled = true, description = "TransferToken existent target in constructor") - public void test3TransferToExistentTargetInConstructor() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000_000_000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long start = System.currentTimeMillis() + 2000; - long end = System.currentTimeMillis() + 1000000000; - - //Create a new AssetIssue success. - Assert - .assertTrue(PublicMethed.createAssetIssue(contractExcAddress3, tokenName, TotalSupply, 1, - 10000, start, end, 1, description, url, 100000L, - 100000L, 1L, 1L, contractExcKey3, blockingStubFull)); - - assetAccountId2 = PublicMethed.queryAccount(contractExcAddress3, blockingStubFull) - .getAssetIssuedID(); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress3, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long testNetAccountCountBefore = PublicMethed - .getAssetIssueValue(contractExcAddress3, assetAccountId2, blockingStubFull); - Long contractAccountCountBefore = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId2, blockingStubFull); - logger.info("testNetAccountCountBefore:" + testNetAccountCountBefore); - logger.info("contractAccountCountBefore:" + contractAccountCountBefore); - - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestA"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(address,uint256,trcToken)"; - String argsStr = - "\"" + Base58.encode58Check(nonexistentAddress) + "\",\"1\",\"" + assetAccountId2 - .toStringUtf8() + "\""; - - String deplTxid = PublicMethed.deployContractWithConstantParame(contractName, abi, code, - constructorStr, argsStr, "", maxFeeLimit, 1000000L, 100, - 1000L, assetAccountId2.toStringUtf8(), 1000L, null, contractExcKey3, - contractExcAddress3, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - contractAddress = info.get().getContractAddress().toByteArray(); - - Long testNetAccountCountAfter = PublicMethed - .getAssetIssueValue(contractExcAddress3, assetAccountId2, blockingStubFull); - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId2, blockingStubFull); - logger.info("testNetAccountCountAfter:" + testNetAccountCountAfter); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(testNetAccountCountBefore.longValue() - 1000L, - testNetAccountCountAfter.longValue()); - Assert.assertEquals(999L, contractAccountCountAfter.longValue()); - - Account nonexistentAddressAccountTrxBalance = PublicMethed - .queryAccount(nonexistentAddress, blockingStubFull1); - Assert.assertEquals(0L, nonexistentAddressAccountTrxBalance.getBalance()); - Long nonexistentAddressAccountTokenBalance = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccountTokenBalance.longValue()); - Long nonexistentAddressAccountTokenBalance2 = PublicMethed - .getAssetIssueValue(nonexistentAddress, assetAccountId2, blockingStubFull1); - Assert.assertEquals(1L, nonexistentAddressAccountTokenBalance2.longValue()); - } - - @Test(enabled = true, description = "TransferToken existent target in constructor") - public void test4GetTokenBalanceInConstructor() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 10000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/accountAssert.sol"; - String contractName = "transferTokenTestC"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - String constructorStr = "constructor(trcToken)"; - String argsStr = "\"" + assetAccountId.toStringUtf8() + "\""; - - String deplTxid = PublicMethed.deployContractWithConstantParame(contractName, abi, code, - constructorStr, argsStr, "", maxFeeLimit, 1000000L, 100,1000L, - "0", 0L, null, contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed - .getTransactionInfoById(deplTxid, blockingStubFull); - Assert.assertTrue(info.get().getResultValue() == 0); - contractAddress = info.get().getContractAddress().toByteArray(); - - Long contractAccountCountAfter = PublicMethed - .getAssetIssueValue(contractAddress, assetAccountId, blockingStubFull); - logger.info("contractAccountCountAfter:" + contractAccountCountAfter); - - Assert.assertEquals(0L, contractAccountCountAfter.longValue()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant001.java deleted file mode 100644 index 38e2a13e64d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant001.java +++ /dev/null @@ -1,1684 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant001 { - - private final String testNetAccountKey = - Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddressNoAbi = null; - byte[] contractAddressWithAbi = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - private String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - private String fullnode1 = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - private String soliditynode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = - Configuration.getByPath("testng.conf").getStringList("solidityNode.ip.list").get(1); - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelRealSolidity = - ManagedChannelBuilder.forTarget(realSoliditynode).usePlaintext(true).build(); - blockingStubRealSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - - { - Assert.assertTrue( - PublicMethed.sendcoin( - contractExcAddress, - 10000_000_000L, - testNetAccountAddress, - testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - final String abi = retMap.get("abI").toString(); - - contractAddressNoAbi = - PublicMethed.deployContract( - contractName, - "[]", - code, - "", - maxFeeLimit, - 0L, - 100, - null, - contractExcKey, - contractExcAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = - PublicMethed.getContract(contractAddressNoAbi, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - contractAddressWithAbi = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 100, - null, - contractExcKey, - contractExcAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract2 = - PublicMethed.getContract(contractAddressWithAbi, blockingStubFull); - Assert.assertFalse(smartContract2.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract2.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract2.getBytecode().toString().isEmpty()); - } - } - - @Test(enabled = true, description = "TriggerConstantContract a payable function without ABI") - public void test01TriggerConstantContract() { - - String txid = ""; - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - TransactionExtention transactionExtentionFromSolidity = - PublicMethed.triggerSolidityContractForExtention( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtentionFromSolidity.getResult().getCode()); - System.out.println( - "Message = " + transactionExtentionFromSolidity.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " without ABI on solidity") - public void test01TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " without ABI on real solidity") - public void test01TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " without ABI") - public void test02TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " without ABI on solidity") - public void test02TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a non-payable function" + " without ABI on real solidity") - public void test02TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test(enabled = true, description = "TriggerConstantContract a view function without ABI") - public void test03TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " without ABI on solidity") - public void test03TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " without ABI on real solidity") - public void test03TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a pure function without ABI") - public void test04TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " without ABI on solidity") - public void test04TriggerConstantContractOnSolidity() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " without ABI on real solidity") - public void test04TriggerConstantContractOnRealSolidity() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a payable function with ABI") - public void test05TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " with ABI on solidity") - public void test05TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a payable function" + " with ABI on real solidity") - public void test05TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "TriggerConstantContract a non-payable function with ABI") - public void test06TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " with ABI on solidity") - public void test06TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a non-payable function" + " with ABI on real solidity") - public void test06TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testNoPayable()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat( - transactionExtention.getResult().getCode().toString(), containsString("SUCCESS")); - Assert.assertEquals( - 1, ByteArray.toInt(transactionExtention.getConstantResult(0).toByteArray())); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "TriggerConstantContract a view function with ABI") - public void test07TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " with ABI on solidity") - public void test07TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view function" + " with ABI on real solidity") - public void test07TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a pure function with ABI") - public void test08TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " with ABI on solidity") - public void test08TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a pure function" + " with ABI on real solidity") - public void test08TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a payable function without ABI") - public void test09TriggerContract() { - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a non-payable function without ABI") - public void test10TriggerContract() { - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a view function without ABI") - public void test11TriggerContract() { - - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a pure function without ABI") - public void test12TriggerContract() { - - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testPure()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a pure function with ABI") - public void test18TriggerContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerContractForExtention( - contractAddressWithAbi, - "testPure()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a payable function with ABI") - public void test19TriggerContract() { - - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = - PublicMethed.triggerContract( - contractAddressWithAbi, - "testPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a non-payable function with ABI") - public void test20TriggerContract() { - Account info; - - AccountResourceMessage resourceInfo = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = - PublicMethed.triggerContract( - contractAddressNoAbi, - "testNoPayable()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = - PublicMethed.getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = - ByteArray.toLong( - ByteArray.fromHexString( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerContract a view function with ABI") - public void test21TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerContractForExtention( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a view function with ABI on solidity") - public void test21TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerContract a view function with ABI on real solidity") - public void test21TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView()", - "#", - false, - 0, - maxFeeLimit, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray.fromHexString(Hex.toHexString(result)))); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view method with ABI ,method has " + "revert()") - public void test24TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method with ABI ,method has " + "revert() on solidity") - public void test24TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method with ABI ,method has " - + "revert() on real solidity") - public void test24TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = "TriggerContract a view method with ABI ,method has " + "revert()") - public void test25TriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerContractForExtention( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = "TriggerContract a view method with ABI ,method has " + "revert() on solidity") - public void test25TriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerContract a view method with ABI ,method has " + "revert() on real solidity") - public void test25TriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressWithAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = "TriggerConstantContract a view method without ABI,method has" + "revert()") - public void testTriggerConstantContract() { - - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtention( - contractAddressNoAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method without ABI,method has" + "revert() on solidity") - public void testTriggerConstantContractOnSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - @Test( - enabled = true, - description = - "TriggerConstantContract a view method without ABI,method has" - + "revert() on real solidity") - public void testTriggerConstantContractOnRealSolidity() { - TransactionExtention transactionExtention = - PublicMethed.triggerConstantContractForExtentionOnSolidity( - contractAddressNoAbi, - "testView2()", - "#", - false, - 0, - 0, - "0", - 0, - contractExcAddress, - contractExcKey, - blockingStubRealSolidity); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), containsString("FAILED")); - Assert.assertThat( - ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant002.java deleted file mode 100644 index cbfbef42dbe..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant002.java +++ /dev/null @@ -1,150 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant002 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-payable function without ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant003.java deleted file mode 100644 index e83946ff234..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant003.java +++ /dev/null @@ -1,243 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant003 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - } - - @Test(enabled = true, description = "TriggerConstantContract a view function without ABI") - public void test001TriggerConstantContract() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a pure function without ABI") - public void test002TriggerConstantContract() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPure()", "#", false, - 0, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a payable function without ABI") - public void test003TriggerConstantContract() { - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 1L, 1000000000, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - transaction = transactionExtention.getTransaction(); - System.out.println(transactionExtention.toString()); - result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - Assert.assertEquals("SUCESS", transaction.getRet(0).getRet().toString()); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant004.java deleted file mode 100644 index 6caa243b2c0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant004.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant004 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a pure function without ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPure()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant005.java deleted file mode 100644 index 82c1f52102d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant005.java +++ /dev/null @@ -1,141 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant005 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a payable function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, "testPayable()", "#", false, 0, 0, - "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant006.java deleted file mode 100644 index 38fa2431758..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant006.java +++ /dev/null @@ -1,150 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant006 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-payable function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert.assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert.assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant007.java deleted file mode 100644 index b2d4e06f49c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant007.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant007 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant008.java deleted file mode 100644 index 252924f21fd..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant008.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant008 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a pure function with ABI") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPure()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant009.java deleted file mode 100644 index 979e5d18ec7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant009.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant009 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a payable function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant010.java deleted file mode 100644 index 9e945289276..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant010.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant010 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a non-payable function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant011.java deleted file mode 100644 index 23909e8bbf4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant011.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant011 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a view function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testView()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant012.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant012.java deleted file mode 100644 index 96a6e807ef2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant012.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant012 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a pure function without ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - - txid = PublicMethed - .triggerContract(contractAddress, - "testPure()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant013.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant013.java deleted file mode 100644 index fd4e6144d80..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant013.java +++ /dev/null @@ -1,338 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant013 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] returnAddressBytes = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelSolidity = null; - public ManagedChannel channelPbft = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelRealSolidity = ManagedChannelBuilder.forTarget(realSoliditynode) - .usePlaintext(true) - .build(); - blockingStubRealSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - } - - @Test(enabled = true, description = "triggerContract a constant function created by create2") - public void test01TriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant015.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2") - public void test15TriggerConstantContract() { - - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2 on solidity") - public void test15TriggerConstantContractOnSolidity() { - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2 on real solidity") - public void test15TriggerConstantContractOnRealSolidity() { - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubRealSolidity); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function " - + "created by create2 on pbft") - public void test17TriggerConstantContractOnPbft() { - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubPbft); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant014.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant014.java deleted file mode 100644 index 3e27bc60807..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant014.java +++ /dev/null @@ -1,277 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant014 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - byte[] returnAddressBytes = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelRealSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubRealSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String realSoliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode).usePlaintext(true).build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - channelRealSolidity = ManagedChannelBuilder.forTarget(realSoliditynode).usePlaintext(true) - .build(); - blockingStubRealSolidity = WalletSolidityGrpc.newBlockingStub(channelRealSolidity); - } - - @Test(enabled = true, description = "TriggerContract a non-constant function created by create2") - public void test01TriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi005.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, "deploy(bytes,uint256)", num, false, 0, maxFeeLimit, "0", - 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - txid = PublicMethed - .triggerContract(returnAddressBytes, "plusOne()", "#", false, 0, maxFeeLimit, "0", 0, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById1 = null; - infoById1 = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee1 = infoById1.get().getFee(); - Long netUsed1 = infoById1.get().getReceipt().getNetUsage(); - Long energyUsed1 = infoById1.get().getReceipt().getEnergyUsage(); - Long netFee1 = infoById1.get().getReceipt().getNetFee(); - long energyUsageTotal1 = infoById1.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee1:" + fee1); - logger.info("netUsed1:" + netUsed1); - logger.info("energyUsed1:" + energyUsed1); - logger.info("netFee1:" + netFee1); - logger.info("energyUsageTotal1:" + energyUsageTotal1); - - Account infoafter1 = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter1 = PublicMethed - .getAccountResource(contractExcAddress, blockingStubFull); - Long afterBalance1 = infoafter1.getBalance(); - Long afterEnergyUsed1 = resourceInfoafter1.getEnergyUsed(); - Long afterNetUsed1 = resourceInfoafter1.getNetUsed(); - Long afterFreeNetUsed1 = resourceInfoafter1.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance1); - logger.info("afterEnergyUsed:" + afterEnergyUsed1); - logger.info("afterNetUsed:" + afterNetUsed1); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed1); - - Assert.assertTrue(infoById1.get().getResultValue() == 0); - Assert.assertTrue(afterBalance1 + fee1 == afterBalance); - Assert.assertTrue(afterEnergyUsed + energyUsed1 >= afterEnergyUsed1); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById1.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - } - - @Test(enabled = true, description = "TriggerConstantContract a non-constant function " - + "created by create2") - public void test16TriggerConstantContract() { - - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, "plusOne()", "#", false, 0, - maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test(enabled = true, description = "TriggerConstantContract a non-constant function " - + "created by create2 on solidity") - public void test16TriggerConstantContractOnSolidity() { - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - @Test(enabled = true, description = "TriggerConstantContract a non-constant function " - + "created by create2 on real solidity") - public void test16TriggerConstantContractOnRealSolidity() { - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(returnAddressBytes, "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubRealSolidity); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out.println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("SUCCESS")); - /*Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL"));*/ - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant015.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant015.java deleted file mode 100644 index 5444b9408ac..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant015.java +++ /dev/null @@ -1,201 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant015 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a constant function " - + "created by create2") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant015.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - SmartContract smartContract = PublicMethed.getContract(returnAddressBytes, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant016.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant016.java deleted file mode 100644 index 33fb1210db6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant016.java +++ /dev/null @@ -1,196 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant016 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-constant function " - + "created by create2") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi005.sol"; - String contractName = "Factory"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String contractName1 = "TestConstract"; - HashMap retMap1 = PublicMethed.getBycodeAbi(filePath, contractName1); - String code1 = retMap1.get("byteCode").toString(); - String abi1 = retMap1.get("abI").toString(); - String txid = ""; - String num = "\"" + code1 + "\"" + "," + 1; - txid = PublicMethed - .triggerContract(contractAddress, - "deploy(bytes,uint256)", num, false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - byte[] returnAddressBytes = infoById.get().getInternalTransactions(0).getTransferToAddress() - .toByteArray(); - String returnAddress = Base58.encode58Check(returnAddressBytes); - logger.info("returnAddress:" + returnAddress); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(returnAddressBytes, - "plusOne()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant017.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant017.java deleted file mode 100644 index 8928e729b87..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant017.java +++ /dev/null @@ -1,175 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant017 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true, description = "TriggerConstantContract a constant function which is " - + "deployed with ABI, but cleared ABI later") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 100000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/ClearAbi001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - String txid = ""; - txid = PublicMethed - .clearContractAbi(contractAddress, contractExcAddress, contractExcKey, blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - - TransactionExtention transactionExtention1 = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testPayable()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - Transaction transaction1 = transactionExtention1.getTransaction(); - - byte[] result1 = transactionExtention1.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction1.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention1.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result1)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result1)))); - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant018.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant018.java deleted file mode 100644 index 614a0ffb4fb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant018.java +++ /dev/null @@ -1,151 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant018 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a pure function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testPure()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant019.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant019.java deleted file mode 100644 index 05bdeffe04f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant019.java +++ /dev/null @@ -1,175 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant019 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a payable function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant001.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = PublicMethed - .triggerContract(contractAddress, - "testPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant020.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant020.java deleted file mode 100644 index 4846cc1a1e4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant020.java +++ /dev/null @@ -1,175 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant020 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a non-payable function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - String txid = ""; - txid = PublicMethed - .triggerContract(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - - Account infoafter = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - AccountResourceMessage resourceInfoafter = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - - Assert.assertTrue(infoById.get().getResultValue() == 0); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - Long returnnumber = ByteArray.toLong(ByteArray - .fromHexString(ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()))); - Assert.assertTrue(1 == returnnumber); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant021.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant021.java deleted file mode 100644 index a33931489e7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant021.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant021 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a view function with ABI") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant003.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testView()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert.assertEquals(1, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant022.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant022.java deleted file mode 100644 index 1a2e0fbb35d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant022.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant022 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a non-payable function " - + "with ABI(constant ABI)") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = "[{\"constant\":true,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"" - + "name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable" - + "\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":" - + "[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\"," - + "\"type\":\"function\"}]"; - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant023.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant023.java deleted file mode 100644 index 6ec25f0e2dc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant023.java +++ /dev/null @@ -1,154 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant023 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a non-payable function with" - + " ABI(constant ABI )") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant002.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = "[{\"constant\":true,\"inputs\":[],\"name\":\"testNoPayable\",\"outputs\":[{\"name" - + "\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"" - + "type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":[{\"na" - + "me\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\"" - + ":\"function\"}]"; - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testNoPayable()", "#", false, - 0, maxFeeLimit, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - System.out.println("Code = " + transactionExtention.getResult().getCode()); - System.out - .println("Message = " + transactionExtention.getResult().getMessage().toStringUtf8()); - - Assert - .assertThat(transactionExtention.getResult().getCode().toString(), - containsString("CONTRACT_EXE_ERROR")); - Assert - .assertThat(transactionExtention.getResult().getMessage().toStringUtf8(), - containsString("Attempt to call a state modifying opcode inside STATICCALL")); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant024.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant024.java deleted file mode 100644 index 4fc3a7470d6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant024.java +++ /dev/null @@ -1,158 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant024 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view method with ABI ,method has " - + "revert()") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant024.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert - .assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert - .assertThat(ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant025.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant025.java deleted file mode 100644 index b2198f98698..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant025.java +++ /dev/null @@ -1,155 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant025 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerContract a view method with ABI ,method has " - + "revert()") - public void testTriggerContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant024.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - - Assert.assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert.assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant026.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant026.java deleted file mode 100644 index 551d094b77e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant026.java +++ /dev/null @@ -1,159 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant026 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view method without ABI," - + "method has revert()") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert - .assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert - .assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant027.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant027.java deleted file mode 100644 index a548b370d42..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/triggerconstant/TriggerConstant027.java +++ /dev/null @@ -1,159 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.triggerconstant; - -import static org.hamcrest.core.StringContains.containsString; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TriggerConstant027 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = false, description = "TriggerConstantContract a view method without ABI," - + "method has revert()") - public void testTriggerConstantContract() { - Assert.assertTrue(PublicMethed - .sendcoin(contractExcAddress, 1000000000L, testNetAccountAddress, testNetAccountKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/TriggerConstant004.sol"; - String contractName = "testConstantContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - contractAddress = PublicMethed.deployContract(contractName, "[]", code, "", maxFeeLimit, - 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - Account info; - - AccountResourceMessage resourceInfo = PublicMethed.getAccountResource(contractExcAddress, - blockingStubFull); - info = PublicMethed.queryAccount(contractExcKey, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, - "testView()", "#", false, - 0, 0, "0", 0, contractExcAddress, contractExcKey, blockingStubFull); - - Transaction transaction = transactionExtention.getTransaction(); - - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println(":" + ByteArray - .toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - - Assert - .assertThat(transaction.getRet(0).getRet().toString(), - containsString("FAILED")); - Assert - .assertThat(ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray()), - containsString("REVERT opcode executed")); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed - .freedResource(contractExcAddress, contractExcKey, testNetAccountAddress, blockingStubFull); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java deleted file mode 100644 index bd3e67c2c4c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest001.java +++ /dev/null @@ -1,254 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tryCatch; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class tryCatchTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - private byte[] errorContractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 10000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "src/test/resources/soliditycode/tryCatch001.sol"; - String contractName = "tryTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - - contractName = "errorContract"; - retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - errorContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - - @Test(enabled = true, description = "try catch revert no msg") - public void tryCatchTest001() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",0"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("NoErrorMsg", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - - } - - @Test(enabled = true, description = "try catch revert msg") - public void tryCatchTest002() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",1"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("Revert Msg.", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch Require no msg") - public void tryCatchTest003() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",2"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("NoErrorMsg", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch Require msg") - public void tryCatchTest004() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("Require Msg.", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch assert") - public void tryCatchTest005() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",4"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "try catch transfer fail") - public void tryCatchTest006() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",5"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("NoErrorMsg", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch Send_Error") - public void tryCatchTest007() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",6"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals("success", PublicMethed - .getContractStringMsg(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch Math_Error") - public void tryCatchTest008() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",7"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "try catch ArrayOverFlow_Error") - public void tryCatchTest009() { - String methodStr = "getErrorSwitch(address,uint256)"; - String argStr = "\"" + Base58.encode58Check(errorContractAddress) + "\",8"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0, transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java deleted file mode 100644 index c55ba174d4f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tryCatch/tryCatchTest002.java +++ /dev/null @@ -1,252 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tryCatch; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class tryCatchTest002 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - private byte[] errorContractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * miraculous.wong. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 10000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/tryCatch001.sol"; - String contractName = "tryTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - - - } - - - @Test(enabled = true, description = "try catch [new] revert no msg") - public void tryCatchTest001() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "0"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] revert msg") - public void tryCatchTest002() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "1"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] Require no msg") - public void tryCatchTest003() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "2"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch [new] Require msg") - public void tryCatchTest004() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "3"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] assert") - public void tryCatchTest005() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "4"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "try catch [new] transfer fail") - public void tryCatchTest006() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "5"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch [new] Send_Error") - public void tryCatchTest007() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "6"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertNotEquals( - "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(transactionInfo.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "try catch [new] Math_Error") - public void tryCatchTest008() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "7"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - - @Test(enabled = true, description = "try catch [new] ArrayOverFlow_Error") - public void tryCatchTest009() { - String methodStr = "catchNewErrorSwitch(uint256)"; - String argStr = "8"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, argStr, false, - 0, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional transactionInfo = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("transactionInfo: " + transactionInfo.get()); - Assert.assertEquals(0,transactionInfo.get().getResultValue()); - Assert.assertTrue(transactionInfo.get().getFee() < maxFeeLimit); - Assert.assertEquals(contractResult.SUCCESS, - transactionInfo.get().getReceipt().getResult()); - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest001.java deleted file mode 100644 index 5556d5d0112..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest001.java +++ /dev/null @@ -1,506 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmFreeze; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class FreezeContractTest001 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] testAddress003 = ecKey3.getAddress(); - String testKey003 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - private long freezeEnergyUseage; - private byte[] create2Address; - private final long freezeCount = 1000_123456L; - - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - - PublicMethed.printAddress(testFoundationKey); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,10_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress003,12000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000_000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - - @Test(description = "contract freeze to account") - void FreezeContractTest001() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertTrue(account002_before.getEnergyLimit() < account002_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - - } - - @Test(description = "contract freeze to self") - void FreezeContractTest002() { - AccountResourceMessage contractResource_before = PublicMethed - .getAccountResource(contractAddress,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage contractResource_after = PublicMethed - .getAccountResource(contractAddress,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + contractResource_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + contractResource_after.getEnergyLimit()); - Assert.assertTrue( - contractResource_before.getEnergyLimit() < contractResource_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getFrozenBalanceForEnergy().getFrozenBalance() + freezeCount, - contractAccount_after.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance()); - - } - - @Test(description = "contract freeze to other contract") - void FreezeContractTest003() { - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - byte[] newContract = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(newContract) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - Assert.assertEquals(TransactionInfo.code.FAILED,info.getResult()); - - AccountResourceMessage contractResource_after = PublicMethed - .getAccountResource(newContract,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + contractResource_after.getEnergyLimit()); - Assert.assertEquals(contractResource_after.getEnergyLimit(),0); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(),contractAccount_after.getBalance()); - - } - - @Test(description = "contract freeze to unactive account", - dependsOnMethods = "FreezeContractTest001") - void FreezeContractTest004() { - - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] testAddress = ecKey.getAddress(); - String testKey = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress) + "\"," + freezeCount + "," + "1"; - logger.info("argsStr: " + argsStr); - - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertTrue(account002_after.getEnergyLimit() > 0); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - // check active account status - Account testAccount = PublicMethed.queryAccount(testAddress,blockingStubFull); - Assert.assertTrue(testAccount.getCreateTime() > 0); - Assert.assertNotNull(testAccount.getOwnerPermission()); - Assert.assertNotNull(testAccount.getActivePermissionList()); - - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(freezeEnergyUseage + 25000L, info.getReceipt().getEnergyUsageTotal()); - - - } - - @Test(description = "contract freeze to pre create2 address, and UnFreeze", - dependsOnMethods = "FreezeContractTest001") - void FreezeContractTest005() { - String create2ArgsStr = "1"; - String create2MethedStr = "deploy(uint256)"; - TransactionExtention exten = PublicMethed.triggerConstantContractForExtention( - contractAddress, create2MethedStr, create2ArgsStr, false, 0, maxFeeLimit, - "#", 0, testAddress001, testKey001, blockingStubFull); - - String addressHex = - "41" + ByteArray.toHexString(exten.getConstantResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - create2Address = ByteArray.fromHexString(addressHex); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(create2Address) + "\"," + freezeCount + "," + "1"; - logger.info("argsStr: " + argsStr); - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(create2Address,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertTrue(account002_after.getEnergyLimit() > 0); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(freezeEnergyUseage + 25000L, info.getReceipt().getEnergyUsageTotal()); - - txid = PublicMethed.triggerContract(contractAddress,create2MethedStr, - create2ArgsStr,false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - methedStr = "getExpireTime(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(create2Address) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - methedStr = "unfreeze(address,uint256)"; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() - freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() + freezeCount, - contractAccount_after.getBalance()); - - } - - @Test(description = "Unfreeze when freeze to account", - dependsOnMethods = "FreezeContractTest001") - void UnFreezeContractTest001() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "getExpireTime(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - methedStr = "unfreeze(address,uint256)"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() - freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - - Assert.assertTrue(account002_before.getEnergyLimit() > account002_after.getEnergyLimit()); - - } - - @Test(description = "Unfreeze when freeze to contract self", - dependsOnMethods = "FreezeContractTest002") - void UnFreezeContractTest002() { - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "getExpireTime(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - methedStr = "unfreeze(address,uint256)"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getFrozenBalanceForEnergy().getFrozenBalance() - freezeCount, - contractAccount_after.getAccountResource().getFrozenBalanceForEnergy().getFrozenBalance()); - - - } - - @Test(description = "energy caulate after transaction end") - public void freezeEnergyCaulate() { - - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - AccountResourceMessage testAccount001 = PublicMethed - .getAccountResource(testAddress001,blockingStubFull); - - - Assert.assertTrue(testAccount001.getEnergyLimit() > 0); - Assert.assertTrue(info.getReceipt().getEnergyFee() > 0); - Assert.assertTrue(testAccount001.getEnergyLimit() > info.getReceipt().getEnergyUsageTotal()); - - methedStr = "unfreeze(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testAddress001) + "\",1"; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - testAccount001 = PublicMethed.getAccountResource(testAddress001,blockingStubFull); - - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - - Assert.assertEquals(0, info.getReceipt().getEnergyFee()); - Assert.assertEquals(0, testAccount001.getEnergyLimit()); - Assert.assertTrue(testAccount001.getEnergyUsed() > 0); - } - - @Test(description = "get Zero Address ExpirTime,used to be that freeze to contract self", - dependsOnMethods = "FreezeContractTest002") - public void getZeroExpireTimeTest() { - String ExpireTimeMethedStr = "getExpireTime(address,uint256)"; - String ExpireTimeArgsStr = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"" + ",0"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime1 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime1: " + ExpireTime1); - Assert.assertEquals(0,ExpireTime1.longValue()); - - ExpireTimeArgsStr = "\"T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb\"" + ",1"; - extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime2 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime2: " + ExpireTime2); - Assert.assertEquals(0,ExpireTime2.longValue()); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb" + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertEquals((ExpireTime + 3) * 1000, info.getBlockTimeStamp()); - - - } - - @Test(description = "freeze in constructor") - public void FreezeContractTest006() { - - AccountResourceMessage account003_before = PublicMethed - .getAccountResource(testAddress003,blockingStubFull); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "D"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callValue = 10000_000000L; - byte[] contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, callValue, - 100, null, testKey003, - testAddress003, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account003_after = PublicMethed - .getAccountResource(testAddress003,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account003_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account003_after.getEnergyLimit()); - Assert.assertTrue(account003_before.getEnergyLimit() < account003_after.getEnergyLimit()); - Assert.assertEquals(callValue, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(0, contractAccount_after.getBalance()); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest002.java deleted file mode 100644 index bb79702f0f0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeContractTest002.java +++ /dev/null @@ -1,271 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmFreeze; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class FreezeContractTest002 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long freezeEnergyUseage; - - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,10_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "contract freeze over balance") - void FreezeContract001() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = contractAccount_before.getBalance() + 1; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertEquals(account002_before.getEnergyLimit(), account002_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(), - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - } - - @Test(enabled = true, description = "contract freeze amount < 1 TRX") - void FreezeContract002() { - - Account account002_before = PublicMethed - .queryAccount(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = 999999L; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account account002_after = PublicMethed - .queryAccount(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - logger.info("account002_before.getAccountResource : " + account002_before.getAccountResource()); - logger.info("account002_after.getAccountResource : " + account002_after.getAccountResource()); - - Assert.assertEquals( - account002_before.getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy(), - account002_after.getAccountResource().getAcquiredDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(), - contractAccount_after.getBalance()); - - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - } - - @Test(enabled = true, description = "contract transfer all balance, then freeze") - void FreezeContract003() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = contractAccount_before.getBalance(); - String methedStr = "freezeAndSend(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getEnergyLimit : " + account002_before.getEnergyLimit()); - logger.info("account002_after.getEnergyLimit : " + account002_after.getEnergyLimit()); - Assert.assertEquals(account002_before.getEnergyLimit(), account002_after.getEnergyLimit()); - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy(), - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance(), - contractAccount_after.getBalance()); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - } - - @Test(enabled = true, description = "contract freeze to ger Net") - void FreezeContract004() { - - AccountResourceMessage account002_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = 1_000000L; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "0"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage account002_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - logger.info("account002_before.getNetLimit : " + account002_before.getNetLimit()); - logger.info("account002_after.getNetLimit : " + account002_after.getNetLimit()); - Assert.assertTrue(account002_before.getNetLimit() < account002_after.getNetLimit()); - Assert.assertEquals(contractAccount_before - .getDelegatedFrozenBalanceForBandwidth() + freezeCount, - contractAccount_after.getDelegatedFrozenBalanceForBandwidth()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - } - - @Test(enabled = true, description = "contract freeze to ger Net") - void FreezeContract005() { - // freeze(address payable receiver, uint amount, uint res) - Long freezeCount = 1000000L; - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String ExpireTimeMethedStr = "getExpireTime(address,uint256)"; - String ExpireTimeArgsStr = "\"" + Base58.encode58Check(testAddress001) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime1 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime1: " + ExpireTime1); - - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo info = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - freezeEnergyUseage = info.getReceipt().getEnergyUsageTotal(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,ExpireTimeMethedStr,ExpireTimeArgsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime2 = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime2: " + ExpireTime2); - - // Test - Assert.assertEquals((ExpireTime2 + 3) * 1000, info.getBlockTimeStamp()); - // Online - // Assert.assertEquals((ExpireTime2.longValue() + 10800) * 1000, info.getBlockTimeStamp()); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeSuicideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeSuicideTest001.java deleted file mode 100644 index e2b14c4277e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmFreeze/FreezeSuicideTest001.java +++ /dev/null @@ -1,290 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmFreeze; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Result.contractResult; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class FreezeSuicideTest001 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long freezeEnergyUseage; - private long callValue; - private byte[] create2Address; - private final Long freezeCount = 1000_000000L; - - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(testKey001); - PublicMethed.printAddress(testKey002); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(testAddress001,2000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(testAddress002,200_0000_000000L, - testFoundationAddress,testFoundationKey,blockingStubFull)); - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - callValue = 50000_000000L; - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, callValue, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(testAddress002, - 100_0000_000000L,0,0,testKey002,blockingStubFull)); - } - - @Test(enabled = true, description = "when delegate freeze, cannot suicide") - public void FreezeSuicideTest001() { - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + freezeCount + "," + "1"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(contractAccount_before.getAccountResource() - .getDelegatedFrozenBalanceForEnergy() + freezeCount, - contractAccount_after.getAccountResource().getDelegatedFrozenBalanceForEnergy()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - - methedStr = "unfreeze(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\"," + "1"; - PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - } - - @Test(enabled = true, description = "when delegate freeze to self, then suicide") - public void FreezeSuicideTest002() { - - Account contractAccount_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - AccountResourceMessage freezeAccount_before = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - - // freeze(address payable receiver, uint amount, uint res) - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"," + freezeCount + "," + "0"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - AccountResourceMessage freezeAccount_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Account contractAccount_after = PublicMethed.queryAccount(contractAddress, blockingStubFull); - - Assert.assertEquals(freezeCount.longValue(), - contractAccount_after.getFrozen(0).getFrozenBalance()); - Assert.assertEquals(contractAccount_before.getBalance() - freezeCount, - contractAccount_after.getBalance()); - - logger.info("freezeAccount_before.getNetLimit : " + freezeAccount_before.getNetLimit()); - logger.info("freezeAccount_after.getNetLimit : " + freezeAccount_after.getNetLimit()); - Assert.assertTrue(freezeAccount_after.getNetLimit() < freezeAccount_before.getNetLimit()); - - - Long beforeBalance = PublicMethed.queryAccount(testAddress002,blockingStubFull).getBalance(); - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - freezeAccount_after = PublicMethed - .getAccountResource(testAddress002,blockingStubFull); - Assert.assertEquals(freezeAccount_before.getNetLimit(), - freezeAccount_after.getNetLimit()); - - Long AfterBalance = PublicMethed.queryAccount(testAddress002,blockingStubFull).getBalance(); - Assert.assertEquals(beforeBalance + callValue, AfterBalance.longValue()); - - - } - - @Test(enabled = true, description = "suicide、freeze、unfreeze、getExpireTime " - + "with suicided create2 address") - public void FreezeSuicideTest003() { - - String filePath = "src/test/resources/soliditycode/freezeContract001.sol"; - String contractName = "TestFreeze"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String bytecode = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - callValue = 10000_000000L; - contractAddress = PublicMethed - .deployContract(contractName, abi, bytecode, "", maxFeeLimit, callValue, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // triggerconstant create2 function, and get create2 Address - String create2ArgsStr = "1"; - String create2MethedStr = "deploy(uint256)"; - TransactionExtention exten = PublicMethed.triggerConstantContractForExtention( - contractAddress, create2MethedStr, create2ArgsStr, false, 0, maxFeeLimit, - "#", 0, testAddress001, testKey001, blockingStubFull); - - String addressHex = - "41" + ByteArray.toHexString(exten.getConstantResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - create2Address = ByteArray.fromHexString(addressHex); - logger.info("create2Address: " + Base58.encode58Check(create2Address)); - - // freeze to create2 Address, active create2 address - String methedStr = "freeze(address,uint256,uint256)"; - String argsStr = "\"" + Base58.encode58Check(create2Address) + "\"," + freezeCount + "," + "1"; - logger.info("argsStr: " + argsStr); - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - TransactionInfo info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - // create2 contract Address, turn create2 address to contract type - txid = PublicMethed.triggerContract(contractAddress,create2MethedStr, - create2ArgsStr,false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - - // create2 contract suicide - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(create2Address,methedStr,argsStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - // get create2 account ExpireTime - methedStr = "getExpireTime(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(create2Address) + "\"" + ",1"; - TransactionExtention extention = PublicMethed - .triggerConstantContractForExtention(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,"#",0, testAddress001,testKey001,blockingStubFull); - Long ExpireTime = ByteArray.toLong(extention.getConstantResult(0).toByteArray()); - logger.info("ExpireTime: " + ExpireTime); - Assert.assertTrue(ExpireTime > 0); - - // suicide FreezeTest contract, and should be failed - methedStr = "destroy(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.FAILED,info.getResult()); - Assert.assertEquals(contractResult.REVERT,info.getReceipt().getResult()); - - Account contract_before = PublicMethed.queryAccount(contractAddress,blockingStubFull); - - // unfreeze suicide create2 account - methedStr = "unfreeze(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(create2Address) + "\"," + "1"; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argsStr, - false,0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull).get(); - Assert.assertEquals(code.SUCESS,info.getResult()); - Assert.assertEquals(contractResult.SUCCESS,info.getReceipt().getResult()); - - Account contract_after = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(contract_before.getBalance() + freezeCount, contract_after.getBalance()); - Assert.assertEquals(contract_after.getAccountResource().getDelegatedFrozenBalanceForEnergy(), - contract_before.getAccountResource().getDelegatedFrozenBalanceForEnergy() - freezeCount); - - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java deleted file mode 100644 index 207406b58ca..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue001.java +++ /dev/null @@ -1,282 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private static String assetIssueId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - } - - @Test(enabled = false, description = "tokenIssue normal") - public void tokenIssueNormal() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - /*String param = "0000000000000000000000000000000000007465737441737365744973737565" - + "0000000000000000000074657374417373657431353938333439363637393631" - + "0000000000000000000000000000000000000000000000000000000000989680" - + "0000000000000000000000000000000000000000000000000000000000000001";*/ - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - } - - @Test(enabled = false, description = "updateAsset normal") - public void updateAssetNormal() { - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - String txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java deleted file mode 100644 index 2b7e693fa91..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue002.java +++ /dev/null @@ -1,744 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue002 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String assetIssueId = null; - long contractAddressBalance; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - } - - @Test(enabled = false, description = "tokenIssue illegal parameter verification") - public void tokenIssue001IllegalParameterVerification() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 2050000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - /*String param = "0000000000000000000000000000000000007465737441737365744973737565" - + "0000000000000000000074657374417373657431353938333439363637393631" - + "0000000000000000000000000000000000000000000000000000000000989680" - + "0000000000000000000000000000000000000000000000000000000000000001";*/ - // assetName is trx - String tokenName = PublicMethed.stringToHexString("trx"); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetName.length > 32 compile fail - /*tokenName = PublicMethed.stringToHexString("testAssetIssue_testAssetIssue_tes"); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size());*/ - - // assetName is "" - tokenName = PublicMethed.stringToHexString(""); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetName is chinese - tokenName = PublicMethed.stringToHexString("名字"); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetAbbr is null - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString(""); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetAbbr is chinese - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("简称"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // totalSupply is Long.MAX_VALUE+1 - param = "a8547918" - + "74657374417373657449737375655f3136303034333636393333333600000000" - + "7472780000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000008000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000006"; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // totalSupply is -1 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("trx"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + -1 + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - logger.info("totalSupply is -1"); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCCESS", infoById.get().getReceipt().getResult().toString()); - Assert.assertTrue(infoById.get().getFee() < 1000000000); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // totalSupply is 0 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("trx"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + 0 + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - logger.info("totalSupply is 0"); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCCESS", infoById.get().getReceipt().getResult().toString()); - Assert.assertTrue(infoById.get().getFee() < 1000000000); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // precision is 7 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 7; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // precision is -1 - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + -1; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - - // assetAbbr is trx will success - tokenName = PublicMethed.stringToHexString(name); - tokenAbbr = PublicMethed.stringToHexString("trx"); - param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals("trx", ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - - // created multiple times will fail - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - String assetIssueId1 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - Assert.assertEquals(assetIssueId, assetIssueId1); - } - - @Test(enabled = false, description = "tokenIssue trx balance insufficient") - public void tokenIssue002TrxBalanceInsufficient() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1023999999L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - // trx balance insufficient - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - } - - @Test(enabled = false, description = "tokenIssue called multiple times in one contract") - public void tokenIssue003CalledMultipleTimesInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue002.sol"; - String contractName = "tvmAssetIssue002"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 5; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(5, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "tokenIssue revert") - public void tokenIssue004Revert() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue003.sol"; - String contractName = "tvmAssetIssue003"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 2500000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 4; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(4, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - String tokenName1 = PublicMethed.stringToHexString(name + "_rev"); - String tokenAbbr1 = PublicMethed.stringToHexString(abbr + "_rev"); - param = - "\"" + tokenName1 + "\",\"" + tokenAbbr1 + "\",\"" + 1000000 + "\",\"" + 3 + "\",\"" - + Base58.encode58Check(dev002Address) + "\""; - logger.info("param: " + param); - String methodTokenIssueRevert = "tokenIssueAndTransfer(bytes32,bytes32,uint64,uint8,address)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssueRevert, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(1, assetV2Map.size()); - String assetIssueId1 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId1: " + assetIssueId1); - Assert.assertEquals(assetIssueId, assetIssueId1); - assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(4, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - long balance = PublicMethed.queryAccount(dev002Address, blockingStubFull).getBalance(); - Assert.assertEquals(200000000L, balance); - } - - @Test(enabled = false, description = "tokenIssue call another contract in one contract") - public void tokenIssue005CallAnotherInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue004.sol"; - String contractName = "tvmAssetIssue004"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1030000000L; - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - callvalue = 1024000000L; - String txid = PublicMethed.triggerContract(contractAddress, "getContractAddress()", "#", false, - callvalue, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressA = ByteArray.fromHexString(addressHex); - logger.info("contractAddressA: " + Base58.encode58Check(contractAddressA)); - contractAddressBalance = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 2; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddressA, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - long assetIssueValue = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(2, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddressA), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - txid = PublicMethed.triggerContract(contractAddressA, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java deleted file mode 100644 index 60ca55d3666..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue003.java +++ /dev/null @@ -1,864 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue003 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private static String assetIssueId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - } - - @Test(enabled = false, description = "updateAsset illegal parameter verification") - public void updateAsset001IllegalParameterVerification() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // desc and url is trx, will success - url = "trx"; - description = "trx"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // desc.length is 201, will fail - String descriptions = - "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890" - + "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc" - + "_1234567890" - + "desc_1234567890desc_1234567890desc_1"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + descriptions + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // desc.length is "", will success - param = "\"" + assetIssueId + "\",\"" + url + "\",\"\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(0, assetIssueById.getDescription().size()); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // desc.length is chinese, will success - description = "token说明"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // url.length is 257, will fail - String urls = - "url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901" - + "url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901url" - + "_12345678901" - + "url_12345678901url_12345678901url_12345678901url_12345678901url_12345678901ur"; - param = "\"" + assetIssueId + "\",\"" + urls + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // url.length is "", will fail - param = "\"" + assetIssueId + "\",\"\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // url.length is chinese, will success - url = "官网"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "updateAsset called multiple times in one contract") - public void updateAsset002CalledMultipleTimesInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue002.sol"; - String contractName = "tvmAssetIssue002"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("infoById: " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // updateAsset - description = "desc1_" + Long.toString(now); - url = "url1_" + Long.toString(now); - String description2 = "desc2_" + Long.toString(now); - String url2 = "url2_" + Long.toString(now); - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\",\"" + url2 + "\",\"" - + description2 + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description2, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url2, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "updateAsset revert") - public void updateAsset003Revert() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1500_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue003.sol"; - String contractName = "tvmAssetIssue003"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1225000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("infoById: " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // updateAsset - String description1 = - "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890" - + "desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc_1234567890desc" - + "_1234567890" - + "desc_1234567890desc_1234567890desc_1"; - String url1 = "url1_" + Long.toString(now); - param = "\"" + assetIssueId + "\",\"" + url1 + "\",\"" + description1 + "\",\"" + Base58 - .encode58Check(dev002Address) + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAssetAndTransfer(trcToken,string,string,address)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - logger.info("assetIssueById: " + assetIssueById); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(0, assetIssueById.getDescription().size()); - Assert.assertEquals(0, assetIssueById.getUrl().size()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - long balance = PublicMethed.queryAccount(dev002Address, blockingStubFull).getBalance(); - Assert.assertEquals(200000000L, balance); - } - - @Test(enabled = false, description = "updateAsset call another contract in one contract") - public void updateAsset004CallAnotherInOneContract() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue004.sol"; - String contractName = "tvmAssetIssue004"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1030000000L; - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - callvalue = 1024000000L; - String txid = PublicMethed.triggerContract(contractAddress, "getContractAddress()", "#", false, - callvalue, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressA = ByteArray.fromHexString(addressHex); - logger.info("contractAddressA: " + Base58.encode58Check(contractAddressA)); - long contractAddressBalance = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - AccountResourceMessage resourceInfo = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Account info = PublicMethed.queryAccount(dev001Address, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = resourceInfo.getEnergyUsed(); - Long beforeNetUsed = resourceInfo.getNetUsed(); - Long beforeFreeNetUsed = resourceInfo.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 2; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddressA, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - Map assetV2Map = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map(); - Assert.assertEquals(0, assetV2Map.size()); - long assetIssueValue = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(2, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddressA), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - Long fee = infoById.get().getFee(); - Long netUsed = infoById.get().getReceipt().getNetUsage(); - Long energyUsed = infoById.get().getReceipt().getEnergyUsage(); - Long netFee = infoById.get().getReceipt().getNetFee(); - long energyUsageTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("fee:" + fee); - logger.info("netUsed:" + netUsed); - logger.info("energyUsed:" + energyUsed); - logger.info("netFee:" + netFee); - logger.info("energyUsageTotal:" + energyUsageTotal); - Protocol.Account infoafter = PublicMethed.queryAccount(dev001Address, blockingStubFull); - GrpcAPI.AccountResourceMessage resourceInfoafter = PublicMethed - .getAccountResource(dev001Address, blockingStubFull); - Long afterBalance = infoafter.getBalance(); - Long afterEnergyUsed = resourceInfoafter.getEnergyUsed(); - Long afterNetUsed = resourceInfoafter.getNetUsed(); - Long afterFreeNetUsed = resourceInfoafter.getFreeNetUsed(); - logger.info("afterBalance:" + afterBalance); - logger.info("afterEnergyUsed:" + afterEnergyUsed); - logger.info("afterNetUsed:" + afterNetUsed); - logger.info("afterFreeNetUsed:" + afterFreeNetUsed); - Assert.assertTrue(afterBalance + fee == beforeBalance); - Assert.assertTrue(beforeEnergyUsed + energyUsed >= afterEnergyUsed); - Assert.assertTrue(beforeFreeNetUsed + netUsed >= afterFreeNetUsed); - Assert.assertTrue(beforeNetUsed + netUsed >= afterNetUsed); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddressA, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // updateAsset - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddressA, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(2, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddressA), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "updateAsset verify token") - public void updateAsset005VerifyTokenId() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 1100_000_000L, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(dev002Address, 50_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1024000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // token id does not exist, will update myself - url = "trx"; - description = "trx"; - param = "\"1119125\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - logger.info("assetIssueById: " + assetIssueById); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // not owner's asset, will update myself - AssetIssueContract assetIssueByIdBefore = PublicMethed - .getAssetIssueById("1000004", blockingStubFull); - final String nameBefore = ByteArray.toStr(assetIssueByIdBefore.getName().toByteArray()); - final String abbrBefore = ByteArray.toStr(assetIssueByIdBefore.getAbbr().toByteArray()); - final String descBefore = assetIssueByIdBefore.getDescription().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdBefore.getDescription().toByteArray()); - final String urlBefore = assetIssueByIdBefore.getUrl().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdBefore.getUrl().toByteArray()); - final long precisionBefore = assetIssueByIdBefore.getPrecision(); - url = url + "123456"; - description = description + "123"; - param = "\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed - .triggerContract(contractAddress, "updateOtherAccountAsset(string,string)", param, false, - 0, maxFeeLimit, dev002Address, dev002Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnAssetId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - logger.info("assetIssueById: " + assetIssueById); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - AssetIssueContract assetIssueByIdAfter = PublicMethed - .getAssetIssueById("1000004", blockingStubFull); - String descAfter = assetIssueByIdBefore.getDescription().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdAfter.getDescription().toByteArray()); - String urlAfter = assetIssueByIdBefore.getUrl().size() == 0 ? "" - : ByteArray.toStr(assetIssueByIdAfter.getUrl().toByteArray()); - Assert.assertEquals(nameBefore, ByteArray.toStr(assetIssueByIdAfter.getName().toByteArray())); - Assert.assertEquals(abbrBefore, ByteArray.toStr(assetIssueByIdAfter.getAbbr().toByteArray())); - Assert.assertEquals(descBefore, descAfter); - Assert.assertEquals(urlBefore, urlAfter); - Assert.assertEquals(precisionBefore, assetIssueByIdAfter.getPrecision()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java deleted file mode 100644 index 9bf181a4c48..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue004.java +++ /dev/null @@ -1,205 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue004 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private static String assetIssueId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] dev003Address = ecKey3.getAddress(); - private String dev003Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - PublicMethed.printAddress(dev003Key); - } - - @Test(enabled = false, description = "tokenIssue and transfer to account") - public void tokenIssueAndTransferToAccount() { - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 3100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue001.sol"; - String contractName = "tvmAssetIssue001"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // transfer token to create exist account - Assert.assertTrue(PublicMethed - .sendcoin(dev003Address, 10_000_000L, dev001Address, dev001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long dev001AddressBalanceBefore = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceBefore: " + dev001AddressBalanceBefore); - param = "\"" + Base58.encode58Check(dev003Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long dev001AddressBalanceAfter = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceAfter: " + dev001AddressBalanceAfter); - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev003AssetValue = PublicMethed - .getAssetIssueValue(dev003Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev003AssetValue); - - // transfer token to create new account - long dev001AddressBalanceBefore1 = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceBefore1: " + dev001AddressBalanceBefore1); - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 30000); - long dev001AddressBalanceAfter2 = PublicMethed.queryAccount(dev001Address, blockingStubFull) - .getBalance(); - logger.info("dev001AddressBalanceAfter2: " + dev001AddressBalanceAfter2); - long assetIssueValueAfter1 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValueAfter - 100L, assetIssueValueAfter1); - Assert.assertEquals(100L, dev002AssetValue); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java deleted file mode 100644 index ba61000f6a6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmassetissue/TvmAssetIssue005.java +++ /dev/null @@ -1,703 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmassetissue; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmAssetIssue005 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000L; - private static String name = "testAssetIssue_" + Long.toString(now); - private static String abbr = "testAsset_" + Long.toString(now); - private static String description = "desc_" + Long.toString(now); - private static String url = "url_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - private long contractAddressBalance; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] dev002Address = ecKey2.getAddress(); - private String dev002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - private byte[] dev003Address = ecKey3.getAddress(); - private String dev003Key = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - private byte[] dev004Address = ecKey4.getAddress(); - private String dev004Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(dev002Key); - PublicMethed.printAddress(dev003Key); - PublicMethed.printAddress(dev004Key); - Assert.assertTrue(PublicMethed - .sendcoin(dev001Address, 7000_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "tokenIssue and updateAsset with suicide to account") - public void tokenIssue001AndSuicideToAccount() { - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue005.sol"; - String contractName = "tvmAssetIssue005"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - // deploy - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - // tokenIssue - name = "testAssetIssu1_" + Long.toString(now); - abbr = "testAsse1_" + Long.toString(now); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - AssetIssueContract assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - AssetIssueContract assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress, blockingStubFull).get().getAssetIssue(0); - AssetIssueContract assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance - 1024000000L, contractAddressBalance2); - - // transferToken - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - - // updateAsset - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - param = "\"" + assetIssueId + "\",\"" + url + "\",\"" + description + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - long returnId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnId); - assetIssueId = PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - - // selfdestruct - String methodSuicide = "SelfdestructTest(address)"; - param = "\"" + Base58.encode58Check(dev003Address) + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodSuicide, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID().size()); - Assert.assertEquals(0, - PublicMethed.getAssetIssueByAccount(dev003Address, blockingStubFull).get() - .getAssetIssueCount()); - Assert.assertEquals(0, - PublicMethed.queryAccount(dev003Address, blockingStubFull).getAssetIssuedID().size()); - long contractAssetCountDev003 = PublicMethed - .getAssetIssueValue(dev003Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValueAfter, contractAssetCountDev003); - assetIssueValue = PublicMethed.queryAccount(dev003Address, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(assetIssueValueAfter, assetIssueValue); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress, blockingStubFull).get().getAssetIssue(0); - assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(100L, dev002AssetValue); - - Assert.assertTrue(PublicMethed - .sendcoin(dev002Address, 100_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // transferAsset,success - Assert.assertTrue(PublicMethed.transferAsset(dev002Address, assetIssueId.getBytes(), 100L, - dev003Address, dev003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long assetIssueValueDev002 = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - long assetIssueValueDev003 = PublicMethed - .getAssetIssueValue(dev003Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(200L, assetIssueValueDev002); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueDev003); - - Assert.assertTrue(PublicMethed.transferAsset(dev004Address, assetIssueId.getBytes(), 102L, - dev002Address, dev002Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long assetIssueValueDev002After = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - long assetIssueValueDev004 = PublicMethed - .getAssetIssueValue(dev004Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(102L, assetIssueValueDev004); - Assert.assertEquals(assetIssueValueDev002 - 102L, assetIssueValueDev002After); - - // updateAsset,will fail - Assert.assertFalse(PublicMethed - .updateAsset(dev003Address, "updateDesc1".getBytes(), "updateURL1".getBytes(), 1L, 2L, - dev003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertFalse(PublicMethed - .updateAsset(contractAddress, "updateDesc2".getBytes(), "updateURL2".getBytes(), 3L, 4L, - dev003Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert - .assertEquals(description, ByteArray.toStr(assetIssueById.getDescription().toByteArray())); - Assert.assertEquals(url, ByteArray.toStr(assetIssueById.getUrl().toByteArray())); - Assert.assertEquals(Base58.encode58Check(contractAddress), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "tokenIssue and updateAsset with suicide to contract") - public void tokenIssue002AndSuicideToContract() { - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue005.sol"; - String contractName = "tvmAssetIssue005"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - long callvalue = 1050000000L; - - // deploy - String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - byte[] contractAddress2 = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress2, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - long contractAddressBalance2 = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance2); - - deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - callvalue, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBalance); - - // tokenIssue - name = "testAssetIssu2_" + Long.toString(now); - abbr = "testAsse2_" + Long.toString(now); - String methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - String param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - String txid = PublicMethed.triggerContract(contractAddress2, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String assetIssueId = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - logger.info("getAssetV2Map(): " + PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map()); - long assetIssueValue = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(totalSupply, assetIssueValue); - AssetIssueContract assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress2), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - AssetIssueContract assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - AssetIssueContract assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress2, blockingStubFull).get().getAssetIssue(0); - AssetIssueContract assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - long contractAddressBalanceAfter2 = PublicMethed - .queryAccount(contractAddress2, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance2 - 1024000000L, contractAddressBalanceAfter2); - - // transferToken - String methodTransferToken = "transferToken(address,uint256,trcToken)"; - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress2, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long assetIssueValueAfter = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(100L, dev002AssetValue); - - param = - "\"" + Base58.encode58Check(contractAddress) + "\"," + 50 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress2, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long assetIssueValueAfter2 = PublicMethed.queryAccount(contractAddress2, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - long contractAssetValue = PublicMethed - .getAssetIssueValue(contractAddress, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValueAfter - 50L, assetIssueValueAfter2); - Assert.assertEquals(50L, contractAssetValue); - - // selfdestruct - String methodSuicide = "SelfdestructTest(address)"; - param = "\"" + Base58.encode58Check(contractAddress) + "\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress2, methodSuicide, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, - PublicMethed.queryAccount(contractAddress2, blockingStubFull).getAssetIssuedID().size()); - Assert.assertEquals(0, - PublicMethed.getAssetIssueByAccount(contractAddress, blockingStubFull).get() - .getAssetIssueCount()); - Assert.assertEquals(0, - PublicMethed.queryAccount(contractAddress, blockingStubFull).getAssetIssuedID().size()); - assetIssueValue = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - Assert.assertEquals(assetIssueValueAfter2 + 50L, assetIssueValue); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(assetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(assetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(totalSupply, assetIssueById.getTotalSupply()); - Assert.assertEquals(6, assetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(contractAddress2), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - assetIssueByName = PublicMethed.getAssetIssueByName(name, blockingStubFull); - assetIssueByAccount = PublicMethed - .getAssetIssueByAccount(contractAddress2, blockingStubFull).get().getAssetIssue(0); - assetIssueListByName = PublicMethed - .getAssetIssueListByName(name, blockingStubFull) - .get().getAssetIssue(0); - Assert.assertEquals(assetIssueId, assetIssueByName.getId()); - Assert.assertEquals(name, ByteArray.toStr(assetIssueByAccount.getName().toByteArray())); - Assert.assertEquals(assetIssueId, assetIssueListByName.getId()); - - // transferToken,success - methodTransferToken = "transferToken(address,uint256,trcToken)"; - param = "\"" + Base58.encode58Check(dev002Address) + "\"," + 100 + ",\"" + assetIssueId + "\""; - txid = PublicMethed.triggerContract(contractAddress, methodTransferToken, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - assetIssueValueAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getAssetV2Map().get(assetIssueId); - dev002AssetValue = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(assetIssueValue - 100L, assetIssueValueAfter); - Assert.assertEquals(200L, dev002AssetValue); - - Assert.assertTrue(PublicMethed.transferAsset(dev004Address, assetIssueId.getBytes(), 12L, - dev002Address, dev002Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - long assetIssueValueDev002After = PublicMethed - .getAssetIssueValue(dev002Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - long assetIssueValueDev004 = PublicMethed - .getAssetIssueValue(dev004Address, ByteString.copyFrom(assetIssueId.getBytes()), - blockingStubFull); - Assert.assertEquals(12L, assetIssueValueDev004); - Assert.assertEquals(dev002AssetValue - 12L, assetIssueValueDev002After); - - // updateAsset,will fail - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - param = "\"" + assetIssueId + "\",\"updateUrl\",\"updateDesc\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(0, returnId); - assetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(0, assetIssueById.getDescription().size()); - Assert.assertEquals(0, assetIssueById.getUrl().size()); - Assert.assertEquals(Base58.encode58Check(contractAddress2), - Base58.encode58Check(assetIssueById.getOwnerAddress().toByteArray())); - } - - @Test(enabled = false, description = "tokenIssue and updateAsset suicide with create2") - public void tokenIssue003AndSuicideWithCreate2() { - String filePath = "./src/test/resources/soliditycode/tvmAssetIssue005.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String deployTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", maxFeeLimit, - 0, 0, 10000, "0", 0L, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - logger.info("Deploy energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - if (deployTxid == null || infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress, blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String methodTokenIssue = "deploy(uint256)"; - String param = "" + 6; - logger.info("param: " + param); - String txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger.info( - "the value: " + PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray())); - List retList = PublicMethed - .getStrings(transactionInfo.getLogList().get(0).getData().toByteArray()); - Long actualSalt = ByteArray.toLong(ByteArray.fromHexString(retList.get(1))); - logger.info("actualSalt: " + actualSalt); - byte[] tmpAddress = new byte[20]; - System.arraycopy(ByteArray.fromHexString(retList.get(0)), - 12, tmpAddress, 0, 20); - String addressHex = "41" + ByteArray.toHexString(tmpAddress); - logger.info("address_hex: " + addressHex); - String addressFinal = Base58.encode58Check(ByteArray.fromHexString(addressHex)); - logger.info("address_final: " + addressFinal); - byte[] callContractAddress = WalletClient.decodeFromBase58Check(addressFinal); - - Assert.assertTrue(PublicMethed - .sendcoin(callContractAddress, 1500_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - name = "testAssetIssu3_" + Long.toString(now); - abbr = "testAsse3_" + Long.toString(now); - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - String tokenName = PublicMethed.stringToHexString(name); - String tokenAbbr = PublicMethed.stringToHexString(abbr); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String assetIssueId = PublicMethed.queryAccount(callContractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId: " + assetIssueId); - long returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId)); - - String methodSuicide = "SelfdestructTest(address)"; - param = "\"" + Base58.encode58Check(dev003Address) + "\"," + 10000000; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodSuicide, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - methodTokenIssue = "deploy(uint256)"; - param = "" + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(contractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .sendcoin(callContractAddress, 1500_000_000L, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - methodTokenIssue = "tokenIssue(bytes32,bytes32,uint64,uint8)"; - tokenName = PublicMethed.stringToHexString("testAssetIssue_11111"); - tokenAbbr = PublicMethed.stringToHexString("testAssetIssue_22222"); - param = - "\"" + tokenName + "\",\"" + tokenAbbr + "\"," + totalSupply + "," + 6; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodTokenIssue, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - - String assetIssueId2 = PublicMethed.queryAccount(callContractAddress, blockingStubFull) - .getAssetIssuedID().toStringUtf8(); - logger.info("assetIssueId2: " + assetIssueId2); - returnAssetId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - logger.info("returnAssetId: " + returnAssetId); - Assert.assertEquals(returnAssetId, Long.parseLong(assetIssueId2)); - Assert.assertEquals(Long.parseLong(assetIssueId) + 1, Long.parseLong(assetIssueId2)); - Assert.assertEquals(2, - PublicMethed.getAssetIssueByAccount(callContractAddress, blockingStubFull).get() - .getAssetIssueCount()); - - // updateAsset - String methodUpdateAsset = "updateAsset(trcToken,string,string)"; - param = "\"123\",\"updateURLURL\",\"updateDESCDESC\""; - logger.info("param: " + param); - txid = PublicMethed.triggerContract(callContractAddress, methodUpdateAsset, param, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - long returnId = ByteArray.toLong((infoById.get().getContractResult(0).toByteArray())); - Assert.assertEquals(1, returnId); - String newAssetIssueId = PublicMethed.queryAccount(callContractAddress, blockingStubFull) - .getAssetIssuedID() - .toStringUtf8(); - logger.info("newAssetIssueId: " + newAssetIssueId); - AssetIssueContract newAssetIssueById = PublicMethed - .getAssetIssueById(newAssetIssueId, blockingStubFull); - Assert.assertEquals("testAssetIssue_11111", - ByteArray.toStr(newAssetIssueById.getName().toByteArray())); - Assert.assertEquals("testAssetIssue_22222", - ByteArray.toStr(newAssetIssueById.getAbbr().toByteArray())); - Assert - .assertEquals("updateDESCDESC", - ByteArray.toStr(newAssetIssueById.getDescription().toByteArray())); - Assert.assertEquals("updateURLURL", ByteArray.toStr(newAssetIssueById.getUrl().toByteArray())); - Assert.assertEquals(6, newAssetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(callContractAddress), - Base58.encode58Check(newAssetIssueById.getOwnerAddress().toByteArray())); - - AssetIssueContract oldAssetIssueById = PublicMethed - .getAssetIssueById(assetIssueId, blockingStubFull); - Assert.assertEquals(name, ByteArray.toStr(oldAssetIssueById.getName().toByteArray())); - Assert.assertEquals(abbr, ByteArray.toStr(oldAssetIssueById.getAbbr().toByteArray())); - Assert.assertEquals(0, oldAssetIssueById.getDescription().size()); - Assert.assertEquals(0, oldAssetIssueById.getUrl().size()); - Assert.assertEquals(6, oldAssetIssueById.getPrecision()); - Assert.assertEquals(Base58.encode58Check(callContractAddress), - Base58.encode58Check(oldAssetIssueById.getOwnerAddress().toByteArray())); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(dev001Address, dev001Key, fromAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java deleted file mode 100644 index 2dbc0b54cf9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/ContractRewardTest001.java +++ /dev/null @@ -1,233 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.Return.response_code; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.Protocol.TransactionInfo.code; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ContractRewardTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String witnessKey = Configuration.getByPath("testng.conf").getString("witness.key1"); - private String witnessAddress = PublicMethed.getAddressString(witnessKey); - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - //= Base58.decode58Check("TQYK8QPAFtxjmse1dShHWYXEMsF836jxxe"); - - @BeforeSuite(enabled = false, description = "stake beforeSuite delete") - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - - String filePath = "src/test/resources/soliditycode/stackContract001.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000_000L, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + witnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - } - - @Test(enabled = false,description = "querry SR account, reward should equal to gerRewardInfo") - void rewardbalanceTest001() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(PublicMethed.getFinalAddress(witnessKey))) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + witnessAddress + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - System.out.println(txen); - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(reward,rewardBalance); - } - - @Test(enabled = false,description = "querry 0x00, reward should be 0") - void rewardbalanceTest002() { - String methedStr = "nullAddressTest()"; - String argStr = ""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(rewardBalance,0); - } - - @Test(enabled = false,description = "querry UnActive account , reward should be 0") - void rewardbalanceTest003() { - ECKey ecKey2 = new ECKey(Utils.getRandom()); - String key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + PublicMethed.getAddressString(key) + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(rewardBalance,0); - } - - @Test(enabled = false,description = "querry contract account,reward should equal to " - + "gerRewardInfo") - void rewardbalanceTest004() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(contractAddress)) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - logger.info("rewardBalance: " + rewardBalance); - logger.info("reward: " + reward); - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(rewardBalance,reward); - } - - @Test(enabled = false,description = "querry ZeroReward account, reward should be 0") - void rewardbalanceTest005() { - BytesMessage bytesMessage = BytesMessage.newBuilder().setValue(ByteString - .copyFrom(PublicMethed.getFinalAddress(testFoundationKey))) - .build(); - long reward = blockingStubFull.getRewardInfo(bytesMessage).getNum(); - - String methedStr = "rewardBalance(address)"; - String argStr = "\"" + PublicMethed.getAddressString(testFoundationKey) + "\""; - TransactionExtention txen = PublicMethed.triggerConstantContractForExtention(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - long rewardBalance = ByteArray.toLong(txen.getConstantResult(0).toByteArray()); - - Assert.assertEquals(txen.getResult().getCode(), response_code.SUCCESS); - Assert.assertEquals(reward,rewardBalance,0); - } - - @Test(enabled = false,description = "withdrawBalance") - void withdrawBalanceTest006() { - //contractAddress = Base58.decode58Check("TBsf2FCSht83CEA8CSZ1ReQTRDByNB7FCe"); - - String methedStr = "withdrawRewardTest()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - int result = ByteArray.toInt(ext.getContractResult(0).toByteArray()); - Assert.assertEquals(result,0); - Assert.assertEquals(ext.getResult(), code.SUCESS); - } - - @Test(enabled = false,description = "withdrawBalance twice") - void withdrawBalanceTest007() { - String methedStr = "withdrawRewardTest()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - int result = ByteArray.toInt(ext.getContractResult(0).toByteArray()); - Assert.assertEquals(result,0); - Assert.assertEquals(ext.getResult(), code.SUCESS); - } - - @Test(enabled = false,description = "withdrawBalance other contract") - void withdrawBalanceTest008() { - String filePath = "src/test/resources/soliditycode/stackContract001.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] otherContract = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 100_000_000L, 100, null, - testFoundationKey, testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - String methedStr = "contractBWithdrawRewardTest(address)"; - String argStr = "\"" + Base58.encode58Check(otherContract) + "\""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - int result = ByteArray.toInt(ext.getContractResult(0).toByteArray()); - Assert.assertEquals(result,0); - Assert.assertEquals(ext.getResult(), TransactionInfo.code.SUCESS); - } - - @Test(enabled = false,description = "new withdrawBalance constructor") - void withdrawBalanceTest009() { - String methedStr = "createA()"; - String argStr = ""; - String txid = PublicMethed.triggerContract(contractAddress, - methedStr,argStr,false,0,maxFeeLimit,"0",0,testAddress001,testKey001,blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - TransactionInfo ext = PublicMethed.getTransactionInfoById(txid, blockingStubFull).get(); - - int result = ByteArray.toInt(ext.getLog(0).getData().toByteArray()); - Assert.assertEquals(result,0); - int result2 = ByteArray.toInt(ext.getLog(1).getData().toByteArray()); - Assert.assertEquals(result2,0); - Assert.assertEquals(ext.getResult(), code.SUCESS); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java deleted file mode 100644 index c1a3d68992e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/IsSrCandidateTest001.java +++ /dev/null @@ -1,118 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class IsSrCandidateTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/isSRCandidate.sol"; - String contractName = "TestIsSRCandidate"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, testKey001, - testAddress001, blockingStubFull); - } - - @Test(enabled = false, description = "Witness Address should be true") - void tvmStakeTest001() { - String methodStr = "isSRCandidateTest(address)"; - String argsStr = "\"" + PublicMethed.getAddressString(testWitnessKey) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,1); - } - - @Test(enabled = false, description = "Account Address should be false") - void tvmStakeTest002() { - String methodStr = "isSRCandidateTest(address)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,0); - } - - @Test(enabled = false, description = "zero Address(0x00) should be false") - void tvmStakeTest003() { - String methodStr = "zeroAddressTest()"; - String argsStr = ""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,0); - } - - @Test(enabled = false, description = "Contract Address should be false") - void tvmStakeTest004() { - String methodStr = "localContractAddrTest()"; - String argsStr = ""; - TransactionExtention returns = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, "", 0, testAddress001, testKey001, blockingStubFull); - int isSR = ByteArray.toInt(returns.getConstantResult(0).toByteArray()); - - Assert.assertEquals(isSR,0); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java deleted file mode 100644 index f1a43ad8e49..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StackSuicideTest001.java +++ /dev/null @@ -1,247 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StackSuicideTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessAddress = PublicMethed.getAddressString(testWitnessKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = false, description = "targetAddress no TRX, and no frozen") - public void stackSuicideTest001() { - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, 100, null, testKey001, - testAddress001, blockingStubFull); - - final byte[] targetAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0, 100, null, testKey001, testAddress001, blockingStubFull); - - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + Base58.encode58Check(targetAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress has TRX, but no frozen") - public void stackSuicideTest002() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, 100, null, testKey001, - testAddress001, blockingStubFull); - - - Long targetBalance = 10_000_000L; - final byte[] targetAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, targetBalance, 100, null, testKey001, testAddress001, blockingStubFull); - - String methedStr = "Stake(address,uint256)"; - String argStr = "\"" + testWitnessAddress + "\",10000000"; - String txid = PublicMethed.triggerContract(contractAddress,methedStr, - argStr,false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(targetAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - - methedStr = "transfer(address,uint256)"; - argStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + targetBalance; - txid = PublicMethed.triggerContract(targetAddress,methedStr,argStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(0,PublicMethed.queryAccount(targetAddress,blockingStubFull).getBalance()); - } - - @Test(enabled = false, description = "targetAddress has TRX, and has frozen") - public void stackSuicideTest003() { - Long targetBalance = 10_000_000L; - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, targetBalance, 100, - null, testKey001, testAddress001, blockingStubFull); - - final byte[] targetAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 12_345_678L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methedStr = "Stake(address,uint256)"; - String argStr = "\"" + testWitnessAddress + "\"," + targetBalance; - String txid = PublicMethed.triggerContract(contractAddress,methedStr, - argStr,false,0,maxFeeLimit, testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - argStr = "\"" + testWitnessAddress + "\"," + 12_000_000L; - String txid2 = PublicMethed.triggerContract(targetAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid2,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozen = targetAccount.getFrozen(0); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(targetAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - - targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccount.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozen.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozen.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozen.getFrozenBalance()); - - methedStr = "transfer(address,uint256)"; - argStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + 345678; - txid = PublicMethed.triggerContract(targetAddress,methedStr,argStr,false,0, - maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertEquals(0,PublicMethed.queryAccount(targetAddress,blockingStubFull).getBalance()); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java deleted file mode 100644 index 2856b2d436c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest002.java +++ /dev/null @@ -1,186 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StakeSuicideTest002 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessAddress = PublicMethed.getAddressString(testWitnessKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "B"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "create2 -> stake -> suicide -> create2 the same Address") - public void stackSuicideAndCreate2Test001() { - - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - - String methedStr = "deploy(bytes,uint256)"; - String argStr = "\"" + code + "\"," + 1; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String hex = "41" + ByteArray.toHexString(ex.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("Deploy Address : " + Base58.encode58Check(ByteArray.fromHexString(hex))); - byte[] ownerAddress = ByteArray.fromHexString(hex); - - methedStr = "Stake(address,uint256)"; - argStr = "\"" + testWitnessAddress + "\"," + 10_000_000; - txid = PublicMethed.triggerContract(ownerAddress,methedStr, - argStr,false,10_000_000,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed.triggerContract(ownerAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - methedStr = "deploy(bytes,uint256)"; - argStr = "\"" + code + "\"," + 1; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - Assert.assertEquals(ownerAccount.getBalance(),0); - Assert.assertEquals(ownerAccount.getFrozenCount(),0); - Assert.assertEquals(ownerAccount.getVotesCount(),0); - - Account targetAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - - } - - @Test(enabled = false, description = "create2 -> stake -> suicide -> sendcoin to create2 Address") - public void stackSuicideAndCreate2Test002() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - - String methedStr = "deploy(bytes,uint256)"; - String argStr = "\"" + code + "\"," + 2; - String txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - String hex = "41" + ByteArray.toHexString(ex.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("Deploy Address : " + Base58.encode58Check(ByteArray.fromHexString(hex))); - byte[] ownerAddress = ByteArray.fromHexString(hex); - - methedStr = "Stake(address,uint256)"; - argStr = "\"" + testWitnessAddress + "\"," + 10_000_000; - txid = PublicMethed.triggerContract(ownerAddress,methedStr, - argStr,false,10_000_000,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - - methedStr = "SelfdestructTest(address)"; - argStr = "\"" + Base58.encode58Check(testAddress001) + "\""; - txid = PublicMethed.triggerContract(ownerAddress,methedStr,argStr,false, - 0,maxFeeLimit,testFoundationAddress,testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long sendcoin = 1; - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress,sendcoin,testFoundationAddress, - testFoundationKey,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ownerAccount = PublicMethed.queryAccount(ownerAddress,blockingStubFull); - Assert.assertEquals(ownerAccount.getBalance(),sendcoin); - Assert.assertEquals(ownerAccount.getFrozenCount(),0); - Assert.assertEquals(ownerAccount.getVotesCount(),0); - - Account targetAccount = PublicMethed.queryAccount(testAddress001,blockingStubFull); - Frozen targetFrozen = targetAccount.getFrozen(0); - - Assert.assertEquals(ownerFrozen.getExpireTime(),targetFrozen.getExpireTime()); - Assert.assertEquals(ownerFrozen.getFrozenBalance(),targetFrozen.getFrozenBalance()); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java deleted file mode 100644 index 6393aece552..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest003.java +++ /dev/null @@ -1,196 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class StakeSuicideTest003 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessAddress = PublicMethed.getAddressString(testWitnessKey); - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.sendcoin(testAddress001,10000000,testFoundationAddress, - testFoundationKey,blockingStubFull); - } - - @Test(enabled = false, description = "suicide target Address is owner Address") - public void stakeSuicideTest001() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen ownerFrozen = ownerAccount.getFrozen(0); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account account = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(account.getFrozenCount(),0); - - } - - @Test(enabled = false, description = "suicide target Address is BlackHoleAddress Address") - public void stakeSuicideTest002() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen ownerFrozen = ownerAccount.getFrozen(0); - - String blackHoleAddress = "TLsV52sRDL79HXGGm9yzwKibb6BeruhUzy"; - final Account accountBefore = PublicMethed - .queryAccount(PublicMethed.decode58Check(blackHoleAddress), - blockingStubFull); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + blackHoleAddress + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account account = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(account.getFrozenCount(),0); - - Account accountAfter = PublicMethed - .queryAccount(PublicMethed.decode58Check(blackHoleAddress), - blockingStubFull); - Assert.assertEquals(accountBefore.getBalance() + ex.get().getReceipt().getEnergyFee() - + 10000000, accountAfter.getBalance()); - } - - @Test(enabled = false, description = "suicide target Address is BlackHoleAddress Address") - public void stakeSuicideTest003() { - String filePath = "src/test/resources/soliditycode/stackSuicide001.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 10000000L, - 100, null, testFoundationKey, - testFoundationAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String txid = PublicMethed.triggerContract(contractAddress,"Stake(address,uint256)", - "\"" + testWitnessAddress + "\",10000000",false,0,maxFeeLimit, - testFoundationAddress, testFoundationKey,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Frozen ownerFrozen = ownerAccount.getFrozen(0); - - final Account accountBefore = PublicMethed - .queryAccount(PublicMethed.decode58Check("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"), - blockingStubFull); - - String methedStr = "SelfdestructTest(address)"; - String argStr = "\"" + "T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb" + "\""; - txid = PublicMethed.triggerContract(contractAddress,methedStr,argStr,false, - 0,maxFeeLimit,testAddress001,testKey001,blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - ex = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account account = PublicMethed.queryAccount(contractAddress,blockingStubFull); - Assert.assertEquals(account.getFrozenCount(),0); - - Account accountAfter = PublicMethed - .queryAccount(PublicMethed.decode58Check("T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb"), - blockingStubFull); - Assert.assertEquals(accountBefore.getBalance() + 10000000, accountAfter.getBalance()); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java deleted file mode 100644 index 69bcbcff619..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest004.java +++ /dev/null @@ -1,397 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class StakeSuicideTest004 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - private byte[] testWitnessAddress2 = PublicMethed.getFinalAddress(testWitnessKey2); - - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] contractAddress; - String filePath = "src/test/resources/soliditycode/testStakeSuicide.sol"; - String contractName = "testStakeSuicide"; - String code = ""; - String abi = ""; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - System.out.println(testKey001); - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_00000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000_000000L, 100, - null, testKey001, testAddress001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "targetAddress has frozen 1,suicide contract stake 1") - void tvmStakeSuicideTest001() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozenBefore.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozenBefore.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress has frozen 1,suicide contract stake all") - void tvmStakeSuicideTest002() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozenBefore.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozenBefore.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress has frozen all,suicide contract stake all") - void tvmStakeSuicideTest003() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 20_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(targetAddress,5_000000L, - 3,1, ByteString.copyFrom(testAddress001),testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,10_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - BigInteger expected = - BigInteger.valueOf(ownerFrozen.getExpireTime()) - .multiply(BigInteger.valueOf(ownerFrozen.getFrozenBalance())) - .add(BigInteger.valueOf(targetFrozenBefore.getExpireTime()) - .multiply(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))) - .divide(BigInteger.valueOf(ownerFrozen.getFrozenBalance()) - .add(BigInteger.valueOf(targetFrozenBefore.getFrozenBalance()))); - - Assert.assertEquals(expected.longValue(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance() + targetFrozenBefore.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress is new account ,suicide contract stake all") - void tvmStakeSuicideTest004() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - System.out.println(Base58.encode58Check(targetAddress)); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - - - Assert.assertEquals(ownerFrozen.getExpireTime(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance()); - - } - - @Test(enabled = false, description = "targetAddress frozen to other address ,suicide contract " - + "stake all") - void tvmStakeSuicideTest005() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] address = ecKey.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(targetAddress,5_000000L, - 3,1, ByteString.copyFrom(testAddress001),testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - System.out.println("aaaa" + Base58.encode58Check(targetAddress)); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 100_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 100_000000L; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional ex = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - System.out.println("aaaaa" + Base58.encode58Check(contractAddress)); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - Assert.assertEquals(ByteArray.toInt(ex.get().getContractResult(0).toByteArray()),1); - - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Frozen ownerFrozen = ownerAccount.getFrozen(0); - Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenAfter = targetAccount.getFrozen(0); - ex = PublicMethed.getTransactionInfoById(txidSuicide, blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - Assert.assertEquals(ownerFrozen.getExpireTime(), targetFrozenAfter.getExpireTime()); - Assert.assertEquals(targetFrozenAfter.getFrozenBalance(), - ownerFrozen.getFrozenBalance()); - - } - - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java deleted file mode 100644 index b324672d6ab..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeSuicideTest005.java +++ /dev/null @@ -1,204 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.Frozen; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -public class StakeSuicideTest005 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - private byte[] testWitnessAddress2 = PublicMethed.getFinalAddress(testWitnessKey2); - - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] testAddress002 = ecKey2.getAddress(); - String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] contractAddress; - String filePath = "src/test/resources/soliditycode/testStakeSuicide.sol"; - String contractName = "testStakeSuicide"; - String code = ""; - String abi = ""; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - @BeforeClass(enabled = false) - public void beforeClass() { - System.out.println(testKey001); - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_00000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "targetAddress is account no TRX, and no frozen") - void tvmStakeSuicideTest001() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000_000000L, 100, - null, testKey001, testAddress001, blockingStubFull); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Long ownerBalance = ownerAccount.getBalance(); - - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txidSuicide, - blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Long targetBalance = targetAccount.getBalance(); - - System.out.println(targetBalance); - Assert.assertEquals(ownerBalance,targetBalance); - - } - - @Test(enabled = false, description = "targetAddress is account 1 TRX, and no frozen") - void tvmStakeSuicideTest002() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - final String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - - PublicMethed - .sendcoin(targetAddress, 1_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Long ownerBalance = ownerAccount.getBalance(); - - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txidSuicide, - blockingStubFull); - ex = PublicMethed.getTransactionInfoById(txidSuicide,blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Long targetBalance = targetAccount.getBalance() - 1_000000L; - - Assert.assertEquals(ownerBalance,targetBalance); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = false, description = "targetAddress is account 1 TRX, and 1 frozen") - void tvmStakeSuicideTest003() { - ECKey ecKeyTargetAddress = new ECKey(Utils.getRandom()); - byte[] targetAddress = ecKeyTargetAddress.getAddress(); - String testKeyTargetAddress = ByteArray.toHexString(ecKeyTargetAddress.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed - .sendcoin(targetAddress, 10_000000L, testFoundationAddress, testFoundationKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethed - .freezeBalance(targetAddress,1_000000L,3,testKeyTargetAddress,blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account targetAccount = PublicMethed.queryAccount(targetAddress,blockingStubFull); - final Frozen targetFrozenBefore = targetAccount.getFrozen(0); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account ownerAccount = PublicMethed.queryAccount(contractAddress,blockingStubFull); - final Long ownerBalance = ownerAccount.getBalance(); - String methodStrSuicide = "SelfdestructTest(address)"; - String argsStrSuicide = "\"" + Base58.encode58Check(targetAddress) + "\""; - String txidSuicide = PublicMethed - .triggerContract(contractAddress, methodStrSuicide, argsStrSuicide, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional ex = PublicMethed.getTransactionInfoById(txidSuicide, - blockingStubFull); - Assert.assertEquals(ex.get().getResult(), TransactionInfo.code.SUCESS); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account targetAccountAfter = PublicMethed.queryAccount(targetAddress,blockingStubFull); - Frozen targetFrozenAfter = targetAccountAfter.getFrozen(0); - Long targetBalance = targetAccountAfter.getBalance() - 9_000000L; - Assert.assertEquals(targetFrozenBefore,targetFrozenAfter); - Assert.assertEquals(ownerBalance,targetBalance); - - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java deleted file mode 100644 index 4b9102fc901..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/StakeTest001.java +++ /dev/null @@ -1,312 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class StakeTest001 { - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private String testWitnessKey2 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - private byte[] testWitnessAddress2 = PublicMethed.getFinalAddress(testWitnessKey2); - - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(testAddress001, 1000_000_00000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/testStakeSuicide.sol"; - String contractName = "testStakeSuicide"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 1000_000_0000L, 100, null, testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Vote for witness") - void tvmStakeTest001() { - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - - Account request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - long balanceAfter = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - Assert.assertEquals(balanceAfter,balanceBefore - 1000000); - byte[] voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0) - .getVoteAddress().toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - Assert.assertEquals(1,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - - - } - - @Test(enabled = false, description = "Non-witness account") - void tvmStakeTest002() { - //account address - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testAddress001) + "\"," + 1000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,0); - - //contract address - methodStr = "Stake(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(contractAddress) + "\"," + 1000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,0); - - - } - - - @Test(enabled = false, description = "Number of votes over balance") - void tvmStakeTest003() { - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + Long.MAX_VALUE; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - - Assert.assertEquals(contractResult,0); - - } - - - @Test(enabled = false, description = "Enough votes for a second ballot") - void tvmStakeTest004() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 21000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - Account request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - byte[] voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0) - .getVoteAddress().toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - System.out.println(blockingStubFull.getAccount(request).getVotesCount()); - Assert.assertEquals(21,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 11000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0).getVoteAddress() - .toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - Assert.assertEquals(11,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - } - - - @Test(enabled = false, description = "Revert test") - void tvmStakeTest005() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "revertTest1(address,uint256,address)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000 + ",\"" - + Base58.encode58Check(testAddress001) + "\""; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - - Assert.assertEquals(contractResult,0); - - } - - - @Test(enabled = false, description = "Contract Call Contract stake") - void tvmStakeTest006() { - String methodStr = "deployB()"; - String argsStr = ""; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("txid:" + txid); - - methodStr = "BStake(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 1000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long callvalue = 1000000000L; - txid = PublicMethed.triggerContract(contractAddress, "deployB()", "#", false, - callvalue, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - byte[] contractAddressB = ByteArray.fromHexString(addressHex); - long contractAddressBBalance = PublicMethed.queryAccount(contractAddressB, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBBalance); - - methodStr = "BStake(address,uint256)"; - argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddressB, blockingStubFull); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - long balanceAfter = account.getBalance(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - Assert.assertEquals(balanceAfter, contractAddressBBalance - 10000000); - - } - - @Test(enabled = false, description = "Vote for the first witness and then vote for the second " - + "witness.") - void tvmStakeTest007() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 21000000; - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - Account request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - byte[] voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0) - .getVoteAddress().toByteArray()); - Assert.assertEquals(testWitnessAddress,voteAddress); - System.out.println(blockingStubFull.getAccount(request).getVotesCount()); - Assert.assertEquals(21,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - argsStr = "\"" + Base58.encode58Check(testWitnessAddress2) + "\"," + 11000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - info = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult,1); - request = Account.newBuilder().setAddress(ByteString.copyFrom(contractAddress)).build(); - voteAddress = (blockingStubFull.getAccount(request).getVotesList().get(0).getVoteAddress() - .toByteArray()); - Assert.assertEquals(testWitnessAddress2,voteAddress); - Assert.assertEquals(11,blockingStubFull.getAccount(request).getVotes(0).getVoteCount()); - - } - -} - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java deleted file mode 100644 index be418169c53..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/tvmstake/UnStakeTest001.java +++ /dev/null @@ -1,471 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.tvmstake; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class UnStakeTest001 { - - private String testFoundationKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private byte[] testFoundationAddress = PublicMethed.getFinalAddress(testFoundationKey); - private String testWitnessKey = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - private byte[] testWitnessAddress = PublicMethed.getFinalAddress(testWitnessKey); - - - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] testAddress001 = ecKey1.getAddress(); - String testKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] testAddress002 = ecKey2.getAddress(); - private String testKey002 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private byte[] contractAddress; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testKey001); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = false, description = "unstake normal") - public void tvmStakeTest001Normal() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - - methodStr = "unStake()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "#", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), balanceBefore); - } - - @Test(enabled = false, description = "unstake when no stake") - public void tvmUnstakeTest002NoStake() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "unStake()"; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - Assert.assertEquals(account.getBalance(), balanceBefore); - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - } - - @Test(enabled = false, description = "unstake twice") - public void tvmUnstakeTest003UnstakeTwice() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - - methodStr = "unStake2()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), balanceBefore); - } - - @Test(enabled = false, description = "unstake revert") - public void tvmUnstakeTest004Revert() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - - methodStr = "revertTest2(address)"; - argsStr = "\"" + Base58.encode58Check(testAddress002) + "\""; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), 993000000L); - long balance = PublicMethed.queryAccount(testAddress002, blockingStubFull).getBalance(); - Assert.assertEquals(7000000L, balance); - } - - @Test(enabled = false, description = "unstake call another contract in one contract") - public void tvmUnstakeTest005CallAnotherInOneContract() { - PublicMethed - .sendcoin(testAddress001, 2120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long callvalue = 1000000000L; - String txid = PublicMethed.triggerContract(contractAddress, "deployB()", "#", false, - callvalue, maxFeeLimit, testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - String addressHex = - "41" + ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()) - .substring(24); - logger.info("address_hex: " + addressHex); - byte[] contractAddressB = ByteArray.fromHexString(addressHex); - logger.info("contractAddressB: " + Base58.encode58Check(contractAddressB)); - long contractAddressBBalance = PublicMethed.queryAccount(contractAddressB, blockingStubFull) - .getBalance(); - Assert.assertEquals(callvalue, contractAddressBBalance); - - String methodStr = "BStake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddressB, blockingStubFull); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - long balanceAfter = account.getBalance(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - Assert.assertEquals(balanceAfter, contractAddressBBalance - 10000000); - long contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance, 1000000000); - - methodStr = "BUnStake()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - account = PublicMethed.queryAccount(contractAddressB, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), contractAddressBBalance); - contractAddressBalance = PublicMethed.queryAccount(contractAddress, blockingStubFull) - .getBalance(); - Assert.assertEquals(contractAddressBalance, 1000000000); - } - - @Test(enabled = false, description = "unstake with reward balance") - public void tvmUnstakeTest006WithRewardBalance() { - PublicMethed - .sendcoin(testAddress001, 1120_000_000L, testFoundationAddress, testFoundationKey, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "./src/test/resources/soliditycode/unStake001.sol"; - String contractName = "unStakeTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 1000000000L, 100, null, - testKey001, testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String methodStr = "Stake(address,uint256)"; - String argsStr = "\"" + Base58.encode58Check(testWitnessAddress) + "\"," + 10000000; - long balanceBefore = PublicMethed.queryAccount(contractAddress, blockingStubFull).getBalance(); - String txid = PublicMethed - .triggerContract(contractAddress, methodStr, argsStr, - false, 0, maxFeeLimit, - testAddress001, testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional info = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - int contractResult = ByteArray.toInt(info.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 1); - Account account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceBefore - 10000000); - long frozenBalance = account.getFrozen(0).getFrozenBalance(); - byte[] voteAddress = account.getVotes(0).getVoteAddress().toByteArray(); - long voteCount = account.getVotes(0).getVoteCount(); - Assert.assertEquals(voteCount, 10); - Assert.assertEquals(voteAddress, testWitnessAddress); - Assert.assertEquals(frozenBalance, 10000000); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - methodStr = "rewardBalance(address)"; - argsStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, false, 0, 0, "0", - 0, testAddress001, testKey001, blockingStubFull); - Transaction transaction = transactionExtention.getTransaction(); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - org.junit.Assert.assertEquals(0, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - - methodStr = "withdrawReward()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - long balanceAfter2 = account.getBalance(); - Assert.assertEquals(balanceAfter, balanceAfter2); - - methodStr = "unStake2()"; - txid = PublicMethed - .triggerContract(contractAddress, methodStr, "", false, 0, maxFeeLimit, testAddress001, - testKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(infoById.toString()); - Assert.assertEquals(0, infoById.get().getResultValue()); - contractResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertEquals(contractResult, 0); - account = PublicMethed.queryAccount(contractAddress, blockingStubFull); - int frozenCount = account.getFrozenCount(); - int votesCount = account.getVotesCount(); - Assert.assertEquals(0, frozenCount); - Assert.assertEquals(0, votesCount); - Assert.assertEquals(account.getBalance(), balanceBefore); - - methodStr = "rewardBalance(address)"; - argsStr = "\"" + Base58.encode58Check(contractAddress) + "\""; - transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddress, methodStr, argsStr, false, 0, 0, "0", - 0, testAddress001, testKey001, blockingStubFull); - transaction = transactionExtention.getTransaction(); - result = transactionExtention.getConstantResult(0).toByteArray(); - System.out.println("message:" + transaction.getRet(0).getRet()); - System.out.println( - ":" + ByteArray.toStr(transactionExtention.getResult().getMessage().toByteArray())); - System.out.println("Result:" + Hex.toHexString(result)); - org.junit.Assert.assertEquals(0, ByteArray.toLong(ByteArray - .fromHexString(Hex - .toHexString(result)))); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - PublicMethed.freedResource(testAddress001, testKey001, testFoundationAddress, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign001.java deleted file mode 100644 index 32d378c4d83..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign001.java +++ /dev/null @@ -1,506 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.validatemultisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class TestValidatemultisign001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey001.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey002.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - ECKey ecKey003 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey003.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey003.getPrivKeyBytes()); - ECKey ecKey004 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey004.getAddress(); - String participateKey = ByteArray.toHexString(ecKey004.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private byte[] contractAddress = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy validatemultisign contract") - public void test001DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/validatemultisign001.sol"; - String contractName = "validatemultisignTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger validatemultisign contract with " - + "Permission(address) case") - public void test002validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - // Trigger with correct Permission address - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with wrong Permission address - merged = ByteUtil.merge(dev001Address, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(dev001Address), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with address that have not permission - merged = ByteUtil.merge(fromAddress, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(fromAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with not exist address - merged = ByteUtil.merge(manager1Address, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(manager1Address), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with error format address - merged = ByteUtil.merge(manager1Address, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList("TVgXWwGWE9huXiE4FuzDuGnCPUowsbZ8VZ", - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Trigger validatemultisign contract with " - + "Permission(permissionId) case") - public void test003validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - // Trigger with wrong PermissionID - long permissionId = 2; - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with error format PermissionID - permissionId = 100; - merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Long.MAX_VALUE + 1 PermissionID - permissionId = Long.MAX_VALUE + 1; - merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Long.MIN_VALUE - 1 PermissionID - permissionId = Long.MIN_VALUE - 1; - merged = ByteUtil.merge(ownerAddress, ByteArray.fromLong(permissionId), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "Trigger validatemultisign contract with " - + "Permission(hash) case") - public void test004validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, 0, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - // Trigger with no sign hash - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with wrong hash - transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, 0, ownerKey, blockingStubFull); - logger.info("hash: {}", Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes()); - - hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // 1) address B create transaction_1, but address A`s permission address sign - // 2) user address A verify transaction_1 that created by B - transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, dev001Address, 0, dev001Key, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - - hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.clear(); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign002.java deleted file mode 100644 index 8898e687459..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign002.java +++ /dev/null @@ -1,378 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.validatemultisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class TestValidatemultisign002 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey001.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey002.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - ECKey ecKey003 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey003.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey003.getPrivKeyBytes()); - ECKey ecKey004 = new ECKey(Utils.getRandom()); - byte[] manager4Address = ecKey004.getAddress(); - String manager4Key = ByteArray.toHexString(ecKey004.getPrivKeyBytes()); - ECKey ecKey005 = new ECKey(Utils.getRandom()); - byte[] manager5Address = ecKey005.getAddress(); - String manager5Key = ByteArray.toHexString(ecKey005.getPrivKeyBytes()); - ECKey ecKey006 = new ECKey(Utils.getRandom()); - byte[] manager6Address = ecKey006.getAddress(); - String manager6Key = ByteArray.toHexString(ecKey006.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private byte[] contractAddress = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy validatemultisign contract") - public void test001DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/validatemultisign001.sol"; - String contractName = "validatemultisignTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":3," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":2}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":3}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager4Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager5Key) + "\",\"weight\":1}," - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger validatemultisign with signatures num") - public void test002validatemultisign() { - List signatures = new ArrayList<>(); - int permissionId = 2; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, permissionId, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - - // Trigger with one signature - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with five signature - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey002.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with six signature - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey002.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey006.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Trigger validatemultisign with Duplicate signatures") - public void test003validatemultisign() { - List signatures = new ArrayList<>(); - int permissionId = 2; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, permissionId, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - // signatures with Duplicate signatures but weight enough - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey002.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Duplicate signatures and weight not enough - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - // Trigger with Duplicate signatures and fix signatures - signatures.clear(); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey005.sign(tosign).toByteArray())); - - parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - input = PublicMethed.parametersString(parameters); - - TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Trigger validatemultisign with weight") - public void test004validatemultisign() { - List signatures = new ArrayList<>(); - int permissionId = 2; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinWithPermissionIdNotSign( - fromAddress, 1L, ownerAddress, permissionId, ownerKey, blockingStubFull); - transaction = TransactionUtils.setTimestamp(transaction); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(permissionId), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - // signatures with weight not enough - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey004.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - permissionId, "0x" + Hex.toHexString(hash), signatures); - String input = PublicMethed.parametersString(parameters); - - String methodStr = "testmulti(address,uint256,bytes32,bytes[])"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, input, false, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign003.java deleted file mode 100644 index 840c86c0102..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/validatemultisign/TestValidatemultisign003.java +++ /dev/null @@ -1,242 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.validatemultisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Sha256Hash; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.AbiUtil; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class TestValidatemultisign003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey001 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey001.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey001.getPrivKeyBytes()); - ECKey ecKey002 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey002.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey002.getPrivKeyBytes()); - ECKey ecKey003 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey003.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey003.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private byte[] contractAddress = null; - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] dev001Address = ecKey1.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - } - - @Test(enabled = true, description = "Deploy validatemultisign contract") - public void test001DeployContract() { - Assert.assertTrue(PublicMethed.sendcoin(dev001Address, 1000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, 100_000_000L, - 0, 0, ByteString.copyFrom(dev001Address), testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(dev001Key, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/validatemultisign001.sol"; - String contractName = "validatemultisignTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Trigger validatemultisign precompiled contract, " - + "with wrong hash bytes") - public void test002validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String argsStr = PublicMethed.parametersString(parameters); - - byte[] inputBytesArray = Hex.decode(AbiUtil.parseMethod( - "validatemultisign(address,uint256,bytes32,bytes[])", argsStr, false)); - String input = ByteArray.toHexString(inputBytesArray); - - String methodStr = "testMultiPrecompileContract(bytes)"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, - AbiUtil.parseParameters(methodStr, Arrays.asList(input)), true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(0, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - - @Test(enabled = true, description = "Trigger validatemultisign precompiled contract, " - + "with correct hash bytes") - public void test003validatemultisign() { - List signatures = new ArrayList<>(); - - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - - Transaction transaction = PublicMethedForMutiSign.sendcoinGetTransaction( - fromAddress, 1L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - byte[] hash = Sha256Hash.of(CommonParameter.getInstance() - .isECKeyCryptoEngine(), transaction.getRawData().toByteArray()).getBytes(); - - byte[] merged = ByteUtil.merge(ownerAddress, ByteArray.fromInt(0), hash); - byte[] tosign = Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), merged); - - signatures.add(Hex.toHexString(ecKey003.sign(tosign).toByteArray())); - signatures.add(Hex.toHexString(ecKey001.sign(tosign).toByteArray())); - - List parameters = Arrays.asList(StringUtil.encode58Check(ownerAddress), - 0, "0x" + Hex.toHexString(hash), signatures); - String argsStr = PublicMethed.parametersString(parameters); - - String input = AbiUtil.parseParameters( - "validatemultisign(address,uint256,bytes32,bytes[])", argsStr); - - String methodStr = "testMultiPrecompileContract(bytes)"; - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methodStr, - AbiUtil.parseParameters(methodStr, Arrays.asList(input)), true, - 0, maxFeeLimit, dev001Address, dev001Key, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - infoById = PublicMethed.getTransactionInfoById(TriggerTxid, blockingStubFull); - logger.info("infoById" + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals(1, ByteArray.toInt(infoById.get().getContractResult(0).toByteArray())); - - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java deleted file mode 100644 index 548ebf5330b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyBurnProof001.java +++ /dev/null @@ -1,326 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class VerifyBurnProof001 { - - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] testAddress001 = ecKey1.getAddress(); - private String testPriKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testPriKey001); - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 1000_000_000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy VerfyMintProof contract ") - public void verifyBurnProof001() { - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testAddress001, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(testPriKey001, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/VerifyBurnProof001.sol"; - String contractName = "VerifyBurnProof001Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, testPriKey001, - testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - @Test(enabled = true, description = "data length != 512") - public void verifyBurnProofTest002() { - - String argsStr = "\"" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a" - /// add more 32bytes - + "0000000000000000000000000000000000000000000000000000000000000064\""; - - //argsStr = argsStr + "0000000000000000000000000000000000000000000000000000000000000064"; - - String methedStr = "VerifyBurnProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - - } - - @Test(enabled = true, description = "data is empty") - public void verifyBurnProofTest003() { - - String methedStr = "VerifyBurnProofSize003()"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, "", false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - - } - - @Test(enabled = true, description = "value greate than Long.MAX_VALUE") - public void verifyBurnProofTest004() { - - //String methedStr = "VerifyBurnProofSize002(bytes)"; - String methedStr = "VerifyBurnProofSize001(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32)"; - String argsStr = "" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000fffffffffffffff" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, true, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - // parseLong will return Long.MAX_VALUE and checkResult false - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - } - - @Test(enabled = true, description = "verify success with address call") - public void verifyBurnProofTest005() { - String argsStr = "\"" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a" - + "\""; - - String methedStr = "VerifyBurnProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000001", contractResult); - } - - @Test(enabled = true, description = "verify success with fuction call") - public void verifyBurnProofTest006() { - String argsStr = "" - + "c9cf924134dd8fbd11d3b245b00adf4797b48c42e001673e7c566ce229b8fdf6" - + "24097774778540c2c4d5acbeffe333e1f595a1b731cbe10848e3d3a527ba4d1b" - + "a079c66e70cae2225cd702a7c0977635755ad104a87f435634d4e5382ac2afc8" - + "1c47919273d4861ad815855ba1b4db5f90cc7e922b65c930c291eddc6d49a6c4" - + "90771325afc8e6e4a506f9dca0889dff75bcb4c46030702a33899b4d1e81122a" - + "a236433cf4c8ff426c66446de2f375b08575c4a18802e19a5fa5500922f7d570" - + "aac680208d05f9f2a9beaef0d9adede10e4a0242a3d1e048dd2a65034ef3f348" - + "0c108652d93da2ed13a0720fce9dce3a01a25cfa898bbaa8730f3fa8bba4b8a9" - + "7a609fd9f4d008a9334dea39acc838298c989ae0f31cbaa08e4b00342ba2c0b1" - + "ba37ac7be8084e0aeb01045f121e87e9cc942ecdc3b5e52933b79aad6f005d8e" - - + "dfc2aabf584106dfb2f6d3eb7f4584f5f2d9cba8340b0f73ba5fab4a4a024db2" - + "d00c5f0b3aba1f98cba6d1c9750591628daca165bac2de6fd694df833110ee01" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "19389f87908cb5f1ede2a9fe0c3047d2ad5fce424d133bacb655ae1179a81084" - + "102ce5ad22d815a64374da9e2207d722b1c9a3099b292eaea0862edc886ff70d" - - + "b85285dd55258a2fbd04cc6ef365677b286d728f73db42c06ecc0a5822a6334a"; - - String methedStr = "VerifyBurnProofSize001(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, true, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString( - infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001", contractResult); - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyMintProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyMintProof001.java deleted file mode 100644 index a0c0df953e2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/VerifyMintProof001.java +++ /dev/null @@ -1,457 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class VerifyMintProof001 { - - private final String foundationKey001 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] foundationAddress001 = PublicMethed.getFinalAddress(foundationKey001); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] contractAddress = null; - - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - private byte[] testAddress001 = ecKey1.getAddress(); - private String testPriKey001 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(testPriKey001); - Assert.assertTrue(PublicMethed.sendcoin(testAddress001, 1000_000_000L, foundationAddress001, - foundationKey001, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "Deploy VerfyMintProof contract ") - public void verifyMintProofTest001() { - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testAddress001, - blockingStubFull); - Protocol.Account info = PublicMethed.queryAccount(testPriKey001, blockingStubFull); - Long beforeBalance = info.getBalance(); - Long beforeEnergyUsed = accountResource.getEnergyUsed(); - Long beforeNetUsed = accountResource.getNetUsed(); - Long beforeFreeNetUsed = accountResource.getFreeNetUsed(); - logger.info("beforeBalance:" + beforeBalance); - logger.info("beforeEnergyUsed:" + beforeEnergyUsed); - logger.info("beforeNetUsed:" + beforeNetUsed); - logger.info("beforeFreeNetUsed:" + beforeFreeNetUsed); - - String filePath = "./src/test/resources/soliditycode/VerifyMintProof001.sol"; - String contractName = "VerifyMintProof001Test"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - String txid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, testPriKey001, - testAddress001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - Assert.assertEquals(0, infoById.get().getResultValue()); - - contractAddress = infoById.get().getContractAddress().toByteArray(); - SmartContract smartContract = PublicMethed.getContract(contractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - } - - @Test(enabled = true, description = "data length != 1504") - public void verifyMintProofTest002() { - - String argsStr = "\"" - + "a634da705bbacb108a276ce26470568873d573e6f1f00d3a2b2e93b93f4b1a0c" - + "2eb2b8ae07c858dafd7d99f4487a779878b1f87fb632c7fccff14d44c0b23e56" - + "61ba88273d52c44cf4e1939ce6e76b97ef2611ce4cf472c5e8a61e66463f948d" - + "8ffed5e9e6125a292dcb2f2855a753893467176b19ed366b3fc7c182e5b62cc1" - + "d01bb22cba6ca8a514f36c5f24e6dcaf953f77db33c5e6db4f2a756b2e4793b7" - + "be6e29b29309c37b9a1a5fe1e6ad42b1ed17c6d84d0fb4ed39772dceb5af6d23" - + "01ed5d94ce6b69efc2bbe863f7798d871ae5bfc3db4eb36073fd9b8eb08d6c0c" - + "52439f429ee437454cd59b8068ec9350b611f9b41cf5fa840c911227a2db3546" - + "f0d190023a929d821aaf0529066bd81eac321ad0c9cf98c4a39060d636140a99" - - + "2ac86687e4c5284a8272390684e557d9a70bcd8dbaec6b8c8cb6114b13e01f22" - + "c1dd79631dc9bd508f87d77bae4bebf31917c981d1ed1f8d8d9e637a7e56db0b" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "33e4e8db7e8d3c127620de9901e7c6e65ca675b1c69455784a98aa7e4ed31a91" - - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - - + "0000000000000000000000000000000000000000000000000000000000000000" - // add more bytes32 - + "0000000000000000000000000000000000000000000000000000000000000064" - + "\""; - - String methedStr = "VerifyMintProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - - } - - @Test(enabled = true, description = "data is empty") - public void verifyMintProofTest003() { - String methedStr = "VerifyMintProofSize003()"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, "", false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray - .toHexString(infoById.get().getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - - } - - @Test(enabled = true, description = "leafCount greate than 2^32-1") - public void verifyMintProofTest004() { - - String methedStr = "VerifyMintProofSize002(bytes)"; - - String argsStr = "\"" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "000000000000000000000000000000000000000000000000000000000000000a" - - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - + "b55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105a" - - + "0000000000000000000000000000000000000000000000000000000100000002" - + "\""; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", contractResult); - } - - @Test(enabled = true, description = "verify success with address call") - public void verifyMintProofTest005() { - String argsStr = - "\"a634da705bbacb108a276ce26470568873d573e6f1f00d3a2b2e93b93f4b1a0c" - + "2eb2b8ae07c858dafd7d99f4487a779878b1f87fb632c7fccff14d44c0b23e56" - + "61ba88273d52c44cf4e1939ce6e76b97ef2611ce4cf472c5e8a61e66463f948d" - + "8ffed5e9e6125a292dcb2f2855a753893467176b19ed366b3fc7c182e5b62cc1" - + "d01bb22cba6ca8a514f36c5f24e6dcaf953f77db33c5e6db4f2a756b2e4793b7" - + "be6e29b29309c37b9a1a5fe1e6ad42b1ed17c6d84d0fb4ed39772dceb5af6d23" - + "01ed5d94ce6b69efc2bbe863f7798d871ae5bfc3db4eb36073fd9b8eb08d6c0c" - + "52439f429ee437454cd59b8068ec9350b611f9b41cf5fa840c911227a2db3546" - + "f0d190023a929d821aaf0529066bd81eac321ad0c9cf98c4a39060d636140a99" - - + "2ac86687e4c5284a8272390684e557d9a70bcd8dbaec6b8c8cb6114b13e01f22" - + "c1dd79631dc9bd508f87d77bae4bebf31917c981d1ed1f8d8d9e637a7e56db0b" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "33e4e8db7e8d3c127620de9901e7c6e65ca675b1c69455784a98aa7e4ed31a91" - - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - - + "0000000000000000000000000000000000000000000000000000000000000000\""; - - String methedStr = "VerifyMintProofSize002(bytes)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, false, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - - Assert.assertEquals("" - + "0000000000000000000000000000000000000000000000000000000000000001" // 1 : true - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000060" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "39e261b362110781a20878cc19f480cb50df5e6b896ed9a1fea8b8a9a4239a17", contractResult); - - } - - @Test(enabled = true, description = "verify success with fuction call") - public void verifyMintProofTest006() { - String argsStr = - "a634da705bbacb108a276ce26470568873d573e6f1f00d3a2b2e93b93f4b1a0c" - + "2eb2b8ae07c858dafd7d99f4487a779878b1f87fb632c7fccff14d44c0b23e56" - + "61ba88273d52c44cf4e1939ce6e76b97ef2611ce4cf472c5e8a61e66463f948d" - + "8ffed5e9e6125a292dcb2f2855a753893467176b19ed366b3fc7c182e5b62cc1" - + "d01bb22cba6ca8a514f36c5f24e6dcaf953f77db33c5e6db4f2a756b2e4793b7" - + "be6e29b29309c37b9a1a5fe1e6ad42b1ed17c6d84d0fb4ed39772dceb5af6d23" - + "01ed5d94ce6b69efc2bbe863f7798d871ae5bfc3db4eb36073fd9b8eb08d6c0c" - + "52439f429ee437454cd59b8068ec9350b611f9b41cf5fa840c911227a2db3546" - + "f0d190023a929d821aaf0529066bd81eac321ad0c9cf98c4a39060d636140a99" - - + "2ac86687e4c5284a8272390684e557d9a70bcd8dbaec6b8c8cb6114b13e01f22" - + "c1dd79631dc9bd508f87d77bae4bebf31917c981d1ed1f8d8d9e637a7e56db0b" - - + "0000000000000000000000000000000000000000000000000000000000000064" - - + "33e4e8db7e8d3c127620de9901e7c6e65ca675b1c69455784a98aa7e4ed31a91" - - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - - + "0000000000000000000000000000000000000000000000000000000000000000"; - - String methedStr = - "VerifyMintProofSize001(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256)"; - - String TriggerTxid = PublicMethed.triggerContract(contractAddress, methedStr, argsStr, true, - 0, maxFeeLimit, testAddress001, testPriKey001, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info("TriggerTxid: " + TriggerTxid); - - Optional infoById = PublicMethed - .getTransactionInfoById(TriggerTxid, blockingStubFull); - - logger.info("infoById : " + infoById); - - Assert.assertEquals(0, infoById.get().getResultValue()); - String contractResult = ByteArray.toHexString(infoById.get() - .getContractResult(0).toByteArray()); - - Assert.assertTrue(contractResult.length() > 1000); - - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash001.java deleted file mode 100644 index 9ea86709e2e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash001.java +++ /dev/null @@ -1,166 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class pedersenHash001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/pedersenHash001.sol"; - String contractName = "pedersenHashTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "data is empty") - public void test01DataIsEmpty() { - String method = "test1()"; - txid = PublicMethed - .triggerContract(contractAddress, method, "", false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - byte[] result = infoById.get().getContractResult(0).toByteArray(); - String boolResult = ByteArray.toHexString(ByteArray.subArray(result, 0, 32)); - System.out.println("boolResult: " + boolResult); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000000", - boolResult); - - } - - @Test(enabled = true, description = "data length limit") - public void test02DataLengthLimit() { - String method = "test2(bytes)"; - // length:64 - String argsStr1 = "\"0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002\""; - Optional infoById = null; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr1, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("SUCESS", infoById.get().getResult().toString()); - int boolResult = ByteArray.toInt(infoById.get().getContractResult(0).toByteArray()); - Assert.assertFalse(Boolean.valueOf(String.valueOf(boolResult))); - Assert.assertTrue(maxFeeLimit > infoById.get().getFee()); - - // length:128 - String argsStr2 = "\"0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000002\""; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr2, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "7d6b910840eb7b47f76492aca4a3344888b8fa5aab77a49e9445cda718d75040", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "normal") - public void test02Normal() { - String method = "test3(uint32,bytes32,bytes32)"; - String argsStr1 = "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000002"; - Optional infoById = null; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr1, true, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("7d6b910840eb7b47f76492aca4a3344888b8fa5aab77a49e9445cda718d75040", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed - .sendcoin(testNetAccountAddress, balance - 1000000, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash002.java deleted file mode 100644 index 26f29e5f69d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/pedersenHash002.java +++ /dev/null @@ -1,476 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Status; -import io.netty.util.internal.StringUtil; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpPost; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.ByteUtil; -import org.tron.common.utils.Commons; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.exception.ZksnarkException; -import org.tron.core.zen.address.DiversifierT; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; - -@Slf4j -public class pedersenHash002 { - - public final String foundationAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - public final byte[] foundationAccountAddress = PublicMethed.getFinalAddress(foundationAccountKey); - public static final String zenTrc20TokenOwnerKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTrc20TokenOwnerKey"); - public static final byte[] zenTrc20TokenOwnerAddress = PublicMethed - .getFinalAddress(zenTrc20TokenOwnerKey); - public static final String zenTrc20TokenOwnerAddressString = PublicMethed - .getAddressString(zenTrc20TokenOwnerKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - public ManagedChannel channelFull = null; - public WalletGrpc.WalletBlockingStub blockingStubFull = null; - public ManagedChannel channelSolidity = null; - public WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - public static long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - public ByteString contractAddressByteString; - public static byte[] contractAddressByte; - public static String contractAddress; - public static ByteString shieldAddressByteString; - public static byte[] shieldAddressByte; - public static String shieldAddress; - public static String deployShieldTrc20Txid; - public static String deployShieldTxid; - private BigInteger publicFromAmount; - Optional receiverShieldAddressInfo; - List shieldOutList = new ArrayList<>(); - public static String transfer = - "transfer(bytes32[10][],bytes32[2][],bytes32[9][],bytes32[2],bytes32[21][])"; - public Wallet wallet = new Wallet(); - static HttpResponse response; - static HttpPost httppost; - public static Integer scalingFactorLogarithm = 0; - public static Long totalSupply = 1000000000000L; - - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Deploy shield trc20 depend contract") - public void deployShieldTrc20DependContract() { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - Assert.assertTrue(PublicMethed.sendcoin(contractExcAddress, 10000000000000L, - foundationAccountAddress, foundationAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String contractName = "shieldTrc20Token"; - - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_shieldTrc20Token"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_shieldTrc20Token"); - String constructorStr = "constructor(uint256,string,string)"; - String data = totalSupply.toString() + "," + "\"TokenTRC20\"" + "," + "\"zen20\""; - logger.info("data:" + data); - deployShieldTrc20Txid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - contractExcKey, contractExcAddress, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTrc20Txid); - Optional infoById = PublicMethed - .getTransactionInfoById(deployShieldTrc20Txid, blockingStubFull); - contractAddressByteString = infoById.get().getContractAddress(); - contractAddressByte = infoById.get().getContractAddress().toByteArray(); - contractAddress = Base58.encode58Check(contractAddressByte); - logger.info(contractAddress); - String filePath = "src/test/resources/soliditycode/pedersenHash002.sol"; - contractName = "TokenTRC20"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - code = retMap.get("byteCode").toString(); - abi = retMap.get("abI").toString(); - data = "\"" + contractAddress + "\"" + "," + scalingFactorLogarithm; - constructorStr = "constructor(address,uint256)"; - deployShieldTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, constructorStr, data, "", - maxFeeLimit, 0L, 100, null, - contractExcKey, contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(deployShieldTxid); - infoById = PublicMethed.getTransactionInfoById(deployShieldTxid, blockingStubFull); - shieldAddressByteString = infoById.get().getContractAddress(); - shieldAddressByte = infoById.get().getContractAddress().toByteArray(); - shieldAddress = Base58.encode58Check(shieldAddressByte); - logger.info(shieldAddress); - - data = "\"" + shieldAddress + "\"" + "," + totalSupply.toString(); - String txid = PublicMethed.triggerContract(contractAddressByte, - "approve(address,uint256)", data, false, - 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info("approve:" + txid); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - publicFromAmount = getRandomAmount(); - } - - - @Test(enabled = true, description = "left and right value is 0") - public void test01LeftAndRightValueIsZero() throws Exception { - //Query account before mint balance - final Long beforeMintAccountBalance = getBalanceOfShieldTrc20(zenTrc20TokenOwnerAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeMintShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Generate new shiled account and set note memo - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters("ByValueIsZero", publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - } - - /** - * constructor. - */ - public GrpcAPI.ShieldedTRC20Parameters createShieldedTrc20Parameters(String methodSuffix, - BigInteger publicFromAmount, GrpcAPI.DecryptNotesTRC20 inputNoteList, - List shieldedAddressInfoList, List outputNoteList, - String publicToAddress, Long pubicToAmount, WalletGrpc.WalletBlockingStub blockingStubFull, - WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity) throws ZksnarkException { - - GrpcAPI.PrivateShieldedTRC20Parameters.Builder builder - = GrpcAPI.PrivateShieldedTRC20Parameters.newBuilder(); - - //Mint type should set public from amount to parameter - if (publicFromAmount.compareTo(BigInteger.ZERO) > 0) { - builder.setFromAmount(publicFromAmount.toString()); - } - - builder.setShieldedTRC20ContractAddress(ByteString.copyFrom(shieldAddressByte)); - long valueBalance = 0; - - if (inputNoteList != null) { - logger.info("Enter transfer type code"); - List rootAndPath = new ArrayList<>(); - for (int i = 0; i < inputNoteList.getNoteTxsCount(); i++) { - long position = inputNoteList.getNoteTxs(i).getPosition(); - rootAndPath.add(getRootAndPath(methodSuffix, position, blockingStubSolidity)); - } - if (rootAndPath.isEmpty() || rootAndPath.size() != inputNoteList.getNoteTxsCount()) { - System.out.println("Can't get all merkle tree, please check the notes."); - return null; - } - for (int i = 0; i < rootAndPath.size(); i++) { - if (rootAndPath.get(i) == null) { - System.out.println("Can't get merkle path, please check the note " + i + "."); - return null; - } - } - - for (int i = 0; i < inputNoteList.getNoteTxsCount(); ++i) { - if (i == 0) { - String shieldedAddress = inputNoteList.getNoteTxs(i).getNote().getPaymentAddress(); - - String spendingKey = ByteArray.toHexString(shieldedAddressInfoList.get(0).getSk()); - BytesMessage sk = BytesMessage.newBuilder() - .setValue(ByteString.copyFrom(ByteArray.fromHexString(spendingKey))).build(); - Optional esk = Optional - .of(blockingStubFull.getExpandedSpendingKey(sk)); - - //ExpandedSpendingKey expandedSpendingKey = spendingKey.expandedSpendingKey(); - builder.setAsk(esk.get().getAsk()); - builder.setNsk(esk.get().getNsk()); - builder.setOvk(esk.get().getOvk()); - } - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldedAddressInfoList.get(0).getAddress()); - noteBuild.setValue(inputNoteList.getNoteTxs(i).getNote().getValue()); - noteBuild.setRcm(inputNoteList.getNoteTxs(i).getNote().getRcm()); - noteBuild.setMemo(inputNoteList.getNoteTxs(i).getNote().getMemo()); - - byte[] eachRootAndPath = ByteArray.fromHexString(rootAndPath.get(i)); - byte[] root = Arrays.copyOfRange(eachRootAndPath, 0, 32); - byte[] path = Arrays.copyOfRange(eachRootAndPath, 32, 1056); - GrpcAPI.SpendNoteTRC20.Builder spendTRC20NoteBuilder = GrpcAPI.SpendNoteTRC20.newBuilder(); - spendTRC20NoteBuilder.setNote(noteBuild.build()); - spendTRC20NoteBuilder.setAlpha(ByteString.copyFrom(blockingStubFull.getRcm( - EmptyMessage.newBuilder().build()).getValue().toByteArray())); - spendTRC20NoteBuilder.setRoot(ByteString.copyFrom(root)); - spendTRC20NoteBuilder.setPath(ByteString.copyFrom(path)); - spendTRC20NoteBuilder.setPos(inputNoteList.getNoteTxs(i).getPosition()); - - valueBalance = Math - .addExact(valueBalance, inputNoteList.getNoteTxs(i).getNote().getValue()); - builder.addShieldedSpends(spendTRC20NoteBuilder.build()); - } - } else { - //@TODO remove randomOvk by sha256.of(privateKey) - byte[] ovk = getRandomOvk(); - if (ovk != null) { - builder.setOvk(ByteString.copyFrom(ovk)); - } else { - System.out.println("Get random ovk from Rpc failure,please check config"); - return null; - } - } - - if (outputNoteList != null) { - for (int i = 0; i < outputNoteList.size(); i++) { - Note note = outputNoteList.get(i); - valueBalance = Math.subtractExact(valueBalance, note.getValue()); - builder.addShieldedReceives( - GrpcAPI.ReceiveNote.newBuilder().setNote(note).build()); - } - } - - if (!StringUtil.isNullOrEmpty(publicToAddress)) { - byte[] to = Commons.decodeFromBase58Check(publicToAddress); - if (to == null) { - return null; - } - builder.setTransparentToAddress(ByteString.copyFrom(to)); - builder.setToAmount(pubicToAmount.toString()); - } - - try { - return blockingStubFull.createShieldedContractParameters(builder.build()); - } catch (Exception e) { - Status status = Status.fromThrowable(e); - System.out.println("createShieldedContractParameters failed,error " - + status.getDescription()); - } - return null; - } - - public String getRootAndPath(String methodSuffix, long position, - WalletSolidityGrpc.WalletSolidityBlockingStub - blockingStubSolidity) { - String methodStr = "getPath" + methodSuffix + "(uint256)"; - byte[] indexBytes = ByteArray.fromLong(position); - String argsStr = ByteArray.toHexString(indexBytes); - argsStr = "000000000000000000000000000000000000000000000000" + argsStr; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtentionOnSolidity(shieldAddressByte, methodStr, argsStr, true, - 0, 1000000000L, "0", 0, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubSolidity); - byte[] result = transactionExtention.getConstantResult(0).toByteArray(); - return ByteArray.toHexString(result); - } - - /** - * constructor. - */ - public static HttpResponse getNewShieldedAddress(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnewshieldedaddress"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - } - - /** - * constructor. - */ - public Optional getNewShieldedAddress(WalletGrpc.WalletBlockingStub - blockingStubFull) { - ShieldedAddressInfo addressInfo = new ShieldedAddressInfo(); - - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - final Optional d = Optional.of(blockingStubFull.getDiversifier( - EmptyMessage.newBuilder().build())); - - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.get().getAsk()); - Optional ak = Optional.of(blockingStubFull.getAkFromAsk(askBuilder.build())); - - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.get().getNsk()); - Optional nk = Optional.of(blockingStubFull.getNkFromNsk(nskBuilder.build())); - - GrpcAPI.ViewingKeyMessage.Builder viewBuilder = GrpcAPI.ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.get().getValue()); - viewBuilder.setNk(nk.get().getValue()); - Optional ivk = Optional.of(blockingStubFull - .getIncomingViewingKey(viewBuilder.build())); - - GrpcAPI.IncomingViewingKeyDiversifierMessage.Builder builder - = GrpcAPI.IncomingViewingKeyDiversifierMessage - .newBuilder(); - builder.setD(d.get()); - builder.setIvk(ivk.get()); - Optional addressMessage = Optional.of(blockingStubFull - .getZenPaymentAddress(builder.build())); - addressInfo.setSk(sk.get().getValue().toByteArray()); - addressInfo.setD(new DiversifierT(d.get().getD().toByteArray())); - addressInfo.setIvk(ivk.get().getIvk().toByteArray()); - addressInfo.setOvk(expandedSpendingKeyMessage.get().getOvk().toByteArray()); - addressInfo.setPkD(addressMessage.get().getPkD().toByteArray()); - - return Optional.of(addressInfo); - - } catch (Exception e) { - e.printStackTrace(); - } - - return Optional.empty(); - } - - /** - * constructor. - */ - public static List addShieldTrc20OutputList(List shieldOutList, - String shieldToAddress, String toAmountString, String menoString, - WalletGrpc.WalletBlockingStub blockingStubFull) { - String shieldAddress = shieldToAddress; - String amountString = toAmountString; - if (menoString.equals("null")) { - menoString = ""; - } - long shieldAmount = 0; - if (!StringUtil.isNullOrEmpty(amountString)) { - shieldAmount = Long.valueOf(amountString); - } - - Note.Builder noteBuild = Note.newBuilder(); - noteBuild.setPaymentAddress(shieldAddress); - //noteBuild.setPaymentAddress(shieldAddress); - noteBuild.setValue(shieldAmount); - noteBuild.setRcm(ByteString.copyFrom(blockingStubFull.getRcm(EmptyMessage.newBuilder().build()) - .getValue().toByteArray())); - noteBuild.setMemo(ByteString.copyFrom(menoString.getBytes())); - shieldOutList.add(noteBuild.build()); - return shieldOutList; - } - - /** - * constructor. - */ - public Long getBalanceOfShieldTrc20(String queryAddress, byte[] ownerAddress, - String ownerKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - String paramStr = "\"" + queryAddress + "\""; - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(contractAddressByte, "balanceOf(address)", - paramStr, false, 0, 0, "0", 0, - ownerAddress, ownerKey, blockingStubFull); - - String hexBalance = Hex.toHexString(transactionExtention - .getConstantResult(0).toByteArray()); - for (int i = 0; i < hexBalance.length(); i++) { - if (hexBalance.charAt(i) != '0') { - hexBalance = hexBalance.substring(i); - break; - } - } - logger.info(hexBalance); - return Long.parseLong(hexBalance, 16); - } - - /** - * constructor. - */ - public byte[] getRandomOvk() { - try { - Optional sk = Optional.of(blockingStubFull - .getSpendingKey(EmptyMessage.newBuilder().build())); - Optional expandedSpendingKeyMessage - = Optional.of(blockingStubFull - .getExpandedSpendingKey(sk.get())); - return expandedSpendingKeyMessage.get().getOvk().toByteArray(); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - /** - * constructor. - */ - public BigInteger getRandomAmount() { - Random random = new Random(); - int x = random.nextInt(100000) + 100; - return BigInteger.valueOf(x); - } - - public byte[] longTo32Bytes(long value) { - byte[] longBytes = ByteArray.fromLong(value); - byte[] zeroBytes = new byte[24]; - return ByteUtil.merge(zeroBytes, longBytes); - } - - - /** - * constructor. - */ - public static String getRcm(String httpNode) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getrcm"; - response = HttpMethed.createConnect(requestUrl); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return HttpMethed.parseResponseContent(response).getString("value"); - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/verifyTransferProof001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/verifyTransferProof001.java deleted file mode 100644 index 82c01e7316a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/tvmnewcommand/zenProofCommand/verifyTransferProof001.java +++ /dev/null @@ -1,802 +0,0 @@ -package stest.tron.wallet.dailybuild.tvmnewcommand.zenProofCommand; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class verifyTransferProof001 { - - private final String testNetAccountKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - byte[] contractAddress = null; - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractExcAddress = ecKey1.getAddress(); - String contractExcKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractExcKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - txid = PublicMethed - .sendcoinGetTransactionId(contractExcAddress, 10000000000L, testNetAccountAddress, - testNetAccountKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String filePath = "src/test/resources/soliditycode/verifyTransferProof001.sol"; - String contractName = "verifyTransferProofTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - contractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, 0L, 100, null, contractExcKey, - contractExcAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true, description = "data is empty") - public void test01DataIsEmpty() { - String method = "test1()"; - txid = PublicMethed - .triggerContract(contractAddress, method, "", false, 0, maxFeeLimit, contractExcAddress, - contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "data length limit") - public void test02DataLengthLimit() { - String method = "test2(bytes)"; - Optional infoById = null; - // length:2048 - String argsStr1 = "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c01b6ef3ac06" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328\""; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr1, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - - // length:2784 - String argsStr2 = "\"0000000000000000000000000000000000000000000000000000000000000520" - + "00000000000000000000000000000000000000000000000000000000000007c0" - + "0000000000000000000000000000000000000000000000000000000000000860" - + "898bb618ff2874a2b706e000d663c8e7ff7095ca404e131ce712583d7a3bf717" - + "b7b6ec3705a0823d09524e13c81bd4f44e6c796e63b197ffcdb6ec7bb44ff505" - + "2487fbd8a96638187266aa9c54795e0c14aabcd72d45b6d13ba304b539cbc7ed" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "82f70d55b1d9131cd3d41b7491636291a5ac41ed3372e4fe502d1c4a911cce4b" - + "49c6eaf2968c27437831622072b8f8cfa18791084189e7c4764c104a360bbe70" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "7c62133e78f43c71c49e8b85b145377c51c7d4dfd7c44656d62363144f243575" - + "1f2b46d412955c11a51cd81f6499bd0e9cf9c5a3fa12befe26b1e992e41cfd4c" - + "f1243c6008688639d9dffa4670b74546f66be60209a9c5664a9de7dcca856f6a" - + "fdfb2e8cf0083a20dbf2899042baa469949f7993f7b0f3606d70f443486ebf46" - + "9232a4e7a899e52a7479d9ca981ee7fe96250e4ef8d6899d89e8c33be62ac65c" - + "a97e4cd3d9a58033d35f9a7c45375f0b8866db6db15fcbd185e6c254cd0300b9" - + "364a3c2d9499e474bf207ce2f2b67427df0796d2c221efb28b7fccea210b58ba" - + "01f5a9b4a12eb295ab0fecbe97f01bf4841002e94e1334a513755403f6832ce3" - + "0ab328b11e8772aa922dc7c84768c887b38b35e39df177e3fc4f760051209e1a" - + "9dfef66affba94f21d5a28c39a893419af506faee2217f0c605830427173a7d5" - + "521c7b5bf3ff99421c69c861af0fc30b565332ff1aad344afd9dd7b40e3da769" - + "67ecbac59d221641a28b19134e599c1d20c5cc55ac45217a68b0b9106872b92a" - + "8d55ca2e65e84ccd45a21d88a0eec096d98525d7e6751d4dbc4ddcb6aaec334b" - + "c7061b48ba27b89f193ad9e9f4d9c98aa1316b08f018222a3d92c1da7e8b7611" - + "806764eeb09ac490eea1f01d16ba8378e0c64396a0c06a707ed6027eae76938e" - + "74fa404d1ed9a955c7fe85eabc07b76eb58287d749a8dd304e810f94f680120b" - + "6e792117717f8b5b7f9f01416205900d962ffb69540e85562688604c26db4987" - + "0de0658d072aeb649809bf6f21714975f87e75df545e583c77bd6f786b3cc5c6" - + "08051b7885a732ac9bd49271d7ae9caea7d995d2ce5b18740f2b5b0de32d1337" - + "46f30ae9eb6d1f54ea1e4e228b6a22849a99f0a2decd09c806d8bd7cad6810de" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "c68b0fa0e76ffae969421ef87a0e27e4ad5a94b5bf2b5237c0a0e57259f20e60" - + "60525cfbc22ff838b067110121840a6885bff4516a5dc21eedce04f79b04b403" - + "10e640233b876885329599a78ce1cdc5dff83a29216f7fe58f225338963ec9b4" - + "9811e7479ef258776289394525c1070b70d3aeacb6d9d4a9065024ca21d8ed08" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "73238d94e2ad7575eb6067b1e5889a8445ef29dc377bdba0807f716b0b75b13e" - + "00ef0b6303b098a8af5e2deb8d506aaa710a58805325aa2097c19a63b876e5b4" - + "26e055e92683f24fab7c79b7d8825928fc3dc356d496c09069b8fd0d01df275b" - + "b0a57952d3adc1f31570d3626d2011a725f9caaf857e253b4e4791adfb7babe7" - + "27c0b4791f16050dfdb1a4763f75fd0f970ca19ee66c36462e43dff2899c5d62" - + "3e363389f3dedb855c09e051f20f3f27ee52d2d267ae1f1bf024c2f63068b682" - + "0b578b39aebb57b8fc055a7d13d25574dfcde58656beec84dde4ba439b0bbb5d" - + "0b5b24a2cf71f6b68b56c5ef1bac89888b5b6827bca8cd8b47fc394cf89a6c23" - + "468f7857b566cddf39f06eed6ac079f20044b42381fb0ca969c4f425ed04e166" - + "09e582987c6af094c8afbfeb52e14b0e4e342c82dc784405631f4a985c826e51" - + "4a9b50b6ad41db1a403b0ced0f5f1e4a9ae2964237b6874056c8044233b331e1" - + "a8bcf84d0584c12dc42ebd27cca972b31c475a644450afcfd40c36c739740566" - + "8b377c8ed99dcca1a5ec03ca990d6c4cb846ad561dd204c66c834fc024030b75" - + "106bdca9e57e8d68d19e4183a349bc488b9c3d666f59f9bdca8e92457dbbacf5" - + "1a0e074d5cb64b54e533aef3d1da2b673b7a87cae612c7faed50563a20970a9b" - + "07539d7ea4d57a83defeaefa024832fe6ec1db4c3a4ef6badcc4d95e0d22f4ec" - + "e4f272a22dcfaa2326bc301f2dfac22fa35bd0c9a40262caf424e2e62b3e0a45" - + "c2fa591c482e923a2d6b3c4ba0819df430f4d548105071f7cb561749459f15d2" - + "c2fa591c482e923a2d6b3c4ba0819df430f4d548105071f7cb561749459f15d2\""; - txid = PublicMethed.triggerContract(contractAddress, method, argsStr2, false, 0, maxFeeLimit, - contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "tree width limit") - public void test03TreeWidthLimit() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c01b6ef3ac06" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "00000000000000000000000000000000000000000000000000000000ffffffff" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328" - + "d50b3131146a9b97443fca616d401b0f5e7c51b3c71b91c3637df35cf4b91864\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "spend count greater than 2") - public void test04SpendCountGreaterThan2() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000521" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "e5ae9d43a82fc3bc74272dbe20dcf99d2d37ff4ae1689c3f9b53d40113cf5fa8" - + "77e4f78bef9e692985e3a7cd08b92a8380aa0aaec623b7cf3aae5c5a13b41602" - + "9b40cc7690e15b1437f1d88aaf3b44649e23cbd4013b4b41da1efdf31b774779" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "22389ba23e8f871b2a2e71d87c67f03eaace9849e59e8cfd54d5ca783c9b8923" - + "2108740b5326d2802e5a09a263a2668f987425af3f76d61a5d3fa98896ea2a52" - + "db286eec8ac754634b2e099f661b194b79d99c4fc33f9eef975b1b2862f72866" - + "60b225e4f8a010864d82e87cbec9d1fab63a6ae57f04a03f0ced73fb7ba73a71" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "000000000000000000000000000000000000000000000000000000000000000d" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "fa05291a6d8af85cf9dc46f04687c31c12a4de8b2e9b51a55f2b777fb0220ddb" - + "c11bbb1f5025494923823c12fe864d290958384d5bc5e4d920e2bd9db70d005b" - + "b609c343bf7a9b3275ef9419ec1c5dfca574b9e17d67a782b745d2a4c830346d" - + "c77bfd763dfab3fa57596693a828cba2dbbd43fa0daa454136cd61f303e66d72" - + "b91efc162b5a4474b71f9b688af8513bc0e19fbcc834223c02c942f504c4286a" - + "359462bc8993d7b41aead7ac25a25c64b5ae662cea2370ff912e2b2a6ef76bbe" - + "f5ae2a40d920ee79197c99b9ba92df929d445bbd4a0384ce3e637d59939086dc" - + "06042ef2abbb6ea7a599acac186d8fce957c1632d1dc64c9cc04a4a597d42923" - + "491440cfa5bf9c0d387ef77902921343929900044165384c73b30b38c466e4f6" - + "d71f6c1e1b6af43ce2ec0572cd3a28e7c1d5caab600cb001effd07e4182e89be" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "3f153ababa83e18ff39b3149b893d90aebd440521b670b10e8268f7a98f42f06" - + "64efcf611c6c0e11f9edfeca53af7e8fc758f92b713fb4c104df4f6868eb6807" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "4fd0c6e8ed03c4e7797c4da435e5da8b7ecf63c765c8f5817fe29aa4f54e6057" - + "fc5dda67c0109f8ce48344c9c55fb8081a79ad549bd7d162b3f334a9219f8169" - + "a2f5c0f129ac81ab9f93b13a09ec25b40356420dbfe9aa21d367af61415a6a45" - + "82b5efd3f827c7ca99371b1a029e1781156f068e000fdb26ea1b078ce24ae4e1" - + "571001515de0d6d55d2eb7ed4371397b993b2fe4df3addd53248e3adfc24c6fe" - + "81e7b3679ba49fb7e5ef8c13661e7d442210cac48e93398f6d731b3770fcb23e" - + "01c0d34d139df0c31c1dbdf8b08fe0d6029845b1abc990986408191905d04e76" - + "44dd0fc25446d753e94638ee48bb5e088f4483ce9e648093e654ba762ea516df" - + "5bb29cb95cfe347fc2f109ff86d5596bdb89c116b4805b9c6bdc019049b597f3" - + "ee52b22ececc9c7bc4d2c4dd61f9e16bc9feb07a5575f28e577a2d67c1eb3d24" - + "d6583d39f9ea3fe2de10132de6303217cca345201a194ecde8ad098f49d3f63b" - + "2f1f12c99a24d5779e7b4d1e6aa4fc3e1f0bd671701f42e43f3530501e7e2c00" - + "b47f9f2c332b75a849eb94a260a9d2a846212562ec57e927e071962ddc5dda5c" - + "dd9d38d346666659216b4897492ee991b359f9d3adf8bb576720f3b1d49be957" - + "a5c39e894b98bea2538645b434d47e4e7c71fdf765aeae264dd916ff41542eee" - + "063bbed2ff1e40ee1a2a949d5bd197e5936709cdb68151108221b8478fa15d86" - + "d8aff952d21265677a1a363cf7f492de8c0715cb95960d149842e3cee99bdb32\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "duplicate nullifiers") - public void test05DuplicateNullifiers() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "00000000000000000000000000000000000000000000000000000000000007c0" - + "0000000000000000000000000000000000000000000000000000000000000860" - + "f95c0de8b0b573b6a302be34f42cab92fb84ad87be4c9e7c5016ccf4e5692552" - + "79279550d90ed369e0c60b07bc0ace565391941aff977ea101b221c26c14490d" - + "43b5d1b2f29511ff3425e353eb022493f3771203daff96e326477afbe34f7357" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0d9a42f99c055f6218415145bdd3b18496273ccd579c9370cbb312505e65ac2f" - + "88a987bdf381b7a6c41f5683334f9becdec01ab10fa4976a9b15191b9e33fc5c" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "0a43f2568d0aca1a589ff1b76a5147123e1b2c76634970378d742088d68187d7" - + "ed942fe6a584633ab56c66b5824fa24e1380d371abf8aedbcae1b45927fcc236" - + "216f0eafbbdee5f09a136f5dedd86ac5a1ebe7317942bc1999cd0b0b1c11b707" - + "295f566ff309ea8510919d2507b558d7f88151746aab05866a8708d1d70acf42" - + "80f40957fe79d81223cbe9f4eef86be1d4ab19fd3f26f6e08aa27477a8b2160f" - + "44de6d5ce257eccdf91ab3de59461420b20ee95a75bd031f117796e9d1995e85" - + "0c8900a176dd7fc60694716ef82d6ba5d72698f5580503575cecf09a912574d0" - + "02d9761fef0f283242404cbadaa10a70270dae33899c626f27cc626e2c7737d7" - + "5cf62af8190938d92f04d9cb4fcab07d98482843c9b062d5a3c48b1d6259f94c" - + "fa6961c578ecd8b87052edd19b7dc9fa168349cc125ed8e9beddb04450e0558b" - + "0a43f2568d0aca1a589ff1b76a5147123e1b2c76634970378d742088d68187d7" - + "ad182389453f849cf316d7d8c1c8b0da2675c404d09a8a7efb6ab4f81e5d253e" - + "2ab630a209d6dbd4446cc274859a4a97175cac7fc9d20544f5df8d5e6cc37856" - + "a305d5f20688846a81e57dd6141049691495e48ad37cf38183408b4e7ff9a250" - + "b449788c9ef60787fa698915b959979713e800c36966dc737032ab5455374854" - + "e31eebc49b73fc73e709962c69da79e4a3eb55c7311d245e671c83213562da8f" - + "751483514e1c9fead10186b95783a29b880f1c443fcb0c12fad1c8f4f1f1f8b2" - + "10792470322970e28ff0f1cff37531a594a164a4af755fa0d7bb9f24c2d4d7df" - + "2ebe0ff20d7a8a01bbc19ea13f92fe1ea3a8676cdb81efaee30ed4a0e15de0e4" - + "7ce1f4304ad9b824b08f26d655c2c04cdb1e1bf69f8796d5360af32193cceb26" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "36ecefb9a2264d4515ef9c1dc23bd8de87930c2434c3426df4b12afc17ccde46" - + "8e6a99a43572ea6c6110db239cd60627e927d339dfad1920bb88ce2335d91e07" - + "eb6968339a770e46c2c7acbedfdcf93678493f2d3ea03c4a78a2f28925e0e5b4" - + "632d959daaa129e79901713f5b8e3a233219371473b5c8f494dc28bceb399508" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "14c1d485df7f471413cf90be5bae3909ccb5812fbee683f91e1fc5b7178d8852" - + "51a559f6632e3beb24ed1e781de05d6fbb2a4600dd9b2195cdf378a18e2a31ed" - + "49936339e06e29754fe00956cde97338c627806596d681de95db6653d110a7a3" - + "95617c958e1c4d81d4baa99b295bddd6c3da2d4fb9dddc886d31461224ed423a" - + "68c4b504cbed65a19a43efe8c7f721cc9406d8251ca03bbdc6217f6f02077b45" - + "02a1db7de8fab00edc14df913fd7369c4e28294086bd2cb86bd1559133f211b6" - + "1382886e7feb401fdb9fc6ac186dd133d456a7a220615bb410ad79da8b0fb7b7" - + "c404341cf42246820f2afb70466b08658d55b24d3a53707ed88b82827e1358d0" - + "2fe7e8c746f6f7124d2dd3d1717d2859e8390f8f76147e1c767831924058ce70\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "duplicate output note") - public void test06DuplicateOutputNote() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "9144cda061b41702bbf641dc3864fa94bc934511895058f01b7bfbdbdb301f8c" - + "d43a44ccd4b131e6b37bd673f8ac6e554eb5b4ab599b6d2b66bc294b7767f506" - + "24614ac147e95287ff8351ed22aa43f2b3e82460dc79b57952e8a39bf4027c47" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "73792777f50b3c5cf7fcf88c7d24baf975c0b4132f2affa898df03874b3e8163" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "92a3ddb4b05a3903fd1d9693e047c7136ac048fd12a7384bfd569e57a265b1f9" - + "2e96a076fcd5722ff4e04bc31cec8aeb2fa5ee3006104a3046c28c4a1584293f" - + "d02e3f11e3ca072628d2fa4755699958223e3467ef7c2039ff699fd9616a5921" - + "0624e9ba16fc55a77d6d872854c638a1c3b6570267130cb43770661793fa9fda" - + "9406c39d8388060ece340e133238f9452e990d1adcc2a91a0bfe46403489043b" - + "51ac2c88e5f0f4fe74b65eb30ec50400a5334a59f3f7f425073edf66bc3ca8cf" - + "f599d1f6742d1ebf0e40dce32d81a4a5cafb1c0ec078a692b95c97265cce277c" - + "11bf7216ff5df3d0d916359abe8b1a5dedf30e5bd5ccf24e6659adc9a4db9558" - + "6369477f2a15447a56249fa1703f31b7b3800aff0cf67772d132bd74cf888ee5" - + "4f45236c6687ac59c89a6157e001bd5190fadba40d515f739636a7dbd77b5108" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "59eca5d4562a891db660355de4de8c14afa64332a8c58afc44108798fc070cba" - + "e90d708016a0f09278a895325c538a0773a011aa9f132dce77e073f39b864606" - + "0000000000000000000000000000000000000000000000000000000000000002" - + "23540e10b3989fc8efdcadda1bcb840cce8580b45718082d5ace9fc4a6f4d45b" - + "d3ad992cbf4a32ece6a7911992c82b94a54705f7fbe680b5250c9b05cb1a31ca" - + "0d26babfd7f9614d5b3cbe84c7006f4aebcea2977d31c9761c5f7ef9c4b0a8eb" - + "98c35f51cd4ed7eef014a56ae50b4efb6555d497991ff7b282183d82f19282d5" - + "5ce8b8f286f6bdeae73981db2a615c7cb9c4fdaa7618502480945647aa1e98eb" - + "4dab59853f9bb3327f7ecbfd92fde4e2f49968562b468ca060447f1036172075" - + "163840bd0f1dca2495392228e23bf49b0934e14a145be29a9e42fb8477925c9f" - + "5a18093e51748a2494ee9191e16511bbae6d8c71d188c46286dd6dc5213b1d7f" - + "95eab6bade1ee763656b06c95d8e907dd8f3310722024cb9322d17724757f686" - + "23540e10b3989fc8efdcadda1bcb840cce8580b45718082d5ace9fc4a6f4d45b" - + "77b1609896bde81495ab555869c6ddbc5c7aac7274830f505486682093284fb6" - + "6f4aeab08e6417ab85026d97aeedfa26407b867227639653ec7a2fb529eb3e9f" - + "a207cb75c8eeb1c77fc3fc9949fc9c95e4b98806a9c6d7558f1f4e8f2a87df47" - + "375dc915db5332f6abbd87967796875ea8922e70e9ba135cdeabd171273884a9" - + "107992ee1a521f648c499620299a45031821e0639abadeec464a3ec3f439a823" - + "15bfe031aaaba0e3bc80fc359d7c7722e448e1e671447c41592cc0f27d35e1bc" - + "b5a4dd42ac75418f70f1a23f0de47fb6a2985ff86958816e52067612df232aa6" - + "9b5cedeab709b800eacc4b2d81582e4bb4f0a0e51571a5b03816126b39e1c9ab\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "checkResult is false") - public void test07CheckResultIsFalse() { - String method = "test2(bytes)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "\"0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c86b6ef8ac86" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328" - + "d50b3131146a9b97443fca616d401b0f5e7c51b3c71b91c3637df35cf4b91864\"", - false, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertEquals("0000000000000000000000000000000000000000000000000000000000000001" - + "0000000000000000000000000000000000000000000000000000000000000040" - + "0000000000000000000000000000000000000000000000000000000000000020" - + "0000000000000000000000000000000000000000000000000000000000000000", - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray())); - } - - @Test(enabled = true, description = "normal") - public void test08Normal() { - String method = "test3(bytes32[10][],bytes32[2][],bytes32[9][]" - + ",bytes32[2],bytes32,uint64,bytes32[33],uint256)"; - txid = PublicMethed.triggerContract(contractAddress, method, - "0000000000000000000000000000000000000000000000000000000000000520" - + "0000000000000000000000000000000000000000000000000000000000000680" - + "00000000000000000000000000000000000000000000000000000000000006e0" - + "f3e912b1f0d8e6a6654c1e9ff16d9eb5c2895b35490a5fa825d275d842efb5e5" - + "45ae827a6fb105d6fc6d125c2a8c1253f753b4973a6505b671b0c01b6ef3ac06" - + "4f4aca9fdf2a460e95df34315749ac432cd5154ad42217b7296b3b5bd81dd00b" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "363f4cb9b6605bbd39b3ccf4fdc834721afc8d38cd25becc7830dab5cacf1852" - + "32431ad6d4cfa89730b413b4ca2f744623a0b4b8315fc5e307ed62a043fa4064" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000000" - + "0000000000000000000000000000000000000000000000000000000000000003" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "66b02f76abecb4de13adc2b9b48edf60edf7e243dba5930276655936b53019ee" - + "626327f3509cadc915c8df9d9f97e17f244c828f3ad82b19f6701ae09dc0e22e" - + "659d5386266aef0a8434fe2ac728a655071f4688ad6cd1dae6e58e4767e1a36a" - + "d2614240434f15b189c8f235e35b281454988d72518df3068d8f512fe992e564" - + "a27d2c53207376e3f179aed8f415acbe1bca1a9ec60188f6fea1d1fd99f80db2" - + "c70271638ea0aa5d99e49fca76157e7692c856f4056b7857ed5ce852e69c713f" - + "42dd888295906c9988cc7fdd6715ea2dac745e97fa8ffd63653ee8e17b8a2ada" - + "1148bed585f91c1ab2f38f77e78a4dacd86587ac899961665e0a6f34d7cf0a41" - + "0f1032d3c26d0ab381ba3fd45f1cbb36b04f889584c1868fdc448eaab9bb8592" - + "d91a58c9e735862cdd346201fb9ab75999c6a57a6a474f2248f71c631375f0a8" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "8dcbff6a27f4e6b39c6e19aab7deb9427368bc8dc1082f0dfe57edc94fbb8c3e" - + "1eb36d9f48c5243dad16ab511dcea3c8489ba0dd774befb12fc58f1ae50e7504" - + "0000000000000000000000000000000000000000000000000000000000000001" - + "9fa6ed64a910bee735eafdb80636852367f6a487f6aec0598708ad80cad8ed09" - + "7aa9686c3cc957f88703e1eea87c5412baba2044c78e9161a7b2ac2b21bfef9b" - + "83ca769ba273d3fe1d4cc0d5d0d1ab8a6540f220c1db981fc8885ee34b51263f" - + "90f31816d21895f518bbb893c62ce296ee8416486c37b9dba9d0cb3cdd5f58c5" - + "7e175a69dbf443509bc060f354862d9787490de120ae665cbcba894854eb8aaf" - + "b811e676c506f7c4f2038afa09fc56b66c0c9cefcc00d780d152f1633d1c90af" - + "058355203f7737de6184b08bbf84248f118c3b540a7dc8f5518676fe0ebb2b35" - + "e4c3ec5f6b2f93138c7e7aa4a9b631dc9786b6df2d317208f220055d3fcab328" - + "d50b3131146a9b97443fca616d401b0f5e7c51b3c71b91c3637df35cf4b91864", - true, 0, maxFeeLimit, contractExcAddress, contractExcKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertTrue( - ByteArray.toHexString(infoById.get().getContractResult(0).toByteArray()).length() > 10000); - } - - @AfterClass - public void shutdown() throws InterruptedException { - long balance = PublicMethed.queryAccount(contractExcKey, blockingStubFull).getBalance(); - PublicMethed - .sendcoin(testNetAccountAddress, balance - 1000000, contractExcAddress, contractExcKey, - blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken001.java deleted file mode 100644 index 4e5a7908092..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken001.java +++ /dev/null @@ -1,262 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.SpendResult; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional shieldAddressInfo; - String shieldAddress; - List shieldOutList = new ArrayList<>(); - List shieldInputList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 8 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - - /** - * constructor. - */ - @BeforeSuite - public void beforeSuite() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - logger.info("enter this"); - if (PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getCreateTime() == 0) { - PublicMethed.sendcoin(foundationZenTokenAddress, 20480000000000L, fromAddress, - testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String name = "shieldToken"; - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - Long totalSupply = 15000000000000001L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - PublicMethed.createAssetIssue(foundationZenTokenAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 1000L, 1000L, - 1L, 1L, foundationZenTokenKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount = - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info("AssetId:" + assetAccountId.toString()); - } - } - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Public to shield transaction") - public void test1Public2ShieldTransaction() { - Args.setFullNodeAllowShieldedTransaction(true); - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - memo = "aaaaaaa"; - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Long afterNetUsed = PublicMethed.getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertTrue(receiverShieldTokenAmount == sendTokenAmount - zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - } - - @Test(enabled = false, description = "Shield to public transaction") - public void test2Shield2PublicTransaction() { - note = notes.getNoteTxs(0).getNote(); - SpendResult result = PublicMethed.getSpendResult(shieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull); - Assert.assertTrue(!result.getResult()); - - shieldOutList.clear(); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, note.getValue() - zenTokenFee, - zenTokenOwnerKey, blockingStubFull)); - - //When you want to send shield coin to public account,you should add one zero output amount cm - /* shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, note.getValue() - zenTokenFee, - zenTokenOwnerKey, blockingStubFull));*/ - - PublicMethed.waitProduceNextBlock(blockingStubFull); - result = PublicMethed.getSpendResult(shieldAddressInfo.get(), notes.getNoteTxs(0), - blockingStubFull); - Assert.assertTrue(result.getResult()); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertTrue(afterAssetBalance - beforeAssetBalance == note.getValue() - zenTokenFee); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance :" + afterAssetBalance); - } - - - @Test(enabled = false, - description = "Output amount can't be zero or below zero") - public void test3Shield2PublicAmountIsZero() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - memo = "Shield to public amount is zero"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (note.getValue() - zenTokenFee - (zenTokenFee - note.getValue())), memo); - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, zenTokenFee - note.getValue(), - zenTokenOwnerKey, blockingStubFull)); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (note.getValue() - zenTokenFee), memo); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, 0, - zenTokenOwnerKey, blockingStubFull)); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (-zenTokenFee), memo); - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - zenTokenOwnerAddress, note.getValue(), - zenTokenOwnerKey, blockingStubFull)); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken002.java deleted file mode 100644 index 6b761422c5b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken002.java +++ /dev/null @@ -1,403 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.contract.ShieldContract.IncrementalMerkleVoucherInfo; -import org.tron.protos.contract.ShieldContract.OutputPoint; -import org.tron.protos.contract.ShieldContract.OutputPointInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken002 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - IncrementalMerkleVoucherInfo firstMerkleVoucherInfo; - IncrementalMerkleVoucherInfo secondMerkleVoucherInfo; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSolidity1 = null; - private ManagedChannel channelPbft = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubPbft = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - } - - @Test(enabled = false, description = "Get merkle tree voucher info") - public void test01GetMerkleTreeVoucherInfo() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - firstMerkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - } - - - @Test(enabled = false, description = "Shield to shield transaction") - public void test02Shield2ShieldTransaction() { - receiverShieldAddressInfo = PublicMethed.generateShieldAddress(); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - ; - memo = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "" + (sendNote.getValue() - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(receiverShieldAddressInfo, blockingStubFull); - receiverNote = notes.getNoteTxs(0).getNote(); - logger.info("Receiver note:" + receiverNote.toString()); - Assert.assertTrue(receiverNote.getValue() == sendNote.getValue() - zenTokenFee); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on FullNode") - public void test03ScanNoteByIvkAndOvk() { - //Scan sender note by ovk equals scan receiver note by ivk on FullNode - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvk(receiverShieldAddressInfo, blockingStubFull).getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvk(sendShieldAddressInfo, blockingStubFull).getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on solidity") - public void test04ScanNoteByIvkAndOvkOnSolidityServer() { - - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvkOnSolidity(sendShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on Pbft") - public void test05ScanNoteByIvkAndOvkOnPbftServer() { - - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubPbft) - .getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvkOnSolidity(sendShieldAddressInfo, blockingStubPbft) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Scan note by ivk and scan not by ivk on solidity") - public void test06ScanNoteByIvkAndOvkOnSolidityServer() { - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity1); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity1) - .getNoteTxs(0).getNote(); - Note scanNoteByOvk = PublicMethed - .getShieldNotesByOvkOnSolidity(sendShieldAddressInfo, blockingStubSolidity1) - - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk.getValue(), scanNoteByOvk.getValue()); - Assert.assertEquals(scanNoteByIvk.getMemo(), scanNoteByOvk.getMemo()); - Assert.assertEquals(scanNoteByIvk.getRcm(), scanNoteByOvk.getRcm()); - Assert.assertEquals(scanNoteByIvk.getPaymentAddress(), scanNoteByOvk.getPaymentAddress()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on solidity") - public void test07QueryNoteIsSpendOnSolidity() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResultOnSolidity(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubSolidity).getResult()); - Assert.assertTrue(PublicMethed.getSpendResultOnSolidity(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubSolidity1).getResult()); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Query whether note is spend on PBFT") - public void test08QueryNoteIsSpendOnPbft() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - //Scan sender note by ovk equals scan receiver note by ivk in Solidity - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResultOnSolidity(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubPbft).getResult()); - } - - - /** - * constructor. - */ - @Test(enabled = false, description = "Query note and spend status on fullnode and solidity") - public void test09QueryNoteAndSpendStatusOnFullnode() { - Assert.assertFalse( - PublicMethed.getShieldNotesAndMarkByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getIsSpend()); - Note scanNoteByIvk = PublicMethed - .getShieldNotesByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk, - PublicMethed.getShieldNotesAndMarkByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getNote()); - - Assert.assertFalse(PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getIsSpend()); - scanNoteByIvk = PublicMethed - .getShieldNotesByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote(); - Assert.assertEquals(scanNoteByIvk, PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getNote()); - Assert.assertEquals(scanNoteByIvk, PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubPbft) - .getNoteTxs(0).getNote()); - - shieldOutList.clear(); - memo = "Query note and spend status on fullnode " + System.currentTimeMillis(); - notes = PublicMethed.listShieldNote(receiverShieldAddressInfo, blockingStubFull); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (notes.getNoteTxs(0).getNote().getValue() - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - receiverShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - Assert.assertTrue( - PublicMethed.getShieldNotesAndMarkByIvk(receiverShieldAddressInfo, blockingStubFull) - .getNoteTxs(0).getIsSpend()); - - Assert.assertTrue(PublicMethed - .getShieldNotesAndMarkByIvkOnSolidity(receiverShieldAddressInfo, blockingStubSolidity) - .getNoteTxs(0).getIsSpend()); - } - - @Test(enabled = false, description = "Get merkle tree voucher info") - public void test10GetMerkleTreeVoucherInfo() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - secondMerkleVoucherInfo = blockingStubFull - .getMerkleTreeVoucherInfo(request.build()); - - Assert.assertEquals(firstMerkleVoucherInfo, secondMerkleVoucherInfo); - } - - @Test(enabled = false, description = "Get merkle tree voucher info from Solidity") - public void test11GetMerkleTreeVoucherInfoFromSolidity() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - secondMerkleVoucherInfo = blockingStubSolidity - .getMerkleTreeVoucherInfo(request.build()); - - Assert.assertEquals(firstMerkleVoucherInfo, secondMerkleVoucherInfo); - } - - @Test(enabled = false, description = "Get merkle tree voucher info from Pbft") - public void test12GetMerkleTreeVoucherInfoFromPbft() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - OutputPointInfo.Builder request = OutputPointInfo.newBuilder(); - - //ShieldNoteInfo noteInfo = shieldWrapper.getUtxoMapNote().get(shieldInputList.get(i)); - OutputPoint.Builder outPointBuild = OutputPoint.newBuilder(); - outPointBuild.setHash(ByteString.copyFrom(notes.getNoteTxs(0).getTxid().toByteArray())); - outPointBuild.setIndex(notes.getNoteTxs(0).getIndex()); - request.addOutPoints(outPointBuild.build()); - secondMerkleVoucherInfo = blockingStubPbft - .getMerkleTreeVoucherInfo(request.build()); - - Assert.assertEquals(firstMerkleVoucherInfo, secondMerkleVoucherInfo); - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelPbft != null) { - channelPbft.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken003.java deleted file mode 100644 index 4480df80b5d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken003.java +++ /dev/null @@ -1,474 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - private Long costTokenAmount = 20 * zenTokenFee; - private String txid; - private Optional infoById; - private Optional byId; - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, - description = "Public to two shield transaction") - public void test1Public2ShieldTransaction() { - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Public to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - } - - @Test(enabled = false, - description = "Public to one public and one shield transaction") - public void test2Public2OneShieldAndOnePublicTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - final Long beforeBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - //When receiver public address don't active,the fee is 1000000 - Long sendToPublicAddressAmount = costTokenAmount - - sendToShiledAddress1Amount - zenTokenWhenCreateNewAddress; - logger.info("costTokenAmount " + costTokenAmount); - logger.info("sendToShiledAddress1Amount " + sendToShiledAddress1Amount); - logger.info("sendToPublicAddressAmount " + sendToPublicAddressAmount); - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull); - logger.info("txid:" + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenWhenCreateNewAddress); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - final Long afterBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - Assert.assertTrue(beforeBalance - afterBalance == 0); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed.getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertEquals(afterReceiverPublicAssetBalance, sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Public to one public and two shield transaction") - public void test3Public2OneShieldAndOnePublicTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = 2 * zenTokenFee; - final Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Public to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - final Long beforeReceiverPublicAssetBalance = PublicMethed - .getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed.getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertTrue(afterReceiverPublicAssetBalance - - beforeReceiverPublicAssetBalance == sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Public to one smart contract and one shield transaction") - public void test4Public2OneShieldAndOneSmartContractAddressTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - final Long beforeBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - - String contractName = "tokenBalanceContract"; - String code = "608060405260ff806100126000396000f30060806040526" - + "004361060485763ffffffff7c010000000000000" - + "0000000000000000000000000000000000000000000600035041663a730416e8114604d578063b69ef8a8146" - + "081575b600080fd5b606f73ffffffffffffffffffffffffffffffffffffffff6004351660243560ab565b604" - + "08051918252519081900360200190f35b348015608c57600080fd5b50d38015609857600080fd5b50d280156" - + "0a457600080fd5b50606f60cd565b73ffffffffffffffffffffffffffffffffffffffff90911690d16000908" - + "15590565b600054815600a165627a7a723058202b6235122df66c062c2e723ad58a9fea93346f3bc19898971" - + "8f211aa1dbd2d7a0029"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}," - + "{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":" - + "[{\"name\":\"b\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":" - + "\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":" - + "\"balance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 100, null, testKey002, fromAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - logger.info(txid); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - com.google.protobuf.ByteString contractAddress = infoById.get().getContractAddress(); - SmartContract smartContract = PublicMethed - .getContract(contractAddress.toByteArray(), blockingStubFull); - org.junit.Assert.assertTrue(smartContract.getAbi() != null); - Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - contractAddress.toByteArray(), sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull); - logger.info("txid:" + txid); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - final Long afterBalance = PublicMethed - .queryAccount(receiverPublicAddress, blockingStubFull).getBalance(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - Assert.assertTrue(beforeBalance - afterBalance == 0); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed - .getAssetIssueValue(contractAddress.toByteArray(), - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertEquals(afterReceiverPublicAssetBalance, sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Public to two same shield address") - public void test5Public2TwoSameShieldAddress() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - - logger.info("shieldAddress1:" + shieldAddress1); - - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList.clear(); - String memo1 = "First public to shield same address transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Second public to shield same address transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress2Amount, memo2); - txid = PublicMethed.sendShieldCoinGetTxid( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getShieldedTransactionFee() == zenTokenFee); - byId = PublicMethed.getTransactionById(txid, blockingStubFull); - Assert.assertTrue(byId.get().getSignatureCount() == 1); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long afterNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - logger.info("beforeAssetBalance:" + beforeAssetBalance); - logger.info("afterAssetBalance:" + afterAssetBalance); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == costTokenAmount); - Assert.assertTrue(beforeNetUsed == afterNetUsed); - notes = PublicMethed.getShieldNotesByIvk(shieldAddressInfo1, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 2); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - note = notes.getNoteTxs(1).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken004.java deleted file mode 100644 index 6284508261e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken004.java +++ /dev/null @@ -1,286 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Optional sendShieldAddressInfo; - String sendshieldAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20 * zenTokenFee; - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Args.setFullNodeAllowShieldedTransaction(true); - Assert.assertTrue(PublicMethed.sendcoin(receiverPublicAddress, 1000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, description = "Shield to two shield transaction") - public void test1Shield2TwoShieldTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "Use to TestZenToken004 shield address"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - String memo1 = "Shield to shield address1 transaction"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Shield to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - } - - @Test(enabled = false, - description = "Shield to one public and one shield transaction") - public void test2Shield2OneShieldAndOnePublicTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "Use to TestZenToken004 shield address"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - zenTokenFee; - shieldOutList.clear(); - String memo1 = "Shield to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - logger.info("receiverShieldTokenAmount1:" + receiverShieldTokenAmount1); - logger.info("sendToShiledAddress1Amount:" + sendToShiledAddress1Amount); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - Long afterReceiverPublicAssetBalance = PublicMethed.getAssetIssueValue(receiverPublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Assert.assertEquals(afterReceiverPublicAssetBalance, sendToPublicAddressAmount); - } - - @Test(enabled = false, - description = "Shield to one public and two shield transaction") - public void test3Public2OneShieldAndOnePublicTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "Use to TestZenToken004 shield address"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = 4 * zenTokenFee; - final Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenWhenCreateNewAddress; - shieldOutList.clear(); - String memo1 = "Shield to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Shield to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - //When receiver public address don't active,the fee is 1000000 - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] notActivePublicAddress = ecKey3.getAddress(); - - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - notActivePublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.listShieldNote(shieldAddressInfo1, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount1 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount1, sendToShiledAddress1Amount); - Assert.assertEquals(memo1, PublicMethed.getMemo(note)); - - notes = PublicMethed.listShieldNote(shieldAddressInfo2, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount2 = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount2, sendToShiledAddress2Amount); - Assert.assertEquals(memo2, PublicMethed.getMemo(note)); - - final Long afterNotActivePublicAssetBalance = PublicMethed - .getAssetIssueValue(notActivePublicAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - logger.info("afterNotActivePublicAssetBalance:" + afterNotActivePublicAssetBalance); - logger.info("sendToPublicAddressAmount:" + sendToPublicAddressAmount); - Assert.assertEquals(afterNotActivePublicAssetBalance, sendToPublicAddressAmount); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken005.java deleted file mode 100644 index 23398284924..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken005.java +++ /dev/null @@ -1,215 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken005 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(receiverPublicAddress, 1000000L, - fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, - description = "The receiver shield address can't more then 2") - public void test1ReceiverShieldAddressCanNotMoreThenTwo() { - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - Optional shieldAddressInfo3 = PublicMethed.generateShieldAddress(); - String shieldAddress3 = shieldAddressInfo3.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - logger.info("shieldAddress3:" + shieldAddress3); - - Long sendToShiledAddress1Amount = 3 * zenTokenFee; - Long sendToShiledAddress2Amount = 2 * zenTokenFee; - Long sendToShiledAddress3Amount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - String memo1 = "Shield to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Shield to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - String memo3 = "Shield to shield address3 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress3, - "" + sendToShiledAddress3Amount, memo3); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - } - - @Test(enabled = false, - description = "The receiver can't only one public address") - public void test2ReceiverPublicCanNotOnlyOnePublic() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - shieldOutList.clear(); - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, costTokenAmount - zenTokenFee, - zenTokenOwnerKey, blockingStubFull)); - } - - @Test(enabled = false, - description = "Public send amount must equal receiver amount + shieldFee") - public void test3SendAmountMustEqualReceiverAmountPlusShieldFee() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional shieldAddressInfo1 = PublicMethed.generateShieldAddress(); - String shieldAddress1 = shieldAddressInfo1.get().getAddress(); - Optional shieldAddressInfo2 = PublicMethed.generateShieldAddress(); - String shieldAddress2 = shieldAddressInfo2.get().getAddress(); - logger.info("shieldAddress1:" + shieldAddress1); - logger.info("shieldAddress2:" + shieldAddress2); - - Long sendToShiledAddress1Amount = 1 * zenTokenFee; - Long sendToShiledAddress2Amount = 2 * zenTokenFee; - - shieldOutList.clear(); - String memo1 = "Public to shield address1 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - String memo2 = "Public to shield address2 transaction"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - - //Public receiver amount is wrong - Long sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount - 1, - zenTokenOwnerKey, blockingStubFull)); - - //Shield receiver amount is wrong - sendToShiledAddress1Amount = 1 * zenTokenFee; - sendToShiledAddress2Amount = 2 * zenTokenFee; - sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + (sendToShiledAddress1Amount - 1), memo1); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - - sendToShiledAddress1Amount = 1 * zenTokenFee; - sendToShiledAddress2Amount = 2 * zenTokenFee; - sendToPublicAddressAmount = costTokenAmount - sendToShiledAddress1Amount - - sendToShiledAddress2Amount - zenTokenFee; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress1, - "" + sendToShiledAddress1Amount, memo1); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress2, - "" + sendToShiledAddress2Amount, memo2); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, costTokenAmount, - null, null, - shieldOutList, - receiverPublicAddress, sendToPublicAddressAmount, - zenTokenOwnerKey, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken006.java deleted file mode 100644 index 7b01959b2cb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken006.java +++ /dev/null @@ -1,266 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken006 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional shieldAddressInfo; - String shieldAddress; - List shieldOutList = new ArrayList<>(); - List shieldInputList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - } - - @Test(enabled = false, description = "Shield note memo is one char") - public void test1ShieldMemoIsOneChar() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //One char. - memo = "."; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - } - - @Test(enabled = false, description = "Shield note memo is 512 char") - public void test2ShieldMemoIs512Char() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //512 char. - memo = "1234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "7812345678"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - } - - @Test(enabled = false, description = "Shield note memo is 514 char") - public void test3ShieldMemoIs513Char() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //514 char. - memo = "-1234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "781234567812345678123456781234567812345678123456781234567812345678123456781234567812" - + "345678123456781234567812345678123456781234567812345678123456781234567812345678123456" - + "7812345678"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, zenTokenFee * 2, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - logger.info(PublicMethed.getMemo(note)); - Assert.assertTrue(PublicMethed.getMemo(note).length() == 512); - Assert.assertEquals(PublicMethed.getMemo(note), memo.substring(0, 512)); - } - - @Test(enabled = false, description = "Shield note memo is empty") - public void test4ShieldMemoIsEmpty() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - //Empty memo - memo = ""; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, 2 * zenTokenFee, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - - //Shield send to it self - memo = ""; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - shieldAddressInfo.get(), - PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull).getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - } - - - @Test(enabled = false, description = "Shield note memo is empty") - public void test5ShieldMemoIsEmpty() { - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - - memo = "{\n" - + " note {\n" - + " value: 49957\n" - + " payment_address: \"ztron1f42n7h0l3p8mlaq0d0rxdkhq" - + "n6xuq49xhvj593wfduy24kn3xrmxfpqt8lnmh9ysnu5nzt3zgzx\"\n" - + " rcm: \"\\210x\\256\\211\\256v\\0344\\267\\240\\375\\377xs\\3" - + "50\\3558^Y\\200i0$S\\312KK\\326l\\234J\\b\"\n" - + " memo: \"System.exit(1);\"\n" - + " }\n" - + " txid: \"\\215\\332\\304\\241\\362\\vbt\\250\\364\\353\\30" - + "7\\'o\\275\\313ya*)\\320>\\001\\262B%\\371\\'\\005w\\354\\200\"\n" - + "}"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - zenTokenOwnerAddress, 2 * zenTokenFee, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertEquals(receiverShieldTokenAmount, zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken007.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken007.java deleted file mode 100644 index f43924eedcc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken007.java +++ /dev/null @@ -1,639 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DiversifierMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExpandedSpendingKeyMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyDiversifierMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.PaymentAddressMessage; -import org.tron.api.GrpcAPI.ViewingKeyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken007 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo1; - Optional sendShieldAddressInfo2; - Optional sendShieldAddressInfo3; - Optional receiverShieldAddressInfo; - String sendShieldAddress1; - String sendShieldAddress2; - String sendShieldAddress3; - String receiverShieldAddress1; - String receiverShieldAddress2; - String receiverShieldAddress3; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo1; - String memo2; - String memo3; - Note sendNote1; - Note sendNote2; - Note sendNote3; - Note receiverNote1; - Note receiverNote2; - Note receiverNote3; - BytesMessage ak; - BytesMessage nk; - BytesMessage sk; - ExpandedSpendingKeyMessage expandedSpendingKeyMessage; - DiversifierMessage diversifierMessage1; - DiversifierMessage diversifierMessage2; - DiversifierMessage diversifierMessage3; - IncomingViewingKeyMessage ivk; - ShieldAddressInfo addressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo3 = new ShieldAddressInfo(); - Optional receiverAddressInfo1; - Optional receiverAddressInfo2; - Optional receiverAddressInfo3; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress1 = ecKey1.getAddress(); - String zenTokenOwnerKey1 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress2 = ecKey2.getAddress(); - String zenTokenOwnerKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress3 = ecKey3.getAddress(); - String zenTokenOwnerKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress4 = ecKey4.getAddress(); - String zenTokenOwnerKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey1); - PublicMethed.printAddress(zenTokenOwnerKey2); - PublicMethed.printAddress(zenTokenOwnerKey3); - PublicMethed.printAddress(zenTokenOwnerKey4); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress1, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress2, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress3, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress4, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo1 = PublicMethed.generateShieldAddress(); - sendShieldAddressInfo2 = PublicMethed.generateShieldAddress(); - sendShieldAddressInfo3 = PublicMethed.generateShieldAddress(); - sendShieldAddress1 = sendShieldAddressInfo1.get().getAddress(); - sendShieldAddress2 = sendShieldAddressInfo2.get().getAddress(); - sendShieldAddress3 = sendShieldAddressInfo3.get().getAddress(); - logger.info("sendShieldAddressInfo1:" + sendShieldAddressInfo1); - logger.info("sendShieldAddressInfo2:" + sendShieldAddressInfo2); - logger.info("sendShieldAddressInfo3:" + sendShieldAddressInfo3); - memo1 = "Shield memo1 in " + System.currentTimeMillis(); - memo2 = "Shield memo2 in " + System.currentTimeMillis(); - memo3 = "Shield memo3 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (sendTokenAmount - zenTokenFee), memo1); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress1, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey1, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (sendTokenAmount - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress2, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress3, - "" + (sendTokenAmount - zenTokenFee), memo3); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress3, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey3, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo1, blockingStubFull); - sendNote1 = notes.getNoteTxs(0).getNote(); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo2, blockingStubFull); - sendNote2 = notes.getNoteTxs(0).getNote(); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo3, blockingStubFull); - sendNote3 = notes.getNoteTxs(0).getNote(); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get spending key") - public void test01GetSpendingKey() { - sk = blockingStubFull.getSpendingKey(EmptyMessage.newBuilder().build()); - logger.info("sk: " + ByteArray.toHexString(sk.getValue().toByteArray())); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get diversifier") - public void test02GetDiversifier() { - diversifierMessage1 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - logger.info("d1: " + ByteArray.toHexString(diversifierMessage1.getD().toByteArray())); - diversifierMessage2 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - logger.info("d2: " + ByteArray.toHexString(diversifierMessage2.getD().toByteArray())); - diversifierMessage3 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - logger.info("d3: " + ByteArray.toHexString(diversifierMessage3.getD().toByteArray())); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get expanded spending key") - public void test03GetExpandedSpendingKey() { - expandedSpendingKeyMessage = blockingStubFull.getExpandedSpendingKey(sk); - logger.info("ask: " + ByteArray.toHexString(expandedSpendingKeyMessage.getAsk().toByteArray())); - logger.info("nsk: " + ByteArray.toHexString(expandedSpendingKeyMessage.getNsk().toByteArray())); - logger.info("ovk: " + ByteArray.toHexString(expandedSpendingKeyMessage.getOvk().toByteArray())); - - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get AK from ASK") - public void test04GetAkFromAsk() { - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.getAsk()); - ak = blockingStubFull.getAkFromAsk(askBuilder.build()); - logger.info("ak: " + ByteArray.toHexString(ak.getValue().toByteArray())); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get Nk from Nsk") - public void test05GetNkFromNsk() { - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.getNsk()); - nk = blockingStubFull.getNkFromNsk(nskBuilder.build()); - logger.info("nk: " + ByteArray.toHexString(nk.getValue().toByteArray())); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get incoming viewing Key") - public void test06GetIncomingViewingKey() { - ViewingKeyMessage.Builder viewBuilder = ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.getValue()); - viewBuilder.setNk(nk.getValue()); - ivk = blockingStubFull.getIncomingViewingKey(viewBuilder.build()); - logger.info("ivk: " + ByteArray.toHexString(ivk.getIvk().toByteArray())); - } - - /** - * constructor. - */ - @Test(enabled = false, description = "Get Zen Payment Address") - public void test07GetZenPaymentAddress() { - IncomingViewingKeyDiversifierMessage.Builder builder = - IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage1); - builder.setIvk(ivk); - PaymentAddressMessage addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - System.out.println("pkd1: " + ByteArray.toHexString(addressMessage.getPkD().toByteArray())); - System.out.println("address1: " + addressMessage.getPaymentAddress()); - addressInfo1.setSk(sk.getValue().toByteArray()); - addressInfo1.setD(new DiversifierT(diversifierMessage1.getD().toByteArray())); - addressInfo1.setIvk(ivk.getIvk().toByteArray()); - addressInfo1.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo1.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo1 = Optional.of(addressInfo1); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage2); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - System.out.println("pkd2: " + ByteArray.toHexString(addressMessage.getPkD().toByteArray())); - System.out.println("address2: " + addressMessage.getPaymentAddress()); - addressInfo2.setSk(sk.getValue().toByteArray()); - addressInfo2.setD(new DiversifierT(diversifierMessage2.getD().toByteArray())); - addressInfo2.setIvk(ivk.getIvk().toByteArray()); - addressInfo2.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo2.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo2 = Optional.of(addressInfo2); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage3); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - System.out.println("pkd3: " + ByteArray.toHexString(addressMessage.getPkD().toByteArray())); - System.out.println("address3: " + addressMessage.getPaymentAddress()); - addressInfo3.setSk(sk.getValue().toByteArray()); - addressInfo3.setD(new DiversifierT(diversifierMessage3.getD().toByteArray())); - addressInfo3.setIvk(ivk.getIvk().toByteArray()); - addressInfo3.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo3.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo3 = Optional.of(addressInfo3); - - - } - - @Test(enabled = false, description = "Shield to shield transaction") - public void test08Shield2ShieldTransaction() { - //S to S address1 - receiverShieldAddress1 = receiverAddressInfo1.get().getAddress(); - shieldOutList.clear(); - ; - memo1 = "Send shield to receiver1 shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress1, - "" + (sendNote1.getValue() - zenTokenFee), memo1); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo1, blockingStubFull); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - //S to S address2 - receiverShieldAddress2 = receiverAddressInfo2.get().getAddress(); - shieldOutList.clear(); - ; - memo2 = "Send shield2 to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress2, - "" + (sendNote2.getValue() - zenTokenFee), memo2); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo2, blockingStubFull); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo2.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - //S to S address3 - receiverShieldAddress3 = receiverAddressInfo3.get().getAddress(); - shieldOutList.clear(); - ; - memo3 = "Send shield3 to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress3, - "" + (sendNote3.getValue() - zenTokenFee), memo3); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo3, blockingStubFull); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo3.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey3, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Same sk and different d can produce different - // shield address,the notes can scan out by same ivk. - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo1, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - - receiverNote1 = notes.getNoteTxs(0).getNote(); - logger.info("Receiver note1:" + receiverNote1.toString()); - Assert.assertTrue(receiverNote1.getValue() == sendNote1.getValue() - zenTokenFee); - receiverNote2 = notes.getNoteTxs(1).getNote(); - logger.info("Receiver note2:" + receiverNote2.toString()); - Assert.assertTrue(receiverNote2.getValue() == sendNote2.getValue() - zenTokenFee); - receiverNote3 = notes.getNoteTxs(2).getNote(); - logger.info("Receiver note3:" + receiverNote3.toString()); - Assert.assertTrue(receiverNote3.getValue() == sendNote3.getValue() - zenTokenFee); - } - - @Test(enabled = false, - description = "Shield to shield transaction without ask") - public void test09Shield2ShieldTransactionWithoutAsk() { - //Same sk and different d can produce different shield address, - // the notes can use by scan from same ovk. - sendShieldAddressInfo1 = PublicMethed.generateShieldAddress(); - sendShieldAddress1 = sendShieldAddressInfo1.get().getAddress(); - sendShieldAddressInfo2 = PublicMethed.generateShieldAddress(); - sendShieldAddress2 = sendShieldAddressInfo2.get().getAddress(); - sendShieldAddressInfo3 = PublicMethed.generateShieldAddress(); - sendShieldAddress3 = sendShieldAddressInfo3.get().getAddress(); - - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo3, blockingStubFull); - receiverNote1 = notes.getNoteTxs(0).getNote(); - receiverNote2 = notes.getNoteTxs(1).getNote(); - receiverNote3 = notes.getNoteTxs(2).getNote(); - shieldOutList.clear(); - ; - memo1 = "Send shield address 1 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (receiverNote1.getValue() - zenTokenFee), memo1); - - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - shieldOutList.clear(); - ; - memo2 = "Send shield address 2 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (receiverNote2.getValue() - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo2.get(), notes.getNoteTxs(1), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - shieldOutList.clear(); - ; - memo3 = "Send shield address 3 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress3, - "" + (receiverNote3.getValue() - zenTokenFee), memo3); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - receiverAddressInfo3.get(), notes.getNoteTxs(2), - shieldOutList, - null, 0, - zenTokenOwnerKey3, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.getShieldNotesByOvk(receiverAddressInfo3, blockingStubFull); - logger.info("notes count:" + notes.getNoteTxsCount()); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - sendNote1 = notes.getNoteTxs(0).getNote(); - logger.info("Receiver1 note:" + sendNote1.toString()); - Assert.assertTrue(sendNote1.getValue() == receiverNote1.getValue() - zenTokenFee); - Assert.assertEquals(memo1, PublicMethed.getMemo(sendNote1)); - - sendNote2 = notes.getNoteTxs(1).getNote(); - logger.info("Receiver2 note:" + sendNote2.toString()); - Assert.assertTrue(sendNote2.getValue() == receiverNote2.getValue() - zenTokenFee); - Assert.assertEquals(memo2, PublicMethed.getMemo(sendNote2)); - - sendNote3 = notes.getNoteTxs(2).getNote(); - logger.info("Receiver3 note:" + sendNote3.toString()); - Assert.assertTrue(sendNote3.getValue() == receiverNote3.getValue() - zenTokenFee); - Assert.assertEquals(memo3, PublicMethed.getMemo(sendNote3)); - } - - @Test(enabled = false, description = "Get shield Nulltifier") - public void test10GetShieldNulltifier() { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo1, blockingStubFull); - Assert.assertEquals(PublicMethed.getShieldNullifier(sendShieldAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).length(), 64); - notes = PublicMethed.listShieldNote(receiverAddressInfo1, blockingStubFull); - Assert.assertEquals(PublicMethed.getShieldNullifier(receiverAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).length(), 64); - - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - } - - @Test(enabled = false, - description = "Same sk transfer shield address note is spent") - public void test11SameSkTransferShieldAddressNoteCanSpent() { - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - - receiverNote1 = notes.getNoteTxs(0).getNote(); - shieldOutList.clear(); - memo1 = "Send shield address 1 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (receiverNote1.getValue() - zenTokenFee), memo1); - Assert.assertFalse(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(1), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo3.get(), - notes.getNoteTxs(2), blockingStubFull).getResult()); - } - - @Test(enabled = false, description = "Same sk transfer two shield address," - + "in one transaction send to these shield transaction") - public void test12SameSkTransferTwoShieldAddressInOneTransaction() { - shieldOutList.clear(); - memo1 = "Send to first shield address " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress1, - "" + zenTokenFee, memo1); - memo2 = "Send to second shield address " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress2, - "" + (costTokenAmount - 2 * zenTokenFee), memo2); - logger.info("address1 receiver amount:" + zenTokenFee); - logger.info("address2 receiver amount:" + (costTokenAmount - 2 * zenTokenFee)); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - zenTokenOwnerAddress4, costTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey4, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 5); - Assert.assertTrue(notes.getNoteTxs(3).getNote().getValue() == zenTokenFee); - Assert.assertTrue(notes.getNoteTxs(4).getNote().getValue() - == (costTokenAmount - 2 * zenTokenFee)); - Assert.assertEquals(PublicMethed.getMemo(notes.getNoteTxs(3).getNote()), memo1); - Assert.assertEquals(PublicMethed.getMemo(notes.getNoteTxs(4).getNote()), memo2); - - shieldOutList.clear(); - ; - receiverNote1 = notes.getNoteTxs(3).getNote(); - receiverNote2 = notes.getNoteTxs(4).getNote(); - memo1 = "Send shield address 1 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress1, - "" + (receiverNote1.getValue() - zenTokenFee), memo1); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo1.get(), notes.getNoteTxs(3), - shieldOutList, - null, 0, - zenTokenOwnerKey1, blockingStubFull)); - - shieldOutList.clear(); - ; - memo2 = "Send shield address 2 without ask" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (receiverNote2.getValue() - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - receiverAddressInfo2.get(), notes.getNoteTxs(4), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo1, blockingStubFull); - sendNote1 = notes.getNoteTxs(0).getNote(); - shieldOutList.clear(); - memo2 = "Send receiver a note and spend it" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "" + (sendNote1.getValue() - zenTokenFee), memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - sendShieldAddressInfo1.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey2, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(3), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(4), blockingStubFull).getResult()); - - notes = PublicMethed.getShieldNotesByOvk(receiverAddressInfo1, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo1.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(1), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo3.get(), - notes.getNoteTxs(2), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo1.get(), - notes.getNoteTxs(3), blockingStubFull).getResult()); - Assert.assertFalse(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(4), blockingStubFull).getResult()); - - //Send shield coin without ask when there is no output shield address - shieldOutList.clear(); - memo2 = "Send receiver a note and spend it" + System.currentTimeMillis(); - - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - sendShieldAddressInfo2.get(), notes.getNoteTxs(1), - shieldOutList, - zenTokenOwnerAddress1, notes.getNoteTxs(1).getNote().getValue() - zenTokenFee, - zenTokenOwnerKey2, blockingStubFull)); - - shieldOutList.clear(); - memo2 = "Send receiver a note and spend it" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress2, - "0", memo2); - Assert.assertTrue(PublicMethed.sendShieldCoinWithoutAsk( - null, 0, - sendShieldAddressInfo3.get(), notes.getNoteTxs(2), - shieldOutList, - zenTokenOwnerAddress1, notes.getNoteTxs(2).getNote().getValue() - zenTokenFee, - zenTokenOwnerKey2, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(receiverAddressInfo2, blockingStubFull); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo2.get(), - notes.getNoteTxs(1), blockingStubFull).getResult()); - Assert.assertTrue(PublicMethed.getSpendResult(receiverAddressInfo3.get(), - notes.getNoteTxs(2), blockingStubFull).getResult()); - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress1, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress1, zenTokenOwnerKey1, blockingStubFull); - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress2, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress2, zenTokenOwnerKey2, blockingStubFull); - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress3, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress3, zenTokenOwnerKey3, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken008.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken008.java deleted file mode 100644 index 59abb2ec9f4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken008.java +++ /dev/null @@ -1,214 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken008 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 1 * zenTokenFee + 1; - private Long sendTokenAmount = 1 * zenTokenFee; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - - - } - - @Test(enabled = false, - description = "Public send 1 token to shield transaction") - public void test1Shield2ShieldTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield 1 token memo in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "1", memo); - Assert.assertFalse(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, costTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - Assert.assertTrue(sendNote.getValue() == 1); - - } - - @Test(enabled = false, - description = "Shield send 0 token to shield transaction") - public void test2Shield2ShieldTransaction() { - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - zenTokenFee * 2, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - - logger.info("token balance is " + afterAssetBalance); - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield costFee token memo in " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - //logger.info(); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, zenTokenFee * 2, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - receiverShieldAddressInfo = PublicMethed.generateShieldAddress(); - receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - memo = "Send shield to receiver shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "0", memo); - - //Wrong proof - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - //Amount is -1 - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "-1", memo); - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverShieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(receiverShieldAddressInfo, blockingStubFull); - receiverNote = notes.getNoteTxs(0).getNote(); - logger.info("Receiver note:" + receiverNote.toString()); - Assert.assertTrue(receiverNote.getValue() == 0); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken009.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken009.java deleted file mode 100644 index af1d45fb2e4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken009.java +++ /dev/null @@ -1,222 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class WalletTestZenToken009 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional shieldAddressInfo; - String shieldAddress; - Optional receiverAddressInfo; - String receiverAddress; - List shieldOutList = new ArrayList<>(); - List shieldInputList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note note; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey4.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 5 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - Assert.assertTrue( - PublicMethed.sendcoin(zenTokenOwnerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = zenTokenOwnerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(zenTokenOwnerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, zenTokenOwnerAddress, zenTokenOwnerKey, - blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = false, - description = "Public to shield transaction with mutisign") - public void test1Public2ShieldTransaction() { - Args.setFullNodeAllowShieldedTransaction(true); - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeBalance = PublicMethed - .queryAccount(zenTokenOwnerAddress, blockingStubFull).getBalance(); - final Long beforeNetUsed = PublicMethed - .getAccountResource(zenTokenOwnerAddress, blockingStubFull).getFreeNetUsed(); - - memo = "aaaaaaa"; - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - - Assert.assertTrue(PublicMethedForMutiSign.sendShieldCoin( - zenTokenOwnerAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull, 0, ownerKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - Long afterNetUsed = PublicMethed.getAccountResource(zenTokenOwnerAddress, blockingStubFull) - .getFreeNetUsed(); - Assert.assertTrue(beforeAssetBalance - afterAssetBalance == sendTokenAmount); - logger.info("Before net:" + beforeNetUsed); - logger.info("After net:" + afterNetUsed); - Assert.assertEquals(beforeNetUsed, afterNetUsed); - final Long afterBalance = PublicMethed - .queryAccount(zenTokenOwnerAddress, blockingStubFull).getBalance(); - Assert.assertTrue(beforeBalance - afterBalance == multiSignFee); - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - Long receiverShieldTokenAmount = note.getValue(); - Assert.assertTrue(receiverShieldTokenAmount == sendTokenAmount - zenTokenFee); - Assert.assertEquals(memo, PublicMethed.getMemo(note)); - } - - @Test(enabled = false, - description = "When from is shield,sign this transaction is forbidden") - public void test2ShieldFromShouldNotSign() { - receiverAddressInfo = PublicMethed.generateShieldAddress(); - receiverAddress = shieldAddressInfo.get().getAddress(); - logger.info("receiver address:" + shieldAddress); - - notes = PublicMethed.listShieldNote(shieldAddressInfo, blockingStubFull); - note = notes.getNoteTxs(0).getNote(); - - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, receiverAddress, - "" + (note.getValue() - zenTokenFee), memo); - - Assert.assertFalse(PublicMethedForMutiSign.sendShieldCoin( - null, 321321, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull, 0, ownerKeyString)); - - Assert.assertFalse(PublicMethed.sendShieldCoin( - null, 321321, - shieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - Assert.assertFalse(PublicMethed.getSpendResult(shieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethedForMutiSign.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, - zenTokenOwnerKey, blockingStubFull, ownerKeyString); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken010.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken010.java deleted file mode 100644 index d1c162f770c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken010.java +++ /dev/null @@ -1,260 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken010 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private String txid; - private Optional infoById; - private Optional byId; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - - } - - @Test(enabled = false, description = "Shield to itself transaction") - public void test1Shield2ShieldTransaction() { - shieldOutList.clear(); - memo = "Send shield to itself memo1 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - - memo = "Send shield to itself memo2 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendNote.getValue() - 2 * zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - Assert.assertTrue(notes.getNoteTxs(1).getNote().getValue() == zenTokenFee); - Assert.assertTrue(notes.getNoteTxs(2).getNote().getValue() - == sendNote.getValue() - 2 * zenTokenFee); - Assert.assertEquals(notes.getNoteTxs(1).getNote().getPaymentAddress(), - notes.getNoteTxs(2).getNote().getPaymentAddress()); - Assert.assertEquals(notes.getNoteTxs(1).getTxid(), notes.getNoteTxs(2).getTxid()); - Assert.assertTrue(PublicMethed.getSpendResult(sendShieldAddressInfo.get(), - notes.getNoteTxs(0), blockingStubFull).getResult()); - - notes = PublicMethed.getShieldNotesByOvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 2); - } - - @Test(enabled = false, description = "From shield only have one zenToken fee") - public void test2Shield2ShieldTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - logger.info("sendShieldAddressInfo:" + sendShieldAddressInfo); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, 2 * zenTokenFee, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - sendNote = notes.getNoteTxs(0).getNote(); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - shieldOutList.clear(); - memo = "Send shield to itself memo1 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "0", memo); - - memo = "Send shield to itself memo2 in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "0", memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(0), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 3); - logger.info("index 0:" + notes.getNoteTxs(0).getNote().getValue()); - logger.info("index 1:" + notes.getNoteTxs(1).getNote().getValue()); - logger.info("index 2:" + notes.getNoteTxs(2).getNote().getValue()); - Assert.assertTrue(notes.getNoteTxs(1).getNote().getValue() == 0); - Assert.assertTrue(notes.getNoteTxs(2).getNote().getValue() == 0); - Assert.assertEquals(notes.getNoteTxs(1).getNote().getPaymentAddress(), - notes.getNoteTxs(2).getNote().getPaymentAddress()); - Assert.assertEquals(notes.getNoteTxs(1).getTxid(), notes.getNoteTxs(2).getTxid()); - } - - @Test(enabled = false, description = "From public and to public is same one") - public void test3Public2ShieldAndPublicItselfTransaction() { - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - ecKey1 = new ECKey(Utils.getRandom()); - zenTokenOwnerAddress = ecKey1.getAddress(); - zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull).getAccountId(), - blockingStubFull); - final Long beforeBalance = PublicMethed.queryAccount(zenTokenOwnerAddress, blockingStubFull) - .getBalance(); - shieldOutList.clear(); - memo = "From public and to public is same one memo in " + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + 2 * zenTokenFee, memo); - - Assert.assertFalse(PublicMethed - .sendShieldCoin(zenTokenOwnerAddress, costTokenAmount, null, null, shieldOutList, - zenTokenOwnerAddress, 7 * zenTokenFee, zenTokenOwnerKey, blockingStubFull)); - - Long afterAssetBalance = PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull).getAccountId(), - blockingStubFull); - Long afterBalance = PublicMethed.queryAccount(zenTokenOwnerAddress, blockingStubFull) - .getBalance(); - - Assert.assertEquals(beforeAssetBalance, afterAssetBalance); - Assert.assertEquals(beforeBalance, afterBalance); - - notes = PublicMethed.getShieldNotesByIvk(sendShieldAddressInfo, blockingStubFull); - Assert.assertTrue(notes.getNoteTxsCount() == 0); - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken011.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken011.java deleted file mode 100644 index 9287e92c0b7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentoken/WalletTestZenToken011.java +++ /dev/null @@ -1,144 +0,0 @@ -package stest.tron.wallet.dailybuild.zentoken; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenToken011 { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 10 * zenTokenFee; - private Long sendTokenAmount = 8 * zenTokenFee; - private String txid; - private Optional infoById; - private Optional byId; - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - - - } - - @Test(enabled = false, description = "Test get new shield address ") - public void test1Shield2ShieldTransaction() { - sendShieldAddress = blockingStubFull.getNewShieldedAddress(GrpcAPI.EmptyMessage.newBuilder() - .build()).getPaymentAddress(); - memo = "Shield memo in" + System.currentTimeMillis(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - Assert.assertTrue(PublicMethed.sendShieldCoin(zenTokenOwnerAddress, sendTokenAmount, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token001.java deleted file mode 100644 index 99d26ce145e..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token001.java +++ /dev/null @@ -1,206 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONObject; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.Note; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; -import stest.tron.wallet.common.client.utils.ShieldNoteInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token001 extends ZenTrc20Base { - - List shieldOutList = new ArrayList<>(); - Optional shieldAddressOptionalInfo1; - Optional shieldAddressOptionalInfo2; - Optional shieldAddressOptionalInfo3; - ShieldAddressInfo shieldAddressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo shieldAddressInfo3 = new ShieldAddressInfo(); - String assetIssueId; - ShieldNoteInfo shieldNote1; - ShieldNoteInfo shieldNote2; - ShieldNoteInfo shieldNote3; - String memo; - String sk; - String d1; - String d2; - String d3; - String ask; - String nsk; - String ovk; - String ak; - String nk; - String ivk; - String pkD1; - String pkD2; - String pkD3; - String paymentAddress1; - String paymentAddress2; - String paymentAddress3; - String rcm; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - //Args.getInstance().setFullNodeAllowShieldedTransaction(true); - //PublicMethed.printAddress(foundationZenTokenKey); - //PublicMethed.printAddress(zenTokenOwnerKey); - } - - @Test(enabled = true, description = "Get spending key by http") - public void test01GetSpendingKey() { - response = HttpMethed.getSpendingKey(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - sk = responseContent.getString("value"); - logger.info("sk: " + sk); - - } - - @Test(enabled = true, description = "Get diversifier by http") - public void test02GetDiversifier() { - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d1 = responseContent.getString("d"); - logger.info("d1: " + d1); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d2 = responseContent.getString("d"); - logger.info("d2: " + d2); - - response = HttpMethed.getDiversifier(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - d3 = responseContent.getString("d"); - logger.info("d3: " + d3); - } - - @Test(enabled = true, description = "Get expanded spending key by http") - public void test03GetExpandedSpendingKey() { - response = HttpMethed.getExpandedSpendingKey(httpnode, sk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ask = responseContent.getString("ask"); - nsk = responseContent.getString("nsk"); - ovk = responseContent.getString("ovk"); - logger.info("ask: " + ask); - logger.info("nsk: " + nsk); - logger.info("ovk: " + ovk); - } - - @Test(enabled = true, description = "Get AK from ASK by http") - public void test04GetAkFromAsk() { - response = HttpMethed.getAkFromAsk(httpnode, ask); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ak = responseContent.getString("value"); - logger.info("ak: " + ak); - } - - @Test(enabled = true, description = "Get Nk from Nsk by http") - public void test05GetNkFromNsk() { - response = HttpMethed.getNkFromNsk(httpnode, nsk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - nk = responseContent.getString("value"); - logger.info("nk: " + nk); - } - - @Test(enabled = true, description = "Get incoming viewing Key by http") - public void test06GetIncomingViewingKey() { - response = HttpMethed.getIncomingViewingKey(httpnode, ak, nk); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - ivk = responseContent.getString("ivk"); - logger.info("ivk: " + ivk); - } - - @Test(enabled = true, description = "Get Zen Payment Address by http") - public void test07GetZenPaymentAddress() { - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d1); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD1 = responseContent.getString("pkD"); - paymentAddress1 = responseContent.getString("payment_address"); - System.out.println("pkd1: " + pkD1); - System.out.println("address1: " + paymentAddress1); - shieldAddressInfo1.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo1.setD(new DiversifierT(ByteArray.fromHexString(d1))); - shieldAddressInfo1.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo1.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo1.setPkD(ByteArray.fromHexString(pkD1)); - shieldAddressOptionalInfo1 = Optional.of(shieldAddressInfo1); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d2); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD2 = responseContent.getString("pkD"); - paymentAddress2 = responseContent.getString("payment_address"); - System.out.println("pkd2: " + pkD2); - System.out.println("address2: " + paymentAddress2); - shieldAddressInfo2.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo2.setD(new DiversifierT(ByteArray.fromHexString(d2))); - shieldAddressInfo2.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo2.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo2.setPkD(ByteArray.fromHexString(pkD2)); - shieldAddressOptionalInfo2 = Optional.of(shieldAddressInfo2); - - response = HttpMethed.getZenPaymentAddress(httpnode, ivk, d3); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - pkD3 = responseContent.getString("pkD"); - paymentAddress3 = responseContent.getString("payment_address"); - System.out.println("pkd3: " + pkD3); - System.out.println("address3: " + paymentAddress3); - shieldAddressInfo3.setSk(ByteArray.fromHexString(sk)); - shieldAddressInfo3.setD(new DiversifierT(ByteArray.fromHexString(d3))); - shieldAddressInfo3.setIvk(ByteArray.fromHexString(ivk)); - shieldAddressInfo3.setOvk(ByteArray.fromHexString(ovk)); - shieldAddressInfo3.setPkD(ByteArray.fromHexString(pkD3)); - shieldAddressOptionalInfo3 = Optional.of(shieldAddressInfo3); - } - - @Test(enabled = true, description = "Get rcm by http") - public void test08GetRcm() { - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - rcm = responseContent.getString("value"); - logger.info("rcm: " + rcm); - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java deleted file mode 100644 index 67518968128..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token002.java +++ /dev/null @@ -1,200 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token002 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo; - private JSONArray noteTxs; - private Long publicFromAmount = getRandomLongAmount(); - - @Test(enabled = true, description = "Get new shield account by http") - public void test01GetNewShieldAccountByHttp() { - response = getNewShieldedAddress(httpnode); - shieldAccountInfo = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo); - Assert.assertEquals(shieldAccountInfo.getString("sk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ask").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("nsk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ovk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ak").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("nk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("ivk").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("d").length(), 22); - Assert.assertEquals(shieldAccountInfo.getString("pkD").length(), 64); - Assert.assertEquals(shieldAccountInfo.getString("payment_address").length(), 81); - - response = HttpMethed.getRcm(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - } - - @Test(enabled = true, description = "Create mint parameters by http") - public void test02MintByHttp() { - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm((httpnode))); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 250000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 250000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - - } - - - @Test(enabled = true, description = "Scan shield TRC20 note by http") - public void test03ScanTrc20NodeByHttp() { - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - logger.info(noteTxs.toJSONString()); - Assert.assertEquals(noteTxs.size(), 2); - Assert.assertEquals(noteTxs.getJSONObject(1) - .getJSONObject("note").getLong("value"), publicFromAmount); - Assert.assertEquals(noteTxs.getJSONObject(1) - .getJSONObject("note").getString("payment_address"), - shieldAccountInfo.getString("payment_address")); - Assert.assertEquals(noteTxs.getJSONObject(1) - .getString("txid"), txid); - } - - @Test(enabled = true, description = "Shield trc20 burn by http") - public void test04ShiledTrc20BurnByHttp() { - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(0)); - - logger.info(shieldSpends.toJSONString()); - - response = createShieldContractParametersForBurn(httpnode, shieldAccountInfo, shieldSpends, - zenTrc20TokenOwnerAddressString, publicFromAmount); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - noteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo); - logger.info("noteTxs ovk:" + noteTxs); - Assert.assertEquals(noteTxs.getJSONObject(0).getLong("to_amount"), publicFromAmount); - Assert.assertEquals(noteTxs.getJSONObject(0).getString("transparent_to_address"), - zenTrc20TokenOwnerAddressString); - Assert.assertEquals(noteTxs.getJSONObject(0).getString("txid"), txid); - } - - - @Test(enabled = true, description = "Shield trc20 burn with ask by http") - public void test05ShiledTrc20BurnWithoutAskByHttp() { - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(1)); - - logger.info(shieldSpends.toJSONString()); - - response = createShieldContractParametersWithoutAskForBurn(httpnode, shieldAccountInfo, - shieldSpends, zenTrc20TokenOwnerAddressString, publicFromAmount); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig = createSpendAuthSig(httpnode, shieldAccountInfo, - shieldedTrc20Parameters.getString("message_hash"), noteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig); - - response = getTriggerInputForShieldedTrc20BurnContract(httpnode, - shieldedTrc20Parameters, spendAuthSigArray, publicFromAmount, - zenTrc20TokenOwnerAddressString); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - } - - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java deleted file mode 100644 index 5fdc4e8039a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token003.java +++ /dev/null @@ -1,289 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token003 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - JSONArray shieldSpends = new JSONArray(); - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo1; - private JSONObject shieldAccountInfo2; - private JSONArray account1IvkNoteTxs = new JSONArray(); - private JSONArray account2IvkNoteTxs = new JSONArray(); - private JSONArray account1OvkNoteTxs = new JSONArray(); - private JSONArray account2OvkNoteTxs = new JSONArray(); - private Long publicFromAmount = getRandomLongAmount(); - private Long account1Receive1V2Amount = 10L; - private Long account2Receive1V2Amount = publicFromAmount - account1Receive1V2Amount; - private Long account1Receive2V2Amount = 13L; - private Long account2Receive2V2Amount = publicFromAmount - + account2Receive1V2Amount - account1Receive2V2Amount; - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Prepare for transfer") - public void prepareForTransfer() { - //Create two shield account - response = getNewShieldedAddress(httpnode); - shieldAccountInfo1 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo1); - - response = getNewShieldedAddress(httpnode); - shieldAccountInfo2 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo2); - //Send two mint to shield account 1 - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - } - - - @Test(enabled = true, description = "Transfer type with 1V1 by http") - public void test01TransferTypeWith1V1ByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(0)); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 1); - } - - @Test(enabled = true, description = "Transfer type with 1V2 by http") - public void test02TransferTypeWith1V2ByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(1)); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive1V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive1V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo1, shieldSpends, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 3); - } - - - @Test(enabled = true, description = "Transfer type with 2V2 by http") - public void test03TransferTypeWith2V2ByHttp() { - account2IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo2); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(0)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(1)); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive2V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo2, shieldSpends, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account2OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo2); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account2OvkNoteTxs.size(), 2); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - - } - - @Test(enabled = true, description = "Transfer type with 2V1 by http") - public void test04TransferTypeWith2V1ByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(2)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(3)); - Long account1Receive2V1Amount = account1IvkNoteTxs.getJSONObject(2) - .getJSONObject("note").getLong("value") - + account1IvkNoteTxs.getJSONObject(3).getJSONObject("note").getLong("value"); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V1Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersForTransfer(httpnode, shieldAccountInfo1, shieldSpends, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.containsKey("trigger_contract_input")); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 4); - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - - } - - - @Test(enabled = true, description = "Query is shielded trc20 contract note spent on " - + "solidity by http") - public void test05QueryIsShieldedTrc20ContractNoteSpentByHttp() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnSolidity(httpSolidityNode, - shieldAccountInfo1, account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnSolidity(httpSolidityNode, - shieldAccountInfo1, account1IvkNoteTxs.getJSONObject(3))); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java deleted file mode 100644 index c874776919f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token004.java +++ /dev/null @@ -1,376 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token004 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - JSONArray shieldSpends = new JSONArray(); - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private String httpPbftNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(4); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo1; - private JSONObject shieldAccountInfo2; - private JSONArray account1IvkNoteTxs = new JSONArray(); - private JSONArray account2IvkNoteTxs = new JSONArray(); - private JSONArray account1OvkNoteTxs = new JSONArray(); - private JSONArray account2OvkNoteTxs = new JSONArray(); - private Long publicFromAmount = getRandomLongAmount(); - private Long account1Receive1V2Amount = 10L; - private Long account2Receive1V2Amount = publicFromAmount - account1Receive1V2Amount; - private Long account1Receive2V2Amount = 13L; - private Long account2Receive2V2Amount = publicFromAmount + account2Receive1V2Amount - - account1Receive2V2Amount; - - /** - * constructor. - */ - @BeforeClass(enabled = true, description = "Prepare for transfer without ask") - public void prepareForTransfer() { - //Create two shield account - response = getNewShieldedAddress(httpnode); - shieldAccountInfo1 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo1); - - response = getNewShieldedAddress(httpnode); - shieldAccountInfo2 = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldAccountInfo2); - //Send two mint to shield account 1 - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo1, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - //HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - } - - - @Test(enabled = true, description = "Transfer type with 1V1 without ask by http") - public void test01TransferTypeWith1V1WithoutAskByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(0)); - HttpMethed.waitToProduceOneBlock(httpnode); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs - .getJSONObject(0).getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 1); - } - - @Test(enabled = true, description = "Transfer type with 1V2 without ask by http") - public void test02TransferTypeWith1V2WithoutAskByHttp() { - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(1)); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive1V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive1V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig1 = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig1); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig1); - //spendAuthSigArray.add(spendAuthSig2); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 3); - } - - - @Test(enabled = true, description = "Transfer type with 2V2 without ask by http") - public void test03TransferTypeWith2V2WithoutAskByHttp() { - account2IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo2); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(0)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account2IvkNoteTxs - .getJSONObject(1)); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V2Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account2Receive2V2Amount, - shieldAccountInfo2.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo2, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - - JSONObject spendAuthSig1 = createSpendAuthSig(httpnode, shieldAccountInfo2, - shieldedTrc20Parameters.getString("message_hash"), account2IvkNoteTxs.getJSONObject(0) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig1); - - JSONObject spendAuthSig2 = createSpendAuthSig(httpnode, shieldAccountInfo2, - shieldedTrc20Parameters.getString("message_hash"), account2IvkNoteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig1); - spendAuthSigArray.add(spendAuthSig2); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - account2OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo2); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account2OvkNoteTxs.size(), 2); - - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(0))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo2, - account2IvkNoteTxs.getJSONObject(1))); - - } - - @Test(enabled = true, description = "Transfer type with 2V1 without ask by http") - public void test04TransferTypeWith2V1WithoutAskByHttp() { - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertFalse(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - shieldSpends.clear(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(2)); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, account1IvkNoteTxs - .getJSONObject(3)); - Long account1Receive2V1Amount = account1IvkNoteTxs.getJSONObject(2) - .getJSONObject("note").getLong("value") - + account1IvkNoteTxs.getJSONObject(3).getJSONObject("note").getLong("value"); - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, account1Receive2V1Amount, - shieldAccountInfo1.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParametersWithoutAskForTransfer(httpnode, shieldAccountInfo1, - shieldSpends, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - - JSONObject spendAuthSig1 = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs.getJSONObject(2) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig1); - - JSONObject spendAuthSig2 = createSpendAuthSig(httpnode, shieldAccountInfo1, - shieldedTrc20Parameters.getString("message_hash"), account1IvkNoteTxs.getJSONObject(3) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig2); - - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig1); - spendAuthSigArray.add(spendAuthSig2); - - response = getTriggerInputForShieldedTrc20Contract(httpnode, shieldedTrc20Parameters, - spendAuthSigArray); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, transfer, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 300000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - logger.info(account1OvkNoteTxs.toJSONString()); - Assert.assertEquals(account1OvkNoteTxs.size(), 4); - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnPbft(httpPbftNode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(2))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpent(httpnode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - Assert.assertTrue(isShieldedTrc20ContractNoteSpentOnPbft(httpPbftNode, shieldAccountInfo1, - account1IvkNoteTxs.getJSONObject(3))); - - } - - - @Test(enabled = true, description = "Scan note by ivk and ovk on solidity and pbft by http") - public void test05ScanNoteByIvkAndOvkOnSOlidityAndPbftByHttp() { - HttpMethed.waitToProduceOneBlockFromSolidity(httpnode, httpSolidityNode); - - account1IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo1); - JSONArray account1IvkNoteTxsOnSolidity = scanShieldTrc20NoteByIvkOnSolidity(httpSolidityNode, - shieldAccountInfo1); - Assert.assertEquals(account1IvkNoteTxs, account1IvkNoteTxsOnSolidity); - JSONArray account1IvkNoteTxsOnPbft = scanShieldTrc20NoteByIvkOnPbft(httpPbftNode, - shieldAccountInfo1); - Assert.assertEquals(account1IvkNoteTxs, account1IvkNoteTxsOnPbft); - - account1OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo1); - JSONArray account1OvkNoteTxsOnSolidity = scanShieldTrc20NoteByOvkOnSolidity(httpSolidityNode, - shieldAccountInfo1); - Assert.assertEquals(account1OvkNoteTxs, account1OvkNoteTxsOnSolidity); - JSONArray account1OvkNoteTxsOnPbft = scanShieldTrc20NoteByOvkOnPbft(httpPbftNode, - shieldAccountInfo1); - Assert.assertEquals(account1OvkNoteTxs, account1OvkNoteTxsOnPbft); - - account2IvkNoteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo2); - JSONArray account2IvkNoteTxsOnSolidity = scanShieldTrc20NoteByIvkOnSolidity(httpSolidityNode, - shieldAccountInfo2); - Assert.assertEquals(account2IvkNoteTxs, account2IvkNoteTxsOnSolidity); - JSONArray account2IvkNoteTxsOnPbft = scanShieldTrc20NoteByIvkOnPbft(httpPbftNode, - shieldAccountInfo2); - Assert.assertEquals(account2IvkNoteTxs, account2IvkNoteTxsOnPbft); - - account2OvkNoteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo2); - JSONArray account2OvkNoteTxsOnSolidity = scanShieldTrc20NoteByOvkOnSolidity(httpSolidityNode, - shieldAccountInfo2); - Assert.assertEquals(account2OvkNoteTxs, account2OvkNoteTxsOnSolidity); - JSONArray account2OvkNoteTxsOnPbft = scanShieldTrc20NoteByOvkOnPbft(httpPbftNode, - shieldAccountInfo2); - Assert.assertEquals(account2OvkNoteTxs, account2OvkNoteTxsOnPbft); - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java deleted file mode 100644 index 998a97a9322..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/HttpShieldTrc20Token005.java +++ /dev/null @@ -1,197 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class HttpShieldTrc20Token005 extends ZenTrc20Base { - - JSONArray shieldedReceives = new JSONArray(); - String txid; - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - private String anotherHttpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(1); - private String httpSolidityNode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(2); - private JSONObject responseContent; - private HttpResponse response; - private JSONObject shieldAccountInfo; - private JSONObject shieldReceiverAccountInfo; - private JSONArray noteTxs; - private Long publicFromAmount = getRandomLongAmount(); - - /** - * constructor. - */ - - @BeforeClass(enabled = true, description = "Get new shield account by http") - public void createTwoNote() { - response = getNewShieldedAddress(httpnode); - shieldAccountInfo = HttpMethed.parseResponseContent(response); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm((httpnode))); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, publicFromAmount, - shieldAccountInfo.getString("payment_address"), getRcm(httpnode)); - response = createShieldContractParameters(httpnode, publicFromAmount, shieldAccountInfo, - shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, mint, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - } - - @Test(enabled = true, description = "Shield trc20 burn to one T and one S by http") - public void test01ShiledTrc20BurnToOnePublicAndOneShieldByHttp() { - response = getNewShieldedAddress(httpnode); - shieldReceiverAccountInfo = HttpMethed.parseResponseContent(response); - - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(0)); - - logger.info(shieldSpends.toJSONString()); - - Long toShieldAmount = 9L; - Long toPublicAmount = publicFromAmount - toShieldAmount; - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, toShieldAmount, - shieldReceiverAccountInfo.getString("payment_address"), getRcm(httpnode)); - - response = createShieldContractParametersForBurn(httpnode, shieldAccountInfo, shieldSpends, - zenTrc20TokenOwnerAddressString, toPublicAmount, shieldedReceives); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("trigger_contract_input"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), - "SUCCESS"); - - noteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo); - logger.info("noteTxs ovk:" + noteTxs); - - Assert.assertEquals(noteTxs.getJSONObject(0).getJSONObject("note") - .getLong("value"), toShieldAmount); - Assert.assertEquals(noteTxs.getJSONObject(0).getJSONObject("note") - .getString("payment_address"), shieldReceiverAccountInfo.getString("payment_address")); - - Assert.assertEquals(noteTxs.getJSONObject(1).getLong("to_amount"), toPublicAmount); - Assert.assertEquals(noteTxs.getJSONObject(1).getString("transparent_to_address"), - zenTrc20TokenOwnerAddressString); - Assert.assertEquals(noteTxs.getJSONObject(1).getString("txid"), txid); - } - - - @Test(enabled = true, description = "Shield trc20 burn without ask to one " - + "public and one shield by http") - public void test02ShiledTrc20BurnWithoutAskToOnePublicAndOneShieldByHttp() { - noteTxs = scanShieldTrc20NoteByIvk(httpnode, shieldAccountInfo); - JSONArray shieldSpends = new JSONArray(); - shieldSpends = createAndSetShieldedSpends(httpnode, shieldSpends, noteTxs.getJSONObject(1)); - - Long toShieldAmount = 8L; - Long toPublicAmount = publicFromAmount - toShieldAmount; - shieldedReceives.clear(); - shieldedReceives = getHttpShieldedReceivesJsonArray(shieldedReceives, toShieldAmount, - shieldReceiverAccountInfo.getString("payment_address"), getRcm(httpnode)); - - response = createShieldContractParametersWithoutAskForBurn(httpnode, shieldAccountInfo, - shieldSpends, zenTrc20TokenOwnerAddressString, toPublicAmount, shieldedReceives); - JSONObject shieldedTrc20Parameters = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(shieldedTrc20Parameters); - JSONObject spendAuthSig = createSpendAuthSig(httpnode, shieldAccountInfo, - shieldedTrc20Parameters.getString("message_hash"), noteTxs.getJSONObject(1) - .getJSONObject("note").getString("rcm")); - HttpMethed.printJsonContent(spendAuthSig); - JSONArray spendAuthSigArray = new JSONArray(); - spendAuthSigArray.add(spendAuthSig); - - response = getTriggerInputForShieldedTrc20BurnContract(httpnode, - shieldedTrc20Parameters, spendAuthSigArray, toPublicAmount, - zenTrc20TokenOwnerAddressString); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - txid = HttpMethed.triggerContractGetTxidWithVisibleTrue(httpnode,anotherHttpnode, - zenTrc20TokenOwnerAddressString, shieldAddress, burn, responseContent - .getString("value"), maxFeeLimit, 0L, 0, 0L, - zenTrc20TokenOwnerKey); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getTransactionInfoById(httpnode, txid, true); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - Assert.assertTrue(responseContent.getJSONObject("receipt") - .getLong("energy_usage_total") > 150000L); - Assert.assertEquals(responseContent.getString("contract_address"), shieldAddress); - Assert.assertEquals(responseContent.getJSONObject("receipt").getString("result"), "SUCCESS"); - - noteTxs = scanShieldTrc20NoteByOvk(httpnode, shieldAccountInfo); - logger.info("noteTxs ovk:" + noteTxs); - - Assert.assertEquals(noteTxs.getJSONObject(2).getJSONObject("note") - .getLong("value"), toShieldAmount); - Assert.assertEquals(noteTxs.getJSONObject(2).getJSONObject("note") - .getString("payment_address"), shieldReceiverAccountInfo.getString("payment_address")); - - Assert.assertEquals(noteTxs.getJSONObject(3).getLong("to_amount"), toPublicAmount); - Assert.assertEquals(noteTxs.getJSONObject(3).getString("transparent_to_address"), - zenTrc20TokenOwnerAddressString); - Assert.assertEquals(noteTxs.getJSONObject(3).getString("txid"), txid); - - } - - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token001.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token001.java deleted file mode 100644 index ee61c9996c9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token001.java +++ /dev/null @@ -1,84 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.TransactionExtention; -import org.tron.api.WalletGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token001 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "Check shield contract deploy success") - public void test01checkShieldContractDeploySuccess() { - Optional infoById = PublicMethed - .getTransactionInfoById(deployShieldTrc20Txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - infoById = PublicMethed - .getTransactionInfoById(deployShieldTxid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //scalingFactor() - } - - @Test(enabled = true, description = "View scaling factor test") - public void test02ViewScalingFactor() { - String txid = PublicMethed.triggerContract(shieldAddressByte, - "scalingFactor()", "", false, - 0, maxFeeLimit, zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - logger.info(txid); - logger.info(Integer.toString(infoById.get().getResultValue())); - - TransactionExtention transactionExtention = PublicMethed - .triggerConstantContractForExtention(shieldAddressByte, "scalingFactor()", - "", false, 0, 0, "0", 0, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("transactionExtention:" + transactionExtention); - String scalingFactor = PublicMethed - .bytes32ToString(transactionExtention.getConstantResult(0).toByteArray()); - Assert.assertEquals("00000000000000000000000000000001", - scalingFactor); - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token002.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token002.java deleted file mode 100644 index f118553d496..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token002.java +++ /dev/null @@ -1,132 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token002 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional receiverShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Send shield trc20 from T account to shield account") - public void test01ShieldTrc20TransactionByTypeMint() throws Exception { - //Query account before mint balance - final Long beforeMintAccountBalance = getBalanceOfShieldTrc20(zenTrc20TokenOwnerAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeMintShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Generate new shiled account and set note memo - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - logger.info(mint + ":" + txid); - logger.info(mint + infoById.get().getReceipt().getEnergyUsageTotal()); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 250000); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Query account after mint balance - Long afterMintAccountBalance = getBalanceOfShieldTrc20(zenTrc20TokenOwnerAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract after mint balance - Long afterMintShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - Assert.assertEquals(BigInteger.valueOf(beforeMintAccountBalance - afterMintAccountBalance), - publicFromAmount); - Assert.assertEquals(BigInteger.valueOf(afterMintShieldAccountBalance - - beforeMintShieldAccountBalance), publicFromAmount); - - GrpcAPI.DecryptNotesTRC20 note = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - logger.info("" + note); - - Assert.assertEquals(note.getNoteTxs(0).getNote().getValue(), publicFromAmount.longValue()); - Assert.assertEquals(note.getNoteTxs(0).getNote().getPaymentAddress(), - receiverShieldAddressInfo.get().getAddress()); - Assert.assertEquals(note.getNoteTxs(0).getNote().getMemo(), ByteString.copyFromUtf8(memo)); - Assert.assertEquals(note.getNoteTxs(0).getTxid(), infoById.get().getId()); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token003.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token003.java deleted file mode 100644 index 81ee7e32b8f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token003.java +++ /dev/null @@ -1,216 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token003 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional senderShieldAddressInfo; - Optional receiverShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 senderNote; - GrpcAPI.DecryptNotesTRC20 receiverNote; - long senderPosition; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - senderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for transfer test " + System.currentTimeMillis(); - String sendShieldAddress = senderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + senderNote); - senderPosition = senderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(senderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type transfer") - public void test01ShieldTrc20TransactionWithTypeTransfer() throws Exception { - final Long beforeMintShieldContractBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - String transferMemo = "Transfer type test " + System.currentTimeMillis(); - String receiverShieldAddress = receiverShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + publicFromAmount, transferMemo, blockingStubFull); - inputShieldAddressList.add(senderShieldAddressInfo.get()); - //inputNoteList.add(senderNote); - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - senderNote, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - //String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan sender note - receiverNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - - logger.info("" + receiverNote); - Assert.assertEquals(receiverNote.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(receiverNote.getNoteTxs(0).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo)); - Assert.assertEquals(receiverNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - Assert.assertEquals(receiverNote.getNoteTxs(0).getNote().getPaymentAddress(), - receiverShieldAddressInfo.get().getAddress()); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - senderNote = scanShieldedTrc20NoteByOvk(senderShieldAddressInfo.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + senderNote:" + senderNote); - - final Long afterMintShieldContractBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - Assert.assertEquals(beforeMintShieldContractBalance, afterMintShieldContractBalance); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type transfer without ask") - public void test02ShieldTrc20TransactionWithTypeTransferWithoutAsk() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Scan receiver note prepare for without type of transfer - receiverNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - String transferMemo = "Transfer type without ask test " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, senderShieldAddressInfo.get() - .getAddress(), - "" + publicFromAmount, transferMemo, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(receiverShieldAddressInfo.get()); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20ParametersWithoutAsk(BigInteger.valueOf(0), - receiverNote, inputShieldAddressList, shieldOutList, "", null, 0L, - blockingStubFull, blockingStubSolidity); - - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - - logger.info("" + senderNote); - Assert.assertEquals(senderNote.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(senderNote.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo)); - Assert.assertEquals(senderNote.getNoteTxs(1).getNote().getValue(), - publicFromAmount.longValue()); - Assert.assertEquals(senderNote.getNoteTxs(1).getNote().getPaymentAddress(), - senderShieldAddressInfo.get().getAddress()); - - //logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - receiverNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(receiverNote.getNoteTxs(0).getIsSpent(), true); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token004.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token004.java deleted file mode 100644 index bad605d1cc9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token004.java +++ /dev/null @@ -1,307 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token004 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional senderShieldAddressInfo; - Optional secondSenderShieldAddressInfo; - Optional receiverShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - List inputNoteList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 senderNote; - GrpcAPI.DecryptNotesTRC20 secondSenderNote; - long senderPosition; - - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddressbyte = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String receiverAddressString = PublicMethed.getAddressString(receiverKey); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - senderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for burn test " + System.currentTimeMillis(); - String sendShieldAddress = senderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + senderNote); - senderPosition = senderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(senderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - //Generate new shiled account for burn to one public and one shield - secondSenderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - - memo = "Create a note for burn to one public and one shield test " - + System.currentTimeMillis(); - sendShieldAddress = secondSenderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + secondSenderNote); - senderPosition = secondSenderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type burn") - public void test01ShieldTrc20TransactionWithTypeBurn() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - //String burnMemo = "Burn type test " + System.currentTimeMillis(); - inputShieldAddressList.add(senderShieldAddressInfo.get()); - BigInteger receiveAmount = publicFromAmount; - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - senderNote, inputShieldAddressList, null, receiverAddressString, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), receiveAmount); - - senderNote = scanShieldedTrc20NoteByOvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(ByteArray.toHexString(senderNote.getNoteTxs(0) - .getTxid().toByteArray()), txid); - Assert.assertEquals(senderNote.getNoteTxs(0).getToAmount(), publicFromAmount.toString()); - - String toAddress = ByteArray.toHexString(senderNote.getNoteTxs(0) - .getTransparentToAddress().toByteArray()); - String receiverHexString = ByteArray.toHexString(PublicMethed.getFinalAddress(receiverKey)); - Assert.assertEquals(toAddress, receiverHexString); - - - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction to one T and one S with type burn") - public void test02ShieldTrc20TransactionWithTypeBurnToOnePublicAndOneShield() throws Exception { - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - inputShieldAddressList.clear(); - inputShieldAddressList.add(secondSenderShieldAddressInfo.get()); - BigInteger shieldReceiveAmount = BigInteger.valueOf(9L); - BigInteger receiveAmount = publicFromAmount.subtract(shieldReceiveAmount); - - ShieldedAddressInfo receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull).get(); - String receiverShieldAddress = receiverShieldAddressInfo.getAddress(); - String memo = "Burn to one shield and one public test " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + shieldReceiveAmount, memo, blockingStubFull); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - secondSenderNote, inputShieldAddressList, shieldOutList, receiverAddressString, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), receiveAmount); - - secondSenderNote = scanShieldedTrc20NoteByOvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - logger.info(secondSenderNote.toString()); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getNote().getValue(), - shieldReceiveAmount.longValue()); - - Assert.assertEquals(ByteArray.toHexString(secondSenderNote.getNoteTxs(1) - .getTxid().toByteArray()), txid); - Assert.assertEquals(secondSenderNote.getNoteTxs(1).getToAmount(), receiveAmount.toString()); - - String toAddress = ByteArray.toHexString(secondSenderNote.getNoteTxs(1) - .getTransparentToAddress().toByteArray()); - String receiverHexString = ByteArray.toHexString(PublicMethed.getFinalAddress(receiverKey)); - Assert.assertEquals(toAddress, receiverHexString); - - GrpcAPI.DecryptNotesTRC20 receiverSenderNote - = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo, - blockingStubFull); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0) - .getIsSpent(), false); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0) - .getNote().getValue(), shieldReceiveAmount.longValue()); - Assert.assertEquals(ByteArray.toHexString(receiverSenderNote - .getNoteTxs(0).getTxid().toByteArray()), txid); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token005.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token005.java deleted file mode 100644 index dcd9feeb8ee..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token005.java +++ /dev/null @@ -1,276 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token005 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional senderShieldAddressInfo; - Optional secondSenderShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - List inputNoteList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 senderNote; - GrpcAPI.DecryptNotesTRC20 secondSenderNote; - GrpcAPI.DecryptNotesTRC20 receiverSenderNote; - long senderPosition; - - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] receiverAddressbyte = ecKey1.getAddress(); - String receiverKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String receiverAddressString = PublicMethed.getAddressString(receiverKey); - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - senderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for burn withoutask test " + System.currentTimeMillis(); - String sendShieldAddress = senderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Create second mint parameters - memo = "Create a note for burn to one public and one shield withoutask test " - + System.currentTimeMillis(); - secondSenderShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - String sesendShieldAddress = secondSenderShieldAddressInfo.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sesendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity); - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), false); - logger.info("" + senderNote); - senderPosition = senderNote.getNoteTxs(0).getPosition(); - Assert.assertEquals(senderNote.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type burn and without ask") - public void test01ShieldTrc20TransactionWithTypeBurnWithoutAsk() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - inputShieldAddressList.add(senderShieldAddressInfo.get()); - BigInteger receiveAmount = publicFromAmount; - //Create burn parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20ParametersWithoutAsk(BigInteger.valueOf(0), - senderNote, inputShieldAddressList, null, receiverAddressString, receiverAddressbyte, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - senderNote = scanShieldedTrc20NoteByIvk(senderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(senderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), - receiveAmount); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transaction with type burn to one " - + "T and one Z address and without ask") - public void test02ShieldTrc20TransactionWithTypeBurnWithoutAsk() throws Exception { - //Scan sender note - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - //Query account before mint balance - final Long beforeBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long beforeBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - inputShieldAddressList.clear(); - inputShieldAddressList.add(secondSenderShieldAddressInfo.get()); - BigInteger shieldReceiveAmount = BigInteger.valueOf(0); - BigInteger receiveAmount = publicFromAmount.subtract(shieldReceiveAmount); - - ShieldedAddressInfo receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull).get(); - String receiverShieldAddress = receiverShieldAddressInfo.getAddress(); - String memo = "Burn to one shield and one public test " + System.currentTimeMillis(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, receiverShieldAddress, - "" + shieldReceiveAmount, memo, blockingStubFull); - - //Create burn parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20ParametersWithoutAsk(BigInteger.valueOf(0), - secondSenderNote, inputShieldAddressList, shieldOutList, receiverAddressString, - receiverAddressbyte, - receiveAmount.longValue(), blockingStubFull, blockingStubSolidity); - - String data = shieldedTrc20Parameters.getTriggerContractInput(); - String txid = PublicMethed.triggerContract(shieldAddressByte, - burn, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 180000); - - logger.info("scanShieldedTrc20NoteByIvk + senderNote:" + senderNote); - secondSenderNote = scanShieldedTrc20NoteByIvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getIsSpent(), true); - - final Long afterBurnAccountBalance = getBalanceOfShieldTrc20(receiverAddressString, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - //Query contract before mint balance - final Long afterBurnShieldAccountBalance = getBalanceOfShieldTrc20(shieldAddress, - zenTrc20TokenOwnerAddress, zenTrc20TokenOwnerKey, blockingStubFull); - - logger.info("afterBurnAccountBalance :" + afterBurnAccountBalance); - logger.info("beforeBurnAccountBalance :" + beforeBurnAccountBalance); - logger.info("beforeBurnShieldAccountBalance:" + beforeBurnShieldAccountBalance); - logger.info("afterBurnShieldAccountBalance :" + afterBurnShieldAccountBalance); - Assert.assertEquals(BigInteger.valueOf(afterBurnAccountBalance - beforeBurnAccountBalance), - receiveAmount); - Assert.assertEquals(BigInteger.valueOf(beforeBurnShieldAccountBalance - - afterBurnShieldAccountBalance), - receiveAmount); - - receiverSenderNote = scanShieldedTrc20NoteByIvk(receiverShieldAddressInfo, - blockingStubFull); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0).getIsSpent(), false); - Assert.assertEquals(receiverSenderNote.getNoteTxs(0).getNote() - .getValue(), shieldReceiveAmount.longValue()); - Assert.assertEquals(ByteArray.toHexString(receiverSenderNote.getNoteTxs(0) - .getTxid().toByteArray()), txid); - - secondSenderNote = scanShieldedTrc20NoteByOvk(secondSenderShieldAddressInfo.get(), - blockingStubFull); - logger.info(secondSenderNote.toString()); - Assert.assertEquals(secondSenderNote.getNoteTxs(0).getNote().getValue(), - shieldReceiveAmount.longValue()); - - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java b/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java deleted file mode 100644 index 079e46de22d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/dailybuild/zentrc20token/ShieldTrc20Token006.java +++ /dev/null @@ -1,525 +0,0 @@ -package stest.tron.wallet.dailybuild.zentrc20token; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Token006 extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliInPbft = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(2); - Optional shieldAddressInfo1; - Optional shieldAddressInfo2; - String shieldAddress1; - String shieldAddress2; - private BigInteger publicFromAmount; - private BigInteger shield1ReceiveAmountFor1to2; - private BigInteger shield2ReceiveAmountFor1to2; - private BigInteger shield1ReceiveAmountFor2to2; - private BigInteger shield2ReceiveAmountFor2to2; - private BigInteger shield1ReceiveAmountFor2to1; - List shieldOutList = new ArrayList<>(); - List inputShieldAddressList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 shield1Note; - GrpcAPI.DecryptNotesTRC20 shield2Note; - long senderPosition; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() throws Exception { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelPbft = ManagedChannelBuilder.forTarget(soliInPbft) - .usePlaintext(true) - .build(); - blockingStubPbft = WalletSolidityGrpc.newBlockingStub(channelPbft); - - publicFromAmount = getRandomAmount(); - - //Generate new shiled account for sender and receiver - shieldAddressInfo1 = getNewShieldedAddress(blockingStubFull); - shieldAddressInfo2 = getNewShieldedAddress(blockingStubFull); - String memo = "Create a note for transfer test " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - - //Scan sender note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - Assert.assertEquals(shield1Note.getNoteTxs(0).getIsSpent(), false); - logger.info("" + shield1Note); - senderPosition = shield1Note.getNoteTxs(0).getPosition(); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getValue(), - publicFromAmount.longValue()); - - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transfer with type 1 to 2") - public void test01ShieldTrc20TransferWith1To2() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - //Prepare parameters - final String transferMemo1 = "1 to 2 for shieldAddressInfo1 " + System.currentTimeMillis(); - final String transferMemo2 = "1 to 2 for shieldAddressInfo2 " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldAddress2 = shieldAddressInfo2.get().getAddress(); - shield1ReceiveAmountFor1to2 = BigInteger.valueOf(30); - shield2ReceiveAmountFor1to2 = publicFromAmount.subtract(shield1ReceiveAmountFor1to2); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + shield1ReceiveAmountFor1to2, transferMemo1, blockingStubFull); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress2, - "" + shield2ReceiveAmountFor1to2, transferMemo2, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(shieldAddressInfo1.get()); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - shield1Note, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - //Create transfer transaction - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan 1 to 2 ivk note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("" + shield1Note); - logger.info("" + shield2Note); - Assert.assertEquals(shield1Note.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getValue(), - shield1ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield2Note.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getValue(), - shield2ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(0).getIsSpent(), true); - - //Scan 1 to 2 ovk note - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + shield1Note:" + shield1Note); - Assert.assertEquals(shield1Note.getNoteTxsCount(), 2); - - Assert.assertEquals(shield1Note.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getValue(), - shield1ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(0).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getValue(), - shield2ReceiveAmountFor1to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(1).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transfer with type 2 to 2") - public void test02ShieldTrc20TransferWith2To2() throws Exception { - //Create a new note for 2 to 2 - String memo = "Create a new note for transfer test " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + publicFromAmount, memo, blockingStubFull); - //Create mint parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - - final GrpcAPI.DecryptNotesTRC20 inputNoteFor2to2 = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(shield1Note.getNoteTxs(1)) - .addNoteTxs(shield1Note.getNoteTxs(2)).build(); - - //Prepare parameters - final String transferMemo1 = "2 to 2 for shieldAddressInfo1 " + System.currentTimeMillis(); - final String transferMemo2 = "2 to 2 for shieldAddressInfo2 " + System.currentTimeMillis(); - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shieldAddress2 = shieldAddressInfo2.get().getAddress(); - shield1ReceiveAmountFor2to2 = BigInteger.valueOf(5); - shield2ReceiveAmountFor2to2 = publicFromAmount.add(shield1ReceiveAmountFor1to2) - .subtract(shield1ReceiveAmountFor2to2); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + shield1ReceiveAmountFor2to2, transferMemo1, blockingStubFull); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress2, - "" + shield2ReceiveAmountFor2to2, transferMemo2, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(shieldAddressInfo1.get()); - inputShieldAddressList.add(shieldAddressInfo1.get()); - - //Create transfer parameters - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - //Create transfer transaction - data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan 2 to 2 ivk note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("" + shield1Note); - logger.info("" + shield2Note); - Assert.assertEquals(shield1Note.getNoteTxs(3).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getValue(), - shield1ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield2Note.getNoteTxs(1).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield2Note.getNoteTxs(1).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield2Note.getNoteTxs(1).getNote().getValue(), - shield2ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield2Note.getNoteTxs(1).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(1).getIsSpent(), true); - Assert.assertEquals(shield1Note.getNoteTxs(2).getIsSpent(), true); - - //Scan 2 to 2 ovk note - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + shield1Note:" + shield1Note); - Assert.assertEquals(shield1Note.getNoteTxsCount(), 4); - - Assert.assertEquals(shield1Note.getNoteTxs(2).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(2).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(2).getNote().getValue(), - shield1ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(2).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield1Note.getNoteTxs(3).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo2)); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getValue(), - shield2ReceiveAmountFor2to2.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(3).getNote().getPaymentAddress(), - shieldAddressInfo2.get().getAddress()); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Shield TRC20 transfer with type 2 to 1") - public void test03ShieldTrc20TransferWith2To1() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - - //Prepare parameters - final String transferMemo1 = "2 to 1 for shieldAddressInfo1 " + System.currentTimeMillis(); - - shieldAddress1 = shieldAddressInfo1.get().getAddress(); - shield1ReceiveAmountFor2to1 = BigInteger.valueOf(shield2Note.getNoteTxs(0) - .getNote().getValue() + shield2Note.getNoteTxs(1).getNote().getValue()); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, shieldAddress1, - "" + shield1ReceiveAmountFor2to1, transferMemo1, blockingStubFull); - inputShieldAddressList.clear(); - inputShieldAddressList.add(shieldAddressInfo2.get()); - inputShieldAddressList.add(shieldAddressInfo2.get()); - - //Create transfer parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - shield2Note, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - //Create transfer transaction - String data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - String txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getReceipt().getResultValue() == 1); - Assert.assertTrue(infoById.get().getReceipt().getEnergyUsageTotal() > 300000); - - //Scan 2 to 1 ivk note - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("" + shield1Note); - logger.info("" + shield2Note); - Assert.assertEquals(shield1Note.getNoteTxs(4).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield1Note.getNoteTxs(4).getNote().getMemo(), - ByteString.copyFromUtf8(transferMemo1)); - Assert.assertEquals(shield1Note.getNoteTxs(4).getNote().getValue(), - shield1ReceiveAmountFor2to1.longValue()); - Assert.assertEquals(shield1Note.getNoteTxs(4).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - Assert.assertEquals(shield2Note.getNoteTxs(0).getIsSpent(), true); - Assert.assertEquals(shield2Note.getNoteTxs(1).getIsSpent(), true); - - //Scan 2 to 1 ovk note - shield2Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull); - logger.info("scanShieldedTrc20NoteByOvk + shield1Note:" + shield2Note); - Assert.assertEquals(shield2Note.getNoteTxsCount(), 1); - - Assert.assertEquals(shield2Note.getNoteTxs(0).getTxid(), infoById.get().getId()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getValue(), - shield1ReceiveAmountFor2to1.longValue()); - Assert.assertEquals(shield2Note.getNoteTxs(0).getNote().getPaymentAddress(), - shieldAddressInfo1.get().getAddress()); - - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Scan shield trc20 note by ivk and ovk on solidity") - public void test04ScanShieldTrc20NoteByIvkAndOvkOnSolidity() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield1NoteOnSolidity - = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield1Note, shield1NoteOnSolidity); - - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield2NoteOnSolidity - = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield2Note, shield2NoteOnSolidity); - - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - shield1NoteOnSolidity - = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield1Note, shield1NoteOnSolidity); - - shield2Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull); - shield2NoteOnSolidity - = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubSolidity); - Assert.assertEquals(shield2Note, shield2NoteOnSolidity); - } - - /** - * constructor. - */ - @Test(enabled = true, description = "Scan shield trc20 note by ivk and ovk on pbft") - public void test04ScanShieldTrc20NoteByIvkAndOvkOnPbft() throws Exception { - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield1NoteOnPbft - = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield1Note, shield1NoteOnPbft); - - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - GrpcAPI.DecryptNotesTRC20 shield2NoteOnPbft - = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield2Note, shield2NoteOnPbft); - - shield1Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull); - shield1NoteOnPbft - = scanShieldedTrc20NoteByOvk(shieldAddressInfo1.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield1Note, shield1NoteOnPbft); - - shield2Note = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull); - shield2NoteOnPbft - = scanShieldedTrc20NoteByOvk(shieldAddressInfo2.get(), - blockingStubFull, blockingStubPbft); - Assert.assertEquals(shield2Note, shield2NoteOnPbft); - } - - - /** - * constructor. - */ - @Test(enabled = true, description = "Query is shield trc20 note spend on solidity and pbft") - public void test05IsShieldTrc20NoteSpendOnSolidityAndPbft() throws Exception { - shield1Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo1.get(), - blockingStubFull); - shield2Note = scanShieldedTrc20NoteByIvk(shieldAddressInfo2.get(), - blockingStubFull); - - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull), true); - - Assert.assertEquals(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull), - getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull, blockingStubSolidity)); - - Assert.assertTrue(getTrc20SpendResult(shieldAddressInfo1.get(), - shield1Note.getNoteTxs(0), blockingStubFull, blockingStubPbft)); - - boolean spend = getTrc20SpendResult(shieldAddressInfo1.get(),shield1Note.getNoteTxs(1), - blockingStubFull); - - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo1.get(), shield1Note.getNoteTxs(1), - blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo1.get(), shield1Note.getNoteTxs(1), - blockingStubFull, blockingStubPbft)); - - spend = getTrc20SpendResult(shieldAddressInfo2.get(),shield2Note.getNoteTxs(0), - blockingStubFull); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(0), - blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(0), - blockingStubFull, blockingStubPbft)); - - spend = getTrc20SpendResult(shieldAddressInfo2.get(),shield2Note.getNoteTxs(1), - blockingStubFull); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(1), - blockingStubFull, blockingStubSolidity)); - Assert.assertEquals(spend, - getTrc20SpendResult(shieldAddressInfo2.get(), shield2Note.getNoteTxs(1), - blockingStubFull, blockingStubPbft)); - - } - - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/AttackSendcoin.java b/framework/src/test/java/stest/tron/wallet/fulltest/AttackSendcoin.java deleted file mode 100644 index b0343368d1b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/AttackSendcoin.java +++ /dev/null @@ -1,439 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import com.google.protobuf.InvalidProtocolBufferException; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Random; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class AttackSendcoin { - - private static final long now = System.currentTimeMillis(); - private static long start; - private static long end; - private static long beforeFromBalance; - private static long beforeNormal1Balance; - private static long beforeNormal2Balance; - private static long beforeNormal3Balance; - private static long beforeNormal4Balance; - private static long beforeAttackBalance; - private static long afterFromBalance; - private static long afterNormal1Balance; - private static long afterNormal2Balance; - private static long afterNormal3Balance; - private static long afterNormal4Balance; - private static long afterAttackBalance; - //testng001、testng002、testng003、testng004 - //Devaccount - private final String testKey001 = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - //Zion - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - //Sun - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - //Normal1 - private final String normalKey001 = - "36c0710378a34634e6baba0d3a79d7439a81183030147e7f4a0dd43bfed1a32f"; - //Normal2 - private final String normalKey002 = - "a6bfbcf98bbe07770bf79bc6b2970bae0992771c1dcbf24cc063a3f033f17fbf"; - //Normal3 - private final String normalKey003 = - "8273f6b26202526cbffb77569b830c1ba8a920040e77f6f26062a67315580ed7"; - //Normal4 - private final String normalKey004 = - "271c824fcb55f04a9f86f768424a80edeb26ab79cf12aa56643b595f689c008a"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] attackAddress = PublicMethed.getFinalAddress(testKey001); - private final byte[] normal1Address = PublicMethed.getFinalAddress(normalKey001); - private final byte[] normal2Address = PublicMethed.getFinalAddress(normalKey002); - private final byte[] normal3Address = PublicMethed.getFinalAddress(normalKey003); - private final byte[] normal4Address = PublicMethed.getFinalAddress(normalKey004); - private final Long sendNromal1Amount = 1L; - private final Long sendNromal2Amount = 2L; - private final Long sendNromal3Amount = 3L; - private final Long sendNromal4Amount = 4L; - private final Long attackAmount = 5L; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - return true; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - final Account fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - final Account attackInfo = PublicMethed.queryAccount(testKey001, blockingStubFull); - final Account normal1Info = PublicMethed.queryAccount(normalKey001, blockingStubFull); - final Account normal2Info = PublicMethed.queryAccount(normalKey002, blockingStubFull); - final Account normal3Info = PublicMethed.queryAccount(normalKey003, blockingStubFull); - final Account normal4Info = PublicMethed.queryAccount(normalKey004, blockingStubFull); - beforeFromBalance = fromInfo.getBalance(); - beforeNormal1Balance = normal1Info.getBalance(); - beforeNormal2Balance = normal2Info.getBalance(); - beforeNormal3Balance = normal3Info.getBalance(); - beforeNormal4Balance = normal4Info.getBalance(); - beforeAttackBalance = attackInfo.getBalance(); - start = System.currentTimeMillis(); - } - - //@Test(enabled = true) - @Test(enabled = false, threadPoolSize = 200, invocationCount = 200) - public void freezeAndSendcoin() throws InterruptedException { - - Integer i = 0; - Random rand = new Random(); - Integer randNum = 0; - Integer n = 0; - - while (i < 20) { - randNum = i % 4; - i++; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - if (randNum == 3) { - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - /* PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(attackAddress, attackAmount, fromAddress, testKey002, - blockingStubFull);*/ - } - - if (randNum == 0) { - PublicMethed.sendcoin(normal1Address, sendNromal1Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - if (randNum == 1) { - PublicMethed.sendcoin(normal2Address, sendNromal2Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - if (randNum == 2) { - PublicMethed.sendcoin(normal3Address, sendNromal3Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - if (randNum == 3) { - PublicMethed.sendcoin(normal4Address, sendNromal4Amount, fromAddress, - testKey002, blockingStubFull); - continue; - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - //Print the duration. - end = System.currentTimeMillis(); - logger.info("The time is " + Long.toString(end - start)); - - //Print 6 account balance information. - final Account fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - final Account attackInfo = PublicMethed.queryAccount(testKey001, blockingStubFull); - final Account normal1Info = PublicMethed.queryAccount(normalKey001, blockingStubFull); - final Account normal2Info = PublicMethed.queryAccount(normalKey002, blockingStubFull); - final Account normal3Info = PublicMethed.queryAccount(normalKey003, blockingStubFull); - final Account normal4Info = PublicMethed.queryAccount(normalKey004, blockingStubFull); - - afterFromBalance = fromInfo.getBalance(); - afterNormal1Balance = normal1Info.getBalance(); - afterNormal2Balance = normal2Info.getBalance(); - afterNormal3Balance = normal3Info.getBalance(); - afterNormal4Balance = normal4Info.getBalance(); - afterAttackBalance = attackInfo.getBalance(); - - logger.info("attack transaction success num is " - + (afterAttackBalance - beforeAttackBalance) / attackAmount); - logger.info("Normal 1 transaction success num is " - + (afterNormal1Balance - beforeNormal1Balance) / sendNromal1Amount); - logger.info("Normal 2 transaction success num is " - + (afterNormal2Balance - beforeNormal2Balance) / sendNromal2Amount); - logger.info("Normal 3 transaction success num is " - + (afterNormal3Balance - beforeNormal3Balance) / sendNromal3Amount); - logger.info("Normal 4 transaction success num is " - + (afterNormal4Balance - beforeNormal4Balance) / sendNromal4Amount); - - Long totalSuccessNum = (afterAttackBalance - beforeAttackBalance) / attackAmount - + (afterNormal1Balance - beforeNormal1Balance) / sendNromal1Amount - + (afterNormal3Balance - beforeNormal3Balance) / sendNromal3Amount - + (afterNormal4Balance - beforeNormal4Balance) / sendNromal4Amount - + (afterNormal2Balance - beforeNormal2Balance) / sendNromal2Amount; - logger.info("Total success transaction is " + Long.toString(totalSuccessNum)); - - Long normaltotalSuccessNum = (afterNormal1Balance - beforeNormal1Balance) / sendNromal1Amount - + (afterNormal3Balance - beforeNormal3Balance) / sendNromal3Amount - + (afterNormal4Balance - beforeNormal4Balance) / sendNromal4Amount - + (afterNormal2Balance - beforeNormal2Balance) / sendNromal2Amount; - logger.info("Total normal success transaction is " + Long.toString(normaltotalSuccessNum)); - - Integer blockTimes = 0; - Integer blockTransNum = 0; - - while (blockTimes < 5) { - blockTimes++; - //Print the current block transaction num. - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - logger.info("The block num " + Long.toString(currentNum) - + "total transaction is " + Long.toString(currentBlock.getTransactionsCount())); - //logger.info(Integer.toString(currentBlock.getTransactionsList() - // .get(0).getRawData().getContract(0).getTypeValue())); - - Integer normal1Num = 0; - Integer normal2Num = 0; - Integer normal3Num = 0; - Integer normal4Num = 0; - Integer attackNum = 0; - Long temp = 0L; - for (Integer m = 0; m < currentBlock.getTransactionsCount(); m++) { - try { - temp = currentBlock.getTransactions(m).getRawData().getContract(0).getParameter() - .unpack(TransferContract.class).getAmount(); - } catch (InvalidProtocolBufferException e) { - e.printStackTrace(); - } - if (temp == sendNromal1Amount) { - normal1Num++; - } - if (temp == sendNromal2Amount) { - normal2Num++; - } - if (temp == sendNromal3Amount) { - normal3Num++; - } - if (temp == sendNromal4Amount) { - normal4Num++; - } - if (temp == attackAmount) { - attackNum++; - } - } - logger.info("Block num " + Long.toString(currentNum) + ", Attack num is " - + Integer.toString(attackNum)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 1 num is " - + Integer.toString(normal1Num)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 2 num is " - + Integer.toString(normal2Num)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 3 num is " - + Integer.toString(normal3Num)); - logger.info("Block num " + Long.toString(currentNum) + ", normal 4 num is " - + Integer.toString(normal4Num)); - blockTransNum = blockTransNum + currentBlock.getTransactionsCount(); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - logger.info("Total block record num is " + Integer.toString(blockTransNum)); - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - BalanceContract.WithdrawBalanceContract.Builder builder = - BalanceContract.WithdrawBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - BalanceContract.WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/ContinueVote.java b/framework/src/test/java/stest/tron/wallet/fulltest/ContinueVote.java deleted file mode 100644 index 5d60cee81f3..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/ContinueVote.java +++ /dev/null @@ -1,410 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class ContinueVote { - - //testng001、testng002、testng003、testng004 - - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7");*/ - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info("Pre fix byte ===== " + WalletClient.getAddressPreFixByte()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test(enabled = false, threadPoolSize = 30, invocationCount = 30) - public void testVoteWitness() { - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account request = Account.newBuilder().setAddress(addressBs).build(); - AccountNetMessage accountNetMessage = blockingStubFull.getAccountNet(request); - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - Base58.encode58Check(fromAddress); - logger.info(Base58.encode58Check(fromAddress)); - String voteStr = "TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"; - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Account fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - - Boolean ret = false; - Integer i = 0; - while (fromInfo.getBalance() > 100000000) { - randNum = rand.nextInt(30) + 1; - voteStr = "TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"; - smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, Integer.toString(randNum)); - if (fromInfo.getFrozen(0).getFrozenBalance() < 10000000) { - PublicMethed.freezeBalance(fromAddress, 10000000000L, 3, testKey002, blockingStubFull); - } - ret = voteWitness(smallVoteMap, fromAddress, testKey002); - if (ret) { - logger.info("This vote num is " + Integer.toString(randNum)); - logger.info("Now the fromaddress vote is " + Long.toString(fromInfo - .getVotes(0).getVoteCount())); - logger.info(Integer.toString(i++)); - } - fromInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - accountNetMessage = blockingStubFull.getAccountNet(request); - logger.info("Now the from net used is " + Long.toString(accountNetMessage.getNetUsed())); - - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - //Assert.assertTrue(afterVote.getVotes(j).getVoteCount() == Long - // .parseLong(witness.get(key))); - } - - } - } - return true; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - Integer wait = 0; - while (searchCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 30) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Another fullnode didn't syn the first fullnode data"); - searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - //logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "afterfrozenbalance =" + Long.toString(afterFrozenBalance) + "beforefrozenbalance = " - + beforeFrozenBalance + "freezebalance = " + Long.toString(freezeBalance)); - //logger.info("afterbandwidth = " + Long.toString(afterBandwidth) + " beforebandwidth = - // " + Long.toString(beforeBandwidth)); - //if ((afterFrozenBalance - beforeFrozenBalance != freezeBalance) || - // (freezeBalance * frozen_duration -(afterBandwidth - beforeBandwidth) !=0)){ - // logger.info("After 20 second, two node still not synchronous"); - // } - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(freezeBalance * frozen_duration - (afterBandwidth - - // beforeBandwidth) <= 1000000); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/Creatasset.java b/framework/src/test/java/stest/tron/wallet/fulltest/Creatasset.java deleted file mode 100644 index b9a2b68ea9f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/Creatasset.java +++ /dev/null @@ -1,189 +0,0 @@ -package stest.tron.wallet.fulltest; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class Creatasset { - - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqa" - + "zxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvq" - + "azxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcxswedcv"; - private static final String tooLongUrl = - "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqasw1qazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqaz" - + "xswedcvqazxswedcvqazxswedcwedcv"; - private static final long now = System.currentTimeMillis(); - private static final long sendAmount = 1025000000L; - private static final long netCostMeasure = 200L; - private static String name = "c_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - long totalSupply = now; - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "f"; - String url = "h"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - logger.info(testKeyForAssetIssue016); - logger.info(transferAssetCreateKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 20, invocationCount = 20) - public void createAssetissue() throws InterruptedException { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Account fromAccountInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - //Assert.assertTrue(PublicMethed.freezeBalance(fromAddress,100000000, 3, testKey002, - // blockingStubFull)); - - Integer i = 0; - //GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - // .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - //logger.info(Integer.toString(assetIssueList.getAssetIssueCount())); - Boolean ret = false; - Boolean transRet = false; - Boolean updateRet = false; - Boolean participateRet = false; - Random rand = new Random(); - Integer randNum; - - while (fromAccountInfo.getBalance() > 1025000000) { - randNum = rand.nextInt(4); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed - .sendcoin(asset016Address, sendAmount, fromAddress, testKey002, blockingStubFull); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - name = "c_" + Long.toString(System.currentTimeMillis()); - totalSupply = now; - - ret = PublicMethed - .createAssetIssue(asset016Address, name, totalSupply, 1, 1, start, end, 1, description, - url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, 1L, testKeyForAssetIssue016, - blockingStubFull); - - if (ret) { - updateRet = PublicMethed - .updateAsset(asset016Address, tooLongDescription.getBytes(), tooLongUrl.getBytes(), - 4000L, 4000L, - testKeyForAssetIssue016, blockingStubFull); - if (updateRet) { - logger.info("update succesfully"); - } - logger.info(Integer.toString(i++)); - //assetIssueList = blockingStubFull - // .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - //logger.info("assetissue num is " + Integer.toString(assetIssueList.getAssetIssueCount())); - try { - randNum = rand.nextInt(10000) + 3000; - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - } - transRet = PublicMethed.transferAsset(toAddress, name.getBytes(), - 1L, asset016Address, testKeyForAssetIssue016, blockingStubFull); - participateRet = PublicMethed - .participateAssetIssue(asset016Address, name.getBytes(), 1L, toAddress, testKey003, - blockingStubFull); - if (participateRet) { - logger.info("participate success"); - } - logger.info(testKeyForAssetIssue016); - if (transRet) { - logger.info("transfer success"); - } - - } - ecKey1 = new ECKey(Utils.getRandom()); - asset016Address = ecKey1.getAddress(); - testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - fromAccountInfo = PublicMethed.queryAccount(testKey002, blockingStubFull); - ret = false; - updateRet = false; - participateRet = false; - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - try { - //randNum = rand.nextInt(10000) + 3000; - Thread.sleep(6000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - /* if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - }*/ - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/CreateAddressAndKey.java b/framework/src/test/java/stest/tron/wallet/fulltest/CreateAddressAndKey.java deleted file mode 100644 index 87b662dc8ce..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/CreateAddressAndKey.java +++ /dev/null @@ -1,234 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.HashMap; -import lombok.extern.slf4j.Slf4j; -import org.bouncycastle.util.encoders.Base64; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CreateAddressAndKey { - - private static String path = "/Users/wangzihe/Documents/"; - private static String filename = "/Users/wangzihe/Sites/postmanUsedKeyandAddress"; - private static String filenameTemp; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - /** - * constructor. - */ - public static boolean createFile(String fileName, String filecontent) { - Boolean bool = false; - filenameTemp = fileName;//文件路径+名称+文件类型 - File file = new File(filenameTemp); - try { - //如果文件不存在,则创建新的文件 - if (!file.exists()) { - file.createNewFile(); - bool = true; - System.out.println("success create file,the file is " + filenameTemp); - //创建文件成功后,写入内容到文件里 - writeFileContent(filenameTemp, filecontent); - } else { - clearInfoForFile(filenameTemp); - writeFileContent(filenameTemp, filecontent); - - } - } catch (Exception e) { - e.printStackTrace(); - - } - - return bool; - } - - /** - * constructor. - */ - public static void clearInfoForFile(String fileName) { - File file = new File(fileName); - try { - if (!file.exists()) { - file.createNewFile(); - } - FileWriter fileWriter = new FileWriter(file); - fileWriter.write(""); - fileWriter.flush(); - fileWriter.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * constructor. - */ - public static boolean writeFileContent(String filepath, String newstr) throws IOException { - Boolean bool = false; - String filein = newstr + "\r\n"; - String temp = ""; - - FileInputStream fis = null; - InputStreamReader isr = null; - BufferedReader br = null; - FileOutputStream fos = null; - PrintWriter pw = null; - try { - File file = new File(filepath); - fis = new FileInputStream(file); - isr = new InputStreamReader(fis); - br = new BufferedReader(isr); - StringBuffer buffer = new StringBuffer(); - - for (int i = 0; (temp = br.readLine()) != null; i++) { - buffer.append(temp); - buffer = buffer.append(System.getProperty("line.separator")); - } - buffer.append(filein); - - fos = new FileOutputStream(file); - pw = new PrintWriter(fos); - pw.write(buffer.toString().toCharArray()); - pw.flush(); - bool = true; - } catch (Exception e) { - // TODO: handle exception - e.printStackTrace(); - } finally { - if (pw != null) { - pw.close(); - } - if (fos != null) { - fos.close(); - } - if (br != null) { - br.close(); - } - if (isr != null) { - isr.close(); - } - if (fis != null) { - fis.close(); - } - } - return bool; - } - - /** - * constructor. - */ - - public static boolean delFile(String fileName) { - Boolean bool = false; - filenameTemp = path + fileName + ".txt"; - File file = new File(filenameTemp); - try { - if (file.exists()) { - file.delete(); - bool = true; - } - } catch (Exception e) { - // TODO: handle exception - } - return bool; - } - - - - /** - * constructor. - */ - @BeforeClass(enabled = false) - public void beforeClass() { - - } - - @Test(enabled = false) - public void createAddressesAndKeys() { - Integer i = 0; - String accountIndex; - String keyIndex; - JsonObject jsonobject = new JsonObject(); - JsonArray jsonarray = new JsonArray(); - HashMap addressAndKey = new HashMap(); - while (i++ < 600) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] address = ecKey1.getAddress(); - String addressString = ByteArray.toHexString(address); - byte[] key = ecKey1.getPrivKeyBytes(); - final String keyString = ByteArray.toHexString(key); - - logger.info(ByteArray.toStr(Base64.encode(key))); - logger.info(ByteArray.toStr(Base64.encode(address))); - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", addressString); - userBaseObj2.addProperty("key", keyString); - //userBaseObj2.addProperty("address",ByteArray.toStr(Base64.encode(address))); - //userBaseObj2.addProperty("key", ByteArray.toStr(Base64.encode(key))); - jsonarray.add(userBaseObj2); - } - Gson gson = new Gson(); - String jsonMap = gson.toJson(addressAndKey); - //createFile(filename,jsonobject.toString()); - createFile(filename, jsonarray.toString()); - - } - - @Test(enabled = true) - public void create() { - Integer i = 0; - String accountIndex; - String keyIndex; - JsonObject jsonobject = new JsonObject(); - JsonArray jsonarray = new JsonArray(); - HashMap addressAndKey = new HashMap(); - while (i++ < 600) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] address = ecKey1.getAddress(); - String key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ArrayList accountList = new ArrayList(); - accountList = PublicMethed.getAddressInfo(key); - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("address", accountList.get(1)); - userBaseObj2.addProperty("key", accountList.get(0)); - jsonarray.add(userBaseObj2); - } - Gson gson = new Gson(); - String jsonMap = gson.toJson(addressAndKey); - //createFile(filename,jsonobject.toString()); - createFile(filename, jsonarray.toString()); - - } - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - } -} - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/FreezeAndSendcoin.java b/framework/src/test/java/stest/tron/wallet/fulltest/FreezeAndSendcoin.java deleted file mode 100644 index c9c43d1e02c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/FreezeAndSendcoin.java +++ /dev/null @@ -1,321 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class FreezeAndSendcoin { - - private static final long now = System.currentTimeMillis(); - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final Long sendAmount = 10000000L; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] freezeAddress = ecKey1.getAddress(); - String testKeyForFreeze = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] transferAssetAddress = ecKey2.getAddress(); - String transferAssetCreateKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - - while (afterBlockNum < beforeBlockNum) { - Protocol.Block currentBlock1 = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - } - return true; - } - - - - //@Test(enabled = false) - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - /* Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4); - try { - randNum = rand.nextInt(20000); - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - - logger.info(testKeyForFreeze); - logger.info(transferAssetCreateKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = false, threadPoolSize = 500, invocationCount = 1000) - public void freezeAndSendcoin() throws InterruptedException { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] freezeAddress = ecKey1.getAddress(); - String testKeyForFreeze = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - Account toAccountInfo = PublicMethed.queryAccount(testKey003, blockingStubFull); - Account freezeAccountInfo = PublicMethed.queryAccount(testKeyForFreeze, blockingStubFull); - - Integer i = 0; - Boolean ret = false; - Boolean sendRet = false; - Boolean updateRet = false; - Boolean participateRet = false; - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - - while (toAccountInfo.getBalance() > 10000009L) { - randNum = rand.nextInt(3); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - freezeBalance(freezeAddress, 3000000L, 3L, testKeyForFreeze, blockingStubFull); - PublicMethed - .sendcoin(freezeAddress, sendAmount, toAddress, testKey003, blockingStubFull); - - ret = freezeBalance(freezeAddress, 1000000L, 3L, testKeyForFreeze, blockingStubFull); - freezeBalance(freezeAddress, 1000000L, 3L, testKeyForFreeze, blockingStubFull); - freezeBalance(freezeAddress, 1000000L, 3L, testKeyForFreeze, blockingStubFull); - - if (ret) { - logger.info("New account freeze success " + Integer.toString(i)); - sendRet = PublicMethed.sendcoin(toAddress, 6000000L, freezeAddress, - testKeyForFreeze, blockingStubFull); - if (sendRet) { - logger.info("This account transfer coin back. " + Integer.toString(i)); - freezeAccountInfo = PublicMethed.queryAccount(testKeyForFreeze, blockingStubFull); - logger.info("This account now has balance is " + Long - .toString(freezeAccountInfo.getBalance())); - - } - - } - - unFreezeBalance(freezeAddress, testKeyForFreeze); - withdrawBalance(freezeAddress, testKeyForFreeze); - - ecKey1 = new ECKey(Utils.getRandom()); - freezeAddress = ecKey1.getAddress(); - testKeyForFreeze = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - toAccountInfo = PublicMethed.queryAccount(testKey003, blockingStubFull); - logger.info("Now the toaddress balance is " + Long.toString(toAccountInfo.getBalance())); - NumberMessage beforeGetTotalTransaction = blockingStubFull - .totalTransaction(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info("Now total transaction is " + Long.toString(beforeGetTotalTransaction.getNum())); - ret = false; - sendRet = false; - i++; - - /* if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - try { - //randNum = rand.nextInt(10000) + 3000; - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - }*/ - - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - // Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - BalanceContract.WithdrawBalanceContract.Builder builder = - BalanceContract.WithdrawBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddress); - BalanceContract.WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/Fuzzytest.java b/framework/src/test/java/stest/tron/wallet/fulltest/Fuzzytest.java deleted file mode 100644 index 0a4ed47dbb1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/Fuzzytest.java +++ /dev/null @@ -1,223 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.db.Manager; -import org.tron.protos.Protocol; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class Fuzzytest { - - private static final long sendAmount = 10000000000L; - private static final long netCostMeasure = 200L; - private static long start; - private static long end; - private static long now = System.currentTimeMillis(); - private static String name = "AssetIssue016_" + Long.toString(now); - private static long totalSupply = now; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "for case assetissue016"; - String url = "https://stest.assetissue016.url/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset017Address = ecKey1.getAddress(); - String testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Manager dbManager; - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - /** - * constructor. - */ - - public static Boolean createAssetIssue(byte[] address, String name, Long totalSupply, - Integer trxNum, Integer icoNum, Long startTime, Long endTime, Integer voteScore, - String description, String url, Long freeAssetNetLimit, Long publicFreeAssetNetLimit, - Long fronzenAmount, Long frozenDay, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(freeAssetNetLimit); - builder.setPublicFreeAssetNetLimit(publicFreeAssetNetLimit); - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("failed reason is " + ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 10000000, 3, testKey002, - blockingStubFull)); - while (assetIssueList.getAssetIssueCount() <= 1) { - //Sendcoin to this account - Assert.assertTrue(PublicMethed - .sendcoin(asset017Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - now = System.currentTimeMillis(); - name = "AssetIssue017_" + Long.toString(now); - totalSupply = now; - Assert.assertTrue(createAssetIssue(asset017Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, 1L, - 1L, testKeyForAssetIssue017, blockingStubFull)); - - assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - - ecKey1 = new ECKey(Utils.getRandom()); - asset017Address = ecKey1.getAddress(); - testKeyForAssetIssue017 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - } - } - - @Test(enabled = false, threadPoolSize = 5, invocationCount = 5) - public void tooManyChannelFull() { - Integer i = 0; - while (i++ < 20000) { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - GrpcAPI.NodeList nodeList = blockingStubFull - .listNodes(GrpcAPI.EmptyMessage.newBuilder().build()); - if (i % 100 == 0) { - logger.info(Integer.toString(i)); - } - - } - - - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - /* if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - }*/ - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/ParticipateAssetIssue.java b/framework/src/test/java/stest/tron/wallet/fulltest/ParticipateAssetIssue.java deleted file mode 100644 index e42128f5cae..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/ParticipateAssetIssue.java +++ /dev/null @@ -1,341 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class ParticipateAssetIssue { - - private static final long now = System.currentTimeMillis(); - private static final long sendAmount = 10250000000L; - private static String name = "PartAssetIssue_" + Long.toString(now); - private static long beforeCreateAssetIssueBalance; - private static long afterCreateAssetIssueBalance; - private static long afterParticipateAssetIssueBalance; - private static long start1; - private static long end1; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - long totalSupply = now; - Long freeAssetNetLimit = 300000000L; - Long publicFreeAssetNetLimit = 300000000L; - String description = "f"; - String url = "h"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] createAddress = ecKey1.getAddress(); - String testKeyForCreate = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAssetAddress = ecKey2.getAddress(); - String testKeyForParticipate = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.ParticipateAssetIssueContract.Builder builder = - AssetIssueContractOuterClass.ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.TransferAssetContract.Builder builder = - AssetIssueContractOuterClass.TransferAssetContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - AssetIssueContractOuterClass.TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - //logger.info("transaction == null"); - } else { - //logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - logger.info(testKeyForCreate); - logger.info(testKeyForParticipate); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - //Send coin to 2 account. - Assert.assertTrue(PublicMethed.sendcoin(createAddress, sendAmount, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(participateAssetAddress, sendAmount, - fromAddress, testKey002, blockingStubFull)); - //Participate account freeze balance to get bandwidth. - Assert.assertTrue(PublicMethed.freezeBalance(participateAssetAddress, - 10000000L, 3, testKeyForParticipate, blockingStubFull)); - //Create an asset issue. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(createAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 10L, 10L, testKeyForCreate, blockingStubFull)); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - final Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - final Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, - blockingStubFull); - - Map assetIssueMap = new HashMap(); - - Long temp = 0L; - assetIssueMap = createInfo.getAssetMap(); - for (String key : assetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : assetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - beforeCreateAssetIssueBalance = temp; - start1 = System.currentTimeMillis(); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 250, invocationCount = 250) - public void testParticipateAssetIssue() throws InterruptedException { - Integer i = 0; - Integer randNum; - - while (i < 20) { - randNum = i % 4; - i++; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - participateAssetIssue(createAddress, name.getBytes(), - 1, participateAssetAddress, testKeyForParticipate, blockingStubFull); - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - //Print the duration. - end1 = System.currentTimeMillis(); - logger.info("The time is " + Long.toString(end1 - start1)); - - Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - - Map createAssetIssueMap = new HashMap(); - - Long temp = 0L; - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - Map participateAssetIssueMap = new HashMap(); - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + " at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + " at the end"); - logger.info("Create account reduce balance " + Long.toString(beforeCreateAssetIssueBalance - - afterCreateAssetIssueBalance)); - logger.info("Participate account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - Integer blockTimes = 0; - Integer blockTransParticipateNum = 0; - - while (blockTimes < 5) { - blockTimes++; - //Print the current block transaction num. - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - logger.info("The block num " + Long.toString(currentNum) - + " total transaction is " + Long.toString(currentBlock.getTransactionsCount())); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - createAssetIssueMap = new HashMap(); - participateAssetIssueMap = new HashMap(); - - temp = 0L; - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + "at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + "at the end"); - logger.info("Participate account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java b/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java deleted file mode 100644 index 34b753c0229..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/SuperWitnessAllowance.java +++ /dev/null @@ -1,398 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class SuperWitnessAllowance { - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7");*/ - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final Long costForCreateWitness = 10009000000L; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String createWitnessUrl = "http://www.createwitnessurl.com/"; - String updateWitnessUrl = "http://www.updatewitnessurl.com/"; - String nullUrl = ""; - String spaceUrl = " ##################~!@#$%^&*()_+}{|:'/.,<>?|]=-"; - byte[] createUrl = createWitnessUrl.getBytes(); - byte[] updateUrl = updateWitnessUrl.getBytes(); - byte[] wrongUrl = nullUrl.getBytes(); - byte[] updateSpaceUrl = spaceUrl.getBytes(); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(lowBalTest); - logger.info(ByteArray.toHexString(PublicMethed.getFinalAddress(lowBalTest))); - logger.info(Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest))); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void testInvaildToApplyBecomeWitness() { - Assert.assertFalse(createWitness(INVAILD_ADDRESS, createUrl, testKey002)); - } - - //@Test(enabled = true,threadPoolSize = 10, invocationCount = 10) - @Test(enabled = false) - public void testCreate130Witness() { - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - while (witnessList.getWitnessesCount() < 130) { - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - logger.info(lowBalTest); - Assert.assertTrue(sendcoin(lowBalAddress, costForCreateWitness, fromAddress, testKey002)); - Assert.assertTrue(PublicMethed.freezeBalance(lowBalAddress, 1000000, - 3, lowBalTest, blockingStubFull)); - Assert.assertTrue(createWitness(lowBalAddress, createUrl, lowBalTest)); - String voteStr = Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest)); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(voteWitness(smallVoteMap, lowBalAddress, lowBalTest)); - witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - result = Optional.ofNullable(witnesslist); - witnessList = result.get(); - - } - - } - - //@Test(enabled = true,threadPoolSize = 10, invocationCount = 10) - @Test(enabled = false) - public void testQueryAllowance() { - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - Integer allowanceNum = 0; - for (Integer i = 0; i < witnessList.getWitnessesCount(); i++) { - /* witnessList.getWitnesses(i).getAddress(); - witnessList.getWitnesses(i).getAddress(); - witnessList.getWitnesses(i).getAddress(); - witnessList.getWitnesses(i).getAddress();*/ - ByteString addressBs = witnessList.getWitnesses(i).getAddress(); - Account request = Account.newBuilder().setAddress(addressBs).build(); - request = blockingStubFull.getAccount(request); - if (request.getAllowance() > 0) { - allowanceNum++; - } - logger.info("Account " + Integer.toString(i) + " allowance is " + Long.toString(request - .getAllowance())); - - } - logger.info("Allowance num is " + Integer.toString(allowanceNum)); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - - } - - /** - * constructor. - */ - - public Boolean updateWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessUpdateContract.Builder builder = WitnessContract.WitnessUpdateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Account beforeVote = PublicMethed.queryAccount(priKey, blockingStubFull); - //Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - return true; - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/TransferAssetIssue.java b/framework/src/test/java/stest/tron/wallet/fulltest/TransferAssetIssue.java deleted file mode 100644 index a9b0a6fe02d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/TransferAssetIssue.java +++ /dev/null @@ -1,371 +0,0 @@ -package stest.tron.wallet.fulltest; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class TransferAssetIssue { - - private static final long now = System.currentTimeMillis(); - private static final long sendAmount = 10250000000L; - private static String name = "PartAssetIssue_" + Long.toString(now); - private static long beforeCreateAssetIssueBalance; - private static long afterCreateAssetIssueBalance; - private static long afterParticipateAssetIssueBalance; - private static long start1; - private static long end1; - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final String testKey003 = - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - long totalSupply = now; - Long freeAssetNetLimit = 300000000L; - Long publicFreeAssetNetLimit = 300000000L; - String description = "f"; - String url = "h"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] createAddress = ecKey1.getAddress(); - String testKeyForCreate = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] participateAssetAddress = ecKey2.getAddress(); - String testKeyForParticipate = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - /** - * constructor. - */ - - - public static boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, - byte[] from, String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.ParticipateAssetIssueContract.Builder builder = - AssetIssueContractOuterClass.ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public static Protocol.Transaction signTransaction(ECKey ecKey, - Protocol.Transaction transaction) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - if (ecKey == null || ecKey.getPrivKey() == null) { - //logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public static boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.TransferAssetContract.Builder builder = - AssetIssueContractOuterClass.TransferAssetContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - AssetIssueContractOuterClass.TransferAssetContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - if (transaction == null) { - //logger.info("transaction == null"); - } else { - //logger.info("transaction.getRawData().getContractCount() == 0"); - } - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - //logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Protocol.Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - logger.info(testKeyForCreate); - logger.info(testKeyForParticipate); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - //Send coin to 2 account. - Assert.assertTrue(PublicMethed.sendcoin(createAddress, sendAmount, - fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(participateAssetAddress, - sendAmount, fromAddress, testKey002, blockingStubFull)); - //Participate account freeze balance to get bandwidth. - Assert.assertTrue(PublicMethed.freezeBalance(participateAssetAddress, 10000000L, 3, - testKeyForParticipate, blockingStubFull)); - //Create an asset issue. - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(createAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 10L, 10L, testKeyForCreate, blockingStubFull)); - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - final Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - final Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, - blockingStubFull); - - Map assetIssueMap = new HashMap(); - - Long temp = 0L; - assetIssueMap = createInfo.getAssetMap(); - for (String key : assetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : assetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - beforeCreateAssetIssueBalance = temp; - start1 = System.currentTimeMillis(); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 200, invocationCount = 200) - public void transferAssetIssue() throws InterruptedException { - Integer i = 0; - Integer randNum; - - while (i < 20) { - randNum = i % 4; - i++; - fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(randNum); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - transferAsset(participateAssetAddress, name.getBytes(), 1, - createAddress, testKeyForCreate, blockingStubFull); - } - } - - /** - * constructor. - */ - - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - //Print the duration. - end1 = System.currentTimeMillis(); - logger.info("The time is " + Long.toString(end1 - start1)); - - Map createAssetIssueMap = new HashMap(); - - Long temp = 0L; - Account createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - Account participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - Map participateAssetIssueMap = new HashMap(); - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + " at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + " at the end"); - logger.info("Create account reduce balance " + Long.toString(beforeCreateAssetIssueBalance - - afterCreateAssetIssueBalance)); - logger.info("Transfer account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - Integer blockTimes = 0; - Integer blockTransParticipateNum = 0; - Integer useNet = 0; - Integer useFee = 0; - - while (blockTimes < 5) { - blockTimes++; - //Print the current block transaction num. - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentNum = currentBlock.getBlockHeader().getRawData().getNumber(); - for (Integer m = 0; m < currentBlock.getTransactionsCount(); m++) { - logger.info(currentBlock.getTransactions(m).getRetList().toString()); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), currentBlock.getTransactions(m) - .getRawData().toByteArray())); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - Optional getTransactionById = Optional.ofNullable(transaction); - if (getTransactionById.get().getRet(0).getFee() > 0) { - logger.info(Long.toString(getTransactionById.get().getRet(0).getFee())); - useFee++; - } else { - logger.info("No use fee"); - useNet++; - } - } - - logger.info("The block num " + Long.toString(currentNum) - + " total transaction is " + Long.toString(currentBlock.getTransactionsCount())); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - logger.info("Use Net num is " + Integer.toString(useNet)); - logger.info("Use Fee num is " + Integer.toString(useFee)); - - createInfo = PublicMethed.queryAccount(testKeyForCreate, blockingStubFull); - participateInfo = PublicMethed.queryAccount(testKeyForParticipate, blockingStubFull); - createAssetIssueMap = new HashMap(); - participateAssetIssueMap = new HashMap(); - - temp = 0L; - createAssetIssueMap = createInfo.getAssetMap(); - for (String key : createAssetIssueMap.keySet()) { - - logger.info("Name is " + key); - } - for (Long key : createAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterCreateAssetIssueBalance = temp; - - temp = 0L; - participateAssetIssueMap = participateInfo.getAssetMap(); - for (Long key : participateAssetIssueMap.values()) { - logger.info("Balance are " + Long.toString(key)); - temp = key; - } - afterParticipateAssetIssueBalance = temp; - - logger.info("Create account has balance " + Long.toString(beforeCreateAssetIssueBalance) - + "at the beginning"); - logger.info("Create account has balance " + Long.toString(afterCreateAssetIssueBalance) - + "at the end"); - logger.info("Participate account total success transaction is " - + Long.toString(afterParticipateAssetIssueBalance)); - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/TronDice.java b/framework/src/test/java/stest/tron/wallet/fulltest/TronDice.java deleted file mode 100644 index e2ad7c3cf61..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/TronDice.java +++ /dev/null @@ -1,138 +0,0 @@ -package stest.tron.wallet.fulltest; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TronDice { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - byte[] contractAddress; - Long maxFeeLimit = 1000000000L; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract008Address = ecKey1.getAddress(); - String contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ArrayList txidList = new ArrayList(); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contract008Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - PublicMethed.printAddress(testKey002); - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract008Address, - blockingStubFull); - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 30) - public void tronDice() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] tronDiceAddress = ecKey1.getAddress(); - String tronDiceKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed - .sendcoin(tronDiceAddress, 100000000000L, fromAddress, testKey002, blockingStubFull); - String contractName = "TronDice"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TronDice_tronDice"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TronDice_tronDice"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 1000000000L, 100, null, tronDiceKey, tronDiceAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Assert.assertTrue(smartContract.getAbi() != null); - - String txid; - - for (Integer i = 0; i < 100; i++) { - String initParmes = "\"" + "10" + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "rollDice(uint256)", initParmes, false, - 1000000, maxFeeLimit, tronDiceAddress, tronDiceKey, blockingStubFull); - logger.info(txid); - txidList.add(txid); - - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - try { - Thread.sleep(20000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Integer successTimes = 0; - Integer failedTimes = 0; - Integer totalTimes = 0; - for (String txid1 : txidList) { - totalTimes++; - infoById = PublicMethed.getTransactionInfoById(txid1, blockingStubFull); - if (infoById.get().getBlockNumber() > 3523732) { - logger.info("blocknum is " + infoById.get().getBlockNumber()); - successTimes++; - } else { - failedTimes++; - } - } - logger.info("Total times is " + totalTimes.toString()); - logger.info("success times is " + successTimes.toString()); - logger.info("failed times is " + failedTimes.toString()); - logger.info("success percent is " + successTimes / totalTimes); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/fulltest/TvmContract.java b/framework/src/test/java/stest/tron/wallet/fulltest/TvmContract.java deleted file mode 100644 index 295376ed8e8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/fulltest/TvmContract.java +++ /dev/null @@ -1,150 +0,0 @@ -package stest.tron.wallet.fulltest; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TvmContract { - - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contract008Address = ecKey1.getAddress(); - String contract008Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(contract008Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(contract008Address, 500000000L, fromAddress, - testKey002, blockingStubFull)); - logger.info(Long.toString(PublicMethed.queryAccount(contract008Key, blockingStubFull) - .getBalance())); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(contract008Address, 1000000L, - 3, 1, contract008Key, blockingStubFull)); - Assert.assertTrue(PublicMethed.buyStorage(50000000L, contract008Address, contract008Key, - blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(contract008Address, 5000000L, - 3, contract008Key, blockingStubFull)); - - } - - @Test(enabled = false) - public void deployErc721CryptoKitties() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contract008Address, - blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long storageLimit = accountResource.getStorageLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long storageUsage = accountResource.getStorageUsed(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before storage limit is " + Long.toString(storageLimit)); - logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 50000000L; - String contractName = "ERC721"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TvmContract_deployErc721CryptoKitties"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TvmContract_deployErc721CryptoKitties"); - Long m = 0L; - Long freeNet; - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - Long net = accountResource.getFreeNetUsed(); - Account account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - Long netUsed = account.getNetUsage(); - logger.info("before net used is " + Long.toString(netUsed)); - logger.info("before balance is " + account.getBalance()); - - for (Integer i = 0; i < 1; i++) { - byte[] contractAddress = PublicMethed.deployContract("1", abi, code, "", - 30000000L, 0L, 1, null, contract008Key, contract008Address, blockingStubFull); - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - freeNet = accountResource.getFreeNetUsed(); - energyUsage = accountResource.getEnergyUsed(); - logger.info( - "Time " + Integer.toString(i) + ": energy usage is " + Long.toString(energyUsage - m)); - logger.info("Time " + Integer.toString(i) + ": free net used is " + Long - .toString(freeNet - net)); - account = PublicMethed.queryAccount(contract008Key, blockingStubFull); - logger.info("after balance is " + account.getBalance()); - netUsed = account.getNetUsage(); - logger.info("after net used is " + Long.toString(netUsed)); - net = freeNet; - m = energyUsage; - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - //SmartContract smartContract = PublicMethed.getContract(contractAddress,blockingStubFull); - - //Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - //Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - //Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - //logger.info(smartContract.getName()); - //logger.info(smartContract.getAbi().toString()); - accountResource = PublicMethed.getAccountResource(contract008Address, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - storageLimit = accountResource.getStorageLimit(); - energyUsage = accountResource.getEnergyUsed(); - storageUsage = accountResource.getStorageUsed(); - //Assert.assertTrue(storageUsage > 0); - //Assert.assertTrue(storageLimit > 0); - //Assert.assertTrue(energyLimit > 0); - //Assert.assertTrue(energyUsage > 0); - - logger.info("after energy limit is " + Long.toString(energyLimit)); - logger.info("after energy usage is " + Long.toString(energyUsage)); - logger.info("after storage limit is " + Long.toString(storageLimit)); - logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign001.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign001.java deleted file mode 100644 index 139ca70fab5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign001.java +++ /dev/null @@ -1,342 +0,0 @@ -package stest.tron.wallet.mutisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign001 { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "MutiSign001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] participateAddress = ecKey4.getAddress(); - String participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSign1CreateAssetissue() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - txid = PublicMethedForMutiSign - .createAssetIssueForTransactionId(ownerAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, ownerKey, blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee + 1024_000000L); - - logger.info(" create asset end"); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign2TransferAssetissue() { - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(manager1Key); - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount(ownerAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign.transferAssetForTransactionId(manager1Address, - assetAccountId1.toByteArray(), 10, ownerAddress, ownerKey, blockingStubFull, - ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign3ParticipateAssetissue() { - ecKey4 = new ECKey(Utils.getRandom()); - participateAddress = ecKey4.getAddress(); - participateKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 2; - - Assert.assertTrue( - PublicMethed.sendcoin(participateAddress, needCoin + 2048000000L, fromAddress, testKey002, - blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Long balanceBefore = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - ownerKeyString[0] = participateKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(participateKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, participateAddress, - participateKey, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - txid = PublicMethedForMutiSign.participateAssetIssueForTransactionId(ownerAddress, - assetAccountId1.toByteArray(), 10, participateAddress, participateKey, 0, - blockingStubFull, ownerKeyString); - - Assert.assertNotNull(txid); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - balanceAfter = PublicMethed.queryAccount(participateAddress, blockingStubFull) - .getBalance(); - energyFee = infoById.get().getReceipt().getEnergyFee(); - netFee = infoById.get().getReceipt().getNetFee(); - fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee + 10); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - /** - * constructor. - */ - - @Test(enabled = true) - public void testMutiSign4updateAssetissue() { - url = "MutiSign001_update_url" + Long.toString(now); - ownerKeyString[0] = ownerKey; - description = "MutiSign001_update_description" + Long.toString(now); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - String txid = PublicMethedForMutiSign - .updateAssetForTransactionId(ownerAddress, description.getBytes(), url.getBytes(), 100L, - 100L, ownerKey, 2, blockingStubFull, permissionKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + multiSignFee); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign003.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign003.java deleted file mode 100644 index 7774d336613..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign003.java +++ /dev/null @@ -1,200 +0,0 @@ -package stest.tron.wallet.mutisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign003 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[3]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testMutiSignForAccount() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - long needCoin = updateAccountPermissionFee * 1 + multiSignFee * 9; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needCoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - ownerKeyString[2] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - String txid = PublicMethedForMutiSign - .accountPermissionUpdateForTransactionId(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - final String updateName = Long.toString(System.currentTimeMillis()); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertNotNull(txid); - - Optional infoById = PublicMethed - .getTransactionInfoById(txid, blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - long energyFee = infoById.get().getReceipt().getEnergyFee(); - long netFee = infoById.get().getReceipt().getNetFee(); - long fee = infoById.get().getFee(); - - logger.info("balanceAfter: " + balanceAfter); - logger.info("energyFee: " + energyFee); - logger.info("netFee: " + netFee); - logger.info("fee: " + fee); - - Assert.assertEquals(balanceBefore - balanceAfter, fee); - Assert.assertEquals(fee, energyFee + netFee + updateAccountPermissionFee); - - balanceBefore = balanceAfter; - - Assert.assertTrue(PublicMethedForMutiSign.createAccount( - ownerAddress, newAddress, ownerKey, blockingStubFull, ownerKeyString)); - - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, ownerAddress, 2, ownerKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - ownerAddress, 1000000L, 0, 0, ownerKey, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergy( - ownerAddress, 1000000L, 0, 2, ownerKey, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiver( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalance( - ownerAddress, ownerKey, 0, null, blockingStubFull, ownerKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - ownerAddress, ownerKey, 0, newAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccount( - ownerAddress, updateName.getBytes(), ownerKey, blockingStubFull, ownerKeyString)); - - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitness( - smallVoteMap, ownerAddress, ownerKey, blockingStubFull, ownerKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - Assert.assertEquals(balanceBefore - balanceAfter, multiSignFee * 9 + 1000000 + 100); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign004.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign004.java deleted file mode 100644 index cbec5d977cb..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign004.java +++ /dev/null @@ -1,198 +0,0 @@ -package stest.tron.wallet.mutisign; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class WalletTestMutiSign004 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForSmartContract() { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - long needcoin = updateAccountPermissionFee + multiSignFee * 3; - - Assert.assertTrue( - PublicMethed.sendcoin(ownerAddress, needcoin + 100000000L, fromAddress, testKey002, - blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 0, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 1000000000, 0, 1, ByteString.copyFrom(ownerAddress), - testKey002, blockingStubFull)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(ownerAddress, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = ownerKey; - ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - //String contractName = "StorageAndCpu" + Integer.toString(randNum); - String filePath = "./src/test/resources/soliditycode/walletTestMutiSign004.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, ownerKey, ownerAddress, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContract(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, ownerAddress, ownerKey, blockingStubFull, ownerKeyString); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - logger.info("Txid is " + txid); - logger.info("Trigger energytotal is " + infoById.get().getReceipt().getEnergyUsageTotal()); - - Assert.assertTrue(infoById.get().getBlockNumber() > 0); - PublicMethedForMutiSign.updateSettingWithPermissionId(contractAddress, 50, ownerKey, - ownerAddress, 0, blockingStubFull, ownerKeyString); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - long balanceAfter = PublicMethed.queryAccount(ownerAddress, blockingStubFull).getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertEquals(balanceBefore - balanceAfter, needcoin); - - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, ownerAddress, blockingStubFull)); - Assert.assertTrue( - PublicMethed.unFreezeBalance(fromAddress, testKey002, 1, ownerAddress, blockingStubFull)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign005.java b/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign005.java deleted file mode 100644 index 3271a36428c..00000000000 --- a/framework/src/test/java/stest/tron/wallet/mutisign/WalletTestMutiSign005.java +++ /dev/null @@ -1,167 +0,0 @@ -package stest.tron.wallet.mutisign; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - - -@Slf4j -public class WalletTestMutiSign005 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private long updateAccountPermissionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.updateAccountPermissionFee"); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testMutiSignForProposal() { - long needcoin = updateAccountPermissionFee + multiSignFee * 3; - Assert.assertTrue(PublicMethed.sendcoin(witness001Address, needcoin + 10000000L, - fromAddress, testKey002, blockingStubFull)); - - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceBefore = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceBefore: " + balanceBefore); - - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - ownerKeyString[0] = witnessKey001; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":2}]}," - + "\"witness_permission\":{\"type\":1,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(witnessKey001) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate( - accountPermissionJson, witness001Address, witnessKey001, - blockingStubFull, ownerKeyString); - - //Create a proposal - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(witness001Address, witnessKey001, - proposalMap, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - witness001Address, witnessKey001, proposalId, - true, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - witness001Address, witnessKey001, proposalId, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long balanceAfter = PublicMethed.queryAccount(witness001Address, blockingStubFull) - .getBalance(); - logger.info("balanceAfter: " + balanceAfter); - - Assert.assertTrue(balanceBefore - balanceAfter >= needcoin); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAccount2Test.java deleted file mode 100644 index fe735b21119..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAccount2Test.java +++ /dev/null @@ -1,120 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountNetMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class CreateAccount2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final long FREENETLIMIT = 5000L; - private static final long BASELINE = 4800L; - private static String name = "AssetIssue012_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - //owner account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] account007Address = ecKey1.getAddress(); - String account007Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - //Wait to be create account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey2.getAddress(); - String newAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(account007Key); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(account007Address, 10000000, - fromAddress, testKey002, blockingStubFull)); - } - - @Test(enabled = true) - public void testCreateAccount2() { - Account accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - final Long beforeBalance = accountInfo.getBalance(); - AccountNetMessage accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - final Long beforeFreeNet = accountNetInfo.getFreeNetUsed(); - GrpcAPI.Return ret1 = PublicMethed.createAccount2(account007Address, newAccountAddress, - account007Key, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - accountInfo = PublicMethed.queryAccount(account007Key, blockingStubFull); - Long afterBalance = accountInfo.getBalance(); - accountNetInfo = PublicMethed.getAccountNet(account007Address, - blockingStubFull); - Long afterFreeNet = accountNetInfo.getFreeNetUsed(); - logger.info(Long.toString(beforeBalance)); - logger.info(Long.toString(afterBalance)); - //When creator has no bandwidth, he can't use the free net. - Assert.assertTrue(afterFreeNet == beforeFreeNet); - //When the creator has no bandwidth, create a new account should spend 0.1TRX. - Assert.assertTrue(beforeBalance - afterBalance == 100000); - } - - @Test(enabled = true) - public void testExceptionCreateAccount2() { - //Try to create an exist account - GrpcAPI.Return ret1 = PublicMethed - .createAccount2(account007Address, account007Address, account007Key, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Account has existed"); - //Try to create an invalid account - byte[] wrongAddress = "wrongAddress".getBytes(); - ret1 = PublicMethed.createAccount2(account007Address, wrongAddress, account007Key, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid account address"); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAssetIssue2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAssetIssue2Test.java deleted file mode 100644 index a33ab4abe7b..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateAssetIssue2Test.java +++ /dev/null @@ -1,398 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class CreateAssetIssue2Test { - - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue001_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test-assetissue-001"; - String url = "https://github.com/tronprotocol/wallet-cli/assetissue001"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(ByteArray.toHexString(ecKey.getPrivKeyBytes())); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test() - public void testTransferAssetBandwitchDecreaseWithin10Second2() { - ByteString addressBS1 = ByteString.copyFrom(noBandwitchAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(noBandwitchAddress, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Long start = System.currentTimeMillis() + 2000000; - Long end = System.currentTimeMillis() + 1000000000; - GrpcAPI.Return ret1 = PublicMethed.createAssetIssue2(noBandwitchAddress, name, totalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, noBandwitch, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - } - - Assert.assertTrue( - transferAsset(toAddress, name.getBytes(), 100L, noBandwitchAddress, noBandwitch)); - //Transfer Asset failed when transfer to yourself - //Assert.assertFalse(transferAsset2(toAddress, name.getBytes(), 100L, toAddress, testKey003)); - Return ret1 = transferAsset2(toAddress, name.getBytes(), 100L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Cannot transfer asset to yourself."); - //Transfer Asset failed when the transfer amount is large than the asset balance you have. - ret1 = - transferAsset2(fromAddress, name.getBytes(), 9100000000000000000L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : assetBalance is not sufficient."); - //Transfer Asset failed when the transfer amount is 0 - ret1 = transferAsset2(fromAddress, name.getBytes(), 0L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Amount must greater than 0."); - //Transfer Asset failed when the transfer amount is -1 - ret1 = transferAsset2(fromAddress, name.getBytes(), -1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Amount must greater than 0."); - //Transfer failed when you want to transfer to an invalid address - ret1 = transferAsset2(INVAILD_ADDRESS, name.getBytes(), - 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "contract validate error : Invalid toAddress"); - //Transfer failed when the asset issue name is not correct. - ret1 = - transferAsset2(fromAddress, (name + "wrong").getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "contract validate error : No asset !"); - //Transfer success. - ret1 = transferAsset2(fromAddress, name.getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //No freeze asset, try to unfreeze asset failed. - Assert.assertFalse(unFreezeAsset(noBandwitchAddress, noBandwitch)); - logger.info("Test no asset frozen balance, try to unfreeze asset, no exception. Test OK!!!"); - - //Not create asset, try to unfreeze asset failed.No exception. - Assert.assertFalse(unFreezeAsset(toAddress, testKey003)); - logger.info("Test not create asset issue, try to unfreeze asset, no exception. Test OK!!!"); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public Return transferAsset2(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - TransferAssetContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.transferAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - //return true; - } - return ret; - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - UnfreezeAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateTransaction2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateTransaction2Test.java deleted file mode 100644 index bc3622f01ba..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateTransaction2Test.java +++ /dev/null @@ -1,352 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class CreateTransaction2Test { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7"); - private static final byte[] toAddress = Base58 - .decodeFromBase58Check("TV75jZpdmP2juMe1dRwGrwpV6AMU6mr1EU");*/ - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //receipt account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiptAccountAddress = ecKey2.getAddress(); - String receiptAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sendAccountAddress = ecKey1.getAddress(); - String sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - } - - @Test - public void testSendCoin2() { - Assert.assertTrue(PublicMethed.sendcoin(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull)); - - logger.info(receiptAccountKey); - Account sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountBeforeBalance = sendAccount.getBalance(); - Assert.assertTrue(sendAccountBeforeBalance == 90000000000L); - Account receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountBeforeBalance = receiptAccount.getBalance(); - Assert.assertTrue(receiptAccountBeforeBalance == 0); - //normal sendcoin2 - Return ret1 = PublicMethed.sendcoin2(receiptAccountAddress, 49880000000L, - sendAccountAddress, sendAccountKey, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountAfterBalance = sendAccount.getBalance(); - logger.info(Long.toString(sendAccountAfterBalance)); - Assert.assertTrue(sendAccountAfterBalance == 90000000000L - 49880000000L - 100000L); - - receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountAfterBalance = receiptAccount.getBalance(); - Assert.assertTrue(receiptAccountAfterBalance == 49880000000L); - //Send coin failed due to no enough balance. - ret1 = PublicMethed - .sendcoin2(receiptAccountAddress, 9199999999999999999L, sendAccountAddress, sendAccountKey, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Validate TransferContract error, balance is not sufficient."); - //Send coin failed due to the amount is 0. - ret1 = PublicMethed - .sendcoin2(receiptAccountAddress, 0L, sendAccountAddress, sendAccountKey, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must be greater than 0."); - //Send coin failed due to the amount is -1Trx. - ret1 = PublicMethed - .sendcoin2(receiptAccountAddress, -1000000L, sendAccountAddress, sendAccountKey, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must be greater than 0.."); - - //Send coin to yourself - ret1 = PublicMethed.sendcoin2(sendAccountAddress, 1000000L, sendAccountAddress, sendAccountKey, - blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Cannot transfer trx to yourself."); - //transfer all balance - ret1 = PublicMethed.sendcoin2(receiptAccountAddress, 40119900000L, - sendAccountAddress, sendAccountKey, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountAfterBalance1 = sendAccount.getBalance(); - logger.info(Long.toString(sendAccountAfterBalance1)); - Assert.assertTrue( - sendAccountAfterBalance1 == 90000000000L - 49880000000L - 100000 - 40119900000L); - - receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountAfterBalance1 = receiptAccount.getBalance(); - logger.info(Long.toString(receiptAccountAfterBalance1)); - Assert.assertTrue(receiptAccountAfterBalance1 == 49880000000L + 40119900000L); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - TransferContract.Builder builder = TransferContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateaAndUpdateWitness2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateaAndUpdateWitness2Test.java deleted file mode 100644 index 19bba10b51f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/CreateaAndUpdateWitness2Test.java +++ /dev/null @@ -1,433 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class CreateaAndUpdateWitness2Test { - - private static final byte[] INVAILD_ADDRESS = Base58 - .decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private static final Long costForCreateWitness = 9999000000L; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String createWitnessUrl = "http://www.createwitnessurl.com/"; - String updateWitnessUrl = "http://www.updatewitnessurl.com/"; - String nullUrl = ""; - String spaceUrl = " ##################~!@#$%^&*()_+}{|:'/.,<>?|]=-"; - byte[] createUrl = createWitnessUrl.getBytes(); - byte[] updateUrl = updateWitnessUrl.getBytes(); - byte[] wrongUrl = nullUrl.getBytes(); - byte[] updateSpaceUrl = spaceUrl.getBytes(); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(lowBalTest); - logger.info(ByteArray.toHexString(PublicMethed.getFinalAddress(lowBalTest))); - logger.info(Base58.encode58Check(PublicMethed.getFinalAddress(lowBalTest))); - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void testInvaildToApplyBecomeWitness2() { - GrpcAPI.Return ret1 = createWitness2(INVAILD_ADDRESS, createUrl, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid address"); - } - - @Test(enabled = true) - public void testCreateWitness2() { - //If you are already is witness, apply failed - createWitness(fromAddress, createUrl, testKey002); - GrpcAPI.Return ret1 = createWitness2(fromAddress, createUrl, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Witness[415624c12e308b03a1a6b21d9b86e3942fac1ab92b] " - + "has existed"); - //balance is not enouhg,try to create witness. - Assert.assertTrue(sendcoin(lowBalAddress, 1000000L, fromAddress, testKey002)); - ret1 = createWitness2(lowBalAddress, createUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : balance < AccountUpgradeCost"); - //Send enough coin to the apply account to make that account - // has ability to apply become witness. - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - Assert.assertTrue(sendcoin(lowBalAddress, costForCreateWitness, fromAddress, testKey002)); - ret1 = createWitness2(lowBalAddress, createUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } - } - - @Test(enabled = true) - public void testUpdateWitness2() { - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - //null url, update failed - GrpcAPI.Return ret1 = updateWitness2(lowBalAddress, wrongUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid url"); - //Content space and special char, update success - ret1 = updateWitness2(lowBalAddress, updateSpaceUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //update success - ret1 = updateWitness2(lowBalAddress, updateUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } else { - logger.info("Update witness case had been test.This time skip it."); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public GrpcAPI.Return createWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - - } - - /** - * constructor. - */ - - public Boolean updateWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessUpdateContract.Builder builder = WitnessContract.WitnessUpdateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return false; - } else { - return true; - } - - } - - /** - * constructor. - */ - - public GrpcAPI.Return updateWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessUpdateContract.Builder builder = WitnessContract.WitnessUpdateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUpdateUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessUpdateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.updateWitness2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - logger.info("response.getRestult() == false"); - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java deleted file mode 100644 index 1253cdc8e0d..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/FreezeBalance2Test.java +++ /dev/null @@ -1,478 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class FreezeBalance2Test { - - private final String noFrozenBalanceTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] noFrozenAddress = PublicMethed.getFinalAddress(noFrozenBalanceTestKey); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test(enabled = true) - public void testFreezeBalance2() { - //Freeze failed when freeze amount is large than currently balance. - Return ret1 = freezeBalance2(fromAddress, 9000000000000000000L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be less than accountBalance"); - //Freeze failed when freeze amount less than 1Trx - ret1 = freezeBalance2(fromAddress, 999999L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be more than 1TRX"); - //Freeze failed when freeze duration isn't 3 days. - ret1 = freezeBalance2(fromAddress, 1000000L, 2L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenDuration must be less than 3 days and more than 3 days"); - //Unfreeze balance failed when 3 days hasn't come. - ret1 = unFreezeBalance2(fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : It's not time to unfreeze."); - //Freeze failed when freeze amount is 0. - ret1 = freezeBalance2(fromAddress, 0L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be positive"); - //Freeze failed when freeze amount is -1. - ret1 = freezeBalance2(fromAddress, -1L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenBalance must be positive"); - //Freeze failed when freeze duration is -1. - ret1 = freezeBalance2(fromAddress, 1000000L, -1L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenDuration must be less than 3 days and more than 3 days"); - //Freeze failed when freeze duration is 0. - ret1 = freezeBalance2(fromAddress, 1000000L, 0L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : frozenDuration must be less than 3 days and more than 3 days"); - - try { - Thread.sleep(16000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Freeze balance success. - ret1 = PublicMethed.freezeBalance2(fromAddress, 1000000L, 3L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - } - - @Test(enabled = true) - public void testUnFreezeBalance2() { - //Unfreeze failed when there is no freeze balance. - Return ret1 = unFreezeBalance2(noFrozenAddress, noFrozenBalanceTestKey); - logger.info("Test unfreezebalance"); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : no frozenBalance(BANDWIDTH)"); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return response; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull.getNowBlock(EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return ret; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public Return unFreezeBalance2(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.unfreezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLatestNum2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLatestNum2Test.java deleted file mode 100644 index 3667882e0c9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLatestNum2Test.java +++ /dev/null @@ -1,178 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class GetBlockByLatestNum2Test { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLatestNum2() { - // - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(3).build(); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.isPresent()); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 3); - Assert.assertTrue(getBlockByLatestNum.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue( - getBlockByLatestNum.get().getBlock(1).getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse( - getBlockByLatestNum.get().getBlock(2).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - logger.info("TestGetBlockByLatestNum ok!!!"); - Assert.assertFalse(getBlockByLatestNum.get().getBlock(0).getBlockid().isEmpty()); - Assert.assertFalse(getBlockByLatestNum.get().getBlock(1).getBlockid().isEmpty()); - Assert.assertFalse(getBlockByLatestNum.get().getBlock(2).getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByExceptionNum2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now the block num is " + Long.toString(currentBlockNum) + " Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - NumberMessage numberMessage = NumberMessage.newBuilder().setNum(-1).build(); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - Optional getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLatestNum.get().getBlock(1).getBlockid().isEmpty()); - - numberMessage = NumberMessage.newBuilder().setNum(0).build(); - blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLatestNum.get().getBlock(1).getBlockid().isEmpty()); - - numberMessage = NumberMessage.newBuilder().setNum(100).build(); - blockList = blockingStubFull.getBlockByLatestNum2(numberMessage); - getBlockByLatestNum = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLatestNum.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLatestNum.get().getBlock(10).getBlockid().isEmpty()); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLimitNext2.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLimitNext2.java deleted file mode 100644 index 6ff1a358c89..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByLimitNext2.java +++ /dev/null @@ -1,204 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class GetBlockByLimitNext2 { - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true) - public void testGetBlockByLimitNext2() { - // - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(2); - builder.setEndNum(4); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.isPresent()); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 2); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getNumber() < 4); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(0).hasBlockHeader()); - Assert.assertTrue(getBlockByLimitNext.get().getBlock(1).hasBlockHeader()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(0).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - Assert.assertFalse( - getBlockByLimitNext.get().getBlock(1).getBlockHeader().getRawData().getParentHash() - .isEmpty()); - Assert.assertFalse(getBlockByLimitNext.get().getBlock(0).getBlockid().isEmpty()); - Assert.assertFalse(getBlockByLimitNext.get().getBlock(1).getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByExceptionLimitNext2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - while (currentBlockNum <= 5) { - logger.info("Now has very little block, Please wait"); - currentBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - } - - //From -1 to 1 - GrpcAPI.BlockLimit.Builder builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(-1); - builder.setEndNum(1); - GrpcAPI.BlockListExtention blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - Optional getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //check o block is empty - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(1).getBlockid().isEmpty()); - //From 3 to 3 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(3); - builder.setEndNum(3); - blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //check the third block is empty - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(3).getBlockid().isEmpty()); - //From 4 to 2 - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(4); - builder.setEndNum(2); - blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(4).getBlockid().isEmpty()); - builder = GrpcAPI.BlockLimit.newBuilder(); - builder.setStartNum(999999990); - builder.setEndNum(999999999); - blockList = blockingStubFull.getBlockByLimitNext2(builder.build()); - getBlockByLimitNext = Optional.ofNullable(blockList); - Assert.assertTrue(getBlockByLimitNext.get().getBlockCount() == 0); - //Assert.assertTrue(getBlockByLimitNext.get().getBlock(999999990).getBlockid().isEmpty()); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByNum2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByNum2Test.java deleted file mode 100644 index e71b2c041e1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetBlockByNum2Test.java +++ /dev/null @@ -1,265 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -@Slf4j -public class GetBlockByNum2Test { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testGetBlockByNum2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //The number is large than the currently number, there is no exception when query this number. - /* Long outOfCurrentBlockNum = currentBlockNum + 10000L; - NumberMessage.Builder builder1 = NumberMessage.newBuilder(); - builder1.setNum(outOfCurrentBlockNum); - Block outOfCurrentBlock = blockingStubFull.getBlockByNum(builder1.build()); - Assert.assertFalse(outOfCurrentBlock.hasBlockHeader());*/ - - //Query the first block - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - GrpcAPI.BlockExtention firstBlock = blockingStubFull.getBlockByNum2(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(firstBlock.getBlockid().isEmpty()); - - //Query the zero block - NumberMessage.Builder builder21 = NumberMessage.newBuilder(); - builder2.setNum(0); - GrpcAPI.BlockExtention zeroBlock = blockingStubFull.getBlockByNum2(builder21.build()); - Assert.assertTrue(zeroBlock.hasBlockHeader()); - Assert.assertTrue(zeroBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(zeroBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(zeroBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(zeroBlock.getBlockid().isEmpty()); - - //Query the -1 block - NumberMessage.Builder builder22 = NumberMessage.newBuilder(); - builder2.setNum(-1); - GrpcAPI.BlockExtention nagtiveBlock = blockingStubFull.getBlockByNum2(builder22.build()); - Assert.assertTrue(nagtiveBlock.hasBlockHeader()); - Assert.assertTrue(nagtiveBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(nagtiveBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(nagtiveBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(nagtiveBlock.getBlockid().isEmpty()); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - GrpcAPI.BlockExtention lastSecondBlock = blockingStubFull.getBlockByNum2(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - Assert.assertFalse(lastSecondBlock.getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockByNumFromSolidity2() { - GrpcAPI.BlockExtention currentBlock = blockingStubSolidity - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Long currentBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Assert.assertFalse(currentBlockNum < 0); - if (currentBlockNum == 1) { - logger.info("Now has very little block, Please test this case by manual"); - Assert.assertTrue(currentBlockNum == 1); - } - - //Query the first block. - NumberMessage.Builder builder2 = NumberMessage.newBuilder(); - builder2.setNum(1); - GrpcAPI.BlockExtention firstBlock = blockingStubSolidity.getBlockByNum2(builder2.build()); - Assert.assertTrue(firstBlock.hasBlockHeader()); - Assert.assertFalse(firstBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getNumber() == 1); - Assert.assertFalse(firstBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(firstBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("firstblock test from solidity succesfully"); - Assert.assertFalse(firstBlock.getBlockid().isEmpty()); - - //Query the second latest block. - NumberMessage.Builder builder3 = NumberMessage.newBuilder(); - builder3.setNum(currentBlockNum - 1); - GrpcAPI.BlockExtention lastSecondBlock = blockingStubSolidity.getBlockByNum2(builder3.build()); - Assert.assertTrue(lastSecondBlock.hasBlockHeader()); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue( - lastSecondBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlockNum); - Assert.assertFalse(lastSecondBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(lastSecondBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("Last second test from solidity succesfully"); - Assert.assertFalse(lastSecondBlock.getBlockid().isEmpty()); - } - - @Test(enabled = true) - public void testGetBlockById2() { - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - ByteString currentHash = currentBlock.getBlockHeader().getRawData().getParentHash(); - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(currentHash).build(); - Block setIdOfBlock = blockingStubFull.getBlockById(request); - Assert.assertTrue(setIdOfBlock.hasBlockHeader()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - logger.info(Long.toString(setIdOfBlock.getBlockHeader().getRawData().getNumber())); - logger.info(Long.toString(currentBlock.getBlockHeader().getRawData().getNumber())); - Assert.assertTrue( - setIdOfBlock.getBlockHeader().getRawData().getNumber() + 1 == currentBlock.getBlockHeader() - .getRawData().getNumber()); - Assert.assertFalse(setIdOfBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(setIdOfBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("By ID test succesfully"); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public GrpcAPI.BlockExtention getBlock2(long blockNum, - WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum2(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetNowBlock2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetNowBlock2Test.java deleted file mode 100644 index e1e66fc1ae2..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetNowBlock2Test.java +++ /dev/null @@ -1,177 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class GetNowBlock2Test { - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test - public void testCurrentBlock2() { - //Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - GrpcAPI.BlockExtention currentBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock is " + Long - .toString(currentBlock.getBlockHeader().getRawData().getNumber())); - Assert.assertFalse(currentBlock.getBlockid().isEmpty()); - - //Improve coverage. - currentBlock.equals(currentBlock); - //Block newBlock = blockingStubFull.getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - GrpcAPI.BlockExtention newBlock = blockingStubFull - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - newBlock.equals(currentBlock); - newBlock.hashCode(); - newBlock.getSerializedSize(); - newBlock.getTransactionsCount(); - newBlock.getTransactionsList(); - Assert.assertFalse(newBlock.getBlockid().isEmpty()); - } - - @Test - public void testCurrentBlockFromSolidity2() { - GrpcAPI.BlockExtention currentBlock = blockingStubSolidity - .getNowBlock2(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(currentBlock.hasBlockHeader()); - Assert.assertFalse(currentBlock.getBlockHeader().getWitnessSignature().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getTimestamp() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getWitnessAddress().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getNumber() > 0); - Assert.assertFalse(currentBlock.getBlockHeader().getRawData().getParentHash().isEmpty()); - Assert.assertTrue(currentBlock.getBlockHeader().getRawData().getWitnessId() >= 0); - logger.info("test getcurrentblock in soliditynode is " + Long - .toString(currentBlock.getBlockHeader().getRawData().getNumber())); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsFromThis2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsFromThis2Test.java deleted file mode 100644 index b3774396a1a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsFromThis2Test.java +++ /dev/null @@ -1,220 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class GetTransactionsFromThis2Test { - - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final String notexist01 = - "DCB620820121A866E4E25905DC37F5025BFA5420B781C69E1BC6E1D83038C88A"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = false) - public void testgetTransactionsFromThis2() { - //Create a transfer. - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(fromAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - Optional gettransactionsfromthis2 = Optional - .ofNullable(transactionListExtention); - - if (gettransactionsfromthis2.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, - testKey002, blockingStubFull)); - } - - Assert.assertTrue(gettransactionsfromthis2.isPresent()); - Integer beforecount = gettransactionsfromthis2.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse( - gettransactionsfromthis2.get().getTransaction(j).getTransaction().getRawData() - .getContractList().isEmpty()); - } - } - - @Test(enabled = false) - public void testgetTransactionsFromThisByInvaildAddress2() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - Optional gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionListExtention = blockingStubExtension - .getTransactionsFromThis2(accountPaginated.build()); - gettransactionsfromthisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - Assert.assertTrue(gettransactionsfromthisByInvaildAddress.get().getTransactionCount() == 0); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsToThis2.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsToThis2.java deleted file mode 100644 index 399ca531578..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/GetTransactionsToThis2.java +++ /dev/null @@ -1,234 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AccountPaginated; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class GetTransactionsToThis2 { - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = - Base58.decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7"); - private static final byte[] toAddress = - Base58.decodeFromBase58Check("TV75jZpdmP2juMe1dRwGrwpV6AMU6mr1EU");*/ - private static final byte[] INVAILD_ADDRESS = - Base58.decodeFromBase58Check("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48"); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final String notexist01 = - "DCB620820121A866E4E25905DC37F5025BFA5420B781C69E1BC6E1D83038C88A"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - - } - - @Test(enabled = true) - public void testgetTransactionsToThis2() { - //Create a transfer. - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000, fromAddress, - testKey002, blockingStubFull)); - - ByteString addressBs = ByteString.copyFrom(toAddress); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - - Optional gettransactionstothis2 = Optional - .ofNullable(transactionListExtention); - - if (gettransactionstothis2.get().getTransactionCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(toAddress, 1000000L, fromAddress, testKey002, - blockingStubFull)); - } - - Assert.assertTrue(gettransactionstothis2.isPresent()); - Integer beforecount = gettransactionstothis2.get().getTransactionCount(); - logger.info(Integer.toString(beforecount)); - for (Integer j = 0; j < beforecount; j++) { - Assert.assertFalse( - gettransactionstothis2.get().getTransaction(j).getTransaction().getRawData() - .getContractList().isEmpty()); - } - } - - @Test(enabled = true) - public void testgetTransactionsToThisByInvaildAddress2() { - //Invaild address. - ByteString addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - Account account = Account.newBuilder().setAddress(addressBs).build(); - AccountPaginated.Builder accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(0); - GrpcAPI.TransactionListExtention transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - Optional gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //Limit is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(1000); - accountPaginated.setLimit(-1); - transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - //offset is -1 - addressBs = ByteString.copyFrom(INVAILD_ADDRESS); - account = Account.newBuilder().setAddress(addressBs).build(); - accountPaginated = AccountPaginated.newBuilder().setAccount(account); - accountPaginated.setOffset(-1); - accountPaginated.setLimit(100); - transactionListExtention = blockingStubExtension - .getTransactionsToThis2(accountPaginated.build()); - gettransactionstothisByInvaildAddress = Optional - .ofNullable(transactionListExtention); - - Assert.assertTrue(gettransactionstothisByInvaildAddress.get().getTransactionCount() == 0); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/ParticipateAssetIssue2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/ParticipateAssetIssue2Test.java deleted file mode 100644 index dea87ebc8ef..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/ParticipateAssetIssue2Test.java +++ /dev/null @@ -1,358 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class ParticipateAssetIssue2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue002_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] participateAccountAddress = ecKey1.getAddress(); - String participateAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] assetIssueAccount002 = ecKey2.getAddress(); - String testKeyForAssetIssueAccount002 = ByteArray.toHexString(ecKey2 - .getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testParticipateAssetissue2() { - ByteString addressBS1 = ByteString.copyFrom(participateAccountAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - //send coin to the new account - Assert.assertTrue(PublicMethed.sendcoin(participateAccountAddress, 2048000000, fromAddress, - testKey002, blockingStubFull)); - //Create a new Asset Issue - Assert.assertTrue(PublicMethed.createAssetIssue(participateAccountAddress, - name, totalSupply, 1, 1, System.currentTimeMillis() + 2000, - System.currentTimeMillis() + 1000000000, 1, description, url, - 2000L, 2000L, 1L, 1L, - participateAccountKey, blockingStubFull)); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - - } - - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Participate AssetIssue success - logger.info(name); - //Freeze amount to get bandwitch. - Assert.assertTrue(PublicMethed.freezeBalance(toAddress, 10000000, 3, testKey003, - blockingStubFull)); - - //The amount is large than the total supply, participate failed. - Return ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - name.getBytes(), 9100000000000000000L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : No enough balance !"); - //The asset issue name is not correct, participate failed. - ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - (name + "wrong").getBytes(), 100L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - //The amount is 0, participate asset issue failed. - ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - name.getBytes(), 0L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0!"); - - //The amount is -1, participate asset issue failed. - ret1 = PublicMethed.participateAssetIssue2(participateAccountAddress, - name.getBytes(), -1L, toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0!"); - //The asset issue owner address is not correct, participate asset issue failed. - ret1 = PublicMethed.participateAssetIssue2(fromAddress, name.getBytes(), 100L, - toAddress, testKey003, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply.newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - //Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/TransferAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/TransferAsset2Test.java deleted file mode 100644 index 0e1b80e1557..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/TransferAsset2Test.java +++ /dev/null @@ -1,402 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class TransferAsset2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static String name = "testAssetIssue001_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String description = "just-test-assetissue-001"; - String url = "https://github.com/tronprotocol/wallet-cli/assetissue001"; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - logger.info(ByteArray.toHexString(ecKey.getPrivKeyBytes())); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test() - public void testTransferAssetBandwitchDecreaseWithin10Second2() { - ByteString addressBS1 = ByteString.copyFrom(noBandwitchAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Assert.assertTrue(PublicMethed.sendcoin(noBandwitchAddress, 2048000000, - fromAddress, testKey002, blockingStubFull)); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - - Return ret1 = PublicMethed.createAssetIssue2(noBandwitchAddress, name, totalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, noBandwitch, blockingStubFull); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - - } - - Return ret1 = transferAsset2(toAddress, name.getBytes(), 100L, noBandwitchAddress, noBandwitch); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Transfer Asset failed when transfer to yourself - ret1 = transferAsset2(toAddress, name.getBytes(), 100L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Cannot transfer asset to yourself."); - //Transfer Asset failed when the transfer amount is large than the asset balance you have. - ret1 = - transferAsset2(fromAddress, name.getBytes(), 9100000000000000000L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : assetBalance is not sufficient."); - //Transfer Asset failed when the transfer amount is 0 - ret1 = transferAsset2(fromAddress, name.getBytes(), 0L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0."); - //Transfer Asset failed when the transfer amount is -1 - ret1 = transferAsset2(fromAddress, name.getBytes(), -1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Amount must greater than 0."); - ret1 = - transferAsset2(fromAddress, (name + "wrong").getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : No asset !"); - //Transfer success. - ret1 = transferAsset2(fromAddress, name.getBytes(), 1L, toAddress, testKey003); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //No freeze asset, try to unfreeze asset failed. - Assert.assertFalse(unFreezeAsset(noBandwitchAddress, noBandwitch)); - logger.info("Test no asset frozen balance, try to unfreeze asset, no exception. Test OK!!!"); - //Not create asset, try to unfreeze asset failed.No exception. - Assert.assertFalse(unFreezeAsset(toAddress, testKey003)); - logger.info("Test not create asset issue, try to unfreeze asset, no exception. Test OK!!!"); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - builder.setFreeAssetNetLimit(20000); - builder.setPublicFreeAssetNetLimit(20000); - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null || transaction.getRawData().getContractCount() == 0"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public Return transferAsset2(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.transferAsset2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - } - return ret; - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UnfreezeAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UnfreezeAsset2Test.java deleted file mode 100644 index 2be9b42c6a1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UnfreezeAsset2Test.java +++ /dev/null @@ -1,632 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass.AssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.ParticipateAssetIssueContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.UnfreezeAssetContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class UnfreezeAsset2Test { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue003_" + Long.toString(now); - - /* //testng001、testng002、testng003、testng004 - private static final byte[] fromAddress = Base58 - .decodeFromBase58Check("THph9K2M2nLvkianrMGswRhz5hjSA9fuH7"); - private static final byte[] toAddress = Base58 - .decodeFromBase58Check("TV75jZpdmP2juMe1dRwGrwpV6AMU6mr1EU");*/ - private static final String shortname = "a"; - private static final String tooLongName = "qazxswedcvfrtgbnhyujmkiolpoiuytre"; - private static final String chineseAssetIssuename = "中文都名字"; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqa" - + "zxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvq" - + "azxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = - "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqasw1qazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqaz" - + "xswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final long totalSupply = now; - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - //get account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] lowBalAddress2 = ecKey2.getAddress(); - String lowBalTest2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true) - public void testGetAllAssetIssue2() { - Return ret1 = PublicMethed.sendcoin2(lowBalAddress, 2124500000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - ret1 = PublicMethed.sendcoin2(lowBalAddress2, 21240500000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - ByteString addressBS1 = ByteString.copyFrom(fromAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull.getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - - //if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 100000; - Long end = System.currentTimeMillis() + 1000000000; - //Freeze amount is large than total supply, create asset issue failed. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 9000000000000000000L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Frozen supply cannot exceed total supply"); - //Freeze day is 0, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 100L, 0L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "frozenDuration must be less than 3652 days and more than 1 days"); - //Freeze amount is 0, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 0L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Frozen supply must be greater than 0!"); - //Freeze day is -1, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 1000L, 1000L, - 1000L, -1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "frozenDuration must be less than 3652 days and more than 1 days"); - //Freeze amount is -1, create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - -1L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Frozen supply must be greater than 0!"); - //Freeze day is 3653(10 years + 1 day), create failed - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3653L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "frozenDuration must be less than 3652 days and more than 1 days"); - //Start time is late than end time. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - end, start, 2, description, url, 10000L, 10000L, - 1L, 2L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : End time should be greater than start time"); - //Start time is early than currently time. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start - 1000000L, end, 2, description, url, 10000L, - 10000L, 1L, 2L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Start time should be greater than HeadBlockTime"); - //totalSupply is zero. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, 0L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TotalSupply must greater than 0!"); - //Totalsupply is -1. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, -1L, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TotalSupply must greater than 0!"); - //TrxNum is zero. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 0, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TrxNum must greater than 0!"); - //TrxNum is -1. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, -1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : TrxNum must greater than 0!"); - //IcoNum is 0. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 0, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Num must greater than 0!"); - //IcoNum is -1. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, -1, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Num must greater than 0!"); - //The asset issue name is null. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, "", totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid assetName"); - //The asset issue name is large than 33 char. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, tooLongName, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid assetName"); - //The asset issue name is chinese name. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, chineseAssetIssuename, totalSupply, 1, - 10, start, end, 2, description, url, 10000L, - 10000L, 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid assetName"); - //The URL is null. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, "", 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - //The URL is too long. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, tooLongUrl, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - //The description is too long, create failed. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, tooLongDescription, url, 10000L, - 10000L, 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid description"); - - //FreezeBalance - Assert.assertTrue(PublicMethed.freezeBalance(lowBalAddress, 10000000L, 3, lowBalTest, - blockingStubFull)); - //Create success - start = System.currentTimeMillis() + 6000; - end = System.currentTimeMillis() + 1000000000; - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Test not in the duration time, participate failed. - ret1 = PublicMethed.participateAssetIssue2(lowBalAddress, name.getBytes(), 1L, - toAddress, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : No longer valid period!"); - //Test another address try to create the same name asset issue, create failed. - ret1 = PublicMethed.createAssetIssue2(lowBalAddress2, name, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, lowBalTest2, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "contract validate error : Token exists"); - - try { - Thread.sleep(4000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - GrpcAPI.AssetIssueList assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - logger.info(Integer.toString(assetIssueList.getAssetIssue(0).getFrozenSupplyCount())); - Assert.assertTrue(assetIssueList.getAssetIssue(0).getFrozenSupplyCount() == 1); - //Assert.assertTrue(assetIssueList.getAssetIssue(j).getFrozenSupplyCount() > 0); - Assert.assertTrue(assetIssueList.getAssetIssue(0).getFrozenSupply(0).getFrozenAmount() > 0); - Assert.assertTrue(assetIssueList.getAssetIssue(0).getFrozenSupply(0).getFrozenDays() > 0); - - //Test one account only can create one asset issue. - start = System.currentTimeMillis() + 3000; - end = System.currentTimeMillis() + 1000000000; - ret1 = PublicMethed.createAssetIssue2(lowBalAddress, shortname, totalSupply, 1, 10, - start, end, 2, description, url, 10000L, 10000L, - 1L, 3652L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : An account can only issue one asset"); - logger.info("FROM ADDRESS create asset issue in this case!!!"); - - assetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - Assert.assertTrue(assetIssueList.getAssetIssueCount() >= 1); - for (Integer j = 0; j < assetIssueList.getAssetIssueCount(); j++) { - Assert.assertFalse(assetIssueList.getAssetIssue(j).getOwnerAddress().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getName().isEmpty()); - Assert.assertFalse(assetIssueList.getAssetIssue(j).getUrl().isEmpty()); - Assert.assertTrue(assetIssueList.getAssetIssue(j).getTotalSupply() > 0); - logger.info("test get all assetissue"); - } - - //Improve coverage. - assetIssueList.equals(assetIssueList); - assetIssueList.equals(null); - GrpcAPI.AssetIssueList newAssetIssueList = blockingStubFull - .getAssetIssueList(GrpcAPI.EmptyMessage.newBuilder().build()); - assetIssueList.equals(newAssetIssueList); - assetIssueList.hashCode(); - assetIssueList.getSerializedSize(); - - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - try { - AssetIssueContract.Builder builder = AssetIssueContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setFreeAssetNetLimit(10000); - builder.setPublicFreeAssetNetLimit(10000); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - TransferAssetContract.Builder builder = TransferAssetContract.newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean unFreezeAsset2(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - UnfreezeAssetContract.Builder builder = UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeAssetContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.unfreezeAsset2(contract); - if (transactionExtention == null) { - return false; - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return false; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return false; - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - ParticipateAssetIssueContract.Builder builder = ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java deleted file mode 100644 index cae5235ebd0..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAccount2Test.java +++ /dev/null @@ -1,961 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.AccountComparator; - -@Slf4j -public class UpdateAccount2Test { - - private static final long now = System.currentTimeMillis(); - private static final String name = "testAssetIssue_" + Long.toString(now); - private static final long TotalSupply = now; - //testng001、testng002、testng003、testng004 - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String mostLongNamePlusOneChar = "1abcdeabcdefabcdefg1abcdefg10o0og1abcdefg10o0oabcd" - + "efabcdefg1abcdefg10o0og1abcdefg10o0oabcdefabcdefg1abcdefg10o0og1abcdefg10o0oab" - + "cdefabcdefg1abcdefg10o0og1abcdefg10o0ofabcdefg1abcdefg10o0og1abcdefg10o0o"; - String mostLongName = "abcdeabcdefabcdefg1abcdefg10o0og1abcdefg10o0oabcd" - + "efabcdefg1abcdefg10o0og1abcdefg10o0oabcdefabcdefg1abcdefg10o0og1abcdefg10o0oab" - + "cdefabcdefg1abcdefg10o0og1abcdefg10o0ofabcdefg1abcdefg10o0og1abcdefg10o0o"; - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - //System.out.println(); - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] noBandwitchAddress = ecKey1.getAddress(); - String noBandwitch = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - PublicMethed.printAddress(lowBalTest); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test - public void testCreateAccount2() { - Account noCreateAccount = queryAccount(lowBalTest, blockingStubFull); - if (noCreateAccount.getAccountName().isEmpty()) { - Assert.assertTrue(PublicMethed.freezeBalance(fromAddress, 10000000, 3, testKey002, - blockingStubFull)); - //Assert.assertTrue(sendCoin2(lowBalAddress, 1L, fromAddress, testKey002)); - GrpcAPI.Return ret1 = sendCoin2(lowBalAddress, 1000000L, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //Assert.assertTrue(Sendcoin(Low_Bal_ADDRESS, 1000000L, fromAddress, testKey002)); - noCreateAccount = queryAccount(lowBalTest, blockingStubFull); - logger.info(Long.toString(noCreateAccount.getBalance())); - //Assert.assertTrue(noCreateAccount.getBalance() == 1); - - //TestVoteToNonWitnessAccount - String voteStr = Base58.encode58Check(lowBalAddress); - - HashMap voteToNonWitnessAccount = new HashMap(); - voteToNonWitnessAccount.put(voteStr, "3"); - - HashMap voteToInvaildAddress = new HashMap(); - voteToInvaildAddress.put("27cu1ozb4mX3m2afY68FSAqn3HmMp815d48SS", "4"); - - //TQkJsN2Q2sZV9H2dQ5x2rSneKNyLQgegVv - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] lowBalAddress2 = ecKey2.getAddress(); - - ret1 = PublicMethed.sendcoin2(lowBalAddress2, 21245000000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - - WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - WitnessList witnessList = result.get(); - if (result.get().getWitnessesCount() < 6) { - String createUrl1 = "adfafds"; - byte[] createUrl = createUrl1.getBytes(); - String lowBalTest2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ret1 = createWitness2(lowBalAddress2, createUrl, lowBalTest2); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - String voteStr1 = Base58.encode58Check(lowBalAddress2); - HashMap voteToWitAddress = new HashMap(); - voteToWitAddress.put(voteStr1, "1"); - PublicMethed.printAddress(lowBalTest); - ret1 = voteWitness2(voteToWitAddress, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //logger.info("vote to non witness account ok!!!"); - } - - //normal freezeBalance - //Assert.assertTrue(freezeBalance2(fromAddress, 10000000L, 3L, testKey002)) - ret1 = freezeBalance2(fromAddress, 100000000L, 3L, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //vote To NonWitnessAccount - ret1 = voteWitness2(voteToNonWitnessAccount, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - //vote to InvaildAddress - ret1 = voteWitness2(voteToInvaildAddress, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : VoteNumber must more than 0"); - - } else { - logger.info( - "Please confirm wither the create account test is pass, or you will do it by manual"); - } - } - - @Test(enabled = true) - public void testUpdateAccount2() { - Account tryToUpdateAccount = queryAccount(lowBalTest, blockingStubFull); - if (tryToUpdateAccount.getAccountName().isEmpty()) { - GrpcAPI.Return ret1 = updateAccount2(lowBalAddress, mostLongNamePlusOneChar.getBytes(), - lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid accountName"); - - ret1 = updateAccount2(lowBalAddress, "".getBytes(), lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : This name is existed"); - - System.out.println("dingwei2:"); - ret1 = updateAccount2(lowBalAddress, mostLongName.getBytes(), lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : This name is existed"); - - ret1 = updateAccount2(lowBalAddress, "secondUpdateName".getBytes(), lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : This name is existed"); - - } - } - - @Test(enabled = true) - public void testNoBalanceCreateAssetIssue2() { - Account lowaccount = queryAccount(lowBalTest, blockingStubFull); - if (lowaccount.getBalance() > 0) { - Assert.assertTrue(sendCoin(toAddress, lowaccount.getBalance(), lowBalAddress, lowBalTest)); - } - - System.out.println("1111112222"); - GrpcAPI.Return ret1 = PublicMethed.createAssetIssue2(lowBalAddress, name, TotalSupply, 1, 1, - now + 100000000L, now + 10000000000L, 2, description, url, 10000L, - 10000L, 1L, 1L, lowBalTest, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : No enough balance for fee!"); - logger.info("nobalancecreateassetissue"); - } - - @Test(enabled = true) - public void testNoBalanceTransferTrx2() { - //Send Coin failed when there is no enough balance. - Assert.assertFalse(sendCoin(toAddress, 100000000000000000L, lowBalAddress, lowBalTest)); - } - - @Test(enabled = true) - public void testNoBalanceCreateWitness2() { - //Apply to be super witness failed when no enough balance. - //Assert.assertFalse(createWitness2(lowBalAddress, fromAddress, lowBalTest)); - System.out.println("1111222333:" + lowBalAddress); - GrpcAPI.Return ret1 = createWitness2(lowBalAddress, fromAddress, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : balance < AccountUpgradeCost"); - - } - - @Test(enabled = true) - public void testNoFreezeBalanceToUnfreezeBalance2() { - //Unfreeze account failed when no freeze balance - Account noFreezeAccount = queryAccount(lowBalTest, blockingStubFull); - if (noFreezeAccount.getFrozenCount() == 0) { - GrpcAPI.Return ret1 = unFreezeBalance2(lowBalAddress, lowBalTest); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : no frozenBalance(BANDWIDTH)"); - } else { - logger.info("This account has freeze balance, please test this case for manual"); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public GrpcAPI.Return createWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean sendCoin(byte[] to, long amount, byte[] owner, String priKey) { - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return response.getResult(); - } - - /** - * constructor. - */ - - public GrpcAPI.Return sendCoin2(byte[] to, long amount, byte[] owner, String priKey) { - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull - .createTransaction2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(TotalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - - Protocol.Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Protocol.Transaction signTransaction(ECKey ecKey, Protocol.Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean updateAccount(byte[] addressBytes, byte[] accountNameBytes, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddress = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddress); - - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("Please check!!! transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - - /** - * constructor. - */ - - public GrpcAPI.Return updateAccount2(byte[] addressBytes, byte[] accountNameBytes, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.updateAccount2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info("Please check!!! response.getresult==false"); - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } else { - logger.info(name); - return response; - } - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - BalanceContract.UnfreezeBalanceContract.Builder builder = - BalanceContract.UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - BalanceContract.UnfreezeBalanceContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public GrpcAPI.Return unFreezeBalance2(byte[] address, String priKey) { - //byte[] address = address; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - BalanceContract.UnfreezeBalanceContract.Builder builder = - BalanceContract.UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - BalanceContract.UnfreezeBalanceContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.unfreezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - return false; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(addRess)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Protocol.Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info("response.getresult() == false"); - return false; - } - return true; - } - - /** - * constructor. - */ - - public GrpcAPI.Return voteWitness2(HashMap witness, byte[] address, - String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(addRess)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull - .voteWitnessAccount2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info("response.getresult() == false"); - return response; - } - return ret; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - return response.getResult(); - - - } - - /** - * constructor. - */ - - public GrpcAPI.Return freezeBalance2(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.freezeBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return response; - } - return ret; - } - - class AccountComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long.compare(((Account) o2).getBalance(), ((Account) o1).getBalance()); - } - } - - -} - - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java deleted file mode 100644 index d394c879416..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/UpdateAsset2Test.java +++ /dev/null @@ -1,467 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.AssetIssueContractOuterClass; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class UpdateAsset2Test { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = now; - private static final long sendAmount = 10000000000L; - private static final String tooLongDescription = - "1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv" - + "qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswe" - + "dcvqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static final String tooLongUrl = "qaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqaswqas" - + "wqaswqasw1qazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazx" - + "swedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedcvqazxswedc" - + "vqazxswedcvqazxswedcvqazxswedcvqazxswedcv"; - private static String name = "testAssetIssue010_" + Long.toString(now); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = "just-test"; - String url = "https://github.com/tronprotocol/wallet-cli/"; - String updateDescription = "This is test for update asset issue, case AssetIssue_010"; - String updateUrl = "www.updateassetissue.010.cn"; - Long freeAssetNetLimit = 1000L; - Long publicFreeAssetNetLimit = 1000L; - Long updateFreeAssetNetLimit = 10001L; - Long updatePublicFreeAssetNetLimit = 10001L; - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] asset010Address = ecKey.getAddress(); - String testKeyForAssetIssue010 = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true) - public void testUpdateAssetIssue2() { - //Sendcoin to this account - ByteString addressBS1 = ByteString.copyFrom(asset010Address); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - //Assert.assertTrue(PublicMethed.freezeBalance(fromAddress,10000000L,3, - // testKey002,blockingStubFull)); - Assert.assertTrue(PublicMethed - .sendcoin(asset010Address, sendAmount, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed - .freezeBalance(asset010Address, 200000000L, 3, testKeyForAssetIssue010, - blockingStubFull)); - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - Assert.assertTrue(PublicMethed.createAssetIssue(asset010Address, name, totalSupply, 1, 1, - start, end, 1, description, url, freeAssetNetLimit, publicFreeAssetNetLimit, - 1L, 1L, testKeyForAssetIssue010, blockingStubFull)); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - name = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0).getName().toByteArray()); - Assert.assertTrue(PublicMethed - .updateAsset(asset010Address, description.getBytes(), url.getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull)); - } - - //Query the description and url,freeAssetNetLimit and publicFreeAssetNetLimit - ByteString assetNameBs = ByteString.copyFrom(name.getBytes()); - GrpcAPI.BytesMessage request = GrpcAPI.BytesMessage.newBuilder().setValue(assetNameBs).build(); - AssetIssueContractOuterClass.AssetIssueContract assetIssueByName = blockingStubFull - .getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(description)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(url)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == freeAssetNetLimit); - Assert.assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == publicFreeAssetNetLimit); - - //Test update asset issue - Return ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - updatePublicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //After update asset issue ,query the description and url, - // freeAssetNetLimit and publicFreeAssetNetLimit - assetNameBs = ByteString.copyFrom(name.getBytes()); - request = GrpcAPI.BytesMessage.newBuilder().setValue(assetNameBs).build(); - assetIssueByName = blockingStubFull.getAssetIssueByName(request); - - Assert.assertTrue( - ByteArray.toStr(assetIssueByName.getDescription().toByteArray()).equals(updateDescription)); - Assert.assertTrue(ByteArray.toStr(assetIssueByName.getUrl().toByteArray()).equals(updateUrl)); - Assert.assertTrue(assetIssueByName.getFreeAssetNetLimit() == updateFreeAssetNetLimit); - Assert - .assertTrue(assetIssueByName.getPublicFreeAssetNetLimit() == updatePublicFreeAssetNetLimit); - } - - @Test(enabled = true) - public void testUpdateAssetIssueExcption2() { - //Test update asset issue for wrong parameter - //publicFreeAssetNetLimit is -1 - Return ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - -1L, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid PublicFreeAssetNetLimit"); - //publicFreeAssetNetLimit is 0 - ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), - updateFreeAssetNetLimit, - 0, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //FreeAssetNetLimit is -1 - ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), -1, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid FreeAssetNetLimit"); - //FreeAssetNetLimit is 0 - ret1 = PublicMethed - .updateAsset2(asset010Address, updateDescription.getBytes(), updateUrl.getBytes(), 0, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Description is null - ret1 = PublicMethed - .updateAsset2(asset010Address, "".getBytes(), updateUrl.getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Url is null - ret1 = PublicMethed - .updateAsset2(asset010Address, description.getBytes(), "".getBytes(), freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - //Too long discription - ret1 = PublicMethed - .updateAsset2(asset010Address, tooLongDescription.getBytes(), url.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : Invalid description"); - //Too long URL - ret1 = PublicMethed - .updateAsset2(asset010Address, description.getBytes(), tooLongUrl.getBytes(), - freeAssetNetLimit, - publicFreeAssetNetLimit, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : Invalid url"); - } - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - Return ret1 = PublicMethed - .updateAsset2(asset010Address, description.getBytes(), url.getBytes(), 1999999999, - 199, testKeyForAssetIssue010, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean createAssetIssue(byte[] address, String name, Long totalSupply, Integer trxNum, - Integer icoNum, Long startTime, Long endTime, - Integer voteScore, String description, String url, Long fronzenAmount, Long frozenDay, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = PublicMethed.queryAccount(priKey, blockingStubFull); - - try { - AssetIssueContractOuterClass.AssetIssueContract.Builder builder = - AssetIssueContractOuterClass.AssetIssueContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - builder.setName(ByteString.copyFrom(name.getBytes())); - builder.setTotalSupply(totalSupply); - builder.setTrxNum(trxNum); - builder.setNum(icoNum); - builder.setStartTime(startTime); - builder.setEndTime(endTime); - builder.setVoteScore(voteScore); - builder.setDescription(ByteString.copyFrom(description.getBytes())); - builder.setUrl(ByteString.copyFrom(url.getBytes())); - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply.Builder frozenBuilder = - AssetIssueContractOuterClass.AssetIssueContract.FrozenSupply - .newBuilder(); - frozenBuilder.setFrozenAmount(fronzenAmount); - frozenBuilder.setFrozenDays(frozenDay); - builder.addFrozenSupply(0, frozenBuilder); - - Transaction transaction = blockingStubFull.createAssetIssue(builder.build()); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } catch (Exception ex) { - ex.printStackTrace(); - return false; - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public boolean transferAsset(byte[] to, byte[] assertName, long amount, byte[] address, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.TransferAssetContract.Builder builder = - AssetIssueContractOuterClass.TransferAssetContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(address); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - AssetIssueContractOuterClass.TransferAssetContract contract = builder.build(); - Transaction transaction = blockingStubFull.transferAsset(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return false; - } else { - Account search = queryAccount(ecKey, blockingStubFull); - return true; - } - - } - - /** - * constructor. - */ - - public boolean unFreezeAsset(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.UnfreezeAssetContract.Builder builder = - AssetIssueContractOuterClass.UnfreezeAssetContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - AssetIssueContractOuterClass.UnfreezeAssetContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeAsset(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - return true; - } - } - - /** - * constructor. - */ - - public boolean participateAssetIssue(byte[] to, byte[] assertName, long amount, byte[] from, - String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AssetIssueContractOuterClass.ParticipateAssetIssueContract.Builder builder = - AssetIssueContractOuterClass.ParticipateAssetIssueContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsName = ByteString.copyFrom(assertName); - ByteString bsOwner = ByteString.copyFrom(from); - builder.setToAddress(bsTo); - builder.setAssetName(bsName); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - AssetIssueContractOuterClass.ParticipateAssetIssueContract contract = builder.build(); - - Transaction transaction = blockingStubFull.participateAssetIssue(contract); - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } else { - logger.info(name); - return true; - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java deleted file mode 100644 index 4219adfeb37..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/VoteWitnessAccount2Test.java +++ /dev/null @@ -1,585 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class VoteWitnessAccount2Test { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info("Pre fix byte ===== " + WalletClient.getAddressPreFixByte()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - } - - @Test(enabled = true) - public void testVoteWitness2() { - //get account - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] lowBalAddress = ecKey.getAddress(); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] lowBalAddress2 = ecKey2.getAddress(); - String lowBalTest2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - //sendcoin - Return ret1 = PublicMethed.sendcoin2(lowBalAddress, 21245000000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - ret1 = PublicMethed.sendcoin2(lowBalAddress2, 21245000000L, - fromAddress, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - //assetissue - String createUrl1 = "adfafds"; - byte[] createUrl = createUrl1.getBytes(); - String lowBalTest = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - ret1 = createWitness2(lowBalAddress, createUrl, lowBalTest); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - String voteStr1 = Base58.encode58Check(lowBalAddress); - - //Base58.encode58Check(getFinalAddress(key); - //String voteStr = "TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes"; - String voteStr = voteStr1; - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - HashMap wrongVoteMap = new HashMap(); - wrongVoteMap.put(voteStr, "-1"); - HashMap zeroVoteMap = new HashMap(); - zeroVoteMap.put(voteStr, "0"); - - HashMap veryLargeMap = new HashMap(); - veryLargeMap.put(voteStr, "1000000000"); - HashMap wrongDropMap = new HashMap(); - wrongDropMap.put(voteStr, "10000000000000000"); - - //Vote failed due to no freeze balance. - //Assert.assertFalse(VoteWitness(smallVoteMap, NO_FROZEN_ADDRESS, no_frozen_balance_testKey)); - - //Freeze balance to get vote ability. - ret1 = PublicMethed.freezeBalance2(fromAddress, 10000000L, 3L, testKey002, blockingStubFull); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - //Vote failed when the vote is large than the freeze balance. - ret1 = voteWitness2(veryLargeMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - - //Vote failed due to 0 vote. - ret1 = voteWitness2(zeroVoteMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : vote count must be greater than 0"); - - ret1 = voteWitness2(wrongVoteMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : vote count must be greater than 0"); - - ret1 = voteWitness2(wrongDropMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - "Contract validate error : overflow: checkedMultiply(10000000000000000, 1000000)"); - ret1 = voteWitness2(smallVoteMap, fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), Return.response_code.SUCCESS); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), ""); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - String value = witness.get(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - long count = Long.parseLong(value); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - Assert - .assertTrue(afterVote.getVotes(j).getVoteCount() == Long.parseLong(witness.get(key))); - } - - } - } - return true; - } - - /** - * constructor. - */ - - public GrpcAPI.Return createWitness2(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.createWitness2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - GrpcAPI.Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Protocol.Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (response.getResult() == false) { - return response; - } - return ret; - - } - - /** - * constructor. - */ - - public Return voteWitness2(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = - WitnessContract.VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - String value = witness.get(addressBase58); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - long count = Long.parseLong(value); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - //Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull - .voteWitnessAccount2(contract); - - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } else { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return response; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - Assert - .assertTrue(afterVote.getVotes(j).getVoteCount() == Long.parseLong(witness.get(key))); - } - - } - } - return ret; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - return false; - } - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - Integer wait = 0; - while (searchCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 30) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Another fullnode didn't syn the first fullnode data"); - searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - //logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "afterfrozenbalance =" + Long.toString(afterFrozenBalance) + "beforefrozenbalance = " - + beforeFrozenBalance + "freezebalance = " + Long.toString(freezeBalance)); - //logger.info("afterbandwidth = " + Long.toString(afterBandwidth) + " beforebandwidth = - // " + Long.toString(beforeBandwidth)); - //if ((afterFrozenBalance - beforeFrozenBalance != freezeBalance) || - // (freezeBalance * frozen_duration -(afterBandwidth - beforeBandwidth) !=0)){ - // logger.info("After 20 second, two node still not synchronous"); - // } - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(freezeBalance * frozen_duration - (afterBandwidth - - // beforeBandwidth) <= 1000000); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java b/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java deleted file mode 100644 index 6c31c38c336..00000000000 --- a/framework/src/test/java/stest/tron/wallet/newaddinterface2/WithdrawBalance2Test.java +++ /dev/null @@ -1,308 +0,0 @@ -package stest.tron.wallet.newaddinterface2; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WithdrawBalance2Test { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - - private final String notWitnessTestKey = - "8CB4480194192F30907E14B52498F594BD046E21D7C4D8FE866563A6760AC891"; - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] notWitness = PublicMethed.getFinalAddress(notWitnessTestKey); - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - } - - @Test - public void testWithdrawBalance2() { - //Withdraw failed when you are not witness - Return ret1 = withdrawBalance2(notWitness, notWitnessTestKey); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), "Contract validate error : " - + "Account[41688b08971e740d7cecfa5d768f2787c1bb4c1268] is not a witnessAccount"); - - //Withdraw failed when the latest time to withdraw within 1 day. - ret1 = withdrawBalance2(fromAddress, testKey002); - Assert.assertEquals(ret1.getCode(), GrpcAPI.Return.response_code.CONTRACT_VALIDATE_ERROR); - Assert.assertEquals(ret1.getMessage().toStringUtf8(), - " Contract validate error : witnessAccount does not have any allowance"); - } - - /** - * constructor. - */ - - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public boolean withdrawBalance(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - - WithdrawBalanceContract.Builder builder = WithdrawBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - WithdrawBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.withdrawBalance(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return false; - } - logger.info("test withdraw" + priKey); - return true; - } - - /** - * constructor. - */ - - public Return withdrawBalance2(byte[] address, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - - WithdrawBalanceContract.Builder builder = WithdrawBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - builder.setOwnerAddress(byteAddreess); - WithdrawBalanceContract contract = builder.build(); - - GrpcAPI.TransactionExtention transactionExtention = blockingStubFull.withdrawBalance2(contract); - if (transactionExtention == null) { - return transactionExtention.getResult(); - } - Return ret = transactionExtention.getResult(); - if (!ret.getResult()) { - System.out.println("Code = " + ret.getCode()); - System.out.println("Message = " + ret.getMessage().toStringUtf8()); - return ret; - } - Transaction transaction = transactionExtention.getTransaction(); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - System.out.println("Transaction is empty"); - return transactionExtention.getResult(); - } - System.out.println( - "Receive txid = " + ByteArray.toHexString(transactionExtention.getTxid().toByteArray())); - - ECKey ecKey = temKey; - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - return response; - } - logger.info("test withdraw" + priKey); - return ret; - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] address, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(address)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote - .newBuilder(); - byte[] addRess = WalletClient.decodeFromBase58Check(addressBase58); - if (addRess == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - return false; - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - if (key.equals(afterVote.getVotes(j).getVoteAddress())) { - Long afterVoteNum = Long.parseLong(witness.get(key)); - Assert.assertTrue(afterVoteNum == afterVote.getVotes(j).getVoteCount()); - logger.info("test equal vote"); - } - } - } - return true; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java deleted file mode 100644 index 837e4c72aa8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ContractEvent001.java +++ /dev/null @@ -1,757 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONObject; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.util.EntityUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.crypto.SignInterface; -import org.tron.common.crypto.SignUtils; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import org.zeromq.ZMQ; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.JsonRpcBase; -import stest.tron.wallet.common.client.utils.PublicMethed; -import zmq.ZMQ.Event; - -@Slf4j -public class ContractEvent001 extends JsonRpcBase { - - private final String testKey002 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = - Configuration.getByPath("testng.conf").getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - String txid; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] event002Address = ecKey2.getAddress(); - String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - // byte[] contractAddress = null; - String param = "10"; - static HttpResponse response; - static JSONObject responseContent; - private String fullnode = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(0); - private String fullnode1 = - Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = - Configuration.getByPath("testng.conf").getLong("defaultParameter.maxFeeLimit"); - - - - /** constructor. */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true).build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1).usePlaintext(true).build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - @Test(enabled = true) - public void test1ContractEventAndLog() { - ecKey1 = new ECKey(Utils.getRandom()); - event001Address = ecKey1.getAddress(); - event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - - ecKey2 = new ECKey(Utils.getRandom()); - event002Address = ecKey2.getAddress(); - event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue( - PublicMethed.sendcoin( - event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue( - PublicMethed.sendcoin( - event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - AccountResourceMessage accountResource = - PublicMethed.getAccountResource(event001Address, blockingStubFull); - Long energyLimit = accountResource.getEnergyLimit(); - Long energyUsage = accountResource.getEnergyUsed(); - Long balanceBefore = PublicMethed.queryAccount(event001Key, blockingStubFull).getBalance(); - - logger.info("before energy limit is " + Long.toString(energyLimit)); - logger.info("before energy usage is " + Long.toString(energyUsage)); - logger.info("before balance is " + Long.toString(balanceBefore)); - - String contractName = "addressDemo"; - String code = - Configuration.getByPath("testng.conf").getString("code.code_ContractEventAndLog1"); - String abi = Configuration.getByPath("testng.conf").getString("abi.abi_ContractEventAndLog1"); - byte[] contractAddress = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 50, - null, - event001Key, - event001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - - Integer i = 0; - for (i = 0; i < 1; i++) { - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventCycle(uint256)", - "100", - false, - 1L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForLogCycle(uint256)", - "100", - false, - 2L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerUintEvent()", - "#", - false, - 0, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerintEvent()", - "#", - false, - 0, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventAndLog()", - "#", - false, - 1, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventNoIndex()", - "#", - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForLog()", - "#", - false, - 1L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventNoIndex()", - "#", - false, - 1L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventOneIndex()", - "#", - false, - 1L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventTwoIndex()", - "#", - false, - 2L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEvent()", - "#", - false, - 3L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForEventCycle(uint256)", - "100", - false, - 1L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForLogCycle(uint256)", - "100", - false, - 2L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForAnonymousHasLog()", - "#", - false, - 4L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "depositForAnonymousNoLog()", - "#", - false, - 5L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - String param = "\"" + code + "\"" + "," + "\"" + code + "\""; - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerStringEvent(string,string)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - param = "\"" + "true1" + "\"" + "," + "\"" + "false1" + "\""; - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerBoolEvent(bool,bool)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - String filename = "/Users/wangzihe/Documents/modify_fullnode/java-tron/tooLongString.txt"; - try { - FileReader fr = new FileReader(filename); - InputStreamReader read = new InputStreamReader(new FileInputStream(new File(filename))); - BufferedReader reader = new BufferedReader(read); - String tooLongString = reader.readLine(); - param = "\"" + tooLongString + "\"" + "," + "\"" + tooLongString + "\""; - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerStringEventAnonymous(string,string)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerStringEvent(string,string)", - param, - false, - 0L, - 100000000L, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - contractName = "addressDemo"; - code = Configuration.getByPath("testng.conf").getString("code.code_ContractEventAndLog2"); - abi = Configuration.getByPath("testng.conf").getString("abi.abi_ContractEventAndLog2"); - contractAddress = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 50, - null, - event001Key, - event001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - - txid = - PublicMethed.triggerContract( - contractAddress, - "triggerEventBytes()", - "#", - false, - 0, - maxFeeLimit, - event001Address, - event001Key, - blockingStubFull); - logger.info(txid); - } - - @Test( - enabled = true, - threadPoolSize = 5, - invocationCount = 5, - description = "test eth_getFilterChanges") - public void testEthGetFilterChanges() throws InterruptedException { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] event001Address = ecKey1.getAddress(); - logger.info("event001Address:" + event001Address); - String event001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] event002Address = ecKey2.getAddress(); - logger.info("event002Address:" + event002Address); - String event002Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - PublicMethed.printAddress(event001Key); - PublicMethed.printAddress(testKey002); - - Assert.assertTrue( - PublicMethed.sendcoin( - event001Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - Assert.assertTrue( - PublicMethed.sendcoin( - event002Address, maxFeeLimit * 30, fromAddress, testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - String contractName = "SolidityTest"; - String filePath = "./src/test/resources/soliditycode/testGetFilterChange.sol"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = - PublicMethed.deployContract( - contractName, - abi, - code, - "", - maxFeeLimit, - 0L, - 50, - null, - event001Key, - event001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - logger.info("11111111111111111111111111111111111"); - Thread.sleep(180000); - - long txidNum = 0; - HttpResponse response = getNowBlock(httpFullNode); - JSONObject responseContent = parseResponseContent(response); - long blockBefore = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - logger.info("blockBefore:" + blockBefore); - Thread.sleep(180000); - for (int i = 0; i < 5000; i++) { - String txid = - PublicMethed.triggerContract( - contractAddress, - "getResult(uint256)", - param, - false, - 2L, - 100000000L, - event002Address, - event002Key, - blockingStubFull); - logger.info("txid:" + txid); - txidNum++; - } - Thread.sleep(180000); - response = getNowBlock(httpFullNode); - responseContent = parseResponseContent(response); - long blockAfter = - responseContent.getJSONObject("block_header").getJSONObject("raw_data").getLong("number"); - - logger.info("txidNum:" + txidNum); - - // 扫块 - long sumLogs = 0; - long totalTransactionsSize = 0; - logger.info("blockBefore:" + blockBefore); - logger.info("blockAfter:" + blockAfter); - for (long i = blockBefore; i <= blockAfter; i++) { - - response = getTransactionCountByBlocknum(httpFullNode, (int) i); - responseContent = parseResponseContent(response); - long transactionsSize = responseContent.getLong("count"); - - totalTransactionsSize += transactionsSize; - } - logger.info( - (int) (Thread.currentThread().getId()) - + "sumLogs:" - + totalTransactionsSize * Long.parseLong(param)); - } - - public static String[] arr = - new String[] { - "00", - "0x6b5c9c34aae469576dfcde3655c9036d", - "0x450de4565abf4434d66948fb2a568608", - "0x02a65b2cc37d2d34808a63b50b86e0cd", - "0x7474d244cecf3a943bf8ac6dbd7d60fa", - "0x4ab110c02b04d7781f774eeffa6432a3" - }; - - @Test( - enabled = true, - threadPoolSize = 5, - invocationCount = 5, - description = "Eth api of eth_getFilterChanges .") - public void test09GetFilterChanges() { - long sumSize = 0; - while (true) { - JsonArray params = new JsonArray(); - String id = arr[(int) (Thread.currentThread().getId()) - 16]; - params.add(id); - JsonObject requestBody = getJsonRpcBody("eth_getFilterChanges", params); - HttpResponse response = getJsonRpc(jsonRpcNode, requestBody); - JSONObject responseContent = parseResponseContent(response); - long size = responseContent.getJSONArray("result").size(); - sumSize += size; - logger.info(Thread.currentThread().getId() + ":sumSize:" + sumSize); - } - } - - /** constructor. */ - public static JSONObject parseResponseContent(HttpResponse response) { - try { - String result = EntityUtils.toString(response.getEntity()); - StringEntity entity = new StringEntity(result, Charset.forName("UTF-8")); - response.setEntity(entity); - JSONObject obj = JSONObject.parseObject(result); - return obj; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - /* public static HttpResponse getNowBlock(String httpNode, Boolean visible) { - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - httppost.releaseConnection(); - return null; - } - return response; - }*/ - - /** constructor. */ - public static HttpResponse getTransactionCountByBlocknum(String httpNode, long blocknum) { - HttpResponse response; - try { - - String requestUrl = "http://" + httpNode + "/wallet/gettransactioncountbyblocknum"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("num", blocknum); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - - return null; - } - return response; - } - - public static HttpResponse getNowBlock(String httpNode) { - return getNowBlock(httpNode, false); - } - - /** constructor. */ - public static HttpResponse getNowBlock(String httpNode, Boolean visible) { - - HttpResponse response; - try { - String requestUrl = "http://" + httpNode + "/wallet/getnowblock"; - JsonObject userBaseObj2 = new JsonObject(); - userBaseObj2.addProperty("visible", visible); - response = createConnect(requestUrl, userBaseObj2); - } catch (Exception e) { - e.printStackTrace(); - - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse createConnect(String url, JsonObject requestBody) { - HttpResponse response; - HttpPost httppost; - HttpClient httpClient; - Integer connectionTimeout = - Configuration.getByPath("testng.conf").getInt("defaultParameter.httpConnectionTimeout"); - Integer soTimeout = - Configuration.getByPath("testng.conf").getInt("defaultParameter.httpSoTimeout"); - PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(); - pccm.setDefaultMaxPerRoute(80); - pccm.setMaxTotal(100); - - httpClient = new DefaultHttpClient(pccm); - try { - - httpClient - .getParams() - .setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - if (requestBody != null) { - StringEntity entity = new StringEntity(requestBody.toString(), Charset.forName("UTF-8")); - entity.setContentEncoding("UTF-8"); - entity.setContentType("application/json"); - httppost.setEntity(entity); - } - - logger.info(httppost.toString()); - response = httpClient.execute(httppost); - } catch (Exception e) { - e.printStackTrace(); - - return null; - } - return response; - } - - /** constructor. */ - public static HttpResponse getJsonRpc(String jsonRpcNode, JsonObject jsonRpcObject) { - HttpResponse response; - try { - String requestUrl = "http://" + jsonRpcNode + "/jsonrpc"; - response = createConnect(requestUrl, jsonRpcObject); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - return response; - } - - @Test(enabled = true, description = "Subscribe event client") - public void testEnergyCostDetail() { - ZMQ.Context context = ZMQ.context(1); - ZMQ.Socket req = context.socket(ZMQ.SUB); - - req.subscribe("blockTrigger"); - req.subscribe("transactionTrigger"); - req.subscribe("contractLogTrigger"); - req.subscribe("contractEventTrigger"); - req.monitor("inproc://reqmoniter", ZMQ.EVENT_CONNECTED | ZMQ.EVENT_DISCONNECTED); - final ZMQ.Socket moniter = context.socket(ZMQ.PAIR); - moniter.connect("inproc://reqmoniter"); - new Thread(new Runnable() { - public void run() { - while (true) { - Event event = Event.read(moniter.base()); - System.out.println(event.event + " " + event.addr); - } - } - - }).start(); - req.connect("tcp://47.94.197.215:55555"); - req.setReceiveTimeOut(10000); - - while (true) { - byte[] message = req.recv(); - if (message != null) { - System.out.println("receive : " + new String(message)); - } - } - } - - @Test(enabled = true) - public void testSingForHex() { - try { - SignInterface cryptoEngine = - SignUtils.fromPrivate( - ByteArray.fromHexString( - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"), - true); - /* ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine - .signHash(Sha256Hash.of(DBConfig.isECKeyCryptoEngine(), - ByteArray.fromHexString( - "ba989430c392dedef66a259a1f1112b178dbe7f2793975d8cf80f9b31ecd33ff")) - .getBytes())));*/ - // - ByteString sig = - ByteString.copyFrom( - cryptoEngine.Base64toBytes( - cryptoEngine.signHash( - ByteArray.fromHexString( - "4f2a4c136f56a41714b42e14d497e38dcbe0f9c4ca2e5957cf3a340c62d133f8")))); - logger.info(ByteArray.toHexString(sig.toByteArray())); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** constructor. */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/CycleMultiSign.java b/framework/src/test/java/stest/tron/wallet/onlinestress/CycleMultiSign.java deleted file mode 100644 index 6da00b39793..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/CycleMultiSign.java +++ /dev/null @@ -1,253 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.List; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Permission; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class CycleMultiSign { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidityInFullnode = null; - - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSolidityInFullnode = null; - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - private ECKey ecKey = new ECKey(Utils.getRandom()); - private byte[] test001Address = ecKey.getAddress(); - private String dev001Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - - - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] test002Address = ecKey2.getAddress(); - private String sendAccountKey2 = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - private ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] test003Address = ecKey3.getAddress(); - String sendAccountKey3 = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - private ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] test004Address = ecKey4.getAddress(); - String sendAccountKey4 = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] test005Address = ecKey5.getAddress(); - String sendAccountKey5 = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - } - - //(use no id) - @Test(enabled = true) - public void testMultiSignActiveAddress() { - Assert.assertTrue(PublicMethed - .sendcoin(test001Address, 10000000000000L, fromAddress, testKey002, - blockingStubFull)); - - Account test001AddressAccount = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList = test001AddressAccount.getActivePermissionList(); - Permission ownerPermission = test001AddressAccount.getOwnerPermission(); - Permission witnessPermission = test001AddressAccount.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission)); - logger.info("wei-----------------------"); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = dev001Key; - - String accountPermissionJson1 = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":1,\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\"," - + "\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}]}]} "; - - Account test001AddressAccount1 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList1 = test001AddressAccount1.getActivePermissionList(); - Permission ownerPermission1 = test001AddressAccount1.getOwnerPermission(); - Permission witnessPermission1 = test001AddressAccount1.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList1); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission1)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission1)); - logger.info("1-----------------------"); - - String accountPermissionJson2 = - "{\"owner_permission\":{\"type\":0,\"permission_name\"" - + ":\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]} "; - String accountPermissionJson3 = "{\"owner_permission\":{\"type\":0,\"permission_name\":" - + "\"owner\",\"threshold\":1,\"keys\":[{\"address\"" - + ":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":" - + "\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations" - + "\":\"0100000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - String accountPermissionJson4 = "{\"owner_permission\":{\"type\":0,\"" - + "permission_name\":\"owner\",\"threshold\":1,\"keys\":" - + "[{\"address\":\"" + PublicMethed.getAddressString(dev001Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1," - + "\"operations\":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\",\"keys\":" - + "[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey4) - + "\",\"weight\":1}]},{\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\"" - + ":\"0100000000000000000000000000000000000000000000000000000000000000\",\"keys\"" - + ":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\":" - + "\"0200000000000000000000000000000000000000000000000000000000000000\",\"keys\"" - + ":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey2) - + "\",\"weight\":1}]},{\"type\":2," - + "\"permission_name\":\"active0\",\"threshold\":1,\"operations\":\"" - + "0200000000000000000000000000000000000000000000000000000000000000\",\"keys\":" - + "[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\"" - + ":\"0200000000000000000000000000000000000000000000000000000000000000\",\"" - + "keys\":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey5) - + "\",\"weight\":1}]}," - + "{\"type\":2,\"permission_name\":\"active0\",\"threshold\":1,\"operations\":" - + "\"0020000000000000000000000000000000000000000000000000000000000000\",\"keys\"" - + ":[{\"address\":\"" + PublicMethed.getAddressString(sendAccountKey3) - + "\",\"weight\":1}]}]}"; - while (true) { - PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson1, test001Address, - dev001Key, - blockingStubFull, 0, - permissionKeyString); - addressPermission(dev001Key, accountPermissionJson2); - addressPermission(dev001Key, accountPermissionJson3); - addressPermission(dev001Key, accountPermissionJson4); - Account test001AddressAccount2 = PublicMethed.queryAccount(test001Address, blockingStubFull); - List permissionsList2 = test001AddressAccount2.getActivePermissionList(); - Permission ownerPermission2 = test001AddressAccount2.getOwnerPermission(); - Permission witnessPermission2 = test001AddressAccount2.getWitnessPermission(); - PublicMethedForMutiSign.printPermissionList(permissionsList2); - logger.info(PublicMethedForMutiSign.printPermission(ownerPermission2)); - logger.info(PublicMethedForMutiSign.printPermission(witnessPermission2)); - } - } - - /** - * constructor. - */ - - public void addressPermission(String addKey, String accountPermissionJson) { - PublicMethed.freezeBalanceForReceiver(test001Address, - 10000000L, 0, 0, - com.google.protobuf.ByteString.copyFrom(fromAddress), testKey002, blockingStubFull); - - String[] permissionKeyString = new String[1]; - permissionKeyString[0] = addKey; - PublicMethedForMutiSign - .accountPermissionUpdateWithPermissionId(accountPermissionJson, test001Address, dev001Key, - blockingStubFull, 0, - permissionKeyString); - PublicMethed.unFreezeBalance(fromAddress, testKey002, 0, - test001Address, blockingStubFull); - } - - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/DelayTransactionStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/DelayTransactionStress.java deleted file mode 100644 index 967067b46a6..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/DelayTransactionStress.java +++ /dev/null @@ -1,340 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -//import org.tron.protos.Protocol.DeferredTransaction; - -@Slf4j -public class DelayTransactionStress { - - public static final long MAX_DEFERRED_TRANSACTION_DELAY_SECONDS = 45 * 24 * 3_600L; //45 days - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Optional infoById = null; - //Optional deferredTransactionById = null; - Optional getTransactionById = null; - ECKey ecKey = new ECKey(Utils.getRandom()); - byte[] delayAccount1Address = ecKey.getAddress(); - String delayAccount1Key = ByteArray.toHexString(ecKey.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] delayAccount2Address = ecKey2.getAddress(); - String delayAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] receiverAccountAddress = ecKey3.getAddress(); - String receiverAccountKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] delayAccount3Address = ecKey4.getAddress(); - String delayAccount3Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - ECKey ecKey5 = new ECKey(Utils.getRandom()); - byte[] receiverAccount4Address = ecKey5.getAddress(); - String receiverAccount4Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private Long delayTransactionFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.delayTransactionFee"); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 2000) - public void test1DelaySendcoinStress() { - String txid = ""; - Integer i = 0; - String cancelId = ""; - while (i++ <= 10000000) { - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] delayAccount2Address = ecKey2.getAddress(); - String delayAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - txid = PublicMethed.sendcoinDelayedGetTxid(delayAccount2Address, 1L, 20, fromAddress, - testKey002, blockingStubFull); - //PublicMethed.waitProduceNextBlock(blockingStubFull); - if (i % 20 == 0) { - cancelId = txid; - //PublicMethed.sendcoin(delayAccount2Address,1L,fromAddress,testKey002,blockingStubFull); - } - if (i % 39 == 0) { - PublicMethed.cancelDeferredTransactionById(cancelId, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(delayAccount2Address, 1L, fromAddress, testKey002, - blockingStubFull); - } - - } - - - } - - /* @Test(enabled = true, description = "Get deferred transaction by id") - public void test2getDeferredTransactionByid() { - //get account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] delayAccount2Address = ecKey2.getAddress(); - String delayAccount2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - receiverAccountAddress = ecKey3.getAddress(); - receiverAccountKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(delayAccount2Key); - PublicMethed.printAddress(receiverAccountKey); - - //Pre sendcoin to the test account - Assert.assertTrue(PublicMethed.sendcoin(delayAccount2Address, 100000000L,fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(receiverAccountAddress, 10L,fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Do delay send coin transaction. - Long delaySecond = 10L; - Long sendCoinAmout = 100L; - - //Query balance before send coin. - Long deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount2Address, - blockingStubFull).getBalance(); - Long recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccountAddress, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - String txid = PublicMethed.sendcoinDelayedGetTxid(receiverAccountAddress, sendCoinAmout, - delaySecond,delayAccount2Address, - delayAccount2Key, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance when pre-sendcoin stage. - Long deplayAccountInDelayBalance = PublicMethed.queryAccount(delayAccount2Address, - blockingStubFull).getBalance(); - Long recevierAccountInDelayalance = PublicMethed.queryAccount(receiverAccountAddress, - blockingStubFull).getBalance(); - logger.info("deplayAccountInDelayBalance " + deplayAccountInDelayBalance); - logger.info("recevierAccountInDelayalance " + recevierAccountInDelayalance); - Assert.assertTrue(recevierAccountBeforeBalance == recevierAccountInDelayalance); - //Assert.assertTrue(); - - - deferredTransactionById = PublicMethed.getDeferredTransactionById(txid,blockingStubFull); - DeferredTransaction transaction = deferredTransactionById.get(); - String finalTxid = ByteArray.toHexString(Sha256Hash.hash(transaction.getTransaction() - .getRawData().toByteArray())); - PublicMethed.getDeferredTransactionById(finalTxid,blockingStubFull); - logger.info(finalTxid); - //logger.info("receiver address is " + Base58.encode58Check(transaction - .getReceiverAddress().toByteArray())); - Assert.assertTrue(Base58.encode58Check(transaction.getReceiverAddress().toByteArray()) - .equalsIgnoreCase(PublicMethed.getAddressString(receiverAccountKey))); - //logger.info("sender address is " + Base58.encode58Check(transaction - .getSenderAddress().toByteArray())); - Assert.assertTrue(Base58.encode58Check(transaction.getSenderAddress().toByteArray()) - .equalsIgnoreCase(PublicMethed.getAddressString(delayAccount2Key))); - // logger.info("delaySeconds is " + transaction.getDelaySeconds()); - Assert.assertTrue(delaySecond == transaction.getDelaySeconds()); - //logger.info("DelayUntil " + transaction.getDelayUntil()); - Assert.assertTrue(transaction.getDelayUntil() > System.currentTimeMillis()); - //logger.info("Expiration " + transaction.getExpiration()); - Assert.assertTrue(transaction.getExpiration() > System.currentTimeMillis()); - //logger.info("PublishTime " + transaction.getPublishTime()); - Assert.assertTrue(transaction.getPublishTime() < System.currentTimeMillis()); - //Assert.assertTrue(transaction.getDelayUntil() + 60000 == transaction.getExpiration()); - getTransactionById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("transaction stage in txid is " + getTransactionById.get().getRawData() - .getDeferredStage().getStage()); - - Assert.assertTrue(getTransactionById.get().getRawData().getDeferredStage().getStage() == 1); - getTransactionById = PublicMethed.getTransactionById(finalTxid, blockingStubFull); - logger.info("transaction stage in final id is " + getTransactionById - .get().getRawData().getDeferredStage().getStage()); - Assert.assertTrue(getTransactionById.get().getRawData().getDeferredStage().getStage() == 0); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - PublicMethed.getDeferredTransactionById(finalTxid,blockingStubFull); - deferredTransactionById = PublicMethed.getDeferredTransactionById(txid,blockingStubFull); - finalTxid = ByteArray.toHexString(Sha256Hash.hash(transaction.getTransaction() - .getRawData().toByteArray())); - transaction = deferredTransactionById.get(); - logger.info(finalTxid); - //logger.info("receiver address is " + Base58.encode58Check(transaction.getReceiverAddress() - .toByteArray())); - //logger.info("receiver address is " + Base58.encode58Check(transaction.getSenderAddress() - .toByteArray())); - //logger.info("delaySeconds is " + transaction.getDelaySeconds()); - //logger.info("DelayUntil " + transaction.getDelayUntil()); - //logger.info("Expiration " + transaction.getExpiration()); - //logger.info("PublishTime " + transaction.getPublishTime()); - getTransactionById = PublicMethed.getTransactionById(txid, blockingStubFull); - logger.info("transaction stage in txid is " + getTransactionById.get().getRawData() - .getDeferredStage().getStage()); - getTransactionById = PublicMethed.getTransactionById(finalTxid, blockingStubFull); - logger.info("transaction stage in final id is " + getTransactionById.get().getRawData() - .getDeferredStage().getStage()); - - - - //Query balance after delay send coin. - Long deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount2Address, - blockingStubFull).getBalance(); - Long recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccountAddress, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - - Assert.assertTrue(deplayAccountBeforeBalance - deplayAccountAfterBalance == sendCoinAmout - + 100000L); - Assert.assertTrue(recevierAccountAfterDelayalance - recevierAccountBeforeBalance - == sendCoinAmout); - - }*/ - - @Test(enabled = true, description = "Delay send coin") - public void test3DelaySendCoin() { - ecKey4 = new ECKey(Utils.getRandom()); - delayAccount3Address = ecKey4.getAddress(); - delayAccount3Key = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - PublicMethed.printAddress(delayAccount3Key); - - ecKey5 = new ECKey(Utils.getRandom()); - receiverAccount4Address = ecKey5.getAddress(); - receiverAccount4Key = ByteArray.toHexString(ecKey5.getPrivKeyBytes()); - PublicMethed.printAddress(receiverAccount4Key); - - Long sendCoinAmount = 100000000L; - //Pre sendcoin to the test account - Assert.assertTrue(PublicMethed.sendcoin(delayAccount3Address, sendCoinAmount, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Do delay send coin transaction. - logger.info("----------------No balance to send coin--------------------"); - //Test no balance to send coin. - //Query balance before send coin. - Long deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - Long recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - Long delaySecond = 4L; - Assert.assertFalse(PublicMethed.sendcoinDelayed(receiverAccount4Address, sendCoinAmount, - delaySecond, delayAccount3Address, delayAccount3Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance after delay send coin. - Long deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - Long recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - - Assert.assertTrue(recevierAccountAfterDelayalance == 0); - logger.info("deplayAccountBeforeBalance: " + deplayAccountBeforeBalance); - logger.info("deplayAccountAfterBalance: " + deplayAccountAfterBalance); - - Assert.assertEquals(deplayAccountBeforeBalance, deplayAccountAfterBalance); - - logger.info("----------------No balance to create account send coin--------------------"); - //Test delay send coin to create account. - deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - Long createAccountFee = 100000L; - Assert.assertTrue(PublicMethed.sendcoinDelayed(receiverAccount4Address, - deplayAccountBeforeBalance - createAccountFee, delaySecond, delayAccount3Address, - delayAccount3Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance after delay send coin. - deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount3Address, blockingStubFull) - .getBalance(); - recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - - Assert.assertTrue(recevierAccountAfterDelayalance == 0); - Assert.assertTrue(deplayAccountBeforeBalance - deplayAccountAfterBalance == 100000); - - logger.info("---------------Balance enough to create account send coin--------------------"); - //Test delay send coin to create account. - createAccountFee = 100000L; - deplayAccountBeforeBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - recevierAccountBeforeBalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountBeforeBalance " + deplayAccountBeforeBalance); - logger.info("recevierAccountBeforeBalance " + recevierAccountBeforeBalance); - Assert.assertTrue(PublicMethed.sendcoinDelayed(receiverAccount4Address, - deplayAccountBeforeBalance - createAccountFee - delayTransactionFee, - delaySecond, delayAccount3Address, delayAccount3Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Query balance after delay send coin. - deplayAccountAfterBalance = PublicMethed.queryAccount(delayAccount3Address, - blockingStubFull).getBalance(); - recevierAccountAfterDelayalance = PublicMethed.queryAccount(receiverAccount4Address, - blockingStubFull).getBalance(); - logger.info("deplayAccountAfterBalance " + deplayAccountAfterBalance); - logger.info("recevierAccountAfterDelayalance " + recevierAccountAfterDelayalance); - Long receiverBalanceShouldBe = deplayAccountBeforeBalance - createAccountFee - - delayTransactionFee; - - Assert.assertEquals(recevierAccountAfterDelayalance, receiverBalanceShouldBe); - Assert.assertTrue(deplayAccountAfterBalance == 0); - } - - - /** - * constructor. - */ - - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ExtCodeHashStressTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ExtCodeHashStressTest.java deleted file mode 100644 index 8c4dab36742..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ExtCodeHashStressTest.java +++ /dev/null @@ -1,619 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class ExtCodeHashStressTest { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2); - private AtomicLong count = new AtomicLong(); - private AtomicLong errorCount = new AtomicLong(); - private long startTime = System.currentTimeMillis(); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private byte[] extCodeHashContractAddress = null; - private byte[] normalContractAddress = null; - private byte[] testContractAddress = null; - private byte[] dev001Address = fromAddress; - private String dev001Key = testKey002; - private ECKey ecKey2 = new ECKey(Utils.getRandom()); - private byte[] user001Address = ecKey2.getAddress(); - private String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - PublicMethed.printAddress(dev001Key); - PublicMethed.printAddress(user001Key); - } - - @Test(enabled = true, description = "Deploy a normal contract to be used for stress testing.") - public void test01DeployNormalContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashStress.sol"; - String contractName = "TriggerNormal"; //TBVEkA72g1wFoBBVLSXFZ2Bp944oL17NeU - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - normalContractAddress = deployContract(code, abi, contractName, blockingStubFull); - - SmartContract smartContract = PublicMethed.getContract(normalContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "Deploy a extcodehash contract.") - public void test02DeployExtCodeHashContract() { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 100_000_000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(dev001Address, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(dev001Key, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "./src/test/resources/soliditycode/extCodeHashStress.sol"; - String contractName = "Trigger"; //THAx2PcAtRCerwrLGN237dahqSUfq5wLnR - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - extCodeHashContractAddress = deployContract(code, abi, contractName, blockingStubFull); - - SmartContract smartContract = PublicMethed.getContract(extCodeHashContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - /** - * trigger. - */ - public byte[] deployContract(String bytecode, String abi, String contractName, - WalletGrpc.WalletBlockingStub blockingStubFull) { - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, bytecode, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, dev001Key, - dev001Address, blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage() - .toStringUtf8()); - } - - return infoById.get().getContractAddress().toByteArray(); - } - - /** - * trigger. - */ - public String triggerContractWithMaxFeeLimit(byte[] testAddress, byte[] user001Address, - String user001Key, long maxFeeLimit) { - Assert.assertTrue(PublicMethed.sendcoin(user001Address, 10000_000_000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(user001Address, user001Key, 50000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(user001Address), testKey002, blockingStubFull)); - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(extCodeHashContractAddress, - "test(address)", param, false, callValue, - maxFeeLimit, "0", 0, user001Address, user001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - scheduledExecutorService - .schedule(new CheckTask(triggerTxid, blockingStubFull), 15, TimeUnit.SECONDS); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - logger - .info("transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - - if (infoById.get().getResMessage().toStringUtf8().toLowerCase().contains("cpu")) { - throw new IllegalArgumentException(); - } - if (infoById.get().getResMessage().toStringUtf8().toLowerCase().contains("timeout")) { - throw new IllegalArgumentException(); - } - return "ok"; - } - - /** - * trigger. - */ - public String triggerAndGetExtCodeHashList(List testAddress, byte[] user001Address, - String user001Key, long maxFeeLimit, WalletGrpc.WalletBlockingStub blockingStubFull) { - - Long callValue = Long.valueOf(0); - List params = new ArrayList<>(); - for (int i = 0; i < testAddress.size(); i++) { - params.add(Base58.encode58Check(testAddress.get(i))); - } - final String triggerTxid = PublicMethed.triggerParamListContract(extCodeHashContractAddress, - "test(address[])", Arrays.asList(params), false, callValue, - maxFeeLimit, "0", 0, user001Address, user001Key, - blockingStubFull); - - scheduledExecutorService - .schedule(new CheckTask(triggerTxid, blockingStubFull), 15, TimeUnit.SECONDS); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger - .info( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - - return "ok"; - - } - - /** - * trigger. - */ - public void triggerAndGetExtCodeHash(byte[] testAddress, byte[] user001Address, - String user001Key, long maxFeeLimit, WalletGrpc.WalletBlockingStub blockingStubFull) { - - Long callValue = Long.valueOf(0); - - String param = "\"" + Base58.encode58Check(testAddress) + "\""; - final String triggerTxid = PublicMethed.triggerContract(normalContractAddress, - "test(address)", param, false, callValue, - 314982000, "0", 0, user001Address, user001Key, - blockingStubFull); - - scheduledExecutorService - .schedule(new CheckTask(triggerTxid, blockingStubFull), 15, TimeUnit.SECONDS); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - logger - .info( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - - private synchronized void wirteLine(String fileName, String line) { - try { - BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true)); - out.write(line); - out.newLine(); - out.flush(); - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test(enabled = true, description = "Deploy multiple long bytecode contract " - + "and write address to file.") - public void test03DeployMultiLongByteCodeContract() { - - ExecutorService pool = Executors.newFixedThreadPool(30); - Map addressMap = new ConcurrentHashMap<>(); - int size = 50_0_000; - int stubSize = 30; - List stubs = new ArrayList<>(); - for (int i = 0; i < stubSize; i++) { - stubs.add(WalletGrpc.newBlockingStub(channelFull)); - } - - CountDownLatch count = new CountDownLatch(size); - for (int i = 0; i < size; i++) { - - String contractName = "extcodehashContract" + i; - logger.info("[" + i + "]contractName: " + contractName); - pool.submit(new DeployTask(addressMap, i, count, stubs.get(i % stubSize))); - - } - - try { - count.await(); - for (String s : addressMap.keySet()) { - System.out.println(s); - } - - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - @Test(enabled = true, description = "Calculate the contract maxfeelimit.", - threadPoolSize = 1, invocationCount = 1) - public void test04StressGetExtCodeHashContract() { - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - extCodeHashContractAddress = WalletClient - .decodeFromBase58Check("TEsdDpJQrLBDPmJfDF2Ex53iMfzetqHvn9"); - - // long bytecode contract - testContractAddress = WalletClient.decodeFromBase58Check("TDqSAv8gLFXQRfug5Pr1Ev6zrEj1efC8qe"); - - HashMap retMap = new HashMap<>(); - - long feeLimit = 314982000; - // long feeLimit = 393624800; - // long feeLimit = 406731800; - - long base = 100; - long lastSuccess = feeLimit; - int failed = 0; - - for (int i = 0; i < 1000000000; i++) { - try { - String retCode = triggerContractWithMaxFeeLimit(testContractAddress, user001Address, - user001Key, - feeLimit); - logger.info("[" + i + "]retCode: " + retCode); - logger.info("[" + i + "]feeLimit: " + feeLimit); - lastSuccess = feeLimit; - base *= 2; - feeLimit += base; - failed = 0; - } catch (Exception e) { - failed++; - if (failed > 3) { - break; - } - logger.error("cpu timeout"); - feeLimit = lastSuccess; - base = 100; - } - } - } - - @Test(enabled = true, description = "Trigger extcodeHash contract stress.") - public void test05TriggerContract() throws FileNotFoundException { - - BufferedReader reader = null; - List addresses = new ArrayList<>(); - try { - reader = new BufferedReader(new FileReader("src/test/resources/address2")); - String line = reader.readLine(); - while (line != null) { - System.out.println(line); - // read next line - line = reader.readLine(); - addresses.add(line); - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - ExecutorService pool = Executors.newFixedThreadPool(50); - int stubSize = 50; - List stubs = new ArrayList<>(); - for (int i = 0; i < stubSize; i++) { - stubs.add(WalletGrpc.newBlockingStub(channelFull)); - } - - int paramsSize = 75; // the address count per trigger - int trigger = 0; - for (int i = 0; i + paramsSize < addresses.size(); i += paramsSize) { - System.err.println(trigger++); - System.err.println(i + " " + (i + paramsSize)); - pool.submit(new TriggerTask(addresses.subList(i, i + paramsSize), stubs.get( - (int) (Math.random() * 100 % stubSize)))); - } - - try { - Thread.sleep(100000000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - /** - * trigger. - */ - public void triggerContact(String[] testList, WalletGrpc.WalletBlockingStub stub) { - - final byte[] user001Address = fromAddress; - final String user001Key = testKey002; - - extCodeHashContractAddress = WalletClient - .decodeFromBase58Check("TJGYcUspHrwPgy72YeaVjD4Skep9Ji8Pnn"); - - final long feeLimit = 102471600; - count.getAndAdd(1); - if (count.get() % 100 == 0) { - long cost = (System.currentTimeMillis() - startTime) / 1000; - logger.info("Count:" + count.get() + ", cost:" + cost - + ", avg:" + count.get() / cost + ", errCount:" + errorCount); - } - - List addressList = new ArrayList<>(); - - for (int k = 0; k < testList.length; k++) { - addressList.add(WalletClient.decodeFromBase58Check(testList[k])); - } - triggerAndGetExtCodeHashList(addressList, user001Address, user001Key, feeLimit, stub); - } - - @Test(enabled = true, description = "Trigger normal contract stress.") - public void test06TriggerNormalContract() throws FileNotFoundException { - - BufferedReader reader = null; - List addresses = new ArrayList<>(); - try { - reader = new BufferedReader(new FileReader( - "src/test/resources/address2")); - String line = reader.readLine(); - while (line != null) { - System.out.println(line); - // read next line - line = reader.readLine(); - addresses.add(line); - } - reader.close(); - } catch (IOException e) { - e.printStackTrace(); - } - ExecutorService pool = Executors.newFixedThreadPool(50); - int stubSize = 50; - List stubs = new ArrayList<>(); - for (int i = 0; i < stubSize; i++) { - stubs.add(WalletGrpc.newBlockingStub(channelFull)); - } - - int paramsSize = 50; - int trigger = 0; - for (int i = 0; i + paramsSize < addresses.size(); i += 1) { - System.err.println(trigger++); - System.err.println(i + " " + (i + paramsSize)); - pool.submit( - new TriggerNormalTask(addresses.subList(0, 0 + paramsSize), stubs.get( - (int) (Math.random() * 100 % stubSize)))); - } - - try { - Thread.sleep(100000000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - /** - * trigger. - */ - public void triggerNormalContact(String[] testList, WalletGrpc.WalletBlockingStub stub) { - - final byte[] user001Address = fromAddress; - final String user001Key = testKey002; - - normalContractAddress = WalletClient - .decodeFromBase58Check("TFUSarvJtCSQhDifdRaioytThohLSLCjq4"); - - final long feeLimit = 51079600; - count.getAndAdd(1); - if (count.get() % 100 == 0) { - long cost = (System.currentTimeMillis() - startTime) / 1000; - logger.info("Count:" + count.get() + ", cost:" + cost - + ", avg:" + count.get() / cost + ", errCount:" + errorCount); - } - - List addressList = new ArrayList<>(); - - for (int k = 0; k < testList.length; k++) { - addressList.add(WalletClient.decodeFromBase58Check(testList[k])); - } - - triggerAndGetExtCodeHash(normalContractAddress, user001Address, - user001Key, feeLimit, stub); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - class DeployTask implements Runnable { - - Map addressList; - CountDownLatch countDownLatch; - WalletGrpc.WalletBlockingStub stub; - int index; - - DeployTask(Map addressList, int index, CountDownLatch countDownLatch, - WalletGrpc.WalletBlockingStub stub) { - this.index = index; - this.addressList = addressList; - this.countDownLatch = countDownLatch; - this.stub = stub; - } - - @Override - public void run() { - logger.info("depoying :" + index); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_veryLarge"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_veryLarge"); - try { - byte[] deployedAddress = deployContract(code, abi, "test" + index, stub); - String address = Base58.encode58Check(deployedAddress); - wirteLine( - "src/test/resources/addresses2", - address); - logger.info("deployed : " + index + " " + address); - } catch (Throwable e) { - logger.error("deploy error: ", e); - } finally { - countDownLatch.countDown(); - } - } - } - - class CheckTask implements Runnable { - - String txid; - WalletGrpc.WalletBlockingStub client; - - CheckTask(String txid, WalletGrpc.WalletBlockingStub client) { - this.txid = txid; - this.client = client; - } - - @Override - public void run() { - - Optional infoById = PublicMethed - .getTransactionInfoById(this.txid, blockingStubFull); - - TransactionInfo transactionInfo = infoById.get(); - if (infoById.get().getResultValue() != 0) { - logger.error("txid:" + this.txid); - logger.error( - "transaction failed with message: " + infoById.get().getResMessage().toStringUtf8()); - } - logger.info("infoById" + infoById); - } - } - - class TriggerTask implements Runnable { - - List addresses; - WalletGrpc.WalletBlockingStub stub; - - TriggerTask(List addresses, WalletGrpc.WalletBlockingStub stub) { - this.addresses = addresses; - this.stub = stub; - } - - @Override - public void run() { - triggerContact(this.addresses.toArray(new String[0]), stub); - } - } - - class TriggerNormalTask implements Runnable { - - List addresses; - WalletGrpc.WalletBlockingStub stub; - - TriggerNormalTask(List addresses, WalletGrpc.WalletBlockingStub stub) { - this.addresses = addresses; - this.stub = stub; - } - - @Override - public void run() { - triggerNormalContact(this.addresses.toArray(new String[0]), stub); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/HttpStressTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/HttpStressTest.java deleted file mode 100644 index 7a1fd953fb7..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/HttpStressTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.params.CoreConnectionPNames; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class HttpStressTest { - - private static final long now = System.currentTimeMillis(); - private static final long totalSupply = 10000000000000000L; - static Integer connectionTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpConnectionTimeout"); - static Integer soTimeout = Configuration.getByPath("testng.conf") - .getInt("defaultParameter.httpSoTimeout"); - private static String name = "testAssetIssue002_" + Long.toString(now); - private static String assetIssueId1; - private static String assetIssueId2; - private static Integer exchangeId; - private static Long beforeInjectBalance; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchangeOwnerAddress = ecKey1.getAddress(); - String exchangeOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] asset2Address = ecKey2.getAddress(); - String asset2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Long amount = 2048000000L; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private JSONObject responseContent; - private HttpResponse response; - private String httpnode = Configuration.getByPath("testng.conf").getStringList("httpnode.ip.list") - .get(0); - - /** - * constructor. - */ - @Test(enabled = true, threadPoolSize = 10, invocationCount = 10) - public void test4InjectExchange() { - final long now = System.currentTimeMillis(); - final long totalSupply = 10000000000000000L; - Long beforeInjectBalance; - HttpClient httpClient = new DefaultHttpClient(); - HttpPost httppost; - httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, - connectionTimeout); - httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, soTimeout); - httppost = new HttpPost(url); - httppost.setHeader("Content-type", "application/json; charset=utf-8"); - httppost.setHeader("Connection", "Close"); - - response = HttpMethed - .sendCoin(httpnode, fromAddress, exchangeOwnerAddress, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - response = HttpMethed.sendCoin(httpnode, fromAddress, asset2Address, amount, testKey002); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - //Create an asset issue - response = HttpMethed.assetIssue(httpnode, exchangeOwnerAddress, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, - 2, 3, description, url, 1000L, 1000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - response = HttpMethed.assetIssue(httpnode, asset2Address, name, name, totalSupply, 1, 1, - System.currentTimeMillis() + 5000, System.currentTimeMillis() + 50000000, - 2, 3, description, url, 1000L, 1000L, asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, exchangeOwnerAddress); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId1 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId1) > 1000000); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.getAccount(httpnode, asset2Address); - responseContent = HttpMethed.parseResponseContent(response); - assetIssueId2 = responseContent.getString("asset_issued_ID"); - Assert.assertTrue(Integer.parseInt(assetIssueId2) > 1000000); - - response = HttpMethed - .transferAsset(httpnode, asset2Address, exchangeOwnerAddress, assetIssueId2, - 100000000000000L, asset2Key); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - - //Create exchange. - response = HttpMethed.exchangeCreate(httpnode, exchangeOwnerAddress, assetIssueId1, - 50000000000000L, assetIssueId2, 50000000000000L, exchangeOwnerKey); - Assert.assertTrue(HttpMethed.verificationResult(response)); - - HttpMethed.waitToProduceOneBlock(httpnode); - HttpMethed.waitToProduceOneBlock(httpnode); - response = HttpMethed.listExchanges(httpnode); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - JSONArray jsonArray = JSONArray.parseArray(responseContent.getString("exchanges")); - Assert.assertTrue(jsonArray.size() >= 1); - exchangeId = jsonArray.size(); - - response = HttpMethed.getExchangeById(httpnode, exchangeId); - responseContent = HttpMethed.parseResponseContent(response); - HttpMethed.printJsonContent(responseContent); - - Integer times = 0; - while (times++ <= 10000) { - HttpMethed.sendCoin(httpnode, fromAddress, exchangeOwnerAddress, 100L, testKey002); - HttpMethed.sendCoin(httpnode, fromAddress, asset2Address, 100L, testKey002); - //Inject exchange. - HttpMethed.exchangeInject(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, - 10L, exchangeOwnerKey); - HttpMethed.exchangeWithdraw(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, - 10L, exchangeOwnerKey); - HttpMethed.exchangeTransaction(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId1, - 100L, 1L, exchangeOwnerKey); - HttpMethed.exchangeTransaction(httpnode, exchangeOwnerAddress, exchangeId, assetIssueId2, - 100L, 1L, exchangeOwnerKey); - HttpMethed.transferAsset(httpnode, asset2Address, exchangeOwnerAddress, assetIssueId2, - 1L, asset2Key); - HttpMethed.transferAsset(httpnode, exchangeOwnerAddress, asset2Address, assetIssueId1, - 1L, exchangeOwnerKey); - HttpMethed.participateAssetIssue(httpnode, exchangeOwnerAddress, asset2Address, - assetIssueId1, 1L, asset2Key); - HttpMethed.participateAssetIssue(httpnode, asset2Address, exchangeOwnerAddress, - assetIssueId2, 1L, exchangeOwnerKey); - HttpMethed.freezeBalance(httpnode, fromAddress, 10000000000L, 0, 0, - exchangeOwnerAddress, testKey002); - HttpMethed.freezeBalance(httpnode, fromAddress, 10000000000L, 0, 1, - exchangeOwnerAddress, testKey002); - HttpMethed.unFreezeBalance(httpnode, fromAddress, 0, exchangeOwnerAddress, testKey002); - HttpMethed.unFreezeBalance(httpnode, fromAddress, 1, exchangeOwnerAddress, testKey002); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - HttpMethed.disConnect(); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetTransferSendOrAsset.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetTransferSendOrAsset.java deleted file mode 100644 index b0f90198084..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetTransferSendOrAsset.java +++ /dev/null @@ -1,153 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class MainNetTransferSendOrAsset { - - //testng001、testng002、testng003、testng004 - //fromAssetIssue - private final String testKey001 = - "BC70ADC5A0971BA3F7871FBB7249E345D84CE7E5458828BE1E28BF8F98F2795B"; - //toAssetIssue - private final String testKey002 = - "F153A0E1A65193846A3D48A091CD0335594C0A3D9817B3441390FDFF71684C84"; - //fromSend - private final String testKey003 = - "2514B1DD2942FF07F68C2DDC0EE791BC7FBE96FDD95E89B7B9BB3B4C4770FFAC"; - //toSend - private final String testKey004 = - "56244EE6B33C14C46704DFB67ED5D2BBCBED952EE46F1FD88A50C32C8C5C64CE"; - //Default - private final String defaultKey = - "8DFBB4513AECF779A0803C7CEBF2CDCC51585121FAB1E086465C4E0B40724AF1"; - - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey001); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] fromSendAddress = PublicMethed.getFinalAddress(testKey003); - private final byte[] toSendAddress = PublicMethed.getFinalAddress(testKey004); - private final byte[] defaultAddress = PublicMethed.getFinalAddress(defaultKey); - - - private final Long transferAmount = 1L; - private final Long sendAmount = 1L; - private Long start; - private Long end; - private Long beforeToBalance; - private Long afterToBalance; - private Long beforeToAssetBalance = 0L; - private Long afterToAssetBalance = 0L; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Account fromAccount = PublicMethed.queryAccount(testKey001, blockingStubFull); - Account toAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - if (fromAccount.getBalance() < 10000000000L) { - PublicMethed - .sendcoin(fromAddress, 10000000000L, defaultAddress, defaultKey, blockingStubFull); - } - if (fromAccount.getAssetCount() == 0) { - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - PublicMethed.createAssetIssue(fromAddress, "testNetAsset", 1000000000000L, - 1, 1, start, end, 1, "wwwwww", "wwwwwwww", 100000L, - 100000L, 1L, 1L, testKey001, blockingStubFull); - } - beforeToBalance = toAccount.getBalance(); - beforeToAssetBalance = toAccount.getAssetMap().get("testNetAsset"); - - Account fromSendAccount = PublicMethed.queryAccount(testKey003, blockingStubFull); - Account toSendAccount = PublicMethed.queryAccount(testKey004, blockingStubFull); - if (fromSendAccount.getBalance() < 1000000000L) { - PublicMethed - .sendcoin(fromSendAddress, 1000000000L, defaultAddress, defaultKey, blockingStubFull); - } - beforeToBalance = toAccount.getBalance(); - logger.info("Before From account balance is " + Long.toString(fromAccount.getBalance())); - logger.info("Before To account balance is " + Long.toString(toAccount.getBalance())); - start = System.currentTimeMillis(); - } - - @Test(enabled = false, threadPoolSize = 20, invocationCount = 100000) - public void freezeAnd() throws InterruptedException { - Random rand = new Random(); - Integer randNum = 0; - randNum = rand.nextInt(1000); - try { - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - Integer i = 0; - while (i < 60) { - PublicMethed - .transferAsset(toAddress, "testNetAsset".getBytes(), transferAmount, fromAddress, - testKey001, blockingStubFull); - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - PublicMethed.sendcoin(toSendAddress, sendAmount, fromSendAddress, testKey003, - blockingStubFull); - try { - Thread.sleep(200); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - end = System.currentTimeMillis(); - logger.info("Time is " + Long.toString(end - start)); - Account fromAccount = PublicMethed.queryAccount(testKey001, blockingStubFull); - Account toAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - afterToBalance = toAccount.getBalance(); - afterToAssetBalance = toAccount.getAssetMap().get("testNetAsset"); - - logger.info("Success times is " + Long.toString(afterToAssetBalance - beforeToAssetBalance)); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetVoteOrFreezeOrCreate.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetVoteOrFreezeOrCreate.java deleted file mode 100644 index 93abe8957b9..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MainNetVoteOrFreezeOrCreate.java +++ /dev/null @@ -1,359 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.GrpcAPI.WitnessList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class MainNetVoteOrFreezeOrCreate { - - private static final long now = System.currentTimeMillis(); - private static String name = "mainNetAsset_" + Long.toString(now); - //testng001、testng002、testng003、testng004 - //Devaccount - private final String testKey001 = - "2514B1DD2942FF07F68C2DDC0EE791BC7FBE96FDD95E89B7B9BB3B4C4770FFAC"; - //Zion - private final String testKey002 = - "56244EE6B33C14C46704DFB67ED5D2BBCBED952EE46F1FD88A50C32C8C5C64CE"; - //Default - private final String defaultKey = - //Mainet - //"8DFBB4513AECF779A0803C7CEBF2CDCC51585121FAB1E086465C4E0B40724AF1"; - //Beta Env - "6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey001); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey002); - private final byte[] defaultAddress = PublicMethed.getFinalAddress(defaultKey); - private final Long sendAmount = 1026000000L; - long totalSupply = now; - Long freeAssetNetLimit = 30000L; - Long publicFreeAssetNetLimit = 30000L; - String description = "f"; - String url = "h"; - Long startTime; - Long endTime; - Boolean ret = false; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] asset016Address = ecKey1.getAddress(); - String testKeyForAssetIssue016 = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long start; - private Long end; - private Long beforeToBalance; - private Long afterToBalance; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - /** - * constructor. - */ - - public static Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - Protocol.Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddress = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddress).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - return true; - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - startTime = System.currentTimeMillis(); - } - - //@Test(enabled = false) - @Test(enabled = false, threadPoolSize = 2, invocationCount = 2) - public void freezeAndSendcoin() throws InterruptedException { - Random rand = new Random(); - Integer randNum = 0; - randNum = rand.nextInt(1000); - try { - Thread.sleep(randNum); - } catch (InterruptedException e) { - e.printStackTrace(); - } - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - Integer i = 0; - while (i++ < 3) { - ret = false; - Integer waitTime = 10; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] accountAddress = ecKey1.getAddress(); - String testKeyAccount = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - logger.info(Base58.encode58Check(accountAddress)); - logger.info(testKeyAccount); - Integer tryTimes = 0; - - while (!ret) { - ret = PublicMethed - .createAccount(defaultAddress, accountAddress, defaultKey, blockingStubFull); - logger.info("createAccount"); - - if (tryTimes++ == 10) { - break; - } - } - - ret = false; - while (!ret) { - ret = PublicMethed - .sendcoin(accountAddress, sendAmount, defaultAddress, defaultKey, blockingStubFull); - logger.info("sendcoin"); - } - ret = false; - while (!ret) { - name = "mainNetAsset_" + Long.toString(System.currentTimeMillis()); - totalSupply = System.currentTimeMillis(); - start = System.currentTimeMillis() + 2000; - end = System.currentTimeMillis() + 1000000000; - ret = PublicMethed.createAssetIssue(accountAddress, name, totalSupply, 1, 1, start, end, - 1, description, url, 3000L, 3000L, 1L, 1L, - testKeyAccount, blockingStubFull); - logger.info("createAssetIssue"); - } - ret = false; - while (!ret) { - ret = freezeBalance(accountAddress, 1000000L, 3, testKeyAccount, - blockingStubFull); - logger.info("freezeBalance"); - } - /* ret = false; - while (!ret) { - ret = PublicMethed - .transferAsset(toAddress, name.getBytes(), 10L, accountAddress, testKeyAccount, - blockingStubFull); - logger.info("transferAsset"); - }*/ - ret = false; - while (!ret) { - String voteStr = Base58 - .encode58Check(result.get().getWitnesses(i % 5).getAddress().toByteArray()); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - ret = voteWitness(smallVoteMap, accountAddress, testKeyAccount); - logger.info("voteWitness"); - } - } - } - - /** - * constructor. - */ - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - endTime = System.currentTimeMillis(); - logger.info("Time is " + Long.toString(endTime - startTime)); - Account fromAccount = PublicMethed.queryAccount(testKey001, blockingStubFull); - Account toAccount = PublicMethed.queryAccount(testKey002, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - WitnessContract.VoteWitnessContract.Builder builder = WitnessContract.VoteWitnessContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - WitnessContract.VoteWitnessContract.Vote.Builder voteBuilder = WitnessContract - .VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address = " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - WitnessContract.VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - //logger.info("transaction == null,\n contract:{},\n transaction:{}" , contract.toString(), - // transaction.toString()); - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - //logger.info(response.getCode().toString()); - return false; - } - /* try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - return true; - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MultiValiSignPerformanceTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MultiValiSignPerformanceTest.java deleted file mode 100644 index 58c07f830f8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MultiValiSignPerformanceTest.java +++ /dev/null @@ -1,336 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.StringUtil; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class MultiValiSignPerformanceTest { - - private final String fromKey = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(fromKey); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] contractDepAddress = ecKey1.getAddress(); - String contractDepKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] nonexistentAddress = ecKey2.getAddress(); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private byte[] ecrecoverContractAddress = null; - private byte[] multiValiSignContractAddress = null; - - @BeforeSuite - public void beforeSuite() { - Wallet wallet = new Wallet(); - Wallet.setAddressPreFixByte(Parameter.CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(contractDepKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - - @Test(enabled = true, description = "deploy ecrecover contract") - public void test01DeployEcrecoverContract() { - Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(contractDepAddress, contractDepKey, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(contractDepAddress), fromKey, blockingStubFull)); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contractDepAddress, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "src/test/resources/soliditycode/multiValiSignPerformance01.sol"; - String contractName = "ecrecoverValidateSign"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, contractDepKey, - contractDepAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(contractDepAddress, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - ecrecoverContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("ecrecoverContractAddress:" + infoById.get().getContractAddress()); - SmartContract smartContract = PublicMethed.getContract(ecrecoverContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "deploy multvalisign contract") - public void test02DeployMultvalisignContract() { - Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceForReceiver(fromAddress, - PublicMethed.getFreezeBalanceCount(contractDepAddress, contractDepKey, 170000L, - blockingStubFull), 0, 1, - ByteString.copyFrom(contractDepAddress), fromKey, blockingStubFull)); - - //before deploy, check account resource - AccountResourceMessage accountResource = PublicMethed.getAccountResource(contractDepAddress, - blockingStubFull); - long energyLimit = accountResource.getEnergyLimit(); - long energyUsage = accountResource.getEnergyUsed(); - long balanceBefore = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - logger.info("before energyLimit is " + Long.toString(energyLimit)); - logger.info("before energyUsage is " + Long.toString(energyUsage)); - logger.info("before balanceBefore is " + Long.toString(balanceBefore)); - - String filePath = "src/test/resources/soliditycode/multiValiSignPerformance02.sol"; - String contractName = "multiValidateSignContract"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - - final String transferTokenTxid = PublicMethed - .deployContractAndGetTransactionInfoById(contractName, abi, code, "", - maxFeeLimit, 0L, 0, 10000, - "0", 0, null, contractDepKey, - contractDepAddress, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - accountResource = PublicMethed.getAccountResource(contractDepAddress, blockingStubFull); - energyLimit = accountResource.getEnergyLimit(); - energyUsage = accountResource.getEnergyUsed(); - long balanceAfter = PublicMethed.queryAccount(contractDepKey, blockingStubFull).getBalance(); - - logger.info("after energyLimit is " + Long.toString(energyLimit)); - logger.info("after energyUsage is " + Long.toString(energyUsage)); - logger.info("after balanceAfter is " + Long.toString(balanceAfter)); - - Optional infoById = PublicMethed - .getTransactionInfoById(transferTokenTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - Assert.fail("deploy transaction failed with message: " + infoById.get().getResMessage()); - } - - TransactionInfo transactionInfo = infoById.get(); - logger.info("EnergyUsageTotal: " + transactionInfo.getReceipt().getEnergyUsageTotal()); - logger.info("NetUsage: " + transactionInfo.getReceipt().getNetUsage()); - - multiValiSignContractAddress = infoById.get().getContractAddress().toByteArray(); - logger.info("multiValiSignContractAddress:" + infoById.get().getContractAddress()); - SmartContract smartContract = PublicMethed.getContract(multiValiSignContractAddress, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - } - - @Test(enabled = true, description = "trigger ecrecover contract test") - public void test03triggerEcrecoverContract() { - /*Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - try { - Thread.sleep(new Long(30000)); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - byte[] hash = ByteArray - .fromHexString("7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e"); - logger.info("hash:" + Hex.toHexString(hash)); - int cnt = 15; - for (int i = 0; i < cnt; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - - String txid = ""; - long start = System.currentTimeMillis(); - txid = PublicMethed - .triggerContract(PublicMethed.decode58Check("TDgdUs1gmn1JoeGMqQGkkxE1pcMNSo8kFj"), - "validateSign(bytes32,bytes[],address[])", input, - false, 0, maxFeeLimit, contractDepAddress, contractDepKey, blockingStubFull); - long timeCosts = System.currentTimeMillis() - start; - logger.info( - "Ecrecover--cnt:" + cnt + ",timeCost:" + timeCosts + ",ms:" + (timeCosts * 1.0 / cnt)); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - - @Test(enabled = true, description = "trigger mulivalisign contract test") - public void test04triggerMuliValiSignContract() { - /*Assert.assertTrue(PublicMethed.sendcoin(contractDepAddress, 1000_000_000L, fromAddress, - fromKey, blockingStubFull)); - try { - Thread.sleep(new Long(30000)); - } catch (InterruptedException e) { - e.printStackTrace(); - }*/ - List signatures = new ArrayList<>(); - List addresses = new ArrayList<>(); - - byte[] hash = ByteArray - .fromHexString("7d889f42b4a56ebe78264631a3b4daf21019e1170cce71929fb396761cdf532e"); - logger.info("hash:" + Hex.toHexString(hash)); - int cnt = 15; - for (int i = 0; i < cnt; i++) { - ECKey key = new ECKey(); - byte[] sign = key.sign(hash).toByteArray(); - signatures.add(Hex.toHexString(sign)); - addresses.add(StringUtil.encode58Check(key.getAddress())); - } - List parameters = Arrays.asList("0x" + Hex.toHexString(hash), signatures, addresses); - String[] inputArr = new String[parameters.size()]; - int i = 0; - for (Object parameter : parameters) { - if (parameter instanceof List) { - StringBuilder sb = new StringBuilder(); - for (Object item : (List) parameter) { - if (sb.length() != 0) { - sb.append(","); - } - sb.append("\"").append(item).append("\""); - } - inputArr[i++] = "[" + sb.toString() + "]"; - } else { - inputArr[i++] = - (parameter instanceof String) ? ("\"" + parameter + "\"") : ("" + parameter); - } - } - String input = StringUtils.join(inputArr, ','); - - String txid = ""; - long start = System.currentTimeMillis(); - txid = PublicMethed - .triggerContract(PublicMethed.decode58Check("TVpTLZbBbP82aufo7p3qmb4ELiowH3mjQW"), - "testArray(bytes32,bytes[],address[])", input, false, - 0, maxFeeLimit, contractDepAddress, contractDepKey, blockingStubFull); - long timeCosts = System.currentTimeMillis() - start; - logger.info( - "MuliValiSign--cnt:" + cnt + ",timeCost:" + timeCosts + ",ms:" + (timeCosts * 1.0 / cnt)); - Optional infoById = null; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/MutiSignStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/MutiSignStress.java deleted file mode 100644 index 31516dc18d8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/MutiSignStress.java +++ /dev/null @@ -1,143 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class MutiSignStress { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 20, invocationCount = 20) - public void testMutiSignForAccount() { - Integer i = 0; - while (i < 20) { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - manager2Address = ecKey2.getAddress(); - manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - PublicMethed.printAddress(ownerKey); - - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - PublicMethed.sendcoin(ownerAddress, 4000000L, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(ownerAddress, 4000000L, fromAddress, testKey002, - blockingStubFull); - PublicMethed.sendcoin(ownerAddress, 4000000L, fromAddress, testKey002, - blockingStubFull); - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = ownerKey; - accountPermissionJson = "[{\"keys\":[{\"address\":\"" - + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":2}],\"name\":\"owner\",\"threshold\":2,\"parent\":\"owner\"}," - + "{\"parent\":\"owner\",\"keys\":[{\"address\":\"" - + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1},{\"address\":\"" - + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}],\"name\":\"active\"," - + "\"threshold\":2}]"; - //logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - String updateName = Long.toString(System.currentTimeMillis()); - - PublicMethedForMutiSign.sendcoin(newAddress, 1000000L, ownerAddress, ownerKey, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.sendcoin(newAddress, 1000000L, ownerAddress, ownerKey, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.sendcoin(newAddress, 1000000L, ownerAddress, ownerKey, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.freezeBalance(ownerAddress, 1000000L, 0, - ownerKey, blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.freezeBalance(ownerAddress, 1000000L, 0, - ownerKey, blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.freezeBalance(ownerAddress, 1000000L, 0, - ownerKey, blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.unFreezeBalance(ownerAddress, ownerKey, 0, null, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.unFreezeBalance(ownerAddress, ownerKey, 0, null, - blockingStubFull, permissionKeyString); - PublicMethedForMutiSign.unFreezeBalance(ownerAddress, ownerKey, 0, null, - blockingStubFull, permissionKeyString); - } - - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ScanBlockTools.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ScanBlockTools.java deleted file mode 100644 index a04dbc86262..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ScanBlockTools.java +++ /dev/null @@ -1,1100 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONArray; -import com.alibaba.fastjson.JSONObject; -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.TransactionInfoList; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.Base58; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Account.AccountResource; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.Transaction.Contract.ContractType; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AccountContract.AccountCreateContract; -import org.tron.protos.contract.AccountContract.AccountPermissionUpdateContract; -import org.tron.protos.contract.AssetIssueContractOuterClass.TransferAssetContract; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.TransferContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.WithdrawBalanceContract; -import org.tron.protos.contract.SmartContractOuterClass.CreateSmartContract; -import org.tron.protos.contract.SmartContractOuterClass.TriggerSmartContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.Sha256Sm3Hash; - -@Slf4j -public class ScanBlockTools { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - private final byte[] testAddress003 = PublicMethed.getFinalAddress(testKey003); - - private final String testKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private final byte[] testAddress004 = PublicMethed.getFinalAddress(testKey004); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = "39.106.110.245:50051"; - private String fullnode1 = "39.106.110.245:50051"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - PublicMethed.printAddress(testKey003); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - currentBlock = blockingStubFull1.getNowBlock(EmptyMessage.newBuilder().build()); - beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - beforeTime = System.currentTimeMillis(); - } - - public static List listForTxid = new ArrayList<>(); - public static HashMap map = new HashMap<>(); - public static HashMap witnessMap = new HashMap<>(); - - @Test(enabled = true,threadPoolSize = 1, invocationCount = 1) - public void test01ScanTransaction() { - getTxidList(); - witnessMap.clear(); - map.clear(); - witnessMap.put(5,"41F08012B4881C320EB40B80F1228731898824E09D"); - witnessMap.put(10,"41DF309FEF25B311E7895562BD9E11AAB2A58816D2"); - witnessMap.put(15,"41BB7322198D273E39B940A5A4C955CB7199A0CDEE"); - witnessMap.put(20,"412080D8A0364E82150DD5235CE7A61A7B40F3F9EF"); - witnessMap.put(25,"4173FC381D3E2AFEFCCED94A57D49520291C38AFBB"); - witnessMap.put(30,"41AF6146B0AD9EE8BBEE811D5858F3252666DFC90C"); - witnessMap.put(35,"41AF6A9D9C0636BD9DF74F687B90C6F44C471A6AB3"); - witnessMap.put(40,"41AF730429E4AB7BF7B53FB15ACB1D45EF5B22F463"); - witnessMap.put(45,"41AF4AEA1C4CBCFA681D98C354C142938381C99389"); - witnessMap.put(50,"41AF53DC31D9DE64DFF59A847125EFCA89D97BC86D"); - witnessMap.put(55,"41AF49468FA1BA966244D76F7D0139FC2CA751FAA5"); - witnessMap.put(60,"41AF5360256F958D2A922D160C429F13D432EFC22F"); - witnessMap.put(65,"41AF5EF33FD79FECB0419A5688035D7BCD3AEFE236"); - witnessMap.put(70,"41AF68F90ED62BA9F6F7A7EABA384E417551CF83E5"); - witnessMap.put(75,"41AF619F8CE75A9E95A19E851BEBE63E89FCB1826E"); - witnessMap.put(80,"41AF71E98F91515D7E5D5379837B9EEFD1AB4650D2"); - witnessMap.put(85,"41AF498B43EE098B26926798CFEAE1AB1154EF4430"); - witnessMap.put(90,"41AF536672333170CB0FBFA78819CD90A05537D872"); - witnessMap.put(95,"41AF5FAC2D62DD1F5C9892BA9D6593337ABBEAAACB"); - witnessMap.put(100,"41AF6981D4562E7B0A6C9E8F8C22D4CCCD03D2F39A"); - witnessMap.put(105,"41AF72A34243836238A533B7E77F3B2B29FD056B14"); - witnessMap.put(110,"41AF49C25D14AED36186B7C89AF405EF37A01EF23D"); - witnessMap.put(115,"41AF53BA37D394575CAD99A2A2C5BE56DEA0227C87"); - witnessMap.put(120,"41AF6A761C941AE2CDC75890D9900AC4B89B7EFCDD"); - witnessMap.put(125,"41AF72B56845F0C4D37388B6E6DC3601A0538ABA71"); - witnessMap.put(130,"41AF4ACF25C1E192285C9BA98522CB3CF20FFBE392"); - witnessMap.put(100000,"416C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - - - - for (String txid : listForTxid) { - - long blockNum = PublicMethed.getTransactionInfoById(txid,blockingStubFull) - .get().getBlockNumber(); - String witnessAddress = ByteArray.toHexString(PublicMethed - .getBlock(blockNum,blockingStubFull).getBlockHeader().getRawData() - .getWitnessAddress().toByteArray()); - - map.put(witnessAddress.toLowerCase(), map.getOrDefault(witnessAddress,0) + 1); - logger.info("end"); - } - - } - - - - - @Test(enabled = true,threadPoolSize = 1, invocationCount = 1) - public void test02ScanBlockGetTransactionAndWriteToCsv() { - witnessMap.clear(); - map.clear(); - witnessMap.put(5,"41F08012B4881C320EB40B80F1228731898824E09D"); - witnessMap.put(10,"41DF309FEF25B311E7895562BD9E11AAB2A58816D2"); - witnessMap.put(15,"41BB7322198D273E39B940A5A4C955CB7199A0CDEE"); - witnessMap.put(20,"412080D8A0364E82150DD5235CE7A61A7B40F3F9EF"); - witnessMap.put(25,"4173FC381D3E2AFEFCCED94A57D49520291C38AFBB"); - witnessMap.put(30,"41AF6146B0AD9EE8BBEE811D5858F3252666DFC90C"); - witnessMap.put(35,"41AF6A9D9C0636BD9DF74F687B90C6F44C471A6AB3"); - witnessMap.put(40,"41AF730429E4AB7BF7B53FB15ACB1D45EF5B22F463"); - witnessMap.put(45,"41AF4AEA1C4CBCFA681D98C354C142938381C99389"); - witnessMap.put(50,"41AF53DC31D9DE64DFF59A847125EFCA89D97BC86D"); - witnessMap.put(55,"41AF49468FA1BA966244D76F7D0139FC2CA751FAA5"); - witnessMap.put(60,"41AF5360256F958D2A922D160C429F13D432EFC22F"); - witnessMap.put(65,"41AF5EF33FD79FECB0419A5688035D7BCD3AEFE236"); - witnessMap.put(70,"41AF68F90ED62BA9F6F7A7EABA384E417551CF83E5"); - witnessMap.put(75,"41AF619F8CE75A9E95A19E851BEBE63E89FCB1826E"); - witnessMap.put(80,"41AF71E98F91515D7E5D5379837B9EEFD1AB4650D2"); - witnessMap.put(85,"41AF498B43EE098B26926798CFEAE1AB1154EF4430"); - witnessMap.put(90,"41AF536672333170CB0FBFA78819CD90A05537D872"); - witnessMap.put(95,"41AF5FAC2D62DD1F5C9892BA9D6593337ABBEAAACB"); - witnessMap.put(100,"41AF6981D4562E7B0A6C9E8F8C22D4CCCD03D2F39A"); - witnessMap.put(105,"41AF72A34243836238A533B7E77F3B2B29FD056B14"); - witnessMap.put(110,"41AF49C25D14AED36186B7C89AF405EF37A01EF23D"); - witnessMap.put(115,"41AF53BA37D394575CAD99A2A2C5BE56DEA0227C87"); - witnessMap.put(120,"41AF6A761C941AE2CDC75890D9900AC4B89B7EFCDD"); - witnessMap.put(125,"41AF72B56845F0C4D37388B6E6DC3601A0538ABA71"); - witnessMap.put(130,"41AF4ACF25C1E192285C9BA98522CB3CF20FFBE392"); - witnessMap.put(100000,"416C0214C9995C6F3A61AB23F0EB84B0CDE7FD9C7C"); - - - Long startNum = 30855000L; - Long endNum = 30858000L; - - Integer totalNum = 0; - Integer successNum = 0; - Integer failedNum = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (endNum >= startNum) { - logger.info("scan block num:" + endNum); - builder.setNum(endNum); - Block block = blockingStubFull1.getBlockByNum(builder.build()); - List transactionList = block.getTransactionsList(); - map.put(ByteArray.toHexString(block.getBlockHeader().getRawData().getWitnessAddress() - .toByteArray()).toLowerCase(), - map.getOrDefault(ByteArray.toHexString(block.getBlockHeader().getRawData() - .getWitnessAddress().toByteArray()).toLowerCase(),0) + 1); - Integer transactionNumInThisBlock = transactionList.size(); - totalNum = totalNum + transactionNumInThisBlock; - for (Transaction transaction : transactionList) { - String txid = ByteArray.toHexString(Sha256Hash.hash(true, - transaction.getRawData().toByteArray())); - //String writeData = ByteArray.toHexString(Sha256Hash.hash(true, - // transaction.getRawData().toByteArray())); - writeDataToCsvFile("txid-stressss.csv",txid); - //System.out.println("Fee:" + PublicMethed.getTransactionInfoById(txid, - // blockingStubFull).get().getFee()); - } - for (Transaction transaction : transactionList) { - if (transaction.getRet(0).getContractRet().name().equals("SUCCESS")) { - successNum++; - } else { - failedNum++; - - String writeData = ByteArray.toHexString(Sha256Hash.hash(true, - transaction.getRawData().toByteArray())); - logger.info(writeData); - writeDataToCsvFile("28164160L-28167324L.csv",writeData); - } - } - endNum--; - } - - logger.info("successNum:" + successNum); - logger.info("failedNum:" + failedNum); - logger.info("totalNum:" + totalNum); - logger.info("Success rate:" + (double)failedNum / (double)totalNum); - - - } - - public static Account account; - public HashSet addressSet = new HashSet<>(); - public HashSet assetIssueSet = new HashSet<>(); - - @Test(enabled = true, description = "Get account from transaction and compare " - + "account info from two different node") - public void test03CompareTwoNodeAccountStatus() throws Exception { - account = PublicMethed.queryAccount( - "7400E3D0727F8A61041A8E8BF86599FE5597CE19DE451E59AED07D60967A5E25",blockingStubFull); - //扫描到28307530块了 - Long startNum = 29266108L; - Long endNum = 29266208L; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - int retryTimes = 0; - HashSet set = new HashSet<>(); - while (startNum++ <= endNum) { - //Block block = blockingStubFull412.getNowBlock(EmptyMessage.newBuilder().build()); - builder.setNum(startNum); - Block block = blockingStubFull.getBlockByNum(builder.build()); - logger.info("Start to scan block :" + block.getBlockHeader().getRawData().getNumber()); - - List transactionList = block.getTransactionsList(); - for (Transaction transaction : transactionList) { - - Any any = transaction.getRawData().getContract(0).getParameter(); - Integer contractType = transaction.getRawData().getContract(0).getType().getNumber(); - - - try { - switch (contractType) { - case 1: - TransferContract transferContract = any.unpack(TransferContract.class); - set.add(transferContract.getOwnerAddress()); - break; - case 2: - TransferAssetContract transferAssetContract = any.unpack(TransferAssetContract.class); - doCheck(transferAssetContract.getOwnerAddress()); - if (!addressSet.contains(transferAssetContract.getAssetName())) { - Assert.assertEquals(PublicMethed.getAssetIssueById(ByteArray - .toStr(transferAssetContract.getAssetName().toByteArray()), - blockingStubFull), - PublicMethed.getAssetIssueById(ByteArray.toStr(transferAssetContract - .getAssetName().toByteArray()), blockingStubFull)); - addressSet.add(transferAssetContract.getAssetName()); - logger.info("check token " + ByteArray.toStr(transferAssetContract - .getAssetName().toByteArray()) + " successfully"); - } - break; - case 31: - TriggerSmartContract triggerSmartContract = any.unpack(TriggerSmartContract.class); - doCheck(triggerSmartContract.getOwnerAddress()); - break; - case 13: - WithdrawBalanceContract withdrawBalanceContract - = any.unpack(WithdrawBalanceContract.class); - doCheck(withdrawBalanceContract.getOwnerAddress()); - break; - case 11: - FreezeBalanceContract freezeBalanceContract = any.unpack(FreezeBalanceContract.class); - doCheck(freezeBalanceContract.getOwnerAddress()); - break; - case 0: - AccountCreateContract accountCreateContract = any.unpack(AccountCreateContract.class); - doCheck(accountCreateContract.getOwnerAddress()); - break; - /* case 4: - VoteWitnessContract voteWitnessContract = any.unpack(VoteWitnessContract.class); - doCheck(voteWitnessContract.getOwnerAddress());*/ - case 12: - UnfreezeBalanceContract unfreezeBalanceContract - = any.unpack(UnfreezeBalanceContract.class); - doCheck(unfreezeBalanceContract.getOwnerAddress()); - break; - case 30: - CreateSmartContract createSmartContract = any.unpack(CreateSmartContract.class); - doCheck(createSmartContract.getOwnerAddress()); - break; - case 46: - AccountPermissionUpdateContract accountPermissionUpdateContract - = any.unpack(AccountPermissionUpdateContract.class); - doCheck(accountPermissionUpdateContract.getOwnerAddress()); - break; - default: - logger.info("Unknown type:" + contractType); - continue; - - } - } catch (Exception e) { - e.printStackTrace(); - - } - - - - - - } - } - - - } - - - @Test(enabled = true, description = "Get all info from smart contract transaction list") - public void test04GetEventTransactionAllInfoList() throws Exception { - - - - HashSet contractAndTopicList = new HashSet<>(); - - - Long startNum = 33662515L - 9500; - Long endNum = startNum - 1000; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - int retryTimes = 0; - HashSet set = new HashSet<>(); - while (startNum-- >= endNum) { - logger.info("current block num:" + startNum); - builder.setNum(startNum); - TransactionInfoList transactionInfoList = blockingStubFull - .getTransactionInfoByBlockNum(builder.build()); - - for (TransactionInfo transactionInfo : transactionInfoList.getTransactionInfoList()) { - if (!transactionInfo.getContractAddress().isEmpty() && transactionInfo.getLogCount() > 0) { - try { - String txid = ByteArray.toHexString(transactionInfo.getId().toByteArray()); - Any any = PublicMethed.getTransactionById(txid, blockingStubFull).get().getRawData() - .getContract(0).getParameter(); - TriggerSmartContract triggerSmartContract = any.unpack(TriggerSmartContract.class); - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(ByteArray.toHexString(triggerSmartContract - .getOwnerAddress().toByteArray())); - stringBuffer.append(","); - stringBuffer.append(ByteArray.toHexString(transactionInfo - .getContractAddress().toByteArray())); - stringBuffer.append(","); - stringBuffer.append(ByteArray.toHexString(triggerSmartContract - .getData().toByteArray())); - stringBuffer.append(","); - //stringBuffer.append(blockHash); - //stringBuffer.append(","); - //stringBuffer.append(startNum); - //stringBuffer.append(","); - stringBuffer.append(txid); - - - - - contractAndTopicList.add(stringBuffer.toString()); - - ; - } catch (Exception e) { - e.printStackTrace(); - - } - } - - - - - } - } - - for (String contractAddressAndTopic : contractAndTopicList) { - writeDataToCsvFile("eth_blockHash.csv", contractAddressAndTopic); - } - - - - } - - - @Test(enabled = true, description = "Get eth block query information") - public void test05CreateEthBlockHash() throws Exception { - HashSet contractAndTopicList = new HashSet<>(); - - - Long startNum = 33662515L; - Long endNum = startNum - 20000; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - int retryTimes = 0; - HashSet set = new HashSet<>(); - while (startNum-- >= endNum) { - logger.info("current block num:" + startNum); - builder.setNum(startNum); - String blockHash = ByteArray.toHexString(PublicMethed.getBlock(startNum + 1, - blockingStubFull).getBlockHeader().getRawData().getParentHash().toByteArray()); - StringBuffer stringBuffer = new StringBuffer(); - stringBuffer.append(blockHash); - stringBuffer.append(","); - stringBuffer.append(startNum); - contractAndTopicList.add(stringBuffer.toString()); - } - - for (String contractAddressAndTopic : contractAndTopicList) { - writeDataToCsvFile("eth_blockHash.csv", contractAddressAndTopic); - } - - - - } - - - ConcurrentHashMap certificationCosts = new ConcurrentHashMap<>(); - Set concurrentHashSet = certificationCosts.newKeySet(); - private static HashSet existAddress = new HashSet<>(); - List list1 = new ArrayList<>(); - - private static AtomicLong blockNum = new AtomicLong(30000523L - 20000L); - private static AtomicLong times = new AtomicLong(5); - - @Test(enabled = true, threadPoolSize = 10, invocationCount = 10) - public void test06ScanMainNetMostActiveAccounts() throws Exception { - getNowAddressList(); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - NumberMessage.Builder builder = NumberMessage.newBuilder(); - long blockNumCurrent = blockNum.getAndAdd(-200); - int times = 200; - while (times-- >= 0) { - if (concurrentHashSet.size() > 1000000) { - break; - } - //list1.add(blockNumCurrent); - builder.setNum(blockNumCurrent--); - Block block = blockingStubFull.getBlockByNum(builder.build()); - logger.info("Start to scan block :" + block.getBlockHeader().getRawData().getNumber()); - - List transactionList = block.getTransactionsList(); - for (Transaction transaction : transactionList) { - - Any any = transaction.getRawData().getContract(0).getParameter(); - Integer contractType = transaction.getRawData().getContract(0).getType().getNumber(); - - - try { - switch (contractType) { - case 1: - TransferContract transferContract = any.unpack(TransferContract.class); - isExist(transferContract.getOwnerAddress()); - isExist(transferContract.getToAddress()); - break; - case 2: - TransferAssetContract transferAssetContract = any.unpack(TransferAssetContract.class); - isExist(transferAssetContract.getOwnerAddress()); - isExist(transferAssetContract.getToAddress()); - break; - case 31: - TriggerSmartContract triggerSmartContract = any.unpack(TriggerSmartContract.class); - isExist(triggerSmartContract.getContractAddress()); - isExist(triggerSmartContract.getOwnerAddress()); - break; - case 13: - WithdrawBalanceContract withdrawBalanceContract - = any.unpack(WithdrawBalanceContract.class); - - isExist(withdrawBalanceContract.getOwnerAddress()); - break; - case 11: - FreezeBalanceContract freezeBalanceContract = any.unpack(FreezeBalanceContract.class); - isExist(freezeBalanceContract.getOwnerAddress()); - break; - case 0: - AccountCreateContract accountCreateContract = any.unpack(AccountCreateContract.class); - isExist(accountCreateContract.getOwnerAddress()); - isExist(accountCreateContract.getAccountAddress()); - break; - case 12: - UnfreezeBalanceContract unfreezeBalanceContract - = any.unpack(UnfreezeBalanceContract.class); - isExist(unfreezeBalanceContract.getOwnerAddress()); - break; - case 30: - CreateSmartContract createSmartContract = any.unpack(CreateSmartContract.class); - isExist(createSmartContract.getOwnerAddress()); - break; - case 46: - AccountPermissionUpdateContract accountPermissionUpdateContract - = any.unpack(AccountPermissionUpdateContract.class); - isExist(accountPermissionUpdateContract.getOwnerAddress()); - break; - case 4: - VoteWitnessContract voteWitnessContract = any.unpack(VoteWitnessContract.class); - isExist(voteWitnessContract.getOwnerAddress()); - break; - default: - logger.info("Unknown type:" + contractType); - continue; - - } - } catch (Exception e) { - e.printStackTrace(); - - } - - - - - - - } - } - - - - - } - - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test07ScanAndCalculateTotalValueOrCallValue() throws Exception { - getNowAddressList(); - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget("47.252.19.181:50051") - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - int total1 = 0; - int total2 = 0; - int totalTrx = 0; - for (long blockNum = 20450668L; blockNum <= 20450790L;blockNum++) { - System.out.println("blockNum " + blockNum); - TransactionInfoList transactionList = PublicMethed.getTransactionInfoByBlockNum(blockNum, - blockingStubFull).get(); - for (int i = 0; i < transactionList.getTransactionInfoCount();i++) { - if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getContractAddress() - .toByteArray()).equalsIgnoreCase("41DF42D1936F0DC3689BB65A19F279747084E13FBD")) { - - - if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getLog(0) - .getTopics(0).toByteArray()).equalsIgnoreCase( - "9b217a401a5ddf7c4d474074aff9958a18d48690d77cc2151c4706aa7348b401")) { - total1 += Integer.parseInt(ByteArray.toHexString(transactionList.getTransactionInfo(i) - .getLog(0).getData().toByteArray()),16); - } else if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getLog(0) - .getTopics(0).toByteArray()).equalsIgnoreCase( - "31472eae9e158460fea5622d1fcb0c5bdc65b6ffb51827f7bc9ef5788410c34c")) { - total2 += Integer.parseInt(ByteArray.toHexString(transactionList.getTransactionInfo(i) - .getLog(0).getData().toByteArray()),16); - } else if (ByteArray.toHexString(transactionList.getTransactionInfo(i).getLog(0) - .getTopics(0).toByteArray()).equalsIgnoreCase( - "3e799b2d61372379e767ef8f04d65089179b7a6f63f9be3065806456c7309f1b")) { - totalTrx += transactionList.getTransactionInfo(i).getInternalTransactions(4) - .getCallValueInfo(0).getCallValue(); - } - - } - } - } - - System.out.println("total1 :" + total1); - System.out.println("total2 :" + total2); - System.out.println("total_callValue :" + totalTrx); - - } - - - - @Test - public void test08ScanAndCalculateWitnessProductBlockStatus() { - Long startNum = 33694340L; - Long endNum = 33694388L; - - Integer testgroup014 = 0; - Integer testgroup015 = 0; - Integer testgroup016 = 0; - Integer testgroup017 = 0; - Integer testgroup018 = 0; - - int transfer = 0; - int trigger = 0; - - while (startNum++ <= endNum) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(startNum); - Block block = blockingStubFull.getBlockByNum(builder.build()); - logger.info("current block:" + startNum); - - String currentAddress = ByteArray.toHexString(block.getBlockHeader().getRawData() - .getWitnessAddress().toByteArray()); - List transactionList = block.getTransactionsList(); - for (Transaction transaction : transactionList) { - if (transaction.getRawData().getContract(0).getType().equals(ContractType - .TriggerSmartContract)) { - trigger++; - } else { - transfer++; - } - } - if (currentAddress.equals(getHexAddress( - "0528dc17428585fc4dece68b79fa7912270a1fe8e85f244372f59eb7e8925e04")) - || currentAddress - .equals(getHexAddress( - "dbc78781ad27f3751358333412d5edc85b13e5eee129a1a77f7232baadafae0e")) - || currentAddress - .equals(getHexAddress( - "a79a37a3d868e66456d76b233cb894d664b75fd91861340f3843db05ab3a8c66")) - || currentAddress - .equals(getHexAddress( - "a8107ea1c97c90cd4d84e79cd79d327def6362cc6fd498fc3d3766a6a71924f6")) - || currentAddress - .equals(getHexAddress( - "b5076206430b2ca069ae2f4dc6f20dd0d74551559878990d1df12a723c228039")) - || currentAddress - .equals(getHexAddress( - "87cc8832b1b4860c3c69994bbfcdae9b520e6ce40cbe2a90566e707a7e04fc70")) - ) { - testgroup014++; - continue; - } - - if (currentAddress.equals(getHexAddress( - "553c7b0dee17d3f5b334925f5a90fe99fb0b93d47073d69ec33eead8459d171e")) - || currentAddress - .equals(getHexAddress( - "541a2d585fcea7e9b1803df4eb49af0eb09f1fa2ce06aa5b8ed60ac95655d66d")) - || currentAddress - .equals(getHexAddress( - "7d5a7396d6430edb7f66aa5736ef388f2bea862c9259de8ad8c2cfe080f6f5a0")) - || currentAddress - .equals(getHexAddress( - "7c4977817417495f4ca0c35ab3d5a25e247355d68f89f593f3fea2ab62c8644f")) - || currentAddress - .equals(getHexAddress( - "4521c13f65cc9f5c1daa56923b8598d4015801ad28379675c64106f5f6afec30")) - || currentAddress - .equals(getHexAddress( - "442513e2e801bc42d14d33b8148851dae756d08eeb48881a44e1b2002b3fb700")) - ) { - testgroup015++; - continue; - } - - if (currentAddress.equals(getHexAddress( - "324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096c6bacb8")) - || currentAddress - .equals(getHexAddress( - "f33101ea976d90491dcb9669be568db8bbc1ad23d90be4dede094976b67d550e")) - || currentAddress - .equals(getHexAddress( - "1bb32958909299db452d3c9bbfd15fd745160d63e4985357874ee57708435a00")) - || currentAddress - .equals(getHexAddress( - "29c91bd8b27c807d8dc2d2991aa0fbeafe7f54f4de9fac1e1684aa57242e3922")) - || currentAddress - .equals(getHexAddress( - "97317d4d68a0c5ce14e74ad04dfc7521f142f5c0f247b632c8f94c755bdbe669")) - ) { - testgroup016++; - continue; - } - - if (currentAddress.equals(getHexAddress( - "ff5d867c4434ac17d264afc6696e15365832d5e8000f75733ebb336d66df148d")) - || currentAddress - .equals(getHexAddress( - "1fe1d91bbe3ac4ac5dc9866c157ef7615ec248e3fd4f7d2b49b0428da5e046b2")) - || currentAddress - .equals(getHexAddress( - "7c37ef485e186e07952bcc8e30cd911a6cd9f2a847736c89132762fb67a42329")) - || currentAddress - .equals(getHexAddress( - "bcc142d57d872cd2cc1235bca454f2efd5a87f612856c979cc5b45a7399272a8")) - || currentAddress - .equals(getHexAddress( - "6054824dc03546f903a06da1f405e72409379b83395d0bbb3d4563f56e828d52")) - ) { - testgroup017++; - continue; - } - - testgroup018++; - } - - - logger.info(testgroup014 + " " + testgroup015 + " " - + testgroup016 + " " + testgroup017 + " " + testgroup018); - - logger.info(transfer + " " + trigger); - - - } - - - @Test - public void test09GetEthFilterData() { - - HashSet set = new HashSet<>(); - Integer startBlockNumber = 35129811 - 2000; - Integer endBlockNumber = startBlockNumber - 3000; - - for (int blockNumber = startBlockNumber; blockNumber >= endBlockNumber;blockNumber-- - ) { - set.clear(); - HttpResponse response = HttpMethed - .getTransactionInfoByBlocknum("1.1.1.1:90", blockNumber); - - List content = HttpMethed.parseResponseContentArray(response); - - String blockNumberHex = "0x" + Integer.toHexString(blockNumber); - - System.out.println(content.size()); - for (JSONObject info : content) { - if (!info.containsKey("log")) { - continue; - } - JSONArray logArray = info.getJSONArray("log"); - for (int i = 0; i < logArray.size();i++) { - JSONObject log = logArray.getJSONObject(i); - String address = "0x" + log.getString("address"); - String topic = "0x" + log.getJSONArray("topics").getString(0); - set.add(address + "," + topic + "," + blockNumberHex); - - } - - - - - } - - for (String data : set) { - writeDataToCsvFile("ys_filter_api.csv", data); - } - } - - - } - - public String getHexAddress(String key) { - return ByteArray.toHexString(PublicMethed.getFinalAddress(key)); - } - - private static HashSet getFileList(String fileName,HashSet set) { - String line = null; - try { - BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"utf-8")); - - while ((line = bufferedReader.readLine()) != null) { - set.add(line); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - - return set; - } - - - - - private static void getNowAddressList() { - String line = null; - try { - //BufferedReader bufferedReader=new BufferedReader(new FileReader(filePath)); - BufferedReader bufferedReader = - new BufferedReader(new InputStreamReader(new FileInputStream("newAddress.csv"),"utf-8")); - - //int i=0; - while ((line = bufferedReader.readLine()) != null) { - existAddress.add(line); - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - - /** - * constructor. - */ - public static void writeDataToCsvFile(String fileName,String writeData) { - - { - try { - File file = new File(fileName); - - if (!file.exists()) { - file.createNewFile(); - } - FileWriter fileWritter = new FileWriter(file.getName(), true); - fileWritter.write(writeData + "\n"); - fileWritter.close(); - //System.out.println("finish"); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - /** - * constructor. - */ - public void doCheck(ByteString address) throws Exception { - if (addressSet.contains(address)) { - //logger.info("skip :" + ByteArray.toHexString(address.toByteArray())); - return; - } else { - addressSet.add(address); - } - logger.info("checking :" + ByteArray.toHexString(address.toByteArray())); - compareTwoAddress(address); - compareNet(address); - compareAccountResource(address); - return; - - } - - /** - * constructor. - */ - public void compareTwoAddress(ByteString address) { - - Assert.assertEquals( - PublicMethed.queryAccount(address.toByteArray(),blockingStubFull).toBuilder() - .clearFreeAssetNetUsageV2() - //.putAllFreeAssetNetUsageV2(account.getFreeAssetNetUsageV2Map()) - .setBalance(1L).setLatestOprationTime(1L) - .setAccountResource(AccountResource.newBuilder()) - .setFreeNetUsage(1L) - .setNetUsage(1L) - .clearAssetV2() - .setLatestConsumeFreeTime(1L) - .setLatestConsumeTime(1L) - .setAllowance(1L) - .clearAccountResource() - //.clearOldVotePower() - .build(), - PublicMethed.queryAccount(address.toByteArray(),blockingStubFull).toBuilder() - .clearFreeAssetNetUsageV2() - //.putAllFreeAssetNetUsageV2(account.getFreeAssetNetUsageV2Map()) - .setBalance(1L).setLatestOprationTime(1L) - .setAccountResource(AccountResource.newBuilder()) - .setFreeNetUsage(1L) - .setNetUsage(1L) - .setLatestConsumeFreeTime(1L) - .setLatestConsumeTime(1L) - .clearAssetV2() - .setAllowance(1L) - .clearAccountResource() - .build() - ); - - } - - - /** - * constructor. - */ - public void compareNet(ByteString address) { - Assert.assertEquals( - PublicMethed.getAccountNet(address.toByteArray(),blockingStubFull) - .toBuilder().setTotalNetWeight(1L) - .setNetUsed(1L) - .setFreeNetUsed(1) - .setNetLimit(1) - .build(), - PublicMethed.getAccountNet(address.toByteArray(),blockingStubFull) - .toBuilder().setTotalNetWeight(1L) - .setNetUsed(1L) - .setFreeNetUsed(1) - .setNetLimit(1) - .build() - ); - } - - /** - * constructor. - */ - public void compareAccountResource(ByteString address) throws Exception { - Assert.assertEquals( - PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setEnergyLimit(1L) - .build(), - PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setEnergyLimit(1L) - .build() - ); - - } - - /** - * constructor. - */ - public boolean isEqual(ByteString address) { - return PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setEnergyLimit(1L) - .build().equals(PublicMethed.getAccountResource(address.toByteArray(),blockingStubFull) - .toBuilder() - .setFreeNetUsed(1L) - .setEnergyUsed(1L) - .setTotalEnergyWeight(1L) - .setTotalNetWeight(1L) - .setNetUsed(1L) - .setNetLimit(1L) - .setEnergyLimit(1L) - .build()); - - } - - /** - * constructor. - */ - public void isExist(ByteString address1) { - byte[] address = address1.toByteArray(); - byte[] hash0 = Sha256Sm3Hash.hash(address); - byte[] hash1 = Sha256Sm3Hash.hash(hash0); - byte[] checkSum = Arrays.copyOfRange(hash1, 0, 4); - byte[] addchecksum = new byte[address.length + 4]; - System.arraycopy(address, 0, addchecksum, 0, address.length); - System.arraycopy(checkSum, 0, addchecksum, address.length, 4); - if (!existAddress.contains(Base58.encode(addchecksum))) { - concurrentHashSet.add(address1); - } - } - - /** - * constructor. - */ - private static void getTxidList() { - String line = null; - try { - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new - FileInputStream("demo.csv"),"utf-8")); - - while ((line = bufferedReader.readLine()) != null) { - listForTxid.add(line.toLowerCase()); - - } - } catch (FileNotFoundException e) { - e.printStackTrace(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - List list = new ArrayList<>(concurrentHashSet); - for (ByteString target : list) { - byte[] address = target.toByteArray(); - byte[] hash0 = Sha256Sm3Hash.hash(address); - byte[] hash1 = Sha256Sm3Hash.hash(hash0); - byte[] checkSum = Arrays.copyOfRange(hash1, 0, 4); - byte[] addchecksum = new byte[address.length + 4]; - System.arraycopy(address, 0, addchecksum, 0, address.length); - System.arraycopy(checkSum, 0, addchecksum, address.length, 4); - writeDataToCsvFile("newAddress.csv", Base58.encode(addchecksum)); - } - Collections.sort(list1); - - - int i = 1; - /* - afterTime = System.currentTimeMillis(); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock.getBlockHeader().getRawData().getNumber() + 2; - Long blockNum = beforeBlockNum; - Integer txsNum = 0; - Integer topNum = 0; - Integer totalNum = 0; - Long energyTotal = 0L; - String findOneTxid = ""; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (blockNum <= afterBlockNum) { - builder.setNum(blockNum); - txsNum = blockingStubFull1.getBlockByNum(builder.build()).getTransactionsCount(); - totalNum = totalNum + txsNum; - if (topNum < txsNum) { - topNum = txsNum; - findOneTxid = ByteArray.toHexString(Sha256Hash.hash(blockingStubFull1 - .getBlockByNum(builder.build()).getTransactionsList().get(2) - .getRawData().toByteArray())); - //logger.info("find one txid is " + findOneTxid); - } - - blockNum++; - } - Long costTime = (afterTime - beforeTime - 31000) / 1000; - logger.info("Duration block num is " + (afterBlockNum - beforeBlockNum - 11)); - logger.info("Cost time are " + costTime); - logger.info("Top block txs num is " + topNum); - logger.info("Total transaction is " + (totalNum - 30)); - logger.info("Average Tps is " + (totalNum / costTime)); - - infoById = PublicMethed.getTransactionInfoById(findOneTxid, blockingStubFull1); - Long oneEnergyTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("EnergyTotal is " + oneEnergyTotal); - logger.info("Average energy is " + oneEnergyTotal * (totalNum / costTime)); - */ - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc10Stress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc10Stress.java deleted file mode 100644 index 92118d87fcc..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc10Stress.java +++ /dev/null @@ -1,147 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class ShieldTrc10Stress { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - Note note; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] receiverPublicAddress = ecKey2.getAddress(); - String receiverPublicKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - Optional sendShieldAddressInfo; - String sendshieldAddress; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 20000 * zenTokenFee; - private Long zenTokenWhenCreateNewAddress = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenWhenCreateNewAddress"); - - - /** - * constructor. - */ - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - Args.setFullNodeAllowShieldedTransaction(true); - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - WalletGrpc.WalletBlockingStub blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - sendshieldAddress = sendShieldAddressInfo.get().getAddress(); - - String memo = "Use to TestZenToken004 shield address"; - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + costTokenAmount, memo); - Assert.assertTrue(PublicMethed.sendShieldCoin( - foundationZenTokenAddress, costTokenAmount + zenTokenFee, - null, null, - shieldOutList, - null, 0, - foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true, threadPoolSize = 100, invocationCount = 100) - public void test1Shield2TwoShieldTransaction() { - ManagedChannel channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - WalletGrpc.WalletBlockingStub blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - DecryptNotes notes; - List shieldOutList = new ArrayList<>(); - - Integer times = 100; - while (times-- > 0) { - notes = PublicMethed.listShieldNote(sendShieldAddressInfo, blockingStubFull); - //logger.info("note size:" + notes.getNoteTxsCount()); - - String memo1 = "Shield to shield address1 transaction" + System.currentTimeMillis(); - shieldOutList.clear(); - Long sendToShiledAddress1Amount = - notes.getNoteTxs(notes.getNoteTxsCount() - 1).getNote().getValue() - zenTokenFee; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendshieldAddress, - "" + sendToShiledAddress1Amount, memo1); - - try { - PublicMethed.sendShieldCoin( - null, 0, - sendShieldAddressInfo.get(), notes.getNoteTxs(notes.getNoteTxsCount() - 1), - shieldOutList, - null, 0, - zenTokenOwnerKey, blockingStubFull); - } catch (Exception e) { - throw e; - } - } - - } - - @AfterClass(enabled = false) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc20Stress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc20Stress.java deleted file mode 100644 index e50f30b869a..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/ShieldTrc20Stress.java +++ /dev/null @@ -1,719 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.alibaba.fastjson.JSONObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.apache.http.HttpResponse; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldedAddressInfo; -import stest.tron.wallet.common.client.utils.ZenTrc20Base; - -@Slf4j -public class ShieldTrc20Stress extends ZenTrc20Base { - - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - Optional sendShieldAddressInfo; - private BigInteger publicFromAmount; - List shieldOutList = new ArrayList<>(); - - private String httpnode = Configuration.getByPath("testng.conf") - .getStringList("httpnode.ip.list").get(0); - - - private AtomicInteger finishMintNumber = new AtomicInteger(0); - private AtomicInteger finishCreateParameterNumber = new AtomicInteger(0); - private AtomicInteger finishTriggerNumber = new AtomicInteger(0); - private AtomicInteger noteNumber = new AtomicInteger(0); - private AtomicInteger dataNumber = new AtomicInteger(0); - private AtomicLong startTriggerNum = new AtomicLong(0); - private AtomicLong endTriggerNum = new AtomicLong(0); - private AtomicLong startmintNum = new AtomicLong(0); - private AtomicLong endmintNum = new AtomicLong(0); - private Integer thread = 40; - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - publicFromAmount = getRandomAmount(); - //startQureyNum = HttpMethed.getNowBlockNum(httpnode); - startmintNum.addAndGet(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - } - - /** - * wqs constructor. - */ - @Test(enabled = false, threadPoolSize = 50, invocationCount = 50) - public void test01ScanAndCreateThenTrigger() throws Exception { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ManagedChannel channelFull1 = null; - WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - BigInteger publicFromAmount = getRandomAmount(); - Optional sendShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - Optional receiverShieldAddressInfo = getNewShieldedAddress( - blockingStubFull); - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", 0L, - blockingStubFull, blockingStubSolidity - ); - - String data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - - //Do mint transaction type - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - List inputShieldAddressList = new ArrayList<>(); - GrpcAPI.DecryptNotesTRC20 sendNote; - List inputList = new ArrayList<>(); - inputShieldAddressList.add(sendShieldAddressInfo.get()); - - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - - while (sendNote.getNoteTxsCount() == 0) { - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - } - - Integer times = 20; - while (times-- > 0) { - //receiverShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - //Scan sender note - /*sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - - while (sendNote.getNoteTxsCount() == 0) { - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - }*/ - - sendNote = scanShieldedTrc20NoteByIvk(sendShieldAddressInfo.get(), - blockingStubFull1); - - String transferMemo = "Transfer type test " + System.currentTimeMillis(); - - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, transferMemo, blockingStubFull); - - //logger.info("send note size:" + sendNote.getNoteTxsCount()); - - //Create transfer parameters - try { - GrpcAPI.DecryptNotesTRC20 inputNoteFor2to2 = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(sendNote.getNoteTxs(sendNote.getNoteTxsCount() - 1)).build(); - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", 0L, - blockingStubFull1, blockingStubSolidity); - } catch (Exception e) { - throw e; - } - - Integer exit = 7; - if (exit == 1) { - continue; - } - - data = encodeTransferParamsToHexString(shieldedTrc20Parameters); - txid = PublicMethed.triggerContract(shieldAddressByte, - transfer, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - - //sendShieldAddressInfo = receiverShieldAddressInfo; - } - - } - - - /** - * constructor. - */ - @Test(enabled = false, threadPoolSize = 40, invocationCount = 40) - public void test02FirstScanCreateParameterThenCreateTrigger() throws Exception { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ManagedChannel channelFull1 = null; - WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - Optional sendShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - Optional receiverShieldAddressInfo = getNewShieldedAddress( - blockingStubFull); - - Integer mintNumber = 50; - - while (--mintNumber >= 0) { - BigInteger publicFromAmount = getRandomAmount(); - - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity - ); - String data = ""; - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e) { - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e1) { - continue; - } - - } - - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - finishMintNumber.addAndGet(1); - endmintNum.getAndAdd(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - while (finishMintNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishMintNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished mint,current finished thread is :" + finishMintNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Long endMintNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - GrpcAPI.DecryptNotesTRC20 sendNote = scanShieldedTrc20NoteByIvkWithRange( - sendShieldAddressInfo.get(), - startmintNum.get(), endMintNum, blockingStubFull1); - - noteNumber.addAndGet(sendNote.getNoteTxsCount()); - - logger.info("sendNote size :" + sendNote.getNoteTxsCount()); - - List shieldOutList = new ArrayList<>(); - - List inputShieldAddressList = new ArrayList<>(); - - inputShieldAddressList.add(sendShieldAddressInfo.get()); - - List dataList = new ArrayList<>(); - for (int i = 0; i < sendNote.getNoteTxsCount() - 1; i = i + 2) { - GrpcAPI.DecryptNotesTRC20 inputNoteFor2to2 = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(sendNote.getNoteTxs(i)) - .addNoteTxs(sendNote.getNoteTxs(i + 1)) - .build(); - - String transferMemo1 = "Transfer1 type test " + getRandomLongAmount() + getRandomLongAmount(); - String transferMemo2 = "Transfer2 type test " + getRandomLongAmount() + getRandomLongAmount(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, - receiverShieldAddressInfo.get().getAddress(), - "" + sendNote.getNoteTxs(i).getNote().getValue(), transferMemo1, blockingStubFull); - shieldOutList = addShieldTrc20OutputList(shieldOutList, - receiverShieldAddressInfo.get().getAddress(), - "" + sendNote.getNoteTxs(i + 1).getNote().getValue(), transferMemo2, blockingStubFull); - - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters = null; - if (i % 2 == 0) { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull1, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity); - } catch (Exception e1) { - throw e1; - } - - } - - } else { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters - = createShieldedTrc20Parameters(BigInteger.valueOf(0), - inputNoteFor2to2, inputShieldAddressList, shieldOutList, "", - 0L, blockingStubFull1, blockingStubSolidity); - } catch (Exception e2) { - throw e2; - } - - - } - } - - dataList.add(encodeTransferParamsToHexString(shieldedTrc20Parameters)); - //logger.info("dataList size:" + dataList.size()); - - } - - finishCreateParameterNumber.addAndGet(1); - dataNumber.addAndGet(dataList.size()); - while (finishCreateParameterNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishCreateParameterNumber.get() % 10 == 0) { - logger.info("Wait all thread finished create parameter ,current finished thread is :" - + finishCreateParameterNumber.get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - startTriggerNum - .addAndGet(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - for (int i = 0; i < dataList.size(); i++) { - if (i % 2 == 0) { - PublicMethed.triggerContract(shieldAddressByte, - transfer, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - } else { - PublicMethed.triggerContract(shieldAddressByte, - transfer, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull1); - } - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - finishTriggerNumber.addAndGet(1); - - while (finishTriggerNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishTriggerNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished trigger ,current finished thread is :" + finishTriggerNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - - } - - /** - * constructor. - */ - @Test(enabled = true, threadPoolSize = 40, invocationCount = 40) - public void test03BurnStress() throws Exception { - ManagedChannel channelFull = null; - WalletGrpc.WalletBlockingStub blockingStubFull = null; - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - ManagedChannel channelFull1 = null; - WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - Optional sendShieldAddressInfo = getNewShieldedAddress(blockingStubFull); - Optional receiverShieldAddressInfo = getNewShieldedAddress( - blockingStubFull); - - Integer mintNumber = 25; - - while (--mintNumber >= 0) { - BigInteger publicFromAmount = getRandomAmount(); - - String memo = "Shield trc20 from T account to shield account in" + System.currentTimeMillis(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - - List shieldOutList = new ArrayList<>(); - shieldOutList.clear(); - shieldOutList = addShieldTrc20OutputList(shieldOutList, sendShieldAddress, - "" + publicFromAmount, memo, blockingStubFull); - - //Create shiled trc20 parameters - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters - = createShieldedTrc20Parameters(publicFromAmount, - null, null, shieldOutList, "", - 0L, blockingStubFull, blockingStubSolidity - ); - String data = ""; - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e) { - try { - data = encodeMintParamsToHexString(shieldedTrc20Parameters, publicFromAmount); - } catch (Exception e1) { - continue; - } - - } - - String txid = PublicMethed.triggerContract(shieldAddressByte, - mint, data, true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - try { - Thread.sleep(2000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - finishMintNumber.addAndGet(1); - endmintNum.getAndAdd(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - while (finishMintNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishMintNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished mint,current finished thread is :" + finishMintNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - Long endMintNum = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber(); - - GrpcAPI.DecryptNotesTRC20 sendNote = scanShieldedTrc20NoteByIvkWithRange( - sendShieldAddressInfo.get(), - startmintNum.get(), endMintNum, blockingStubFull1); - - noteNumber.addAndGet(sendNote.getNoteTxsCount()); - - logger.info("sendNote size :" + sendNote.getNoteTxsCount()); - - List shieldOutList = new ArrayList<>(); - - List inputShieldAddressList = new ArrayList<>(); - - inputShieldAddressList.add(sendShieldAddressInfo.get()); - - List dataList = new ArrayList<>(); - for (int i = 0; i < sendNote.getNoteTxsCount(); i++) { - String burnnMemo1 = "burnnMemo1 type test " + getRandomLongAmount() + getRandomLongAmount(); - GrpcAPI.DecryptNotesTRC20 burnInput = GrpcAPI.DecryptNotesTRC20.newBuilder() - .addNoteTxs(sendNote.getNoteTxs(i)) - .build(); - - GrpcAPI.ShieldedTRC20Parameters shieldedTrc20Parameters = null; - createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull, blockingStubSolidity); - - if (i % 2 == 0) { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull1, - blockingStubSolidity); - } catch (Exception e1) { - throw e1; - } - - } - - } else { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull, blockingStubSolidity); - } catch (Exception e) { - try { - shieldedTrc20Parameters = createShieldedTrc20Parameters(BigInteger.valueOf(0), - burnInput, inputShieldAddressList, null, zenTrc20TokenOwnerAddressString, - burnInput.getNoteTxs(0).getNote().getValue(), blockingStubFull1, - blockingStubSolidity); - } catch (Exception e1) { - throw e1; - } - - - } - } - - dataList.add(shieldedTrc20Parameters.getTriggerContractInput()); - - } - - finishCreateParameterNumber.addAndGet(1); - dataNumber.addAndGet(dataList.size()); - while (finishCreateParameterNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishCreateParameterNumber.get() % 10 == 0) { - logger.info("Wait all thread finished create parameter ,current finished thread is :" - + finishCreateParameterNumber.get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - startTriggerNum - .addAndGet(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - - for (int i = 0; i < dataList.size(); i++) { - if (i % 2 == 0) { - PublicMethed.triggerContract(shieldAddressByte, - burn, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull); - } else { - PublicMethed.triggerContract(shieldAddressByte, - burn, dataList.get(i), true, 0, maxFeeLimit, zenTrc20TokenOwnerAddress, - zenTrc20TokenOwnerKey, blockingStubFull1); - } - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - finishTriggerNumber.addAndGet(1); - - while (finishTriggerNumber.get() != thread) { - try { - Thread.sleep(3000); - if (finishTriggerNumber.get() % 10 == 0) { - logger.info( - "Wait all thread finished trigger ,current finished thread is :" + finishTriggerNumber - .get()); - } - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - - } - - /** - * constructor. - */ - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test04QueryResult() throws Exception { - - endTriggerNum.set(blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()) - .getBlockHeader().getRawData().getNumber()); - Long endmintnum = endmintNum.longValue() / thread; - Long starttriggernum = startTriggerNum.longValue() / thread; - logger.info("Start trigger block number: " + starttriggernum); - logger.info("end trigger block number: " + endTriggerNum.get()); - logger.info("Start mint block number: " + startmintNum.get()); - logger.info("End mint block number: " + endmintnum); - - Integer success = 0; - Integer failed = 0; - Integer outOfTime = 0; - Integer notMintContract = 0; - startmintNum.getAndAdd(-5); - endmintnum = endmintnum + 5; - - startmintNum.set(2016); - endmintnum = 2180L; - starttriggernum = 3040L; - endTriggerNum.set(3060); - - while (startmintNum.get() < endmintnum) { - HttpResponse response = HttpMethed - .getTransactionInfoByBlocknum(httpnode, startmintNum.getAndAdd(1)); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(response); - for (int i = 0; i < responseContentByBlocknum.size(); i++) { - String result = responseContentByBlocknum.get(i).getJSONObject("receipt") - .getString("result"); - logger.info(result); - if (result == null) { - notMintContract++; - continue; - } - if (result.equals("SUCCESS")) { - success++; - continue; - } - if (result.equals("OUT_OF_TIME")) { - outOfTime++; - continue; - } - failed++; - } - } - - Integer triggerSuccess = 0; - Integer triggerFailed = 0; - Integer triggerOutOfTime = 0; - Integer notTriggerContract = 0; - startTriggerNum.getAndAdd(-5); - endTriggerNum.getAndAdd(5); - - while (starttriggernum < endTriggerNum.get()) { - HttpResponse response = HttpMethed.getTransactionInfoByBlocknum(httpnode, starttriggernum++); - List responseContentByBlocknum = HttpMethed - .parseResponseContentArray(response); - for (int i = 0; i < responseContentByBlocknum.size(); i++) { - String result = responseContentByBlocknum.get(i).getJSONObject("receipt") - .getString("result"); - logger.info(result); - if (result == null) { - notTriggerContract++; - continue; - } - if (result.equals("SUCCESS")) { - triggerSuccess++; - continue; - } - if (result.equals("OUT_OF_TIME")) { - triggerOutOfTime++; - continue; - } - triggerFailed++; - } - } - - logger.info("Mint Success mint times:" + success); - logger.info("Mint Failed mint times:" + failed); - logger.info("Mint Out of times mint times:" + outOfTime); - logger.info("Not mint times:" + notMintContract); - - logger.info("Success trigger times:" + triggerSuccess); - logger.info("Failed trigger times:" + triggerFailed); - logger.info("Out of times trigger times:" + triggerOutOfTime); - logger.info("Not trigger times:" + notTriggerContract); - - logger.info("note size:" + noteNumber.get()); - logger.info("data size:" + dataNumber.get()); - - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - //endNum = HttpMethed.getNowBlockNum(httpnode); - //logger.info("startNum:" + startNum); - //logger.info("endNum:" + endNum); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java b/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java deleted file mode 100644 index 4b7ede49ab8..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/SupportTronlinkAutoTest.java +++ /dev/null @@ -1,374 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.contract.WitnessContract; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class SupportTronlinkAutoTest { - - private final String testKey002 - = "7400E3D0727F8A61041A8E8BF86599FE5597CE19DE451E59AED07D60967A5E25"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - ByteString assetAccountId1; - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - //Mainnet fullnode - private String fullnode = "47.252.19.181:50051"; - //dappchain fullnode - //private String fullnode = "47.252.7.241:50051"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void testMutiSignForAccount() { - Integer i = 0; - System.out.println("Start genterate address"); - while (i++ < 20) { - ecKey1 = new ECKey(Utils.getRandom()); - manager1Address = ecKey1.getAddress(); - manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - //PublicMethed.printAddress(ownerKey); - - PublicMethed.sendcoin(ownerAddress, 200000000000L, fromAddress, testKey002, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = ownerKey; - ownerKeyString[0] = ownerKey; - //ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0," - + "\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2," - + "\"permission_name\":\"active\",\"threshold\":2," - + "\"operations\":\"" - + "7fff1fc0033e0b00000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - //logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - System.out.println("owner" + i + " --------------------------------------------------------"); - PublicMethed.printAddress(ownerKey); - System.out.println("mutli sig address for owner " - + i + " ----------------------------------"); - PublicMethed.printAddress(manager1Key); - System.out.println("-------------------------------" - + "-----------------------------------------"); - - } - - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test002CreateWitness() { - Integer i = 0; - System.out.println("Start genterate witness address"); - while (i++ < 10) { - ecKey3 = new ECKey(Utils.getRandom()); - ownerAddress = ecKey3.getAddress(); - ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - //PublicMethed.printAddress(ownerKey); - - PublicMethed.sendcoin(ownerAddress, 50000000000L, fromAddress, testKey002, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String createWitnessUrl = "IOS-UI-Witness-00" + i; - byte[] createUrl = createWitnessUrl.getBytes(); - createWitness(ownerAddress, createUrl, ownerKey); - PublicMethed.waitProduceNextBlock(blockingStubFull); - System.out.println("witness " + i + " -----------------------------" - + "---------------------------"); - PublicMethed.printAddress(ownerKey); - System.out.println("witness url is : " + createWitnessUrl); - System.out.println("-------------------------------------------" - + "-----------------------------"); - - } - - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test03MutiSignForAccount() { - HashMap muti = new HashMap(); - muti.put("9a2ba173645be8d37a82084f984ba873fbcf817b589c62a59b3ba1494c3406e0", - "cefba96470224724bde255f3402fca3d67b6c7c5d34deb7a8524c9482c58fe8b"); - muti.put("36f5430b4003f41ee8969421d9366ab1414e62111aec07a73d06eefcda8aad14", - "3adcd73ad1fa03ce2fd4d29e29a7c96ef2f78bece85cba6e58997826682c4c1e"); - muti.put("4b47cf37528724dc8bc99188063f5aec9a7bc32aadfad5a96a9e9cccba7cede1", - "948d856ebeb787aabd495fc13627f7442e7c1f21e9ed784f795e14f13cbebb94"); - muti.put("75d0856799cf2b2c807ed0eb5bb091bb943f2caed830add4b8df14c537f86e9a", - "7fb13ad0b62d4ff116ebd3d901d458697902ce81a8fc30c20c60aba1ca6964ec"); - muti.put("327bf1b4a3193c2bebf239c1c5bda09a8d375251361ea9c7418aa2adf2d17b7e", - "a8236968966db785ffe63d613174ee25e1baff03817b64db905c5940ed3dcc4b"); - muti.put("cf83d9494a9268fd3a75bd76bcfabaa7ec766e9084129a20e1823f81fbdca933", - "1e53c948e949e39f60a3be2382382f9a50f88b658ea79c418ece1c5f9b169441"); - muti.put("19ff919e92462f07c7eced256d4cb588a66ac900d544d0d4d16ae49732de79cb", - "166ddc2cd6379e7971e2c65d224594b709ebb59b3c6051c156214c299129f420"); - muti.put("7901db57a410a26d333b6d7fe4e054ddffbdc646f94ca03577bfd5e87120b9af", - "89d9a47b37f5625e14082b575d5e657b21f6dae125125bee51fafd1e8cdf0804"); - muti.put("e3c7204d652a6fdcda05cbce061904d441dece7bf0a1778c1ddf0906aa36a279", - "7d308998f829c0581447831003d994216a3a003ba00eef6a4e48e28b3178fbb3"); - muti.put("826fc86d572ba9de06f20963fcbfb44f4c397875bd4d7b36fdcb83476df33f05", - "25aa122142a52ea8ba7bdf832c39a194d498774d4f675b8bcb17280c33990a08"); - muti.put("9705dd852465d04be349e94865142fc636d038138a4bfe8f94abc9b49f1dc14a", - "0b675f14c1e06a6473c517dded162472ce2bb5c8934f198df1a791b75c30f983"); - muti.put("075f86d3d4053929714ddedb3e458467e6d494c3d4b0c71dafb63279de1beb89", - "4880695a6e31f4f69d6f261eedfa5dcb5fc1b9194483658f77625ec4e6b2e493"); - muti.put("91ae6c8a1bff0b71f6f2b9de54d3b39502bcab906f980569109ab8425cb0bdc5", - "90ef4adb0772ee49089784ccad234867a10395064749788b461cbe91265424fb"); - muti.put("9acb90c4d15c87dd2a1f322eddaabdde22cd78fe5eab371bfcf0c8be80bef8a8", - "951f03193e1d7d4bff016da100b74f8ac220aabfd9c2841438ee758702c8e3f4"); - muti.put("f8eae7be0fac4e9fab40139e58b405f7e5d5b13a83220a6e4955ffaacbbe2a7d", - "66692c0aaad6cfd349bdffbf3fdd688558a6c7a95ff67f249e0e80847167013a"); - muti.put("2e20c1a4b9a3a79696cbf0d03dedc39d8021657028fbf3dbc5da85ea61ad5dff", - "ae7ecb7fba0d77d116a23f96a4dfecdef09741e363f0be12f99c86b3815d8fff"); - muti.put("e5e60c52f3b11ce0cfbc4e86d078ab53435ebc2422fd851614a25b5063ae7040", - "42c575d8848809082c6872b2dcdb0e81d5f06ca120c636b90d0b062965ea0871"); - muti.put("fd4ee3a678a749c2049d5b1cba757648386c84ac2481be8de02069d41e4fb312", - "ef2095532f572be8d021886780f7e508665ef40c1499273b91813ddc27d1354b"); - muti.put("297f6e034e9366691922ff5394810f724094bd0a07b4ca60f0f281ec71562094", - "4ab67f1c42db0b63bafc0f33cf59575998c3259e96f5f89ea379dac4298d2bd7"); - int i = 1; - for (HashMap.Entry entry : muti.entrySet()) { - //entry.getKey().toString(); - //entry.getValue().toString(); - - ownerKey = entry.getKey().toString(); - ownerAddress = PublicMethed.getFinalAddress(ownerKey); - - manager1Key = entry.getValue().toString(); - manager1Address = PublicMethed.getFinalAddress(manager1Key); - - //System.out.println("ownerKey:" + ownerKey); - //System.out.println("manager1Key:" + manager1Key); - - //System.exit(1); - PublicMethed.sendcoin(ownerAddress, 20000000000L, fromAddress, testKey002, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = ownerKey; - ownerKeyString[0] = ownerKey; - //ownerKeyString[1] = manager1Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"" - + "threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"" - + "active\",\"threshold\":2," - + "\"operations\":\"" - + "7fff1fc0033e0b00000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}" - + "]}]}"; - - //logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - System.out.println("owner " + i++ + " -----------------" - + "---------------------------------------"); - PublicMethed.printAddress(ownerKey); - System.out.println("mutli sig address for owner " + i++ + " ------------" - + "----------------------"); - PublicMethed.printAddress(manager1Key); - System.out.println("-----------------------------------" - + "-------------------------------------"); - - } - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test004CreateWitness() { - - String[] witnessKey = { - - "c74fb4d8101572041c6fab30e1602ba1ec8247e1ead19641fb985b3ed3a8261e", - "25f98ac22c9fd02aa8a2ef354db0aa13ebc2a6c31377ea7e2b342f0d3898af0d", - "939a2cec3768bd2d2834126c20d2b1c513e3711f085ce374f654a7b144aa409f", - "39862f4dd51972ca22ce50b7b9e629043387000120c33bf263399ad9b334da1a", - "79045aab0f3199ac456ce2039e809e6c942983ede0e3a398d571dedddb351348", - "d50fe9c48e95289cde324ffeff095f8275f9ab07375e5e843167a0a54d3e1462", - "61651f2b8a87e1ae0ced5e700807f2abb50e97fe7d3d3e6a8aa58f0a6b0149a6", - "bb03d70e5187258ffb6cddb1becade5c1b2606b7ea84636b7dfaeef6216610a5", - "25858c236634e353d018f310f61e077b78e1410766565ed56ff11ee7410dcf20", - "ede941a01eb8234866f60c7e8e95db4614bb0d05298d82bae0abea81f1861046", - - }; - int i = 1; - for (String ownerKey : witnessKey) { - byte[] ownerAddress = PublicMethed.getFinalAddress(ownerKey); - PublicMethed.sendcoin(ownerAddress, 20000000000L, fromAddress, testKey002, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String createWitnessUrl = "IOS-UI-Witness-00" + i++; - byte[] createUrl = createWitnessUrl.getBytes(); - createWitness(ownerAddress, createUrl, ownerKey); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.printAddress(ownerKey); - System.out.println("witness url is : " + createWitnessUrl); - System.out.println("---------------------------------------------------------------------"); - - } - - - } - - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void test005SendTrc20() { - - String[] witnessKey = { - "TR8CyAPJFMjCvphCVuWeeVxBh5iTG7VWxe", - "TMhGDU7NiXwckCW64PqAvWFuC2kR1WSF5J", - "TDf3JZtjDeEqsFdPGp6vT9meG3JxMwmXwA", - "TEtG9fnVi2qythiog6owPrg4sD9rwFBQBN", - "TUvda1oqrNLbqDKhZDxDnrPhiDCdxem218", - "TKEH31jJ2YQ3Bteh1ngjwdT8667ztyYPSp", - "TAzrJHKa57nXnn3dZGFG87PDuWx12dY97s", - "TWhc6AAh6BWRr3k5dV8iMvkp8ys7NHzXCk", - "TSsaSxHnb3xLTop2A8LrDk1P896yiDeupe", - "TMDs8oTj8mVnakqiVyDKdp2ruWPdFeDgbq", - "TWv2FEsoPp5XKxujVHffoNwksgJSxvf3QG", - "TGamEmt6U9ZUg9bFsMq7KT9bRa3uvkdtHM", - "TXhQk442CCGLydh6cfyfqvM6yJanEGeQj1", - "TKktQcbjXsXZDKPYLvUm8sxox2cT83g5rP", - "TBQUhYhdQpMRksBGAbpbTWSiE7WkGgy3Km", - "TALf34yjuLZjF1WQqCaUkf73X8WbhfiEyM", - "TCGp3JAFM5vQZpsdNiKRTci7fVb7A2TPcu", - "TBExF3mNvnhmEFgHW4TmYXXdhevRchnQyb", - "TS8o6WcHroSnzWNt4AiserAuVkye5Msvcm", - "TBtMRD79NkLyAvMkCTTj5VC5KZnz2Po2XZ", - }; - int i = 1; - for (String ownerKey : witnessKey) { - String triggerString = "\"" + ownerKey - + "\"" + ", 20000000000"; - System.out.println(triggerString); - //dapp chain trc20 tract TXkdXbzjoLpxGAD2strP1zwjJzR6osNfD7 - byte[] contractAddress = PublicMethed.decode58Check("TXkdXbzjoLpxGAD2strP1zwjJzR6osNfD7"); - //main chain TRC 20 contract TCCcBZEdTHmS1NfFtCYfwpjBKeTv515n71 - //byte[] contractAddress = PublicMethed.decode58Check("TCCcBZEdTHmS1NfFtCYfwpjBKeTv515n71"); - - PublicMethed - .triggerContract(contractAddress, "transfer(address,uint256)", triggerString, false, - 0, 1000000000, "0", 0, fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - public Boolean createWitness(byte[] owner, byte[] url, String priKey) { - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - WitnessContract.WitnessCreateContract.Builder builder = WitnessContract.WitnessCreateContract - .newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(owner)); - builder.setUrl(ByteString.copyFrom(url)); - WitnessContract.WitnessCreateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createWitness(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = PublicMethed.signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java deleted file mode 100644 index f4a97d2ba33..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestApproveProposal.java +++ /dev/null @@ -1,169 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.HashMap; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.ChainParameters; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.HttpMethed; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class TestApproveProposal { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - //Witness 47.93.33.201 - private final String witnessKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key2"); - //Witness 123.56.10.6 - private final String witnessKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - //Wtiness 39.107.80.135 - private final String witnessKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - //Witness 47.93.184.2 - private final String witnessKey005 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] witness001Address = PublicMethed.getFinalAddress(witnessKey001); - private final byte[] witness002Address = PublicMethed.getFinalAddress(witnessKey002); - private final byte[] witness003Address = PublicMethed.getFinalAddress(witnessKey003); - private final byte[] witness004Address = PublicMethed.getFinalAddress(witnessKey004); - private final byte[] witness005Address = PublicMethed.getFinalAddress(witnessKey005); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testApproveProposal() { - HashMap proposalMap = new HashMap(); - //proposalMap.put(25L, 1L); - proposalMap.put(27L, 0L); - //proposalMap.put(28L, 1L); - Assert.assertTrue(PublicMethed.createProposal(witness001Address, witnessKey001, - proposalMap, blockingStubFull)); - try { - Thread.sleep(20000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - //Get proposal list after approve - proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - listProposals = Optional.ofNullable(proposalList); - //logger.info(Integer.toString(listProposals.get().getProposals(0).getApprovalsCount())); - - String[] witnessKey = { - - "369F095838EB6EED45D4F6312AF962D5B9DE52927DA9F04174EE49F9AF54BC77", - "9FD8E129DE181EA44C6129F727A6871440169568ADE002943EAD0E7A16D8EDAC", - - }; - byte[] witnessAddress; - for (String key : witnessKey) { - witnessAddress = PublicMethed.getFinalAddress(key); - PublicMethed.approveProposal(witnessAddress, key, proposalId, - true, blockingStubFull); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - @Test(enabled = true) - public void testGetChainParameters() { - //Set the default map - HashMap defaultCommitteeMap = new HashMap(); - defaultCommitteeMap.put("MAINTENANCE_TIME_INTERVAL", 300000L); - defaultCommitteeMap.put("ACCOUNT_UPGRADE_COST", 9999000000L); - defaultCommitteeMap.put("CREATE_ACCOUNT_FEE", 100000L); - defaultCommitteeMap.put("TRANSACTION_FEE", 10L); - defaultCommitteeMap.put("ASSET_ISSUE_FEE", 1024000000L); - defaultCommitteeMap.put("WITNESS_PAY_PER_BLOCK", 32000000L); - defaultCommitteeMap.put("WITNESS_STANDBY_ALLOWANCE", 115200000000L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_FEE_IN_SYSTEM_CONTRACT", 0L); - defaultCommitteeMap.put("CREATE_NEW_ACCOUNT_BANDWIDTH_RATE", 1L); - - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - logger.info("Index is:" + i); - logger.info(getChainParameters.get().getChainParameter(i).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(i).getValue())); - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestExchangeTransaction.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestExchangeTransaction.java deleted file mode 100644 index db0de1d5b47..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestExchangeTransaction.java +++ /dev/null @@ -1,176 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import static org.tron.core.config.Parameter.ChainSymbol.TRX_SYMBOL_BYTES; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Exchange; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - - -@Slf4j -public class TestExchangeTransaction { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - } - - @Test(enabled = true) - public void testCreateShieldToken() { - String tokenOwnerKey = "2925e186bb1e88988855f11ebf20ea3a6e19ed92328b0ffb576122e769d45b68"; - byte[] tokenOwnerAddress = PublicMethed.getFinalAddress(tokenOwnerKey); - PublicMethed.printAddress(tokenOwnerKey); - Assert.assertTrue(PublicMethed.sendcoin(tokenOwnerAddress, 20480000000L, fromAddress, - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String name = "shieldToken"; - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - Long totalSupply = 1500000000000001L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - Assert.assertTrue(PublicMethed.createAssetIssue(tokenOwnerAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 1000L, 1000L, - 1L, 1L, tokenOwnerKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount = - PublicMethed.queryAccount(tokenOwnerAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info("AssetId:" + assetAccountId.toString()); - - - } - - @Test(enabled = true, threadPoolSize = 20, invocationCount = 20) - public void testExchangeTransaction() { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] exchangeAddress = ecKey1.getAddress(); - String exchangeKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - final byte[] transactionAddress = ecKey2.getAddress(); - String transactionKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - PublicMethed.printAddress(exchangeKey); - PublicMethed.printAddress(transactionKey); - - Assert.assertTrue(PublicMethed.sendcoin(exchangeAddress, 1500000000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(transactionAddress, 1500000000000000L, fromAddress, - testKey002, blockingStubFull)); - Long totalSupply = 1500000000000000L; - Random rand = new Random(); - Integer randNum = rand.nextInt(900000000) + 1; - String name = "exchange_" + Long.toString(randNum); - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - Assert.assertTrue(PublicMethed.createAssetIssue(exchangeAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 100000000L, 10000000000L, - 10L, 10L, exchangeKey, blockingStubFull)); - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Assert.assertTrue(PublicMethed.transferAsset(transactionAddress, name.getBytes(), - 1500000000L, exchangeAddress, exchangeKey, blockingStubFull)); - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - //500000000000000L //5000000L - Assert.assertTrue(PublicMethed.exchangeCreate(name.getBytes(), 500000000000000L, - TRX_SYMBOL_BYTES, 500000000000000L, exchangeAddress, exchangeKey, blockingStubFull)); - try { - Thread.sleep(300000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Integer i = 0; - while (i++ < 10000) { - PublicMethed.exchangeTransaction(exchangeId, TRX_SYMBOL_BYTES, 100000, 99, - transactionAddress, transactionKey, blockingStubFull); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - PublicMethed.exchangeTransaction(exchangeId, name.getBytes(), 100000, 1, - transactionAddress, transactionKey, blockingStubFull); - try { - Thread.sleep(100); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMapBigLongAndNumbers.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestMapBigLongAndNumbers.java deleted file mode 100644 index efee959ba63..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMapBigLongAndNumbers.java +++ /dev/null @@ -1,183 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -//import java.io.FileWriter; -//import java.io.BufferedWriter; - - -@Slf4j -public class TestMapBigLongAndNumbers { - - //testng001、testng002、testng003、testng004 - //testng001、testng002、testng003、testng004 - private final String testKey002 = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - //private final String testAddress41 = ByteArray.toHexString(fromAddress); - String kittyCoreAddressAndCut = ""; - byte[] kittyCoreContractAddress = null; - byte[] saleClockAuctionContractAddress = null; - byte[] siringClockAuctionContractAddress = null; - byte[] geneScienceInterfaceContractAddress = null; - //Integer consumeUserResourcePercent = 20; - Integer consumeUserResourcePercent = 100; - String txid = ""; - Optional infoById = null; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] triggerAddress = ecKey2.getAddress(); - String triggerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(triggerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - - } - - @Test(enabled = true, threadPoolSize = 10, invocationCount = 10) - public void deployErc721KittyCore() { - - Long maxFeeLimit = 1000000000L; - - String contractName = "MappingExample"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestMapBigLongAndNumbers_deployErc721KittyCore"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestMapBigLongAndNumbers_deployErc721KittyCore"); - kittyCoreContractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, consumeUserResourcePercent, null, testKey002, - fromAddress, blockingStubFull); - - String data1 = "a"; - String data2 = "b"; - String data3 = "c"; - String data4 = "d"; - - for (int i = 0; i < 13; i++) { - data1 += data1; - } - - for (int i = 0; i < 12; i++) { - data2 += data2; - } - for (int i = 0; i < 11; i++) { - data3 += data3; - } - for (int i = 0; i < 10; i++) { - data4 += data4; - } - String data; - data = data1 + data2 + data3 + data4; - - String data5 = "a"; - - Account account = PublicMethed.queryAccountByAddress(fromAddress, blockingStubFull); - System.out.println(Long.toString(account.getBalance())); - long accountBalance = account.getBalance(); - - Random random = new Random(); - int randNumber = random.nextInt(15) + 15; - - System.out.println("random number:" + randNumber); - - try { - Thread.sleep(randNumber); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - for (int ii = 1; ii < 111100000; ii++) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] userAddress = ecKey1.getAddress(); - String inputKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String addresstest = Base58.encode58Check(userAddress); - - String saleContractString = "\"" + data + "\"" + "," + "\"" - + Base58.encode58Check(userAddress) + "\""; - - System.out.println("long string address:" + addresstest); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "update2(string,address)", - saleContractString, false, 0, 1000000000L, fromAddress, testKey002, blockingStubFull); - logger.info(txid); - - String saleContractString1 = "\"" + data5 + "\"" + "," + "\"" - + Base58.encode58Check(userAddress) + "\""; - - System.out.println("short string address:" + addresstest); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "update2(string,address)", - saleContractString1, false, 0, 1000000000L, fromAddress, testKey002, blockingStubFull); - logger.info(txid); - - System.out.println("time out"); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "testUseCpu(uint256)", - "1000000000", false, 0, 1000000000L, fromAddress, testKey002, blockingStubFull); - - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - - infoById.get().getResultValue(); - - String isSuccess; - - if (infoById.get().getResultValue() == 0) { - logger.info("success:" + " Number:" + ii); - isSuccess = "success"; - } else { - logger.info("failed" + " Number:" + ii); - isSuccess = "fail"; - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMutiSignStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestMutiSignStress.java deleted file mode 100644 index 7f0382b2681..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestMutiSignStress.java +++ /dev/null @@ -1,146 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; - -@Slf4j -public class TestMutiSignStress { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - ByteString assetAccountId1; - String[] ownerKeyString = new String[1]; - String accountPermissionJson = ""; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 30) - public void testMutiSignForAccount() { - PublicMethed.printAddress(testKey002); - - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] ownerAddress = ecKey3.getAddress(); - - Assert.assertTrue(PublicMethed.sendcoin(ownerAddress, 9968981537400L, fromAddress, testKey002, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - String[] permissionKeyString = new String[3]; - permissionKeyString[0] = manager1Key; - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - permissionKeyString[1] = manager2Key; - String ownerKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - permissionKeyString[2] = ownerKey; - String[] ownerKeyString = new String[1]; - ownerKeyString[0] = ownerKey; - - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":3,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(ownerKey) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"7fff1fc0033e0000000000000000000000000000000000000000000000000000\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - logger.info(accountPermissionJson); - PublicMethedForMutiSign.accountPermissionUpdate(accountPermissionJson, ownerAddress, ownerKey, - blockingStubFull, ownerKeyString); - - //permissionKeyString[0] = ownerKey; - - String[] ownerKeyString1 = new String[3]; - ownerKeyString1[0] = ownerKey; - ownerKeyString1[1] = manager1Key; - ownerKeyString1[2] = manager2Key; - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Integer i = 0; - while (i++ <= 1000) { - ecKey4 = new ECKey(Utils.getRandom()); - newAddress = ecKey4.getAddress(); - newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - PublicMethed.printAddress(newKey); - - PublicMethedForMutiSign.sendcoin( - newAddress, 4000000L, ownerAddress, ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.freezeBalance( - ownerAddress, 1000000L, 0, ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.freezeBalanceGetEnergy( - ownerAddress, 1000000L, 0, 1, ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.freezeBalanceForReceiver( - ownerAddress, 1000000L, 0, 0, ByteString.copyFrom(newAddress), - ownerKey, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.unFreezeBalance( - ownerAddress, ownerKey, 0, null, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.unFreezeBalance( - ownerAddress, ownerKey, 0, newAddress, blockingStubFull, ownerKeyString1); - PublicMethedForMutiSign.updateAccount( - ownerAddress, Long.toString(System.currentTimeMillis()).getBytes(), ownerKey, - blockingStubFull, ownerKeyString1); - } - - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetErc721Cat.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetErc721Cat.java deleted file mode 100644 index 8af17ca172f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetErc721Cat.java +++ /dev/null @@ -1,389 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestNetErc721Cat { - - //testng001、testng002、testng003、testng004 - //testng001、testng002、testng003、testng004 - private final String testKey002 = - //"7306c6044ad7c03709980aa188b8555288b7e0608f5edbf76ff2381c5a7a15a8"; - //"3a54ba30e3ee41b602eca8fb3a3ca1f99f49a3d3ab5d8d646a2ccdd3ffd9c21d"; - //fromAddress - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String kittyCoreAddressAndCut = ""; - byte[] kittyCoreContractAddress = null; - byte[] saleClockAuctionContractAddress = null; - byte[] siringClockAuctionContractAddress = null; - byte[] geneScienceInterfaceContractAddress = null; - Integer consumeUserResourcePercent = 20; - String txid = ""; - Optional infoById = null; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] deployAddress = ecKey1.getAddress(); - String deployKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] triggerAddress = ecKey2.getAddress(); - String triggerKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(deployKey); - PublicMethed.printAddress(triggerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(deployAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.sendcoin(triggerAddress, 50000000000L, fromAddress, - testKey002, blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(deployAddress, 100000000L, - 3, 1, deployKey, blockingStubFull)); - /* Assert.assertTrue(PublicMethed.freezeBalanceGetCpu(triggerAddress,100000000L, - 3,1,triggerKey,blockingStubFull));*/ - /*Assert.assertTrue(PublicMethed.buyStorage(500000000L,deployAddress,deployKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed.buyStorage(500000000L,triggerAddress,triggerKey, - blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(deployAddress,100000000L,3, - deployKey,blockingStubFull)); - Assert.assertTrue(PublicMethed.freezeBalance(triggerAddress,100000000L,3, - triggerKey,blockingStubFull));*/ - - } - - @Test(enabled = false) - public void deployErc721KittyCore() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployAddress, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "KittyCore"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deployErc721KittyCore"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deployErc721KittyCore"); - logger.info("Kitty Core"); - kittyCoreContractAddress = PublicMethed.deployContract(contractName, abi, code, "", - maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(kittyCoreContractAddress, - blockingStubFull); - - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress)); - logger.info(ByteArray.toHexString(kittyCoreContractAddress).substring(2)); - - kittyCoreAddressAndCut = "000000000000000000000000" + ByteArray - .toHexString(kittyCoreContractAddress).substring(2); - kittyCoreAddressAndCut = kittyCoreAddressAndCut + "0000000000000000000000000000000000000000000" - + "000000000000000000100"; - } - - @Test(enabled = false) - public void deploySaleClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "SaleClockAuction"; - logger.info("Sale Clock Auction"); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deploySaleClockAuction"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deploySaleClockAuction"); - saleClockAuctionContractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(saleClockAuctionContractAddress, - blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - @Test(enabled = false) - public void deploySiringClockAuction() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "SiringClockAuction"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deploySiringClockAuction"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deploySiringClockAuction"); - logger.info("Siring Clock Auction"); - siringClockAuctionContractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, 0L, consumeUserResourcePercent, null, deployKey, - deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(siringClockAuctionContractAddress, - blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - @Test(enabled = false) - public void deployGeneScienceInterface() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(deployAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "GeneScienceInterface"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetErc721Cat_deployGeneScienceInterface"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetErc721Cat_deployGeneScienceInterface"); - logger.info("gene Science Interface"); - geneScienceInterfaceContractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, consumeUserResourcePercent, null, deployKey, deployAddress, blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(geneScienceInterfaceContractAddress, - blockingStubFull); - Assert.assertTrue(smartContract.getAbi() != null); - accountResource = PublicMethed.getAccountResource(deployAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(deployKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - } - - @Test(enabled = false) - public void triggerToSetThreeContractAddressToKittyCore() { - //Set SaleAuctionAddress to kitty core. - String saleContractString = "\"" + Base58.encode58Check(saleClockAuctionContractAddress) + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "setSaleAuctionAddress(address)", - saleContractString, false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getReceipt().getStorageDelta() > 50); - - //Set SiringAuctionAddress to kitty core. - String siringContractString = "\"" + Base58.encode58Check(siringClockAuctionContractAddress) - + "\""; - txid = PublicMethed - .triggerContract(kittyCoreContractAddress, "setSiringAuctionAddress(address)", - siringContractString, false, 0, 10000000L, - deployAddress, deployKey, blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getReceipt().getStorageDelta() > 50); - - //Set gen contract to kitty core - String genContractString = "\"" + Base58.encode58Check(geneScienceInterfaceContractAddress) - + "\""; - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setGeneScienceAddress(address)", genContractString, - false, 0, 10000000L, deployAddress, deployKey, blockingStubFull); - logger.info(txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getReceipt().getStorageDelta() > 50); - - //Start the game. - txid = PublicMethed.triggerContract(kittyCoreContractAddress, "unpause()", "", false, 0, - 10000000L, deployAddress, deployKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - logger.info("start the game " + txid); - - //Create one gen0 cat. - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "-1000000000000000", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "gen0CreatedCount()", "#", false, - 0, 100000000L, deployAddress, deployKey, blockingStubFull); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - /* txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "name()","#",false,0,10000000,triggerAddress, - triggerKey,blockingStubFull); - logger.info("getname " + txid);*/ - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "getKitty(uint256)", "1", false, 0, 10000000, triggerAddress, - triggerKey, blockingStubFull); - logger.info("getKitty " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - String newCxoAddress = "\"" + Base58.encode58Check(triggerAddress) - + "\""; - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCOO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("COO " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCFO(address)", newCxoAddress, false, 0, 10000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CFO " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "setCEO(address)", newCxoAddress, false, 0, 1000000, deployAddress, - deployKey, blockingStubFull); - logger.info("CEO " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0); - } - - @Test(enabled = false, threadPoolSize = 1, invocationCount = 1) - public void unCreateKitty() { - Integer times = 0; - logger.info("In create kitty, kitty core address is " + ByteArray - .toHexString(kittyCoreContractAddress)); - while (times++ < 20) { - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createGen0Auction(uint256)", "0", false, - 0, 100000000L, triggerAddress, triggerKey, blockingStubFull); - logger.info("createGen0 " + txid); - infoById = PublicMethed.getTransactionInfoById(txid, blockingStubFull); - //Assert.assertTrue(infoById.get().getResultValue() == 0); - /* String promoKitty = "\"" + times.toString() + "\",\"" - + Base58.encode58Check(kittyCoreContractAddress) + "\""; - logger.info(promoKitty); - txid = PublicMethed.triggerContract(kittyCoreContractAddress, - "createPromoKitty(uint256,address)", promoKitty,false, - 0,10000000L,triggerAddress,triggerKey,blockingStubFull); - logger.info("createPromoKitty " + txid); - infoById = PublicMethed.getTransactionInfoById(txid,blockingStubFull); - Assert.assertTrue(infoById.get().getResultValue() == 0);*/ - try { - Thread.sleep(10); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - } - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetFomo3D.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetFomo3D.java deleted file mode 100644 index 9c84ac0bf96..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestNetFomo3D.java +++ /dev/null @@ -1,207 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import static stest.tron.wallet.common.client.utils.PublicMethed.getTransactionInfoById; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.AccountResourceMessage; -import org.tron.api.WalletGrpc; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestNetFomo3D { - - //testng001、testng002、testng003、testng004 - private final String testNetAccountKey = - "FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6"; - //"BC70ADC5A0971BA3F7871FBB7249E345D84CE7E5458828BE1E28BF8F98F2795B"; - private final byte[] testNetAccountAddress = PublicMethed.getFinalAddress(testNetAccountKey); - Optional infoById = null; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = false) - public void beforeClass() { - PublicMethed.printAddress(testNetAccountKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - logger.info(Long.toString(PublicMethed.queryAccount(testNetAccountKey, blockingStubFull) - .getBalance())); - //Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(testNetAccountAddress,10000000L, - //3,1,testNetAccountKey,blockingStubFull)); - /* Assert.assertTrue(PublicMethed.buyStorage(50000000L,testNetAccountAddress, - testNetAccountKey, - blockingStubFull));*/ - - } - - @Test(enabled = false) - public void deployErc721CryptoKitties() { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testNetAccountAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - //Long storageLimit = accountResource.getStorageLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - //Long storageUsage = accountResource.getStorageUsed(); - Account account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - //logger.info("before storage limit is " + Long.toString(storageLimit)); - //logger.info("before storage usaged is " + Long.toString(storageUsage)); - Long maxFeeLimit = 3900000000L; - String contractName = "Fomo3D"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetFomo3D_deployErc721CryptoKitties"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetFomo3D_deployErc721CryptoKitties"); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, testNetAccountKey, testNetAccountAddress, blockingStubFull); - - String code1 = Configuration.getByPath("testng.conf") - .getString("code.code1_TestNetFomo3D_deployErc721CryptoKitties"); - String abi1 = Configuration.getByPath("testng.conf") - .getString("abi.abi1_TestNetFomo3D_deployErc721CryptoKitties"); - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi1, - code1, "", maxFeeLimit, 0L, 100, null, - testNetAccountKey, testNetAccountAddress, blockingStubFull); - - final SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - accountResource = PublicMethed.getAccountResource(testNetAccountAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - //logger.info("after storage limit is " + Long.toString(storageLimit)); - //logger.info("after storage usaged is " + Long.toString(storageUsage)); - //Assert.assertTrue(storageUsage > 0); - //Assert.assertTrue(storageLimit > 0); - Assert.assertTrue(cpuLimit > 0); - Assert.assertTrue(cpuUsage > 0); - - Assert.assertFalse(smartContract.getAbi().toString().isEmpty()); - Assert.assertTrue(smartContract.getName().equalsIgnoreCase(contractName)); - Assert.assertFalse(smartContract.getBytecode().toString().isEmpty()); - //logger.info(smartContract.getName()); - //logger.info(smartContract.getAbi().toString()); - - } - - @Test(enabled = false) - public void tooLargeStorage() throws IOException { - AccountResourceMessage accountResource = PublicMethed.getAccountResource(testNetAccountAddress, - blockingStubFull); - Long cpuLimit = accountResource.getEnergyLimit(); - Long cpuUsage = accountResource.getEnergyUsed(); - Account account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("before balance is " + Long.toString(account.getBalance())); - logger.info("before cpu limit is " + Long.toString(cpuLimit)); - logger.info("before cpu usage is " + Long.toString(cpuUsage)); - Long maxFeeLimit = 100000000000000000L; - String contractName = "tooLargeStorage"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestNetFomo3D_tooLargeStorage"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestNetFomo3D_tooLargeStorage"); - String txid = PublicMethed.deployContractAndGetTransactionInfoById(contractName, abi, - code, "", maxFeeLimit, 0L, 100, null, - testNetAccountKey, testNetAccountAddress, blockingStubFull); - infoById = getTransactionInfoById(txid, blockingStubFull); - accountResource = PublicMethed.getAccountResource(testNetAccountAddress, blockingStubFull); - cpuLimit = accountResource.getEnergyLimit(); - //storageLimit = accountResource.getStorageLimit(); - cpuUsage = accountResource.getEnergyUsed(); - //storageUsage = accountResource.getStorageUsed(); - account = PublicMethed.queryAccount(testNetAccountKey, blockingStubFull); - logger.info("after balance is " + Long.toString(account.getBalance())); - logger.info("after cpu limit is " + Long.toString(cpuLimit)); - logger.info("after cpu usage is " + Long.toString(cpuUsage)); - - /* String name = readFromXieChang();*/ - String stringTimes = Integer.toString(7); - byte[] contractAddress = infoById.get().getContractAddress().toByteArray(); - txid = PublicMethed.triggerContract(contractAddress, "slice(uint256)", stringTimes, false, - 0, maxFeeLimit, testNetAccountAddress, testNetAccountKey, blockingStubFull); - logger.info("slice " + txid); - logger.info(Integer.toString(infoById.get().getResultValue())); - infoById = getTransactionInfoById(txid, blockingStubFull); - - txid = PublicMethed.triggerContract(contractAddress, "s()", "#", false, - 0, maxFeeLimit, testNetAccountAddress, testNetAccountKey, blockingStubFull); - logger.info(txid); - logger.info(Integer.toString(infoById.get().getResultValue())); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public String readFromXieChang() throws IOException { - File file = new File( - "/Users/wangzihe/Desktop/ddd.txt"); - FileReader reader = null; - try { - reader = new FileReader(file); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - BufferedReader reAder = new BufferedReader(reader); - StringBuilder sb = new StringBuilder(); - String s = ""; - while ((s = reAder.readLine()) != null) { - sb.append(s); - } - - String code = sb.toString(); - reAder.close(); - return code; - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestOperations.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestOperations.java deleted file mode 100644 index ece70cb9ccf..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestOperations.java +++ /dev/null @@ -1,43 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.Test; -import org.tron.common.utils.ByteArray; - -@Slf4j -public class TestOperations { - - @Test(enabled = true) - public void test002() { - //指定需要支持的合约id(查看proto中Transaction.ContractType定义), - // 这里包含除AccountPermissionUpdateContract(id=46)以外的所有合约 - Integer[] contractId = {0, 1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 30, 31, 33, - 41, 42, 43, 44, 45, 48, 49}; - List list = new ArrayList<>(Arrays.asList(contractId)); - byte[] operations = new byte[32]; - list.forEach(e -> { - operations[e / 8] |= (1 << e % 8); - }); - //77ff07c0023e0300000000000000000000000000000000000000000000000000 - logger.info(ByteArray.toHexString(operations)); - } - - @Test(enabled = true) - public void test003() { - String operations = "77ff07c0023e0300000000000000000000000000000000000000000000000000"; - List contractId = new ArrayList<>(); - for (int i = 0; i < operations.length(); i = i + 2) { - int operation16 = Integer.valueOf(operations.substring(i, i + 2), 16); - for (int n = 0; n < 8; n++) { - int tmp = 1 << n; - if ((tmp & operation16) == tmp) { - contractId.add(i * 4 + n); - } - } - } - logger.info(contractId.toString()); - } -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java deleted file mode 100644 index 458daa381b4..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestStorageAndCpu.java +++ /dev/null @@ -1,233 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Random; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.ChainParameters; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; - -@Slf4j -public class TestStorageAndCpu { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("witness.key5"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("witness.key4"); - private final byte[] testAddress003 = PublicMethed.getFinalAddress(testKey003); - - private final String testKey004 = Configuration.getByPath("testng.conf") - .getString("witness.key3"); - private final byte[] testAddress004 = PublicMethed.getFinalAddress(testKey004); - ArrayList txidList = new ArrayList(); - Optional infoById = null; - Long beforeTime; - Long afterTime; - Long beforeBlockNum; - Long afterBlockNum; - Block currentBlock; - Long currentBlockNum; - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = "47.94.243.150:50051"; - private String fullnode1 = "47.94.243.150:50051"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(testKey002); - PublicMethed.printAddress(testKey003); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - beforeTime = System.currentTimeMillis(); - } - - @Test(enabled = true,threadPoolSize = 1, invocationCount = 1) - public void scanBlock() { - Long startNum = 26165658L; - Long endNum = 26166320L; - Integer totalNum = 0; - Integer successNum = 0; - Integer failedNum = 0; - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (startNum <= endNum) { - logger.info("scan block num:" + startNum); - builder.setNum(startNum); - List transactionList = blockingStubFull - .getBlockByNum(builder.build()).getTransactionsList(); - Integer transactionNumInThisBlock = transactionList.size(); - totalNum = totalNum + transactionNumInThisBlock; - for (Transaction transaction : transactionList) { - if (transaction.getRet(0).getContractRet().name().equals("SUCCESS")) { - successNum++; - } else { - failedNum++; - logger.info(transaction.getRet(0).getContractRet().name()); - } - } - startNum++; - } - logger.info("successNum:" + successNum); - logger.info("failedNum:" + failedNum); - logger.info("totalNum:" + totalNum); - logger.info("Success rate:" + (double)failedNum / (double)totalNum); - } - - @Test(enabled = true, threadPoolSize = 1, invocationCount = 1) - public void storageAndCpu() { - Random rand = new Random(); - Integer randNum = rand.nextInt(30) + 1; - randNum = rand.nextInt(4000); - - Long maxFeeLimit = 1000000000L; - String contractName = "StorageAndCpu" + Integer.toString(randNum); - String code = Configuration.getByPath("testng.conf") - .getString("code.code_TestStorageAndCpu_storageAndCpu"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_TestStorageAndCpu_storageAndCpu"); - PublicMethed - .freezeBalanceGetEnergy(fromAddress, 1000000000000L, 3, 1, testKey002, blockingStubFull); - byte[] contractAddress = PublicMethed.deployContract(contractName, abi, code, - "", maxFeeLimit, - 0L, 100, null, testKey002, fromAddress, blockingStubFull); - try { - Thread.sleep(30000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - String txid; - - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - - Integer i = 1; - while (i++ < 8000) { - String initParmes = "\"" + "930" + "\""; - txid = PublicMethed.triggerContract(contractAddress, - "testUseCpu(uint256)", "9100", false, - 0, maxFeeLimit, fromAddress, testKey002, blockingStubFull); - txid = PublicMethed.triggerContract(contractAddress, - "storage8Char()", "", false, - 0, maxFeeLimit, fromAddress, testKey002, blockingStubFull); - //storage 9 EnergyUsageTotal is 211533, 10 is 236674, 5 is 110969,21 is 500000 - txid = PublicMethed.triggerContract(contractAddress, - "testUseStorage(uint256)", "21", false, - 0, maxFeeLimit, fromAddress, testKey002, blockingStubFull); - //logger.info("i is " +Integer.toString(i) + " " + txid); - //txidList.add(txid); - try { - Thread.sleep(50); - } catch (InterruptedException e) { - e.printStackTrace(); - } - if (i % 10 == 0) { - chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - getChainParameters = Optional.ofNullable(chainParameters); - logger.info(getChainParameters.get().getChainParameter(22).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(22).getValue())); - logger.info(getChainParameters.get().getChainParameter(23).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(23).getValue())); - - } - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - /* - afterTime = System.currentTimeMillis(); - try { - Thread.sleep(10000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - currentBlock = blockingStubFull1.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock.getBlockHeader().getRawData().getNumber() + 2; - Long blockNum = beforeBlockNum; - Integer txsNum = 0; - Integer topNum = 0; - Integer totalNum = 0; - Long energyTotal = 0L; - String findOneTxid = ""; - - NumberMessage.Builder builder = NumberMessage.newBuilder(); - while (blockNum <= afterBlockNum) { - builder.setNum(blockNum); - txsNum = blockingStubFull1.getBlockByNum(builder.build()).getTransactionsCount(); - totalNum = totalNum + txsNum; - if (topNum < txsNum) { - topNum = txsNum; - findOneTxid = ByteArray.toHexString(Sha256Hash.hash(blockingStubFull1 - .getBlockByNum(builder.build()).getTransactionsList().get(2) - .getRawData().toByteArray())); - //logger.info("find one txid is " + findOneTxid); - } - - blockNum++; - } - Long costTime = (afterTime - beforeTime - 31000) / 1000; - logger.info("Duration block num is " + (afterBlockNum - beforeBlockNum - 11)); - logger.info("Cost time are " + costTime); - logger.info("Top block txs num is " + topNum); - logger.info("Total transaction is " + (totalNum - 30)); - logger.info("Average Tps is " + (totalNum / costTime)); - - infoById = PublicMethed.getTransactionInfoById(findOneTxid, blockingStubFull1); - Long oneEnergyTotal = infoById.get().getReceipt().getEnergyUsageTotal(); - logger.info("EnergyTotal is " + oneEnergyTotal); - logger.info("Average energy is " + oneEnergyTotal * (totalNum / costTime)); -*/ - - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TestTransferTokenInContract.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TestTransferTokenInContract.java deleted file mode 100644 index 628b2843d8f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TestTransferTokenInContract.java +++ /dev/null @@ -1,324 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.AssetIssueList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class TestTransferTokenInContract { - - private static final long TotalSupply = 1000000L; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private AtomicLong count = new AtomicLong(); - private AtomicLong errorCount = new AtomicLong(); - private long startTime = System.currentTimeMillis(); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - - private static int randomInt(int minInt, int maxInt) { - return (int) Math.round(Math.random() * (maxInt - minInt) + minInt); - } - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - } - - /** - * constructor. - */ - - public ByteString createAssetissue(byte[] devAddress, String devKey, String tokenName) { - - ByteString assetAccountId = null; - ByteString addressBS1 = ByteString.copyFrom(devAddress); - Account request1 = Account.newBuilder().setAddress(addressBS1).build(); - GrpcAPI.AssetIssueList assetIssueList1 = blockingStubFull - .getAssetIssueByAccount(request1); - Optional queryAssetByAccount = Optional.ofNullable(assetIssueList1); - if (queryAssetByAccount.get().getAssetIssueCount() == 0) { - Long start = System.currentTimeMillis() + 2000; - Long end = System.currentTimeMillis() + 1000000000; - - logger.info("The token name: " + tokenName); - - //Create a new AssetIssue success. - Assert.assertTrue(PublicMethed.createAssetIssue(devAddress, tokenName, TotalSupply, 1, - 100, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, devKey, blockingStubFull)); - - Account getAssetIdFromThisAccount = PublicMethed.queryAccount(devAddress, blockingStubFull); - assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - } else { - logger.info("This account already create an assetisue"); - Optional queryAssetByAccount1 = Optional.ofNullable(assetIssueList1); - tokenName = ByteArray.toStr(queryAssetByAccount1.get().getAssetIssue(0) - .getName().toByteArray()); - } - return assetAccountId; - } - - @Test(enabled = true, threadPoolSize = 2, invocationCount = 2) - public void continueRun() { - - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] dev001Address = ecKey1.getAddress(); - String dev001Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] user001Address = ecKey2.getAddress(); - String user001Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert - .assertTrue(PublicMethed.sendcoin(dev001Address, 2048000000, fromAddress, - testKey002, blockingStubFull)); - Assert - .assertTrue(PublicMethed.sendcoin(user001Address, 4048000000L, fromAddress, - testKey002, blockingStubFull)); - - // freeze balance - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(dev001Address, 204800000, - 0, 1, dev001Key, blockingStubFull)); - - Assert.assertTrue(PublicMethed.freezeBalanceGetEnergy(user001Address, 2048000000, - 0, 1, user001Key, blockingStubFull)); - - String tokenName = "testAI_" + randomInt(10000, 90000); - ByteString tokenId = createAssetissue(user001Address, user001Key, tokenName); - - // devAddress transfer token to A - PublicMethed.transferAsset(dev001Address, tokenId.toByteArray(), 101, user001Address, - user001Key, blockingStubFull); - - // deploy transferTokenContract - String contractName = "transferTokenContract"; - String code = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000" - + "000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080" - + "fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b604051" - + "73ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8a" - + "d094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a723058200ba246bdb58b" - + "e0f221ad07e1b19de843ab541150b329ddd01558c2f1cefe1e270029"; - String abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}," - + "{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}]," - + "\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":" - + "\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\"" - + ":\"payable\",\"type\":\"constructor\"}]"; - byte[] transferTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, 10000, tokenId.toStringUtf8(), - 100, null, dev001Key, dev001Address, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // deploy receiveTokenContract - contractName = "recieveTokenContract"; - code = "60806040526000805560c5806100166000396000f30060806040526004361060485763ffffffff7c0100000" - + "00000000000000000000000000000000000000000000000000060003504166362548c7b8114604a578063890" - + "eba68146050575b005b6048608c565b348015605b57600080fd5b50d38015606757600080fd5b50d28015607" - + "357600080fd5b50607a6093565b60408051918252519081900360200190f35b6001600055565b60005481560" - + "0a165627a7a723058204c4f1bb8eca0c4f1678cc7cc1179e03d99da2a980e6792feebe4d55c89c022830029"; - abi = "[{\"constant\":false,\"inputs\":[],\"name\":\"setFlag\",\"outputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[]," - + "\"name\":\"flag\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"fallback\"}]"; - byte[] receiveTokenContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - // deploy tokenBalanceContract - contractName = "tokenBalanceContract"; - code = "608060405260ff806100126000396000f30060806040526004361060485763ffffffff7c010000000000000" - + "0000000000000000000000000000000000000000000600035041663a730416e8114604d578063b69ef8a8146" - + "081575b600080fd5b606f73ffffffffffffffffffffffffffffffffffffffff6004351660243560ab565b604" - + "08051918252519081900360200190f35b348015608c57600080fd5b50d38015609857600080fd5b50d280156" - + "0a457600080fd5b50606f60cd565b73ffffffffffffffffffffffffffffffffffffffff90911690d16000908" - + "15590565b600054815600a165627a7a723058202b6235122df66c062c2e723ad58a9fea93346f3bc19898971" - + "8f211aa1dbd2d7a0029"; - abi = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}," - + "{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":" - + "[{\"name\":\"b\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":" - + "\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":" - + "\"balance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false," - + "\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true," - + "\"stateMutability\":\"payable\",\"type\":\"constructor\"}]"; - byte[] tokenBalanceContractAddress = PublicMethed - .deployContract(contractName, abi, code, "", maxFeeLimit, - 0L, 100, null, dev001Key, dev001Address, blockingStubFull); - - // devAddress transfer token to userAddress - PublicMethed.transferAsset(user001Address, tokenId.toByteArray(), 100, dev001Address, dev001Key, - blockingStubFull); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull1); - - for (int i = 0; i < 1000000000000L; i++) { - logger.info("** This is " + i + "times --------------------------------------------"); - count.getAndAdd(4); - if (count.get() % 500 == 0) { - long cost = (System.currentTimeMillis() - startTime) / 1000; - logger.info("Count:" + count.get() + ", cost:" + cost - + ", avg:" + count.get() / cost + ", errCount:" + errorCount); - } - PublicMethed.freezeBalanceForReceiver(user001Address, - PublicMethed.getFreezeBalanceCount(user001Address, - user001Key, 300000L, blockingStubFull), 0, - 1, ByteString.copyFrom(fromAddress), testKey002, blockingStubFull); - PublicMethed.freezeBalanceForReceiver(user001Address, 10_000_000L, - 0, 0, ByteString.copyFrom(fromAddress), testKey002, blockingStubFull); - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - // user trigger A to transfer token to B - String param = - "\"" + Base58.encode58Check(receiveTokenContractAddress) + "\",\"" + tokenId - .toStringUtf8() - + "\",\"5\""; - - String triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, tokenId.toStringUtf8(), - 10, user001Address, user001Key, - blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - // user trigger A to transfer token to devAddress - param = - "\"" + Base58.encode58Check(dev001Address) + "\",\"" + tokenId.toStringUtf8() - + "\",\"5\""; - - triggerTxid = PublicMethed.triggerContract(transferTokenContractAddress, - "TransferTokenTo(address,trcToken,uint256)", - param, false, 0, 100000000L, user001Address, - user001Key, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - // user trigger C to get B's token balance - param = - "\"" + Base58.encode58Check(receiveTokenContractAddress) + "\",\"" + tokenId - .toStringUtf8() - + "\""; - - triggerTxid = PublicMethed - .triggerContract(tokenBalanceContractAddress, "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - PublicMethed.triggerContract(tokenBalanceContractAddress, "balance()", - "#", false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - // user trigger C to get devAddress's token balance - param = "\"" + Base58.encode58Check(dev001Address) + "\",\"" + tokenId.toStringUtf8() + "\""; - - triggerTxid = PublicMethed - .triggerContract(tokenBalanceContractAddress, "getTokenBalnce(address,trcToken)", - param, false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - infoById = PublicMethed - .getTransactionInfoById(triggerTxid, blockingStubFull); - - if (infoById.get().getResultValue() != 0) { - errorCount.incrementAndGet(); - } - - PublicMethed.triggerContract(tokenBalanceContractAddress, "balance()", - "#", false, 0, 1000000000L, user001Address, - user001Key, blockingStubFull); - - PublicMethed.unFreezeBalance(fromAddress, user001Key, 1, - user001Address, blockingStubFull); - PublicMethed.unFreezeBalance(fromAddress, user001Key, 0, - user001Address, blockingStubFull); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/TransactionCheck.java b/framework/src/test/java/stest/tron/wallet/onlinestress/TransactionCheck.java deleted file mode 100644 index c14e596e378..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/TransactionCheck.java +++ /dev/null @@ -1,52 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import org.testng.annotations.Test; -import org.tron.common.crypto.ECKey.ECDSASignature; -import org.tron.common.crypto.SignUtils; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Sha256Hash; - -public class TransactionCheck { - - @Test - public void hexToTransaction() throws Exception { - String targetHex1 = ""; - String targetHex2 = ""; - String hex = targetHex1; - org.tron.protos.Protocol.Transaction transaction = org.tron.protos.Protocol.Transaction - .parseFrom(ByteArray.fromHexString(hex)); - getBase64FromByteString(transaction.getSignature(0)); - String base64 = getBase64FromByteString(transaction.getSignature(0)); - byte[] address = SignUtils - .signatureToAddress((Sha256Hash - .hash(CommonParameter.getInstance().isECKeyCryptoEngine(), - transaction.getRawData().toByteArray())), base64, - CommonParameter.getInstance().isECKeyCryptoEngine()); - String addressStr = WalletClient.encode58Check(address); - String data = String.valueOf(transaction.getRawData().getData().toStringUtf8()); - System.out.println(addressStr); - System.out.println(data); - } - - - /** - * constructor. - */ - public static String getBase64FromByteString(ByteString sign) { - byte[] r = sign.substring(0, 32).toByteArray(); - byte[] s = sign.substring(32, 64).toByteArray(); - byte v = sign.byteAt(64); - if (v < 27) { - v += 27; //revId -> v - } - ECDSASignature signature = ECDSASignature.fromComponents(r, s, v); - return signature.toBase64(); - } - - - - -} diff --git a/framework/src/test/java/stest/tron/wallet/onlinestress/WalletTestZenTokenStress.java b/framework/src/test/java/stest/tron/wallet/onlinestress/WalletTestZenTokenStress.java deleted file mode 100644 index 68924eb6d56..00000000000 --- a/framework/src/test/java/stest/tron/wallet/onlinestress/WalletTestZenTokenStress.java +++ /dev/null @@ -1,268 +0,0 @@ -package stest.tron.wallet.onlinestress; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.DecryptNotes; -import org.tron.api.GrpcAPI.DiversifierMessage; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExpandedSpendingKeyMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyDiversifierMessage; -import org.tron.api.GrpcAPI.IncomingViewingKeyMessage; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.PaymentAddressMessage; -import org.tron.api.GrpcAPI.ViewingKeyMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.core.zen.address.DiversifierT; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - - -@Slf4j -public class WalletTestZenTokenStress { - - private static ByteString assetAccountId = null; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - Optional sendShieldAddressInfo; - Optional receiverShieldAddressInfo; - String sendShieldAddress; - String receiverShieldAddress; - List shieldOutList = new ArrayList<>(); - DecryptNotes notes; - String memo; - Note sendNote; - Note receiverNote; - BytesMessage ak; - BytesMessage nk; - BytesMessage sk; - ExpandedSpendingKeyMessage expandedSpendingKeyMessage; - DiversifierMessage diversifierMessage1; - DiversifierMessage diversifierMessage2; - DiversifierMessage diversifierMessage3; - IncomingViewingKeyMessage ivk; - ShieldAddressInfo addressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo3 = new ShieldAddressInfo(); - - Optional receiverAddressInfo1; - Optional receiverAddressInfo2; - Optional receiverAddressInfo3; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private ManagedChannel channelSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private ManagedChannel channelSolidity1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity1 = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - private String soliditynode1 = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private Long costTokenAmount = 1 * zenTokenFee + 1; - private Long sendTokenAmount = 1 * zenTokenFee; - - - - /** - * constructor. - */ - @BeforeClass(enabled = true) - public void beforeClass() { - PublicMethed.printAddress(foundationZenTokenKey); - PublicMethed.printAddress(zenTokenOwnerKey); - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - channelSolidity1 = ManagedChannelBuilder.forTarget(soliditynode1) - .usePlaintext(true) - .build(); - blockingStubSolidity1 = WalletSolidityGrpc.newBlockingStub(channelSolidity1); - - Assert.assertTrue(PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Args.setFullNodeAllowShieldedTransaction(true); - - - } - - @Test(enabled = true, threadPoolSize = 3, invocationCount = 3) - public void test1Shield2ShieldTransaction() throws InterruptedException { - List shieldOutList = new ArrayList<>(); - Integer times = 0; - Optional sendShieldAddressInfo = PublicMethed.generateShieldAddress(); - String sendShieldAddress = sendShieldAddressInfo.get().getAddress(); - String memo = "7"; - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - while (times++ < 10000) { - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] zenTokenOwnerAddress = ecKey1.getAddress(); - - PublicMethed.transferAsset(zenTokenOwnerAddress, tokenId, - zenTokenFee * 2, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - memo = times + ":shield note number"; - shieldOutList.clear(); - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, sendShieldAddress, - "" + zenTokenFee, memo); - String zenTokenOwnerKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - PublicMethed.sendShieldCoin(zenTokenOwnerAddress, 2 * zenTokenFee, null, - null, shieldOutList, null, 0, zenTokenOwnerKey, blockingStubFull); - /* logger.info("Note number:" - + PublicMethed.getShieldNotesCount(sendShieldAddressInfo,blockingStubFull));*/ - } - - - } - - @Test(enabled = true, threadPoolSize = 30, invocationCount = 30) - public void test2Shield2ShieldTransaction() throws InterruptedException { - BytesMessage ak; - BytesMessage nk; - BytesMessage sk; - ExpandedSpendingKeyMessage expandedSpendingKeyMessage; - DiversifierMessage diversifierMessage1; - DiversifierMessage diversifierMessage2; - DiversifierMessage diversifierMessage3; - IncomingViewingKeyMessage ivk; - ShieldAddressInfo addressInfo1 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo2 = new ShieldAddressInfo(); - ShieldAddressInfo addressInfo3 = new ShieldAddressInfo(); - - Optional receiverAddressInfo1; - Optional receiverAddressInfo2; - Optional receiverAddressInfo3; - - Integer times = 0; - while (times++ < 10000) { - sk = blockingStubFull.getSpendingKey(EmptyMessage.newBuilder().build()); - //logger.info("sk: " + ByteArray.toHexString(sk.getValue().toByteArray())); - - diversifierMessage1 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - //logger.info("d1: " + ByteArray.toHexString(diversifierMessage1.getD().toByteArray())); - diversifierMessage2 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - //logger.info("d2: " + ByteArray.toHexString(diversifierMessage2.getD().toByteArray())); - diversifierMessage3 = blockingStubFull.getDiversifier(EmptyMessage.newBuilder().build()); - //logger.info("d3: " + ByteArray.toHexString(diversifierMessage3.getD().toByteArray())); - - expandedSpendingKeyMessage = blockingStubFull.getExpandedSpendingKey(sk); - - BytesMessage.Builder askBuilder = BytesMessage.newBuilder(); - askBuilder.setValue(expandedSpendingKeyMessage.getAsk()); - ak = blockingStubFull.getAkFromAsk(askBuilder.build()); - //logger.info("ak: " + ByteArray.toHexString(ak.getValue().toByteArray())); - - BytesMessage.Builder nskBuilder = BytesMessage.newBuilder(); - nskBuilder.setValue(expandedSpendingKeyMessage.getNsk()); - nk = blockingStubFull.getNkFromNsk(nskBuilder.build()); - //logger.info("nk: " + ByteArray.toHexString(nk.getValue().toByteArray())); - - ViewingKeyMessage.Builder viewBuilder = ViewingKeyMessage.newBuilder(); - viewBuilder.setAk(ak.getValue()); - viewBuilder.setNk(nk.getValue()); - ivk = blockingStubFull.getIncomingViewingKey(viewBuilder.build()); - //logger.info("ivk: " + ByteArray.toHexString(ivk.getIvk().toByteArray())); - - IncomingViewingKeyDiversifierMessage.Builder builder = - IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage1); - builder.setIvk(ivk); - PaymentAddressMessage addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - //System.out.println("address1: " + addressMessage.getPaymentAddress()); - addressInfo1.setSk(sk.getValue().toByteArray()); - addressInfo1.setD(new DiversifierT(diversifierMessage1.getD().toByteArray())); - addressInfo1.setIvk(ivk.getIvk().toByteArray()); - addressInfo1.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo1.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo1 = Optional.of(addressInfo1); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage2); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - //System.out.println("address2: " + addressMessage.getPaymentAddress()); - addressInfo2.setSk(sk.getValue().toByteArray()); - addressInfo2.setD(new DiversifierT(diversifierMessage2.getD().toByteArray())); - addressInfo2.setIvk(ivk.getIvk().toByteArray()); - addressInfo2.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo2.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo2 = Optional.of(addressInfo2); - - builder.clear(); - builder = IncomingViewingKeyDiversifierMessage.newBuilder(); - builder.setD(diversifierMessage3); - builder.setIvk(ivk); - addressMessage = blockingStubFull.getZenPaymentAddress(builder.build()); - //System.out.println("address3: " + addressMessage.getPaymentAddress()); - addressInfo3.setSk(sk.getValue().toByteArray()); - addressInfo3.setD(new DiversifierT(diversifierMessage3.getD().toByteArray())); - addressInfo3.setIvk(ivk.getIvk().toByteArray()); - addressInfo3.setOvk(expandedSpendingKeyMessage.getOvk().toByteArray()); - addressInfo3.setPkD(addressMessage.getPkD().toByteArray()); - receiverAddressInfo3 = Optional.of(addressInfo3); - } - - } - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - PublicMethed.transferAsset(foundationZenTokenAddress, tokenId, - PublicMethed.getAssetIssueValue(zenTokenOwnerAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull), zenTokenOwnerAddress, zenTokenOwnerKey, blockingStubFull); - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity1 != null) { - channelSolidity1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} \ No newline at end of file diff --git a/framework/src/test/java/stest/tron/wallet/other/deployMainGateway.java b/framework/src/test/java/stest/tron/wallet/other/deployMainGateway.java deleted file mode 100644 index 2a81c673f23..00000000000 --- a/framework/src/test/java/stest/tron/wallet/other/deployMainGateway.java +++ /dev/null @@ -1,129 +0,0 @@ -package stest.tron.wallet.other; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class deployMainGateway { - - - private final String testDepositTrx = "324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096" - + "c6bacb7"; - private final byte[] testDepositAddress = PublicMethed.getFinalAddress(testDepositTrx); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] depositAddress = ecKey1.getAddress(); - String testKeyFordeposit = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "deploy Main Chain Gateway") - public void test1DepositTrc20001() { - - PublicMethed.printAddress(testKeyFordeposit); - - Assert.assertTrue(PublicMethed - .sendcoin(depositAddress, 1000_000_000L, testDepositAddress, testDepositTrx, - blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Account accountOralce = PublicMethed.queryAccount(depositAddress, blockingStubFull); - long OralceBalance = accountOralce.getBalance(); - logger.info("OralceBalance: " + OralceBalance); - - String contractName = "gateWayContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_MainGateway"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_MainGateway"); - String parame = "\"" + Base58.encode58Check(testDepositAddress) + "\""; - - String deployTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address)", - parame, "", - maxFeeLimit, - 0L, 100, null, testKeyFordeposit, depositAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - byte[] mainChainGateway = infoById.get().getContractAddress().toByteArray(); - String mainChainGatewayAddress = WalletClient.encode58Check(mainChainGateway); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertNotNull(mainChainGateway); - - SmartContract smartContract = PublicMethed.getContract(mainChainGateway, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String outputPath = "./src/test/resources/mainChainGatewayAddress"; - try { - File mainChainFile = new File(outputPath); - Boolean cun = mainChainFile.createNewFile(); - FileWriter writer = new FileWriter(mainChainFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(mainChainGatewayAddress); - - out.close(); - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/other/deploySideGateway.java b/framework/src/test/java/stest/tron/wallet/other/deploySideGateway.java deleted file mode 100644 index 90b3266b149..00000000000 --- a/framework/src/test/java/stest/tron/wallet/other/deploySideGateway.java +++ /dev/null @@ -1,122 +0,0 @@ -package stest.tron.wallet.other; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class deploySideGateway { - - - private final String testDepositTrx = "324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096" - + "c6bacb7"; - private final byte[] testDepositAddress = PublicMethed.getFinalAddress(testDepositTrx); - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] depositAddress = ecKey1.getAddress(); - String testKeyFordeposit = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private Long maxFeeLimit = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.maxFeeLimit"); - private String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - private String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = "127.0.0.1:50151"; - - - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - } - - @Test(enabled = true, description = "deploy Side Chain Gateway") - public void test1DepositTrc20001() { - - PublicMethed.printAddress(testKeyFordeposit); - - String contractName = "gateWaysidechainContract"; - String code = Configuration.getByPath("testng.conf") - .getString("code.code_SideGateway"); - String abi = Configuration.getByPath("testng.conf") - .getString("abi.abi_SideGateway"); - String parame = "\"" + Base58.encode58Check(testDepositAddress) + "\""; - - String deployTxid = PublicMethed - .deployContractWithConstantParame(contractName, abi, code, "constructor(address)", - parame, "", - maxFeeLimit, - 0L, 100, null, testKeyFordeposit, depositAddress, - blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionInfoById(deployTxid, blockingStubFull); - byte[] mainChainGateway = infoById.get().getContractAddress().toByteArray(); - String mainChainGatewayAddress = WalletClient.encode58Check(mainChainGateway); - Assert.assertEquals(0, infoById.get().getResultValue()); - Assert.assertNotNull(mainChainGateway); - - SmartContract smartContract = PublicMethed.getContract(mainChainGateway, - blockingStubFull); - Assert.assertNotNull(smartContract.getAbi()); - - String outputPath = "./src/test/resources/sideChainGatewayAddress"; - try { - File mainChainFile = new File(outputPath); - Boolean cun = mainChainFile.createNewFile(); - FileWriter writer = new FileWriter(mainChainFile); - BufferedWriter out = new BufferedWriter(writer); - out.write(mainChainGatewayAddress); - - out.close(); - writer.close(); - } catch (Exception e) { - e.printStackTrace(); - } - - } - - /** - * constructor. - */ - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - -} diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java deleted file mode 100644 index e8b3d3acfe5..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer001.java +++ /dev/null @@ -1,320 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestTransfer001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - //send account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - final byte[] sendAccountAddress = ecKey1.getAddress(); - String sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - //receipt account - ECKey ecKey2 = new ECKey(Utils.getRandom()); - final byte[] receiptAccountAddress = ecKey2.getAddress(); - String receiptAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test - public void testSendCoin() { - //send account - ecKey1 = new ECKey(Utils.getRandom()); - final byte[] sendAccountAddress = ecKey1.getAddress(); - sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - //receipt account - ecKey2 = new ECKey(Utils.getRandom()); - final byte[] receiptAccountAddress = ecKey2.getAddress(); - receiptAccountKey = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull)); - - logger.info(receiptAccountKey); - //Test send coin. - Account sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountBeforeBalance = sendAccount.getBalance(); - Assert.assertTrue(sendAccountBeforeBalance == 90000000000L); - Account receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountBeforeBalance = receiptAccount.getBalance(); - Assert.assertTrue(receiptAccountBeforeBalance == 0); - - //Test send coin - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert.assertTrue(PublicMethed.sendcoin(receiptAccountAddress, 49880000000L, - sendAccountAddress, sendAccountKey, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - sendAccount = PublicMethed.queryAccount(sendAccountKey, blockingStubFull); - Long sendAccountAfterBalance = sendAccount.getBalance(); - logger.info(Long.toString(sendAccountAfterBalance)); - Assert.assertTrue(sendAccountAfterBalance == 90000000000L - 49880000000L - 100000L); - - receiptAccount = PublicMethed.queryAccount(receiptAccountKey, blockingStubFull); - Long receiptAccountAfterBalance = receiptAccount.getBalance(); - logger.info(Long.toString(receiptAccountAfterBalance)); - Assert.assertTrue(receiptAccountAfterBalance == 49880000000L); - - //Send coin failed due to no enough balance. - Assert.assertFalse(sendcoin(toAddress, 9199999999999999999L, fromAddress, testKey002)); - //Send coin failed due to the amount is 0. - Assert.assertFalse(sendcoin(toAddress, 0L, fromAddress, testKey002)); - //Send coin failed due to the amount is -1Trx. - Assert.assertFalse(sendcoin(toAddress, -1000000L, fromAddress, testKey002)); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - final Long beforeBlockNum = currentBlock.getBlockHeader().getRawData().getNumber(); - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - BalanceContract.FreezeBalanceContract.Builder builder = BalanceContract.FreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - BalanceContract.FreezeBalanceContract contract = builder.build(); - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction = null"); - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (response.getResult() == false) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - - Long afterBlockNum = 0L; - Integer wait = 0; - while (afterBlockNum < beforeBlockNum + 1 && wait < 10) { - Block currentBlock1 = searchBlockingStubFull - .getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - afterBlockNum = currentBlock1.getBlockHeader().getRawData().getNumber(); - wait++; - try { - Thread.sleep(2000); - logger.info("wait 2 second"); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "beforefronen" + beforeFrozenBalance.toString() + " afterfronzen" + afterFrozenBalance - .toString()); - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(afterBandwidth - beforeBandwidth == freezeBalance * frozen_duration); - return true; - - - } - - /** - * constructor. - */ - - public Boolean sendcoin(byte[] to, long amount, byte[] owner, String priKey) { - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java deleted file mode 100644 index 3c6435ee193..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer003.java +++ /dev/null @@ -1,389 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.parameter.CommonParameter; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import org.tron.protos.contract.AccountContract.AccountUpdateContract; -import org.tron.protos.contract.BalanceContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.Sha256Hash; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer003 { - - private static final long now = System.currentTimeMillis(); - private static final String name = "transaction007_" + Long.toString(now); - private static Protocol.Transaction sendCoinTransaction; - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final Long createUseFee = 100000L; - //get account - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sendCoinAddress = ecKey1.getAddress(); - String testKeyForSendCoin = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] newAccountAddress = ecKey2.getAddress(); - String testKeyForNewAccount = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private ManagedChannel channelFull1 = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull1 = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String fullnode1 = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - private static Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - /** - * constructor. - */ - - public static Protocol.Transaction sendcoin(byte[] to, long amount, byte[] owner, String priKey, - WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - //Protocol.Account search = queryAccount(priKey, blockingStubFull); - - BalanceContract.TransferContract.Builder builder = BalanceContract.TransferContract - .newBuilder(); - ByteString bsTo = ByteString.copyFrom(to); - ByteString bsOwner = ByteString.copyFrom(owner); - builder.setToAddress(bsTo); - builder.setOwnerAddress(bsOwner); - builder.setAmount(amount); - - BalanceContract.TransferContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.createTransaction(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return transaction; - } - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - logger.info(testKeyForSendCoin); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelFull1 = ManagedChannelBuilder.forTarget(fullnode1) - .usePlaintext(true) - .build(); - blockingStubFull1 = WalletGrpc.newBlockingStub(channelFull1); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - - } - - @Test(enabled = true) - public void test1UseFeeOrNet() { - //get account - ecKey1 = new ECKey(Utils.getRandom()); - sendCoinAddress = ecKey1.getAddress(); - testKeyForSendCoin = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - - ecKey2 = new ECKey(Utils.getRandom()); - newAccountAddress = ecKey2.getAddress(); - testKeyForNewAccount = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - - Assert.assertTrue(PublicMethed.sendcoin(sendCoinAddress, 200000L, - fromAddress, testKey002, blockingStubFull)); - Long feeNum = 0L; - Long netNum = 0L; - Long sendNum = 0L; - Long feeCost = 0L; - Long times = 0L; - Account sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - final Long beforeBalance = sendAccountInfo.getBalance(); - Long netUsed1 = 0L; - Long netUsed2 = 1L; - logger.info("Before test, the account balance is " + Long.toString(beforeBalance)); - - while (!(netUsed1.equals(netUsed2))) { - sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - netUsed1 = sendAccountInfo.getFreeNetUsage(); - sendCoinTransaction = sendcoin(fromAddress, 1L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - - sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - netUsed2 = sendAccountInfo.getFreeNetUsage(); - - if (times++ < 1) { - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), sendCoinTransaction - .getRawData().toByteArray())); - logger.info(txId); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo = blockingStubFull.getTransactionInfoById(request); - Optional getTransactionById = Optional.ofNullable(transactionInfo); - logger.info("solidity block num is " + Long.toString(getTransactionById - .get().getBlockNumber())); - Assert.assertTrue(getTransactionById.get().getBlockNumber() > 0); - } - - logger.info(Long.toString(netUsed1)); - logger.info(Long.toString(netUsed2)); - try { - Thread.sleep(500); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - Assert.assertTrue(netUsed2 > 4500); - //Next time, use fee - sendCoinTransaction = sendcoin(fromAddress, 1L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), sendCoinTransaction - .getRawData().toByteArray())); - logger.info(txId); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo = blockingStubFull.getTransactionInfoById(request); - Optional getTransactionById = Optional.ofNullable(transactionInfo); - logger.info(getTransactionById.get().toString()); - logger.info("when use fee, the block num is " + Long.toString(getTransactionById - .get().getBlockNumber())); - Assert.assertTrue(getTransactionById.get().getFee() > 0); - Assert.assertTrue(getTransactionById.get().getBlockNumber() > 0); - } - - @Test(enabled = true) - public void test2CreateAccountUseFee() { - Account sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - final Long beforeBalance = sendAccountInfo.getBalance(); - logger.info("before balance " + Long.toString(beforeBalance)); - Long times = 0L; - sendCoinTransaction = sendcoin(newAccountAddress, 1L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull,blockingStubSolidity); - String txId = ByteArray.toHexString(Sha256Hash.hash(CommonParameter.getInstance() - .isECKeyCryptoEngine(), sendCoinTransaction - .getRawData().toByteArray())); - logger.info(txId); - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo = blockingStubFull.getTransactionInfoById(request); - Optional getTransactionById = Optional.ofNullable(transactionInfo); - - logger.info("In create account case, the fee is " + getTransactionById.get().getFee()); - Assert.assertTrue(getTransactionById.get().getFee() == createUseFee); - - sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - final Long afterBalance = sendAccountInfo.getBalance(); - logger.info("after balance " + Long.toString(afterBalance)); - Assert.assertTrue(afterBalance + 1L + createUseFee == beforeBalance); - } - - @Test(enabled = true) - public void test3InvalidGetTransactionById() { - String txId = ""; - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - Transaction transaction = blockingStubFull.getTransactionById(request); - Optional getTransactionById = Optional.ofNullable(transaction); - Assert.assertTrue(getTransactionById.get().getRawData().getContractCount() == 0); - - txId = "1"; - bsTxid = ByteString.copyFrom(ByteArray.fromHexString(txId)); - request = BytesMessage.newBuilder().setValue(bsTxid).build(); - transaction = blockingStubFull.getTransactionById(request); - getTransactionById = Optional.ofNullable(transaction); - Assert.assertTrue(getTransactionById.get().getRawData().getContractCount() == 0); - } - - @Test(enabled = true) - public void test4NoBalanceCanSend() { - Long feeNum = 0L; - Account sendAccountInfo = PublicMethed.queryAccount(testKeyForSendCoin, blockingStubFull); - Long beforeBalance = sendAccountInfo.getBalance(); - logger.info("Before test, the account balance is " + Long.toString(beforeBalance)); - while (feeNum < 250) { - sendCoinTransaction = sendcoin(fromAddress, 10L, sendCoinAddress, - testKeyForSendCoin, blockingStubFull); - feeNum++; - } - Assert.assertTrue(PublicMethed.waitProduceNextBlock(blockingStubFull)); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelFull1 != null) { - channelFull1.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - /** - * constructor. - */ - - public Protocol.Transaction updateAccount(byte[] addressBytes, byte[] accountNameBytes, - String priKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - Wallet.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - final ECKey ecKey = temKey; - - AccountUpdateContract.Builder builder = AccountUpdateContract.newBuilder(); - ByteString basAddreess = ByteString.copyFrom(addressBytes); - ByteString bsAccountName = ByteString.copyFrom(accountNameBytes); - - builder.setAccountName(bsAccountName); - builder.setOwnerAddress(basAddreess); - - AccountUpdateContract contract = builder.build(); - Protocol.Transaction transaction = blockingStubFull.updateAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction ==null"); - } - transaction = signTransaction(ecKey, transaction); - GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction); - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - } - return transaction; - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer004.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer004.java deleted file mode 100644 index 181328d0f0f..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer004.java +++ /dev/null @@ -1,288 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletExtensionGrpc; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - - -@Slf4j -public class WalletTestTransfer004 { - - private static final long now = System.currentTimeMillis(); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletExtensionGrpc.WalletExtensionBlockingStub blockingStubExtension = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /* @Test(enabled = true) - public void testGetTransactionsByTimestamp() { - long start = now - 16400000; - long end = now; - GrpcAPI.TimeMessage.Builder timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - TimePaginatedMessage.Builder timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - TransactionList transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - Optional gettransactionbytimestamp = Optional - .ofNullable(transactionList); - - if (gettransactionbytimestamp.get().getTransactionCount() == 0) { - logger.info("Last one day there is no transfaction,please test for manual!!!"); - } - - Assert.assertTrue(gettransactionbytimestamp.isPresent()); - logger.info(Integer.toString(gettransactionbytimestamp.get().getTransactionCount())); - for (Integer j = 0; j < gettransactionbytimestamp.get().getTransactionCount(); j++) { - Assert.assertTrue(gettransactionbytimestamp.get().getTransaction(j).hasRawData()); - Assert.assertFalse(gettransactionbytimestamp.get().getTransaction(j) - .getRawData().getContractList().isEmpty()); - } - } - - @Test(enabled = true) - public void testExceptionTimeToGetGetTransactionsByTimestamp() { - //Start time is below zero. - long start = -10000; - long end = -1; - GrpcAPI.TimeMessage.Builder timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - TimePaginatedMessage.Builder timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - TransactionList transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - Optional gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //Start time is equal with end time. - long now = System.currentTimeMillis(); - start = now; - end = now; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //No transeration occured. - now = System.currentTimeMillis(); - start = now; - end = now + 1; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - - //Start time is late than currently time,no exception. - start = now + 1000000; - end = start + 1000000; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //Start time is late than the end time, no exception. - start = now; - end = now - 10000000; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //The offset is -1 - start = now - 10000000; - end = now; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(-1); - timePageMessage.setLimit(999); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - //The setLimit is -1 - start = now - 10000000; - end = now; - timeMessage = GrpcAPI.TimeMessage.newBuilder(); - timeMessage.setBeginInMilliseconds(start); - timeMessage.setEndInMilliseconds(end); - timePageMessage = TimePaginatedMessage.newBuilder(); - timePageMessage.setTimeMessage(timeMessage); - timePageMessage.setOffset(0); - timePageMessage.setLimit(-1); - transactionList = blockingStubExtension - .getTransactionsByTimestamp(timePageMessage.build()); - gettransactionbytimestamp = Optional - .ofNullable(transactionList); - Assert.assertTrue(gettransactionbytimestamp.get().getTransactionCount() == 0); - - - }*/ - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode).usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - blockingStubExtension = WalletExtensionGrpc.newBlockingStub(channelSolidity); - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer007.java b/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer007.java deleted file mode 100644 index 3619db66a17..00000000000 --- a/framework/src/test/java/stest/tron/wallet/transfer/WalletTestTransfer007.java +++ /dev/null @@ -1,149 +0,0 @@ -package stest.tron.wallet.transfer; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.junit.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.BytesMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.Protocol.TransactionInfo; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.utils.PublicMethed; - -@Slf4j -public class WalletTestTransfer007 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidityInFullnode = null; - - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - private ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] sendAccountAddress = ecKey1.getAddress(); - String sendAccountKey = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - private ManagedChannel channelSolidity = null; - private ManagedChannel channelSolidityInFullnode = null; - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - /* private String solidityInFullnode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(1);*/ - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - - /* channelSolidityInFullnode = ManagedChannelBuilder.forTarget(solidityInFullnode) - .usePlaintext(true) - .build(); - blockingStubSolidityInFullnode = WalletSolidityGrpc.newBlockingStub(channelSolidityInFullnode); - */ - } - - - @Test - public void testSendCoin() { - String transactionId = PublicMethed.sendcoinGetTransactionId(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull); - Optional infoById = PublicMethed - .getTransactionById(transactionId, blockingStubFull); - Long timestamptis = PublicMethed.printTransactionRow(infoById.get().getRawData()); - Long timestamptispBlockOne = PublicMethed.getBlock(1, blockingStubFull).getBlockHeader() - .getRawData().getTimestamp(); - Assert.assertTrue(timestamptis >= timestamptispBlockOne); - } - - @Test - public void testSendCoin2() { - String transactionId = PublicMethed.sendcoinGetTransactionId(sendAccountAddress, 90000000000L, - fromAddress, testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Optional infoById = PublicMethed - .getTransactionById(transactionId, blockingStubFull); - Long timestamptis = PublicMethed.printTransactionRow(infoById.get().getRawData()); - Long timestampBlockOne = PublicMethed.getBlock(1, blockingStubFull).getBlockHeader() - .getRawData().getTimestamp(); - Assert.assertTrue(timestamptis >= timestampBlockOne); - PublicMethed.waitSolidityNodeSynFullNodeData(blockingStubFull, blockingStubSolidity); - - infoById = PublicMethed.getTransactionById(transactionId, blockingStubSolidity); - timestamptis = PublicMethed.printTransactionRow(infoById.get().getRawData()); - timestampBlockOne = PublicMethed.getBlock(1, blockingStubFull).getBlockHeader() - .getRawData().getTimestamp(); - Assert.assertTrue(timestamptis >= timestampBlockOne); - - ByteString bsTxid = ByteString.copyFrom(ByteArray.fromHexString(transactionId)); - BytesMessage request = BytesMessage.newBuilder().setValue(bsTxid).build(); - TransactionInfo transactionInfo; - - transactionInfo = blockingStubSolidity.getTransactionInfoById(request); - Assert.assertTrue(transactionInfo.getBlockTimeStamp() >= timestampBlockOne); - - transactionInfo = blockingStubFull.getTransactionInfoById(request); - Assert.assertTrue(transactionInfo.getBlockTimeStamp() >= timestampBlockOne); - - //transactionInfo = blockingStubSolidityInFullnode.getTransactionInfoById(request); - //Assert.assertTrue(transactionInfo.getBlockTimeStamp() >= timestampBlockOne); - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - -} diff --git a/framework/src/test/java/stest/tron/wallet/updateCompatibility/MutisignOperationerGodicTest.java b/framework/src/test/java/stest/tron/wallet/updateCompatibility/MutisignOperationerGodicTest.java deleted file mode 100644 index 72ee459aae1..00000000000 --- a/framework/src/test/java/stest/tron/wallet/updateCompatibility/MutisignOperationerGodicTest.java +++ /dev/null @@ -1,504 +0,0 @@ -package stest.tron.wallet.updateCompatibility; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI.EmptyMessage; -import org.tron.api.GrpcAPI.ExchangeList; -import org.tron.api.GrpcAPI.Note; -import org.tron.api.GrpcAPI.ProposalList; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.common.utils.Utils; -import org.tron.core.Wallet; -import org.tron.core.config.args.Args; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.ChainParameters; -import org.tron.protos.Protocol.Exchange; -import org.tron.protos.contract.SmartContractOuterClass.SmartContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.PublicMethedForMutiSign; -import stest.tron.wallet.common.client.utils.ShieldAddressInfo; - -@Slf4j -public class MutisignOperationerGodicTest { - - final String updateName = Long.toString(System.currentTimeMillis()); - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String operations = Configuration.getByPath("testng.conf") - .getString("defaultParameter.operations"); - String[] permissionKeyString = new String[2]; - String[] ownerKeyString = new String[2]; - String accountPermissionJson = ""; - String description = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetDescription"); - String url = Configuration.getByPath("testng.conf") - .getString("defaultParameter.assetUrl"); - Optional shieldAddressInfo; - String shieldAddress; - List shieldOutList = new ArrayList<>(); - Account firstAccount; - ByteString assetAccountId1; - ByteString assetAccountId2; - Optional listExchange; - Optional exchangeIdInfo; - Integer exchangeId = 0; - Integer exchangeRate = 10; - Long firstTokenInitialBalance = 10000L; - Long secondTokenInitialBalance = firstTokenInitialBalance * exchangeRate; - ECKey ecKey1 = new ECKey(Utils.getRandom()); - byte[] manager1Address = ecKey1.getAddress(); - String manager1Key = ByteArray.toHexString(ecKey1.getPrivKeyBytes()); - ECKey ecKey2 = new ECKey(Utils.getRandom()); - byte[] manager2Address = ecKey2.getAddress(); - String manager2Key = ByteArray.toHexString(ecKey2.getPrivKeyBytes()); - ECKey ecKey3 = new ECKey(Utils.getRandom()); - byte[] mutisignAccountAddress = ecKey3.getAddress(); - String mutisignAccountKey = ByteArray.toHexString(ecKey3.getPrivKeyBytes()); - ECKey ecKey4 = new ECKey(Utils.getRandom()); - byte[] newAddress = ecKey4.getAddress(); - String newKey = ByteArray.toHexString(ecKey4.getPrivKeyBytes()); - private ManagedChannel channelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(0); - private String foundationZenTokenKey = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenOwnerKey"); - byte[] foundationZenTokenAddress = PublicMethed.getFinalAddress(foundationZenTokenKey); - private String zenTokenId = Configuration.getByPath("testng.conf") - .getString("defaultParameter.zenTokenId"); - private byte[] tokenId = zenTokenId.getBytes(); - private Long zenTokenFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.zenTokenFee"); - private long multiSignFee = Configuration.getByPath("testng.conf") - .getLong("defaultParameter.multiSignFee"); - private Long costTokenAmount = 8 * zenTokenFee; - private Long sendTokenAmount = 3 * zenTokenFee; - - /** - * constructor. - */ - @BeforeSuite - public void beforeSuite() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - if (PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getCreateTime() == 0) { - PublicMethed.sendcoin(foundationZenTokenAddress, 20480000000000L, fromAddress, - testKey002, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - String name = "shieldToken"; - Long start = System.currentTimeMillis() + 20000; - Long end = System.currentTimeMillis() + 10000000000L; - Long totalSupply = 15000000000000001L; - String description = "This asset issue is use for exchange transaction stress"; - String url = "This asset issue is use for exchange transaction stress"; - PublicMethed.createAssetIssue(foundationZenTokenAddress, name, totalSupply, 1, 1, - start, end, 1, description, url, 1000L, 1000L, - 1L, 1L, foundationZenTokenKey, blockingStubFull); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Account getAssetIdFromThisAccount = - PublicMethed.queryAccount(foundationZenTokenAddress, blockingStubFull); - ByteString assetAccountId = getAssetIdFromThisAccount.getAssetIssuedID(); - logger.info("AssetId:" + assetAccountId.toString()); - } - } - - /** - * constructor. - */ - - @BeforeClass(enabled = true) - public void beforeClass() { - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - Assert.assertTrue(PublicMethed.sendcoin(mutisignAccountAddress, 1000_000_000_000L, fromAddress, - testKey002, blockingStubFull)); - //updatepermission权限,账户交易所需钱等前置条件写在这 - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = manager1Key; - ownerKeyString[1] = manager2Key; - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, mutisignAccountAddress, mutisignAccountKey, - blockingStubFull, new String[]{mutisignAccountKey})); - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true) - public void test001MutiSignGodicAccountTypeTransaction() { - Assert.assertTrue( - PublicMethedForMutiSign.setAccountId1(("" + System.currentTimeMillis()).getBytes(), - mutisignAccountAddress, mutisignAccountKey, 2, blockingStubFull, - permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.createAccountWhtiPermissionId( - mutisignAccountAddress, newAddress, mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.sendcoinWithPermissionId( - newAddress, 100L, mutisignAccountAddress, 2, - mutisignAccountKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceWithPermissionId( - mutisignAccountAddress, 1000000L, 0, 2, - mutisignAccountKey, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceGetEnergyWithPermissionId( - mutisignAccountAddress, 1000000L, 0, 1, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.freezeBalanceForReceiverWithPermissionId( - mutisignAccountAddress, 1000000L, 0, 0, - ByteString.copyFrom(newAddress), - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - mutisignAccountAddress, mutisignAccountKey, 0, null, - 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.unFreezeBalanceWithPermissionId( - mutisignAccountAddress, mutisignAccountKey, 0, newAddress, - 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue(PublicMethedForMutiSign.updateAccountWithPermissionId( - mutisignAccountAddress, updateName.getBytes(), mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - } - - @Test(enabled = true) - public void test002MutiSignGodicContractTypeTransaction() { - Long maxFeeLimit = 1000000000L; - //String contractName = "StorageAndCpu" + Integer.toString(randNum); - String filePath = "./src/test/resources/soliditycode/walletTestMutiSign004.sol"; - String contractName = "timeoutTest"; - HashMap retMap = PublicMethed.getBycodeAbi(filePath, contractName); - - String code = retMap.get("byteCode").toString(); - String abi = retMap.get("abI").toString(); - byte[] contractAddress = PublicMethedForMutiSign.deployContractWithPermissionId( - contractName, abi, code, "", maxFeeLimit, - 0L, 100, maxFeeLimit, "0", 0L, null, - mutisignAccountKey, mutisignAccountAddress, blockingStubFull, permissionKeyString, 2); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - SmartContract smartContract = PublicMethed.getContract(contractAddress, blockingStubFull); - Assert.assertTrue(smartContract.getAbi().toString() != null); - String txid; - String initParmes = "\"" + "930" + "\""; - txid = PublicMethedForMutiSign.triggerContractWithPermissionId(contractAddress, - "testUseCpu(uint256)", initParmes, false, - 0, maxFeeLimit, "0", 0L, mutisignAccountAddress, - mutisignAccountKey, blockingStubFull, permissionKeyString, 2); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue( - PublicMethedForMutiSign.updateSettingWithPermissionId( - contractAddress, 50, mutisignAccountKey, - mutisignAccountAddress, 2, blockingStubFull, permissionKeyString)); - Assert.assertTrue( - PublicMethedForMutiSign.updateEnergyLimitWithPermissionId( - contractAddress, 50, mutisignAccountKey, - mutisignAccountAddress, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethedForMutiSign - .clearContractAbi(contractAddress, mutisignAccountAddress, mutisignAccountKey, - blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - } - - @Test(enabled = true) - public void test003MutiSignGodicTokenTypeTransaction() { - - long now = System.currentTimeMillis(); - String name = "MutiSign001_" + Long.toString(now); - long totalSupply = now; - Long start = System.currentTimeMillis() + 5000; - Long end = System.currentTimeMillis() + 1000000000; - logger.info("try create asset issue"); - - Assert.assertTrue(PublicMethedForMutiSign - .createAssetIssueWithpermissionId(mutisignAccountAddress, name, totalSupply, 1, - 1, start, end, 1, description, url, 2000L, 2000L, - 1L, 1L, mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - //Assert.assertTrue(PublicMethedForMutiSign.unFreezeAsset(mutisignAccountAddress, - // mutisignAccountKey,2,ownerKeyString,blockingStubFull)); - - Account getAssetIdFromOwnerAccount; - getAssetIdFromOwnerAccount = PublicMethed.queryAccount( - mutisignAccountAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromOwnerAccount.getAssetIssuedID(); - - Assert.assertTrue(PublicMethedForMutiSign.transferAssetWithpermissionId(manager1Address, - assetAccountId1.toByteArray(), 10, mutisignAccountAddress, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Assert.assertTrue(PublicMethedForMutiSign - .updateAssetWithPermissionId(mutisignAccountAddress, description.getBytes(), url.getBytes(), - 100L, 100L, mutisignAccountKey, - 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - - } - - @Test(enabled = true) - public void test004MutiSignGodicExchangeTypeTransaction() { - - ECKey ecKey22 = new ECKey(Utils.getRandom()); - byte[] secondExchange001Address = ecKey22.getAddress(); - String secondExchange001Key = ByteArray.toHexString(ecKey22.getPrivKeyBytes()); - Long secondTransferAssetToFirstAccountNum = 100000000L; - - long now = System.currentTimeMillis(); - String name2 = "exchange001_2_" + Long.toString(now); - String name1 = "exchange001_1_" + Long.toString(now); - final long totalSupply = 1000000001L; - - org.junit.Assert - .assertTrue(PublicMethed.sendcoin(secondExchange001Address, 10240000000L, fromAddress, - testKey002, blockingStubFull)); - org.junit.Assert.assertTrue(PublicMethed - .freezeBalanceForReceiver(fromAddress, 100000000000L, 0, 0, - ByteString.copyFrom(secondExchange001Address), - testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - Long start = System.currentTimeMillis() + 5000L; - Long end = System.currentTimeMillis() + 5000000L; - org.junit.Assert - .assertTrue(PublicMethed.createAssetIssue(secondExchange001Address, name2, totalSupply, 1, - 1, start, end, 1, description, url, 10000L, 10000L, - 1L, 1L, secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - Account getAssetIdFromThisAccount; - getAssetIdFromThisAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - assetAccountId1 = getAssetIdFromThisAccount.getAssetIssuedID(); - - getAssetIdFromThisAccount = PublicMethed - .queryAccount(secondExchange001Address, blockingStubFull); - assetAccountId2 = getAssetIdFromThisAccount.getAssetIssuedID(); - - firstAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - org.junit.Assert.assertTrue(PublicMethed.transferAsset( - mutisignAccountAddress, assetAccountId2.toByteArray(), - secondTransferAssetToFirstAccountNum, secondExchange001Address, - secondExchange001Key, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign.exchangeCreate1( - assetAccountId1.toByteArray(), firstTokenInitialBalance, - assetAccountId2.toByteArray(), secondTokenInitialBalance, mutisignAccountAddress, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - listExchange = PublicMethed.getExchangeList(blockingStubFull); - exchangeId = listExchange.get().getExchangesCount(); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign.injectExchange1( - exchangeId, assetAccountId1.toByteArray(), 100, - mutisignAccountAddress, mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign.exchangeWithdraw1( - exchangeId, assetAccountId1.toByteArray(), 200, - mutisignAccountAddress, mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - - org.junit.Assert.assertTrue( - PublicMethedForMutiSign - .exchangeTransaction1(exchangeId, assetAccountId1.toByteArray(), 50, 1, - mutisignAccountAddress, mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - firstAccount = PublicMethed.queryAccount(mutisignAccountAddress, blockingStubFull); - - Assert.assertTrue(PublicMethedForMutiSign.participateAssetIssueWithPermissionId( - secondExchange001Address, - assetAccountId2.toByteArray(), 1, mutisignAccountAddress, mutisignAccountKey, 2, - blockingStubFull, ownerKeyString)); - - } - - @Test(enabled = true) - public void test005MutiSignGodicShieldTransaction() { - - Assert.assertTrue(PublicMethed.transferAsset(mutisignAccountAddress, tokenId, - costTokenAmount, foundationZenTokenAddress, foundationZenTokenKey, blockingStubFull)); - Args.setFullNodeAllowShieldedTransaction(true); - shieldAddressInfo = PublicMethed.generateShieldAddress(); - shieldAddress = shieldAddressInfo.get().getAddress(); - logger.info("shieldAddress:" + shieldAddress); - final Long beforeAssetBalance = PublicMethed.getAssetIssueValue(mutisignAccountAddress, - PublicMethed.queryAccount(foundationZenTokenKey, blockingStubFull).getAssetIssuedID(), - blockingStubFull); - final Long beforeBalance = PublicMethed - .queryAccount(mutisignAccountAddress, blockingStubFull).getBalance(); - final Long beforeNetUsed = PublicMethed - .getAccountResource(mutisignAccountAddress, blockingStubFull).getFreeNetUsed(); - - String memo = "aaaaaaa"; - - shieldOutList = PublicMethed.addShieldOutputList(shieldOutList, shieldAddress, - "" + (sendTokenAmount - zenTokenFee), memo); - - Assert.assertTrue(PublicMethedForMutiSign.sendShieldCoin( - mutisignAccountAddress, sendTokenAmount, - null, null, - shieldOutList, - null, 0, - mutisignAccountKey, blockingStubFull, 2, permissionKeyString)); - - PublicMethed.waitProduceNextBlock(blockingStubFull); - } - - @Test(enabled = true) - public void test006MutiSignGodicWitnessTransaction() { - permissionKeyString[0] = manager1Key; - permissionKeyString[1] = manager2Key; - ownerKeyString[0] = manager1Key; - ownerKeyString[1] = manager2Key; - PublicMethed.printAddress(newKey); - accountPermissionJson = - "{\"owner_permission\":{\"type\":0,\"permission_name\":\"owner\",\"threshold\":2,\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) - + "\",\"weight\":1}]}," - + "\"active_permissions\":[{\"type\":2,\"permission_name\":\"active0\",\"threshold\":2," - + "\"operations\":\"" + operations + "\"," - + "\"keys\":[" - + "{\"address\":\"" + PublicMethed.getAddressString(manager1Key) + "\",\"weight\":1}," - + "{\"address\":\"" + PublicMethed.getAddressString(manager2Key) + "\",\"weight\":1}" - + "]}]}"; - - Assert.assertTrue(PublicMethed.sendcoin(newAddress, 1000000_000_000L, fromAddress, - testKey002, blockingStubFull)); - logger.info(accountPermissionJson); - Assert.assertTrue(PublicMethedForMutiSign - .accountPermissionUpdate(accountPermissionJson, newAddress, newKey, - blockingStubFull, new String[]{newKey})); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - long now = System.currentTimeMillis(); - String url = "MutiSign001_" + Long.toString(now) + ".com"; - Assert.assertTrue(PublicMethedForMutiSign.createWitness(url, newAddress, - newKey, 2, permissionKeyString, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - Assert - .assertTrue(PublicMethedForMutiSign.updateWitness2(newAddress, "newWitness.com".getBytes(), - newKey, 2, permissionKeyString, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - - String voteStr = Base58.encode58Check(newAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - Assert.assertTrue(PublicMethedForMutiSign.voteWitnessWithPermissionId( - smallVoteMap, mutisignAccountAddress, mutisignAccountKey, blockingStubFull, - 2, permissionKeyString)); - - - } - - @Test(enabled = true) - public void test007MutiSignGodicProposalTypeTransaction() { - - PublicMethed.waitProduceNextBlock(blockingStubFull); - HashMap proposalMap = new HashMap(); - proposalMap.put(0L, 81000L); - Assert.assertTrue( - PublicMethedForMutiSign.createProposalWithPermissionId(newAddress, newKey, - proposalMap, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Get proposal list - ProposalList proposalList = blockingStubFull.listProposals(EmptyMessage.newBuilder().build()); - Optional listProposals = Optional.ofNullable(proposalList); - final Integer proposalId = listProposals.get().getProposalsCount(); - logger.info(Integer.toString(proposalId)); - - Assert.assertTrue(PublicMethedForMutiSign.approveProposalWithPermission( - newAddress, newKey, proposalId, - true, 2, blockingStubFull, permissionKeyString)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Delete proposal list after approve - Assert.assertTrue(PublicMethedForMutiSign.deleteProposalWithPermissionId( - newAddress, newKey, proposalId, 2, blockingStubFull, permissionKeyString)); - } - - @Test(enabled = true) - public void test008MutiSignGodicWithdrawBanlanceTransaction() { - long MaintenanceTimeInterval = -1L; - ChainParameters chainParameters = blockingStubFull - .getChainParameters(EmptyMessage.newBuilder().build()); - Optional getChainParameters = Optional.ofNullable(chainParameters); - logger.info(Long.toString(getChainParameters.get().getChainParameterCount())); - for (Integer i = 0; i < getChainParameters.get().getChainParameterCount(); i++) { - logger.info("Index is:" + i); - logger.info(getChainParameters.get().getChainParameter(i).getKey()); - logger.info(Long.toString(getChainParameters.get().getChainParameter(i).getValue())); - if (getChainParameters.get().getChainParameter(i).getKey() - .equals("getMaintenanceTimeInterval")) { - MaintenanceTimeInterval = getChainParameters.get().getChainParameter(i).getValue(); - break; - } - } - - try { - Thread.sleep(MaintenanceTimeInterval); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Assert.assertTrue(PublicMethedForMutiSign.withdrawBalance(newAddress, newKey, - 2, permissionKeyString, blockingStubFull)); - } - - - /** - * constructor. - */ - @AfterClass(enabled = true) - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java b/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java deleted file mode 100644 index 322cdf9e3be..00000000000 --- a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness001.java +++ /dev/null @@ -1,399 +0,0 @@ -package stest.tron.wallet.witness; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.math.BigInteger; -import java.util.HashMap; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.GrpcAPI.Return; -import org.tron.api.WalletGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.common.utils.ByteArray; -import org.tron.core.Wallet; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import org.tron.protos.contract.BalanceContract.FreezeBalanceContract; -import org.tron.protos.contract.BalanceContract.UnfreezeBalanceContract; -import org.tron.protos.contract.WitnessContract.VoteWitnessContract; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.Base58; -import stest.tron.wallet.common.client.utils.PublicMethed; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -@Slf4j -public class WalletTestWitness001 { - - private final String testKey002 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key1"); - private final byte[] fromAddress = PublicMethed.getFinalAddress(testKey002); - private final String testKey003 = Configuration.getByPath("testng.conf") - .getString("foundationAccount.key2"); - private final byte[] toAddress = PublicMethed.getFinalAddress(testKey003); - private final String witnessKey001 = Configuration.getByPath("testng.conf") - .getString("witness.key1"); - private final byte[] witnessAddress = PublicMethed.getFinalAddress(witnessKey001); - - - private ManagedChannel channelFull = null; - private ManagedChannel searchChannelFull = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletGrpc.WalletBlockingStub searchBlockingStubFull = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String searchFullnode = Configuration.getByPath("testng.conf") - .getStringList("fullnode.ip.list").get(1); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - logger.info("Pre fix byte ===== " + WalletClient.getAddressPreFixByte()); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - searchChannelFull = ManagedChannelBuilder.forTarget(searchFullnode) - .usePlaintext(true) - .build(); - searchBlockingStubFull = WalletGrpc.newBlockingStub(searchChannelFull); - } - - @Test(enabled = true) - public void testVoteWitness() { - String voteStr = Base58.encode58Check(witnessAddress); - HashMap smallVoteMap = new HashMap(); - smallVoteMap.put(voteStr, "1"); - HashMap wrongVoteMap = new HashMap(); - wrongVoteMap.put(voteStr, "-1"); - HashMap zeroVoteMap = new HashMap(); - zeroVoteMap.put(voteStr, "0"); - - HashMap veryLargeMap = new HashMap(); - veryLargeMap.put(voteStr, "1000000000"); - HashMap wrongDropMap = new HashMap(); - wrongDropMap.put(voteStr, "10000000000000000"); - - //Vote failed due to no freeze balance. - //Assert.assertFalse(VoteWitness(smallVoteMap, NO_FROZEN_ADDRESS, no_frozen_balance_testKey)); - - //Freeze balance to get vote ability. - Assert.assertTrue(PublicMethed.freezeBalanceGetTronPower(fromAddress, 1200000L, 3L, - 2,null,testKey002, blockingStubFull)); - PublicMethed.waitProduceNextBlock(blockingStubFull); - //Vote failed when the vote is large than the freeze balance. - Assert.assertFalse(voteWitness(veryLargeMap, fromAddress, testKey002)); - //Vote failed due to 0 vote. - Assert.assertFalse(voteWitness(zeroVoteMap, fromAddress, testKey002)); - //Vote failed duo to -1 vote. - Assert.assertFalse(voteWitness(wrongVoteMap, fromAddress, testKey002)); - //Vote is so large, vote failed. - Assert.assertFalse(voteWitness(wrongDropMap, fromAddress, testKey002)); - - //Vote success - Assert.assertTrue(voteWitness(smallVoteMap, fromAddress, testKey002)); - - - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (searchChannelFull != null) { - searchChannelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Boolean voteWitness(HashMap witness, byte[] addRess, String priKey) { - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeVote = queryAccount(ecKey, blockingStubFull); - Long beforeVoteNum = 0L; - if (beforeVote.getVotesCount() != 0) { - beforeVoteNum = beforeVote.getVotes(0).getVoteCount(); - } - - VoteWitnessContract.Builder builder = VoteWitnessContract.newBuilder(); - builder.setOwnerAddress(ByteString.copyFrom(addRess)); - for (String addressBase58 : witness.keySet()) { - String value = witness.get(addressBase58); - final long count = Long.parseLong(value); - VoteWitnessContract.Vote.Builder voteBuilder = VoteWitnessContract.Vote - .newBuilder(); - byte[] address = WalletClient.decodeFromBase58Check(addressBase58); - logger.info("address ====== " + ByteArray.toHexString(address)); - if (address == null) { - continue; - } - voteBuilder.setVoteAddress(ByteString.copyFrom(address)); - voteBuilder.setVoteCount(count); - builder.addVotes(voteBuilder.build()); - } - - VoteWitnessContract contract = builder.build(); - - Transaction transaction = blockingStubFull.voteWitnessAccount(contract); - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - logger.info("transaction == null"); - return false; - } - transaction = signTransaction(ecKey, transaction); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - logger.info(ByteArray.toStr(response.getMessage().toByteArray())); - return false; - } - try { - Thread.sleep(5000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - Account afterVote = queryAccount(ecKey, searchBlockingStubFull); - //Long afterVoteNum = afterVote.getVotes(0).getVoteCount(); - for (String key : witness.keySet()) { - for (int j = 0; j < afterVote.getVotesCount(); j++) { - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - logger.info(key); - if (key.equals("TB4B1RMhoPeivkj4Hebm6tttHjRY9yQFes")) { - logger.info("catch it"); - logger.info(Long.toString(afterVote.getVotes(j).getVoteCount())); - logger.info(Long.toString(Long.parseLong(witness.get(key)))); - Assert - .assertTrue(afterVote.getVotes(j).getVoteCount() == Long.parseLong(witness.get(key))); - } - - } - } - return true; - } - - /** - * constructor. - */ - - public Boolean freezeBalance(byte[] addRess, long freezeBalance, long freezeDuration, - String priKey) { - byte[] address = addRess; - long frozenBalance = freezeBalance; - long frozenDuration = freezeDuration; - - //String priKey = testKey002; - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account beforeFronzen = queryAccount(ecKey, blockingStubFull); - - Long beforeFrozenBalance = 0L; - //Long beforeBandwidth = beforeFronzen.getBandwidth(); - if (beforeFronzen.getFrozenCount() != 0) { - beforeFrozenBalance = beforeFronzen.getFrozen(0).getFrozenBalance(); - //beforeBandwidth = beforeFronzen.getBandwidth(); - //logger.info(Long.toString(beforeFronzen.getBandwidth())); - logger.info(Long.toString(beforeFronzen.getFrozen(0).getFrozenBalance())); - } - - FreezeBalanceContract.Builder builder = FreezeBalanceContract.newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess).setFrozenBalance(frozenBalance) - .setFrozenDuration(frozenDuration); - - FreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.freezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - - if (!response.getResult()) { - return false; - } - - Block currentBlock = blockingStubFull.getNowBlock(GrpcAPI.EmptyMessage.newBuilder().build()); - Block searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - Integer wait = 0; - while (searchCurrentBlock.getBlockHeader().getRawData().getNumber() - < currentBlock.getBlockHeader().getRawData().getNumber() + 1 && wait < 30) { - try { - Thread.sleep(3000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - logger.info("Another fullnode didn't syn the first fullnode data"); - searchCurrentBlock = searchBlockingStubFull.getNowBlock(GrpcAPI - .EmptyMessage.newBuilder().build()); - wait++; - if (wait == 9) { - logger.info("Didn't syn,skip to next case."); - } - } - - Account afterFronzen = queryAccount(ecKey, searchBlockingStubFull); - Long afterFrozenBalance = afterFronzen.getFrozen(0).getFrozenBalance(); - //Long afterBandwidth = afterFronzen.getBandwidth(); - //logger.info(Long.toString(afterFronzen.getBandwidth())); - //logger.info(Long.toString(afterFronzen.getFrozen(0).getFrozenBalance())); - //logger.info(Integer.toString(search.getFrozenCount())); - logger.info( - "afterfrozenbalance =" + Long.toString(afterFrozenBalance) + "beforefrozenbalance = " - + beforeFrozenBalance + "freezebalance = " + Long.toString(freezeBalance)); - //logger.info("afterbandwidth = " + Long.toString(afterBandwidth) + " beforebandwidth = - // " + Long.toString(beforeBandwidth)); - //if ((afterFrozenBalance - beforeFrozenBalance != freezeBalance) || - // (freezeBalance * frozen_duration -(afterBandwidth - beforeBandwidth) !=0)){ - // logger.info("After 20 second, two node still not synchronous"); - // } - Assert.assertTrue(afterFrozenBalance - beforeFrozenBalance == freezeBalance); - //Assert.assertTrue(freezeBalance * frozen_duration - (afterBandwidth - - // beforeBandwidth) <= 1000000); - return true; - - - } - - /** - * constructor. - */ - - public boolean unFreezeBalance(byte[] addRess, String priKey) { - byte[] address = addRess; - - ECKey temKey = null; - try { - BigInteger priK = new BigInteger(priKey, 16); - temKey = ECKey.fromPrivate(priK); - } catch (Exception ex) { - ex.printStackTrace(); - } - ECKey ecKey = temKey; - Account search = queryAccount(ecKey, blockingStubFull); - - UnfreezeBalanceContract.Builder builder = UnfreezeBalanceContract - .newBuilder(); - ByteString byteAddreess = ByteString.copyFrom(address); - - builder.setOwnerAddress(byteAddreess); - - UnfreezeBalanceContract contract = builder.build(); - - Transaction transaction = blockingStubFull.unfreezeBalance(contract); - - if (transaction == null || transaction.getRawData().getContractCount() == 0) { - return false; - } - - transaction = TransactionUtils.setTimestamp(transaction); - transaction = TransactionUtils.sign(transaction, ecKey); - Return response = blockingStubFull.broadcastTransaction(transaction); - return response.getResult(); - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } -} - - diff --git a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness002.java b/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness002.java deleted file mode 100644 index 876f7b64b58..00000000000 --- a/framework/src/test/java/stest/tron/wallet/witness/WalletTestWitness002.java +++ /dev/null @@ -1,210 +0,0 @@ -package stest.tron.wallet.witness; - -import com.google.protobuf.ByteString; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.StringUtils; -import org.bouncycastle.util.encoders.Hex; -import org.testng.Assert; -import org.testng.annotations.AfterClass; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.BeforeSuite; -import org.testng.annotations.Test; -import org.tron.api.GrpcAPI; -import org.tron.api.GrpcAPI.NumberMessage; -import org.tron.api.WalletGrpc; -import org.tron.api.WalletSolidityGrpc; -import org.tron.common.crypto.ECKey; -import org.tron.core.Wallet; -import org.tron.protos.Protocol; -import org.tron.protos.Protocol.Account; -import org.tron.protos.Protocol.Block; -import org.tron.protos.Protocol.Transaction; -import stest.tron.wallet.common.client.Configuration; -import stest.tron.wallet.common.client.Parameter.CommonConstant; -import stest.tron.wallet.common.client.WalletClient; -import stest.tron.wallet.common.client.utils.TransactionUtils; - -//import stest.tron.wallet.common.client.WitnessComparator; - -//import stest.tron.wallet.common.client.WitnessComparator; - -@Slf4j -public class WalletTestWitness002 { - - - private ManagedChannel channelFull = null; - private ManagedChannel channelSolidity = null; - private WalletGrpc.WalletBlockingStub blockingStubFull = null; - private WalletSolidityGrpc.WalletSolidityBlockingStub blockingStubSolidity = null; - private String fullnode = Configuration.getByPath("testng.conf").getStringList("fullnode.ip.list") - .get(0); - private String soliditynode = Configuration.getByPath("testng.conf") - .getStringList("solidityNode.ip.list").get(0); - - public static String loadPubKey() { - char[] buf = new char[0x100]; - return String.valueOf(buf, 32, 130); - } - - - - /** - * constructor. - */ - - @BeforeClass - public void beforeClass() { - WalletClient.setAddressPreFixByte(CommonConstant.ADD_PRE_FIX_BYTE_MAINNET); - channelFull = ManagedChannelBuilder.forTarget(fullnode) - .usePlaintext(true) - .build(); - blockingStubFull = WalletGrpc.newBlockingStub(channelFull); - - channelSolidity = ManagedChannelBuilder.forTarget(soliditynode) - .usePlaintext(true) - .build(); - blockingStubSolidity = WalletSolidityGrpc.newBlockingStub(channelSolidity); - } - - @Test(enabled = true) - public void testQueryAllWitness() { - GrpcAPI.WitnessList witnesslist = blockingStubFull - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(witnesslist); - if (result.isPresent()) { - GrpcAPI.WitnessList witnessList = result.get(); - List list = witnessList.getWitnessesList(); - List newList = new ArrayList(); - newList.addAll(list); - newList.sort(new WitnessComparator()); - GrpcAPI.WitnessList.Builder builder = GrpcAPI.WitnessList.newBuilder(); - newList.forEach(witness -> builder.addWitnesses(witness)); - result = Optional.of(builder.build()); - } - logger.info(Integer.toString(result.get().getWitnessesCount())); - Assert.assertTrue(result.get().getWitnessesCount() > 0); - for (int j = 0; j < result.get().getWitnessesCount(); j++) { - Assert.assertFalse(result.get().getWitnesses(j).getAddress().isEmpty()); - Assert.assertFalse(result.get().getWitnesses(j).getUrl().isEmpty()); - //Assert.assertTrue(result.get().getWitnesses(j).getLatestSlotNum() > 0); - result.get().getWitnesses(j).getUrlBytes(); - result.get().getWitnesses(j).getLatestBlockNum(); - result.get().getWitnesses(j).getLatestSlotNum(); - result.get().getWitnesses(j).getTotalMissed(); - result.get().getWitnesses(j).getTotalProduced(); - } - - //Improve coverage. - witnesslist.equals(result.get()); - witnesslist.hashCode(); - witnesslist.getSerializedSize(); - witnesslist.equals(null); - } - - @Test(enabled = true) - public void testSolidityQueryAllWitness() { - GrpcAPI.WitnessList solidityWitnessList = blockingStubSolidity - .listWitnesses(GrpcAPI.EmptyMessage.newBuilder().build()); - Optional result = Optional.ofNullable(solidityWitnessList); - if (result.isPresent()) { - GrpcAPI.WitnessList witnessList = result.get(); - List list = witnessList.getWitnessesList(); - List newList = new ArrayList(); - newList.addAll(list); - newList.sort(new WitnessComparator()); - GrpcAPI.WitnessList.Builder builder = GrpcAPI.WitnessList.newBuilder(); - newList.forEach(witness -> builder.addWitnesses(witness)); - result = Optional.of(builder.build()); - } - logger.info(Integer.toString(result.get().getWitnessesCount())); - Assert.assertTrue(result.get().getWitnessesCount() > 0); - for (int j = 0; j < result.get().getWitnessesCount(); j++) { - Assert.assertFalse(result.get().getWitnesses(j).getAddress().isEmpty()); - Assert.assertFalse(result.get().getWitnesses(j).getUrl().isEmpty()); - } - } - - /** - * constructor. - */ - - @AfterClass - public void shutdown() throws InterruptedException { - if (channelFull != null) { - channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - if (channelSolidity != null) { - channelSolidity.shutdown().awaitTermination(5, TimeUnit.SECONDS); - } - } - - /** - * constructor. - */ - - public Account queryAccount(ECKey ecKey, WalletGrpc.WalletBlockingStub blockingStubFull) { - byte[] address; - if (ecKey == null) { - String pubKey = loadPubKey(); //04 PubKey[128] - if (StringUtils.isEmpty(pubKey)) { - logger.warn("Warning: QueryAccount failed, no wallet address !!"); - return null; - } - byte[] pubKeyAsc = pubKey.getBytes(); - byte[] pubKeyHex = Hex.decode(pubKeyAsc); - ecKey = ECKey.fromPublicOnly(pubKeyHex); - } - return grpcQueryAccount(ecKey.getAddress(), blockingStubFull); - } - - public byte[] getAddress(ECKey ecKey) { - return ecKey.getAddress(); - } - - /** - * constructor. - */ - - public Account grpcQueryAccount(byte[] address, WalletGrpc.WalletBlockingStub blockingStubFull) { - ByteString addressBs = ByteString.copyFrom(address); - Account request = Account.newBuilder().setAddress(addressBs).build(); - return blockingStubFull.getAccount(request); - } - - /** - * constructor. - */ - - public Block getBlock(long blockNum, WalletGrpc.WalletBlockingStub blockingStubFull) { - NumberMessage.Builder builder = NumberMessage.newBuilder(); - builder.setNum(blockNum); - return blockingStubFull.getBlockByNum(builder.build()); - - } - - private Transaction signTransaction(ECKey ecKey, Transaction transaction) { - if (ecKey == null || ecKey.getPrivKey() == null) { - logger.warn("Warning: Can't sign,there is no private key !!"); - return null; - } - transaction = TransactionUtils.setTimestamp(transaction); - return TransactionUtils.sign(transaction, ecKey); - } - - class WitnessComparator implements Comparator { - - public int compare(Object o1, Object o2) { - return Long - .compare(((Protocol.Witness) o2).getVoteCount(), ((Protocol.Witness) o1).getVoteCount()); - } - } -} - - diff --git a/framework/src/test/resources/args-test.conf b/framework/src/test/resources/args-test.conf new file mode 100644 index 00000000000..cf5d0b8d718 --- /dev/null +++ b/framework/src/test/resources/args-test.conf @@ -0,0 +1,225 @@ +net { + // type = mainnet + type = testnet +} + + +storage { + # Directory for storing persistent data + + db.engine = "LEVELDB" + db.directory = "database", + index.directory = "index", + + # You can custom these 14 databases' configs: + + # account, account-index, asset-issue, block, block-index, + # block_KDB, peers, properties, recent-block, trans, + # utxo, votes, witness, witness_schedule. + + # Otherwise, db configs will remain defualt 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 !!! + default = { + maxOpenFiles = 50 + } + defaultM = { + maxOpenFiles = 500 + } + defaultL = { + maxOpenFiles = 1000 + } + properties = [ + { + name = "account", + path = "storage_directory_test", + createIfMissing = true, + paranoidChecks = true, + verifyChecksums = true, + compressionType = 1, // compressed with snappy + blockSize = 4096, // 4 KB = 4 * 1024 B + writeBufferSize = 10485760, // 10 MB = 10 * 1024 * 1024 B + cacheSize = 10485760, // 10 MB = 10 * 1024 * 1024 B + maxOpenFiles = 100 + }, + { + name = "account-index", + path = "storage_directory_test", + createIfMissing = true, + paranoidChecks = true, + verifyChecksums = true, + compressionType = 1, // compressed with snappy + blockSize = 4096, // 4 KB = 4 * 1024 B + writeBufferSize = 10485760, // 10 MB = 10 * 1024 * 1024 B + cacheSize = 10485760, // 10 MB = 10 * 1024 * 1024 B + maxOpenFiles = 100 + }, + { # only for unit test + name = "test_name", + path = "test_path", + createIfMissing = false, + paranoidChecks = false, + verifyChecksums = false, + compressionType = 1, + blockSize = 2, + writeBufferSize = 3, + cacheSize = 4, + maxOpenFiles = 5 + }, + ] + + needToUpdateAsset = false + +} + +node.discovery = { + enable = true + persist = true + external.ip = "46.168.1.1" +} + +node { + + trustNode = "127.0.0.1:50051" + + listen.port = 18888 + + connection.timeout = 2 + + active = [] + + maxConnections = 30 + minConnections = 8 + minActiveConnections = 3 + inactiveThreshold = 600 //seconds + + p2p { + version = 43 # 43: testnet; 101: debug + } + + rpc { + port = 50051 + } + +} + +sync { + node.count = 30 +} + +seed.node = { + ip.list = [ + ] +} + +genesis.block = { + # Reserve balance + assets = [ + { + accountName = "Devaccount" + accountType = "AssetIssue" + address = "27d3byPxZXKQWfXX7sJvemJJuv5M65F3vjS" + balance = "10000000000000000" + }, + { + accountName = "Zion" + accountType = "AssetIssue" + address = "27fXgQ46DcjEsZ444tjZPKULcxiUfDrDjqj" + balance = "15000000000000000" + }, + { + accountName = "Sun" + accountType = "AssetIssue" + address = "27SWXcHuQgFf9uv49FknBBBYBaH3DUk4JPx" + balance = "10000000000000000" + }, + { + accountName = "Blackhole" + accountType = "AssetIssue" + address = "27WtBq2KoSy5v8VnVZBZHHJcDuWNiSgjbE3" + balance = "-9223372036854775808" + } + ] + + witnesses = [ + { + address: 27Ssb1WE8FArwJVRRb8Dwy3ssVGuLY8L3S1 + url = "http://mercury.org/", + voteCount = 105 + }, + { + address: 27anh4TDZJGYpsn4BjXzb7uEArNALxwiZZW + url = "http://venus.org/", + voteCount = 104 + }, + { + address: 27Wkfa5iEJtsKAKdDzSmF1b2gDm5s49kvdZ + url = "http://earth.org/", + voteCount = 103 + }, + { + address: 27bqKYX9Bgv7dgTY7xBw5SUHZ8EGaPSikjx + url = "http://mars.org/", + voteCount = 102 + }, + { + address: 27fASUY6qKtsaAEPz6QxhZac2KYVz2ZRTXW + url = "http://jupiter.org/", + voteCount = 101 + }, + { + address: 27Q3RSbiqm59VXcF8shQWHKbyztfso5FwvP + url = "http://saturn.org/", + voteCount = 100 + }, + { + address: 27YkUVSuvCK3K84DbnFnxYUxozpi793PTqZ + url = "http://uranus.org/", + voteCount = 99 + }, + { + address: 27kdTBTDJ16hK3Xqr8PpCuQJmje1b94CDJU + url = "http://neptune.org/", + voteCount = 98 + }, + { + address: 27mw9UpRy7inTMQ5kUzsdTc2QZ6KvtCX4uB + url = "http://pluto.org/", + voteCount = 97 + }, + { + address: 27QzC4PeQZJ2kFMUXiCo4S8dx3VWN5U9xcg + url = "http://altair.org/", + voteCount = 96 + }, + { + address: 27VZHn9PFZwNh7o2EporxmLkpe157iWZVkh + url = "http://alphalyrae.org/", + voteCount = 95 + } + ] + + timestamp = "0" #2017-8-26 12:00:00 + + parentHash = "0x0000000000000000000000000000000000000000000000000000000000000000" +} + + +localwitness = [ + +] + +block = { + needSyncCheck = true # first node : false, other : true +} + +vm = { + supportConstant = true + minTimeRatio = 0.0 + maxTimeRatio = 5.0 +} +committee = { + allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 + allowOldRewardOpt = 1 +} diff --git a/framework/src/test/resources/config-localtest.conf b/framework/src/test/resources/config-localtest.conf index 22a41d22564..ff31369a915 100644 --- a/framework/src/test/resources/config-localtest.conf +++ b/framework/src/test/resources/config-localtest.conf @@ -5,7 +5,6 @@ net { storage { # Directory for storing persistent data - db.version = 2, db.engine ="LEVELDB", db.directory = "database", index.directory = "index", @@ -58,7 +57,6 @@ storage { node.discovery = { enable = true persist = true - bind.ip = "" external.ip = null } @@ -88,12 +86,7 @@ node { # Number of validate sign thread, default availableProcessors / 2 # validateSignThreadNum = 16 - connectFactor = 0.3 - activeConnectFactor = 0.1 - - maxActiveNodes = 30 - - maxActiveNodesWithSameIp = 10 + maxConnectionsWithSameIp = 10 minParticipationRate = 0 @@ -102,10 +95,8 @@ node { zenTokenId = 1000001 # check the peer data transfer ,disconnect factor - disconnectNumberFactor = 0.4 - maxConnectNumberFactor = 0.8 - receiveTcpMinDataLength = 2048 isOpenFullTcpDisconnect = true + inactiveThreshold = 600 //seconds p2p { version = 333 # 11111: mainnet; 20180622: testnet @@ -126,14 +117,21 @@ node { ] http { + fullNodeEnable = false fullNodePort = 8090 + solidityEnable = false solidityPort = 8091 + PBFTEnable = false + PBFTPort = 8092 } rpc { + enable = false port = 50051 - # This configuration takes effect only if db.version = 2,default value is 50061 - # solidityPort = 50061 + solidityEnable = false + solidityPort = 50061 + PBFTEnable = false + PBFTPort = 50071 # Number of gRPC thread, default availableProcessors / 2 # thread = 16 @@ -155,6 +153,9 @@ node { # The maximum size of header list allowed to be received, default 8192 # maxHeaderListSize = + + # The switch of the reflection service, effective for all gRPC services + reflectionService = true } jsonrpc { @@ -164,6 +165,8 @@ node { # httpSolidityPort = 8555 # httpPBFTEnable = true # httpPBFTPort = 8565 + # maxBlockRange = 5000 + # maxSubTopics = 1000 } } @@ -194,8 +197,6 @@ genesis.block = { accountType = "AssetIssue" address = "TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW" balance = "25000000000000000" - #priKey = D95611A9AF2A2A45359106222ED1AFED48853D9A44DEFF8DC7913F5CBA727366 - #password = 2VYRqa8qKkU1kQYiLtGv7UiFPZpE3v+Nx5E/XLpyc2Y= }, # the account of payment @@ -204,8 +205,6 @@ genesis.block = { accountType = "AssetIssue" address = "TGehVcNhud84JDCGrNHKVz9jEAVKUpbuiv" balance = "10000000000000000" - #priKey = cba92a516ea09f620a16ff7ee95ce0df1d56550a8babe9964981a7144c8a784a - #password = y6kqUW6gn2IKFv9+6Vzg3x1WVQqLq+mWSYGnFEyKeEo= }, # the account of coin burn @@ -214,37 +213,31 @@ genesis.block = { accountType = "AssetIssue" address = "THKrowiEfCe8evdbaBzDDvQjM5DGeB3s3F" balance = "-9223372036854775808" - #priKey = 8E812436A0E3323166E1F0E8BA79E19E217B2C4A53C970D4CCA0CFB1078979DF - #password = joEkNqDjMjFm4fDounnhniF7LEpTyXDUzKDPsQeJed8= } ] witnesses = [ { - address: TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz + address: TEDapYSVvAZ3aYH7w8N9tMEEFKaNKUD5Bp url = "http://test.org/", voteCount = 106 - #priKey = f4df789d3210ac881cb900464dd30409453044d2777060a0c391cbdf4c6a4f57 6666 }, // { // address: TPrLL5ckUdMaPNgJYmGv23qtYjBE34aBf8 // url = "http://mercury.org/", // voteCount = 105 - // #priKey = f5583fd20e13073900a513f333ed13db8c9e83e7e3cf37e74adacef96c5afeaa 7777 // }, // { // address: TEZBh76rouEQpB2zqYVopbRXGx7RfyWorT // #address: 27TfVERREG3FeWMHEAQ95tWHG4sb3ANn3Qe // url = "http://venus.org/", // voteCount = 104 - // #priKey = 9f5c5e48bf87cf92017313082e8cf0f58ccfce423097f0fcebf801695fc99bd4 8888 // }, // { // address: TN27wbfCLEN1gP2PZAxHgU3QZrntsLyxdj // #address: 27b8RUuyZnNPFNZGct2bZkNu9MnGWNAdH3Z // url = "http://earth.org/", // voteCount = 103 - // #priKey = 6781f44d9a2083b14fad1702b8e9ba82749162b795e2fc3f136192fc63f80de2 9999 // }, ] @@ -262,7 +255,7 @@ genesis.block = { //localWitnessAccountAddress = TN3zfjYUmMFK3ZsHSsrdJoNRtGkQmZLBLz localwitness = [ - f4df789d3210ac881cb900464dd30409453044d2777060a0c391cbdf4c6a4f57 + 1234567890123456789012345678901234567890123456789012345678901234 ] diff --git a/framework/src/test/resources/config-test-dbbackup.conf b/framework/src/test/resources/config-test-dbbackup.conf index b39cb54d354..4f9ddf8d32b 100644 --- a/framework/src/test/resources/config-test-dbbackup.conf +++ b/framework/src/test/resources/config-test-dbbackup.conf @@ -5,7 +5,6 @@ net { storage { # Directory for storing persistent data - db.version = 2, db.engine = "ROCKSDB", db.directory = "database", index.directory = "index", @@ -61,7 +60,6 @@ storage { node.discovery = { enable = true persist = true - bind.ip = "" external.ip = null } @@ -97,19 +95,11 @@ node { # Number of validate sign thread, default availableProcessors / 2 # validateSignThreadNum = 16 - connectFactor = 0.3 - activeConnectFactor = 0.1 - - maxActiveNodes = 30 - - maxActiveNodesWithSameIp = 2 + maxConnectionsWithSameIp = 2 minParticipationRate = 15 # check the peer data transfer ,disconnect factor - disconnectNumberFactor = 0.4 - maxConnectNumberFactor = 0.8 - receiveTcpMinDataLength = 2048 isOpenFullTcpDisconnect = true p2p { diff --git a/framework/src/test/resources/config-test-index.conf b/framework/src/test/resources/config-test-index.conf index d2feabff04e..faa2f93dc5e 100644 --- a/framework/src/test/resources/config-test-index.conf +++ b/framework/src/test/resources/config-test-index.conf @@ -54,7 +54,6 @@ storage { node.discovery = { enable = true persist = true - bind.ip = "" external.ip = null } @@ -73,15 +72,29 @@ node { # } ] - maxActiveNodes = 30 - p2p { version = 43 # 43: testnet; 101: debug } + http { + fullNodeEnable = false + solidityEnable = false + PBFTEnable = false + } + + jsonrpc { + httpFullNodeEnable = false + httpSolidityEnable = false + httpPBFTEnable = false + # maxBlockRange = 5000 + # maxSubTopics = 1000 + } + rpc { port = 50051 - + enable = false + solidityEnable = false + PBFTEnable = false # Number of gRPC thread, default availableProcessors / 2 # thread = 16 diff --git a/framework/src/test/resources/config-test-mainnet.conf b/framework/src/test/resources/config-test-mainnet.conf index 82d64a466ab..12acad64d8d 100644 --- a/framework/src/test/resources/config-test-mainnet.conf +++ b/framework/src/test/resources/config-test-mainnet.conf @@ -53,7 +53,6 @@ storage { node.discovery = { enable = true persist = true - bind.ip = "127.0.0.1" external.ip = "46.168.1.1" } @@ -75,12 +74,34 @@ node { # } ] - maxActiveNodes = 30 + maxConnections = 30 + minConnections = 8 + minActiveConnections = 3 p2p { version = 43 # 43: testnet; 101: debug } + http { + fullNodeEnable = false + solidityEnable = false + PBFTEnable = false + } + + jsonrpc { + httpFullNodeEnable = false + httpSolidityEnable = false + httpPBFTEnable = false + # maxBlockRange = 5000 + # maxSubTopics = 1000 + } + + rpc { + enable = false + solidityEnable = false + PBFTEnable = false + } + } sync { @@ -209,7 +230,7 @@ genesis.block = { } localwitness = [ - f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62 + ] block = { diff --git a/framework/src/test/resources/config-test-storagetest.conf b/framework/src/test/resources/config-test-storagetest.conf index 1a551b23be3..25127cdab91 100644 --- a/framework/src/test/resources/config-test-storagetest.conf +++ b/framework/src/test/resources/config-test-storagetest.conf @@ -7,7 +7,6 @@ net { storage { # Directory for storing persistent data - db.version = 2, db.engine = "LEVELDB" db.directory = "database", index.directory = "index", @@ -77,7 +76,6 @@ storage { node.discovery = { enable = true persist = true - bind.ip = "127.0.0.1" external.ip = "46.168.1.1" } @@ -99,7 +97,9 @@ node { # } ] - maxActiveNodes = 30 + maxConnections = 30 + minConnections = 8 + minActiveConnections = 3 p2p { version = 43 # 43: testnet; 101: debug @@ -267,7 +267,7 @@ genesis.block = { //localWitnessAccountAddress = localwitness = [ - f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62 + ] block = { @@ -284,4 +284,6 @@ vm = { } committee = { allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 -} \ No newline at end of file + allowOldRewardOpt = 1 + allowNewRewardAlgorithm = 1 +} diff --git a/framework/src/test/resources/config-test.conf b/framework/src/test/resources/config-test.conf index 4f851e84bcf..eaa6659a8c4 100644 --- a/framework/src/test/resources/config-test.conf +++ b/framework/src/test/resources/config-test.conf @@ -7,7 +7,6 @@ net { storage { # Directory for storing persistent data - db.version = 2, db.engine = "LEVELDB" db.directory = "database", index.directory = "index", @@ -62,13 +61,25 @@ storage { ] needToUpdateAsset = false + snapshot.maxFlushCount = 200 + + # the estimated number of block transactions (default 1000, min 100, max 10000). + # so the total number of cached transactions is 65536 * txCache.estimatedTransactions + txCache.estimatedTransactions = 50 + # if true, transaction cache initialization will be faster. default false + txCache.initOptimization = true + + # data root setting, for check data, currently, only reward-vi is used. + + merkleRoot = { + reward-vi = e0ebe2f3243391ed674dff816a07f589a3279420d6d88bc823b6a9d5778337ce + } } node.discovery = { enable = true persist = true - bind.ip = "127.0.0.1" external.ip = "46.168.1.1" } @@ -89,21 +100,88 @@ node { # nodeId = e437a4836b77ad9d9ffe73ee782ef2614e6d8370fcf62191a6e488276e23717147073a7ce0b444d485fff5a0c34c4577251a7a990cf80d8542e21b95aa8c5e6c # } ] - - maxActiveNodes = 30 + inactiveThreshold = 600 //seconds p2p { version = 43 # 43: testnet; 101: debug } http { - fullNodeEnable = true - fullNodePort = 8090 - solidityEnable = true - solidityPort = 8091 + fullNodeEnable = false + solidityEnable = false + PBFTEnable = false + } + + jsonrpc { + httpFullNodeEnable = false + httpSolidityEnable = false + httpPBFTEnable = false + # maxBlockRange = 5000 + # maxSubTopics = 1000 + } + + # use your ipv6 address for node discovery and tcp connection, default false + enableIpv6 = false + + # if your node's highest block num is below than all your pees', try to acquire new connection, default false + effectiveCheckEnable = false + + dns { + # dns urls to get nodes, url format tree://{pubkey}@{domain}, default empty + treeUrls = [ + #"tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes1.example.org", + ] + + # enable or disable dns publish, default false + publish = false + + # dns domain to publish nodes, required if publish is true + dnsDomain = "nodes1.example.org" + + # dns private key used to publish, required if publish is true, hex string of length 64 + dnsPrivate = "1234567890123456789012345678901234567890123456789012345678901234" + + # known dns urls to publish if publish is true, url format tree://{pubkey}@{domain}, default empty + knownUrls = [ + #"tree://APFGGTFOBVE2ZNAB3CSMNNX6RRK3ODIRLP2AA5U4YFAA6MSYZUYTQ@nodes2.example.org", + ] + + staticNodes = [ + # static nodes to published on dns + # Sample entries: + # "ip:port", + # "ip:port" + ] + + # merge several nodes into a leaf of tree, should be 1~5 + maxMergeSize = 5 + + # only nodes change percent is bigger then the threshold, we update data on dns + changeThreshold = 0.1 + + # dns server to publish, required if publish is true, only aws or aliyun is support + serverType = "aws" + + # access key id of aws or aliyun api, required if publish is true, string + accessKeyId = "your-key-id" + + # access key secret of aws or aliyun api, required if publish is true, string + accessKeySecret = "your-key-secret" + + # if publish is true and serverType is aliyun, it's endpoint of aws dns server, string + aliyunDnsEndpoint = "alidns.aliyuncs.com" + + # if publish is true and serverType is aws, it's region of aws api, such as "eu-south-1", string + awsRegion = "us-east-1" + + # if publish is true and server-type is aws, it's host zone id of aws's domain, string + awsHostZoneId = "your-host-zone-id" } rpc { + enable = false + solidityEnable = false + PBFTEnable = false port = 50051 PBFTPort = 50072 @@ -128,6 +206,9 @@ node { # The maximum size of header list allowed to be received, default 8192 # maxHeaderListSize = + + # The switch of the reflection service, effective for all gRPC services + reflectionService = true } } @@ -267,7 +348,7 @@ genesis.block = { //localWitnessAccountAddress = localwitness = [ - f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62 + ] block = { @@ -284,4 +365,18 @@ vm = { } committee = { allowCreationOfContracts = 1 //mainnet:0 (reset by committee),test:1 -} \ No newline at end of file +} + +rate.limiter.global.qps = 1000 +rate.limiter.global.ip.qps = 1000 +rate.limiter.global.api.qps = 100 +rate.limiter.http = [ + { + component = "GetNowBlockServlet", + strategy = "GlobalPreemptibleAdapter", + paramString = "permit=1" + } +] + +node.dynamicConfig.enable = true +node.dynamicConfig.checkInterval = 0 \ No newline at end of file diff --git a/framework/src/test/resources/daily-build.xml b/framework/src/test/resources/daily-build.xml deleted file mode 100644 index 4120973c34a..00000000000 --- a/framework/src/test/resources/daily-build.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/framework/src/test/resources/solcDir/README.txt b/framework/src/test/resources/solcDir/README.txt deleted file mode 100644 index f390cc49698..00000000000 --- a/framework/src/test/resources/solcDir/README.txt +++ /dev/null @@ -1 +0,0 @@ -to storage solidity compiler \ No newline at end of file diff --git a/framework/src/test/resources/solidityFile.xml b/framework/src/test/resources/solidityFile.xml deleted file mode 100644 index 6082ba41ccd..00000000000 --- a/framework/src/test/resources/solidityFile.xml +++ /dev/null @@ -1,81 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/AssertException002.sol b/framework/src/test/resources/soliditycode/AssertException002.sol deleted file mode 100644 index 15cc07ff984..00000000000 --- a/framework/src/test/resources/soliditycode/AssertException002.sol +++ /dev/null @@ -1,17 +0,0 @@ - - -contract AssertException{ - function divideIHaveArgsReturn(int x,int y) public returns (int z) { - return x / y; - } - function testAssert() public { - require(2==1); - } -} -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/AssignToExternal.sol b/framework/src/test/resources/soliditycode/AssignToExternal.sol deleted file mode 100644 index d4f09590a36..00000000000 --- a/framework/src/test/resources/soliditycode/AssignToExternal.sol +++ /dev/null @@ -1,30 +0,0 @@ -contract AssignToExternal { - // Not allow: - // function f(uint256[] calldata x, uint256[] calldata y) external pure { - // x = y; - // } - - // allow: - - function f(uint256 a) external returns (uint){ - a = a + 1; - return a; - } - - function StringSet(string calldata a) external returns (string memory){ - return a; - } - - function ByteSet(bytes32 a) external returns (bytes32){ - return a; - } - - function UintArraySet(uint256[2] calldata a) external returns (uint256[2] memory){ - return a; - } - - function AddSet(address a) external returns (address){ - return a; - } - -} diff --git a/framework/src/test/resources/soliditycode/BlockHash.sol b/framework/src/test/resources/soliditycode/BlockHash.sol deleted file mode 100644 index 6603da65e44..00000000000 --- a/framework/src/test/resources/soliditycode/BlockHash.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract TestBlockHash { - - function testOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) | bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) | blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) & bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) & blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) ^ bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) ^ blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ClearAbi001.sol b/framework/src/test/resources/soliditycode/ClearAbi001.sol deleted file mode 100644 index 39a8e8cf005..00000000000 --- a/framework/src/test/resources/soliditycode/ClearAbi001.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract testConstantContract{ -function testPayable() public view returns (int z) { -return 1; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ClearAbi005.sol b/framework/src/test/resources/soliditycode/ClearAbi005.sol deleted file mode 100644 index a3115398386..00000000000 --- a/framework/src/test/resources/soliditycode/ClearAbi005.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=0; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ConstructorDefaults.sol b/framework/src/test/resources/soliditycode/ConstructorDefaults.sol deleted file mode 100644 index 4b6186ccb95..00000000000 --- a/framework/src/test/resources/soliditycode/ConstructorDefaults.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract testIsContract{ - bool result; - constructor (bool a) public { - result = a; - } -function test( address a) public returns (bool) { -return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/Create2Test023.sol b/framework/src/test/resources/soliditycode/Create2Test023.sol deleted file mode 100644 index ef022a8e83d..00000000000 --- a/framework/src/test/resources/soliditycode/Create2Test023.sol +++ /dev/null @@ -1,31 +0,0 @@ -contract factory { - constructor() payable public { - } - - function deploy(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } - - function testCreate() payable public returns (address){ - Caller add = (new Caller){value:0}(); - return address(add); - } - - function kill( ) payable public{ - selfdestruct(payable(msg.sender)); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/Create2Test024.sol b/framework/src/test/resources/soliditycode/Create2Test024.sol deleted file mode 100644 index 5d43c0f4ab2..00000000000 --- a/framework/src/test/resources/soliditycode/Create2Test024.sol +++ /dev/null @@ -1,56 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(payable(msg.sender)); - addr.set(); - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } - - function deploy2(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - //addr.testSuicideNonexistentTarget(msg.sender); - //addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr1)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/Create2Test025.sol b/framework/src/test/resources/soliditycode/Create2Test025.sol deleted file mode 100644 index 895dc43e56f..00000000000 --- a/framework/src/test/resources/soliditycode/Create2Test025.sol +++ /dev/null @@ -1,34 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } -} - -contract TestContract{ - uint256 public num; - constructor(uint256 j) public{ - num = j; - } - function getNum() public returns (uint256){ - return num; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/EthGrammer.sol b/framework/src/test/resources/soliditycode/EthGrammer.sol deleted file mode 100644 index 1be4d2d0881..00000000000 --- a/framework/src/test/resources/soliditycode/EthGrammer.sol +++ /dev/null @@ -1,191 +0,0 @@ -contract C { - constructor() public payable{} - - function baseFee() external view returns (uint ret) { - assembly { - ret := basefee() - } - assert(block.basefee == ret); - } - - function baseFeeOnly() external view returns (uint ret) { - assembly { - ret := basefee() - } - } - - function gasPrice() external view returns (uint ret) { - assembly { - ret := basefee() - } - assert(tx.gasprice == ret); - } - - function gasPriceOnly() external view returns (uint) { - return tx.gasprice; - } - - function testCall(address payable caller, address payable transferTo) public { - (bool success, bytes memory data) = caller.call(abi.encodeWithSignature("transfer(address)",transferTo)); - require(success); - } - - function testDelegateCall(address payable caller, address payable transferTo) public { - (bool success, bytes memory data) = caller.delegatecall(abi.encodeWithSignature("transfer(address)",transferTo)); - require(success); - } - - uint sum = 0; - function transfer(address payable transerTo) public { - for (uint i = 0; i < type(uint256).max; i++) - sum = 0; - for (uint j = 0; j < type(uint8).max; j++) - sum += j; - transerTo.transfer(1); - } - - function testCallFunctionInContract(address payable transferTo) public { - this.transfer(transferTo); - } - - - function getRipemd160(string memory input) public returns(bytes32 output) { - bytes memory tem = bytes(input); - assembly { - if iszero(staticcall(not(0), 0x020003, add(tem, 0x20), mload(tem), output, 0x20)) { - revert(0, 0) - } - output := mload(add(output,0x0c)) - } - } - - function getRipemd160Str(string memory input) public view returns(bytes32 output) { - assembly { - if iszero(staticcall(not(0), 0x020003, add(input, 0x20), mload(input), output, 0x20)) { - revert(0, 0) - } - output := mload(add(output,0x0c)) - } - - } - - function F(uint32 rounds, bytes32[2] memory h, bytes32[4] memory m, bytes8[2] memory t, bool f) public view returns (bytes32[2] memory) { - bytes32[2] memory output; - - bytes memory args = abi.encodePacked(rounds, h[0], h[1], m[0], m[1], m[2], m[3], t[0], t[1], f); - - assembly { - if iszero(staticcall(not(0), 0x020009, add(args, 32), 0xd5, output, 0x40)) { - revert(0, 0) - } - } - - return output; - } - - function callF() public view returns (bytes32[2] memory) { - uint32 rounds = 12; - - bytes32[2] memory h; - h[0] = hex"48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5"; - h[1] = hex"d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b"; - - bytes32[4] memory m; - m[0] = hex"6162630000000000000000000000000000000000000000000000000000000000"; - m[1] = hex"0000000000000000000000000000000000000000000000000000000000000000"; - m[2] = hex"0000000000000000000000000000000000000000000000000000000000000000"; - m[3] = hex"0000000000000000000000000000000000000000000000000000000000000000"; - - bytes8[2] memory t; - t[0] = hex"03000000"; - t[1] = hex"00000000"; - - bool f = true; - - // Expected output: - // ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d1 - // 7d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923 - return F(rounds, h, m, t, f); - } - - -} - -contract D { - constructor() public payable{} - - function deploy(uint256 salt) public returns(address){ - address addr; - bytes memory code = type(C).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - } - return addr; - } - - uint sum = 0; - function transfer(address payable transerTo) public { - for (uint i = 0; i < type(uint256).max; i++) - sum = 0; - for (uint j = 0; j < type(uint8).max; j++) - sum += j; - transerTo.transfer(1); - } - - function callCreate2(uint256 salt) public returns(address){ - address addr; - bytes memory code = type(C).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - } - return addr; - } - - function fixCreate2StackDepth(uint salt) public { - if (isEmptyAddress(callCreate2(salt + 1))) { - revert(); - } - this.fixCreate2StackDepth(salt + 1); - } - - function callCreate() public returns(address){ - address addr; - bytes memory code = type(C).creationCode; - assembly { - addr := create(0, add(code, 0x20), mload(code)) - } - return addr; - } - - function fixCreateStackDepth() public { - if (isEmptyAddress(callCreate())) { - revert(); - } - this.fixCreateStackDepth(); - } - - bool constant bool1 = true; - function isEmptyAddress(address add2) public returns(bool result){ - - assembly { - if iszero(extcodesize(add2)) { - result := bool1 - } - } - } - - function deployef(bytes memory code) public payable{ - address addr; - assembly { - addr := create(0, add(code, 0x20), mload(code)) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - } -} - - - - - diff --git a/framework/src/test/resources/soliditycode/EthGrammer02.sol b/framework/src/test/resources/soliditycode/EthGrammer02.sol deleted file mode 100644 index d032b531fa6..00000000000 --- a/framework/src/test/resources/soliditycode/EthGrammer02.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract D { - constructor() public payable{} - - event createAddress(address addr); - function createDeployEf(bytes memory code) public returns(address addr){ - address addr; - assembly { - addr := create(0, add(code, 0x20), mload(code)) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return addr; - } - - function create2DeployEf(bytes memory code,uint256 salt) public returns(address addr){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit createAddress(addr); - return addr; - } - - function setSlot(bytes memory slot,uint256 value) external { -// uint256 value = 123; - assembly { - sstore(slot, value) - } - } - - function getSlot(bytes memory slot) view external returns(uint res) { - assembly { - res := sload(slot) - } - } -} - - - - - diff --git a/framework/src/test/resources/soliditycode/ExtCodeHashTest010.sol b/framework/src/test/resources/soliditycode/ExtCodeHashTest010.sol deleted file mode 100644 index e54c302addb..00000000000 --- a/framework/src/test/resources/soliditycode/ExtCodeHashTest010.sol +++ /dev/null @@ -1,46 +0,0 @@ -contract Counter { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); - constructor() public{ - owner = payable(msg.sender); - } - function getCodeHashSuicide(address addr) public returns (bytes32 _hashBefore){ - assembly{ - _hashBefore := extcodehash(addr) - } - selfdestruct(owner); - return _hashBefore; - } - - function getCodeHashRevert() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - address addr = address(this); - assembly { - _hashBefore := extcodehash(addr) - } - if (owner == msg.sender) { - selfdestruct(owner); - } - assembly { - _hashAfter := extcodehash(addr) - } - revert(); - emit LogResult(_hashBefore, _hashAfter); - } - - function getCodeHashCreate() public returns (bytes32 _hashBefore){ - TestContract A = (new TestContract){value:0}(); - address addr = address(A); - assembly{ - _hashBefore := extcodehash(addr) - } - revert(); - return _hashBefore; - } -} - -contract TestContract{ - uint256 count = 1; - constructor() public payable{ - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ExternalSelector.sol b/framework/src/test/resources/soliditycode/ExternalSelector.sol deleted file mode 100644 index 01fddac9e2e..00000000000 --- a/framework/src/test/resources/soliditycode/ExternalSelector.sol +++ /dev/null @@ -1,92 +0,0 @@ -//pragma solidity ^0.6.0; - -contract selectorContract { - function testSelectorNoParam() external pure returns(uint) { - return 11; - } - - function testSelectorWithParam(uint x) external pure returns(uint) { - return 22; - } -} - -interface interfaceSelector { - function getSelector() external pure returns(uint); -} - -interface B is interfaceSelector { - // interface现在可以继承自其他interface - function testImplemention() external pure returns(uint); -} - -contract implementContract is B{ - function getSelector() external override pure returns(uint) { - return 66; - } - - function testImplemention() external override pure returns(uint) { - return 77; - } - - constructor() public payable {} -} - -contract basicContract{ - function testNewUse() external payable returns(uint) { - return 345; - } - - constructor() public payable {} -} - -contract TestGasValue{ - constructor() public payable {} - - function testNewUse() external payable returns(uint) { - return 123; - } - basicContract bc = new basicContract(); - // external方法在调用时可以采用c.f{gas: 10000, value: 4 trx}()的形式 - function callWithGasAndValue(uint x,uint y) external returns(uint) { - return bc.testNewUse{gas:x, value:y}(); - } - - function callThisNoGasAnd1Value() external returns(uint) { - return this.testNewUse{gas:0, value:1}(); - } - - // inline assembly中允许true和false字面量 - function testAssemblyTrue() public pure returns(uint x) { - assembly { - x := true - } - } - - // inline assembly中允许true和false字面量 - function testAssemblyFalse() public pure returns(uint x) { - assembly { - x := false - } - } - - // create2的high-level用法new C{salt: 0x1234, value: 1 ether}(arg1, arg2) - function testCreate2() public returns(address) { - basicContract c = new basicContract{salt: bytes32(bytes1(0x01)), value: 1 trx}(); - return address(c); - } - - - function getContractSelectorNoParam() public pure returns(bytes4) { - return selectorContract.testSelectorNoParam.selector; - } - - function getContractSelectorWithParam() public pure returns(bytes4) { - return selectorContract.testSelectorWithParam.selector; - } - - function getInterfaceSelectorNoParam() public pure returns(bytes4) { - return interfaceSelector.getSelector.selector; - } - -} - diff --git a/framework/src/test/resources/soliditycode/NewFeature068.sol b/framework/src/test/resources/soliditycode/NewFeature068.sol deleted file mode 100644 index 8bfe805450c..00000000000 --- a/framework/src/test/resources/soliditycode/NewFeature068.sol +++ /dev/null @@ -1,131 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0 -//pragma solidity ^0.6.8; - -abstract contract testModifier { - modifier isOwner() virtual; -} - -abstract contract testInterfaceId { - function getValue() external view virtual returns(uint); - function getOwner() external view virtual returns(uint); - -} - -interface a { - function getValue() external view returns(uint); - function getOwner() external view returns(uint); -} - -contract testMapKey is testModifier{ - - enum size{ - SMALL, - LARGE - } - - mapping(size => uint) public enums; - - mapping(testMapKey => uint) public contracts; - - function setEnumValue(uint value) public { - enums[size.SMALL] = value; - } - - function getEnumValue() public view returns(uint) { - return enums[size.SMALL]; - } - - function setContractValue() public { - contracts[this] = 2; - } - - function getContractValue() public view returns(uint) { - return contracts[this]; - } - - bytes4 constant functionSelector = this.getEnumValue.selector; - - function getfunctionSelector() public pure returns(bytes4) { - return functionSelector; - } - - uint immutable x; - address immutable owner = msg.sender; - - constructor() public { - x = 5; - } - - string b = "test"; - - function testStorage() public view returns(string memory) { - string storage aa; - aa = b; - return aa; - - } - - function getImmutableVal() public view returns(uint) { - return x; - } - - function getOwner() public view returns(address) { - return owner; - } - - function getInterfaceId() public pure returns(bytes4,bytes4) { - return (type(a).interfaceId, type(testInterfaceId).interfaceId); - } - - modifier isOwner() override { - require(msg.sender == owner); - _; - } - - function requireOwner() public view isOwner returns(uint) { - return 6; - } - - - function getUint256MinAndMax() public pure returns(uint, uint) { - return (type(uint).min, type(uint).max); - } - - - function getUint8MinAndMax() public pure returns(uint8, uint8) { - return (type(uint8).min, type(uint8).max); - } - - function calldataModifier(bytes calldata a) external returns(bytes calldata) { - bytes calldata b = a; - return b; - } - -} - - -abstract contract base { - function abstractfun() virtual public returns(uint); -} - -abstract contract callEmptyFunction is base { - function callfun() public returns(uint) { - return abstractfun(); - } -} - - - - - - - - - - - - - - - - diff --git a/framework/src/test/resources/soliditycode/NewFeature076.sol b/framework/src/test/resources/soliditycode/NewFeature076.sol deleted file mode 100644 index 3191acb8f1d..00000000000 --- a/framework/src/test/resources/soliditycode/NewFeature076.sol +++ /dev/null @@ -1,21 +0,0 @@ -function a() returns (uint) { - return 1; -} -abstract contract abvd { - -} -interface qwer { - function getValue() external view returns(uint); - function getOwner() external view returns(uint); -} -contract C { - function getOutsideMethod() external returns (uint) { - return a(); - } - function getAbstractName() public returns(string memory) { - return type(abvd).name; - } - function getInterfaceName() public returns(string memory) { - return type(qwer).name; - } -} diff --git a/framework/src/test/resources/soliditycode/NewFeature080.sol b/framework/src/test/resources/soliditycode/NewFeature080.sol deleted file mode 100644 index 7422e8d34b4..00000000000 --- a/framework/src/test/resources/soliditycode/NewFeature080.sol +++ /dev/null @@ -1,109 +0,0 @@ -contract C { - constructor() public payable{} - - function subNoUncheck() public pure returns (uint) { - uint8 x = 0; - return x--; - } - - function subWithUncheck() public pure returns (uint) { - uint8 x = 0; - unchecked { x--; } - return x; - } - - function addNoUncheck() public pure returns (uint) { - uint8 x = 255; - return x++; - } - - function divideZeroNoUncheck() public pure returns (uint) { - uint8 x = 0; - uint8 y = 1; - return y/x; - } - - function assertFailNoUncheck() public pure { - assert(1==2); - } - - int64[] b = [-1, 2, -3]; - function arrayOutofIndex() public view returns (int) { - return b[3]; - } - - function typeConvert() public pure returns(uint16) { - // return uint16(int8(-1)); //0.8.0报错 之前不报错 - return uint16(int16(int8(-1))); //0xffff - // return uint16(uint8(int8(-1))); // 0xff - } - - function powerMultiRightToLeft() public pure returns(uint) { - return 2**1**2**3; - } - - function powerMultiLeftToRight() public pure returns(uint) { - return ((2**1)**2)**3; - } - - function powerMultiWith2Params() public pure returns(uint) { - return 2**3; - } - //log 0,1,2,3 disallowed in solidity v0.8.0 -// function f2() public payable { -// uint256 x=1; -// uint256 y=2; -// uint256 z=3; -// bytes32 _id = bytes32(x); -// log3( -// bytes32(x), -// bytes32(y), -// bytes32(z), -// _id -// ); -// } - - - function getBlockChainId111111() view public returns(uint256) { - return block.chainid; - } - - - function getBlockChainId() view public returns(uint256) { - uint256 id; - assembly { - id := chainid() - } - assert(block.chainid == id); - return block.chainid; - } - function getAddressCodehash(address addr) view public returns(bytes32 newHash) { - bytes32 _hashBefore; - assembly{ - _hashBefore := extcodehash(addr) - } - bytes32 newHash = addr.codehash; - assert(_hashBefore == newHash); - return newHash; - } - - function transferToTxorigin(uint64 value) payable public { - payable(tx.origin).transfer(value); - } - -// msg.data was removed in receive() function -// event FallbackCalled(bytes data); -// receive() external payable { -// -// emit FallbackCalled(msg.data); -// } - - function transferToLiteralAddress(uint64 value) public{ - uint160 num = type(uint160).max-3; - address add = address(num); - payable(add).transfer(value); - } -} - - - diff --git a/framework/src/test/resources/soliditycode/NewFeature0811.sol b/framework/src/test/resources/soliditycode/NewFeature0811.sol deleted file mode 100644 index bb7cb1ab567..00000000000 --- a/framework/src/test/resources/soliditycode/NewFeature0811.sol +++ /dev/null @@ -1,101 +0,0 @@ - -type TestInt128 is int128; -pragma abicoder v2; -interface I { -function foo() external; -} - -contract C is I { -uint8 immutable i; -uint8 x; - -constructor() { -i = 33; -x = readI(); -} - -function readX() public view returns (uint8) { -return x; -} - -function readI() public view returns (uint8) { -return i; -} - - - - -function fExternal(uint256 p, string memory t) external {} - -function fSignatureFromLiteralCall() public view returns (bytes memory) { -return abi.encodeCall(this.fExternal, (1, "123")); -} - - - - - -enum FreshJuiceSize{ SMALL, MEDIUM, LARGE, FINAL } - - -TestInt128 a = TestInt128.wrap(45); -function getUserDefinedValue() public view returns(TestInt128) { -return a; -} - - - - -function foo() external { // Does not compile without override -} - -function getEnumMin() public view returns (FreshJuiceSize) { -return type(FreshJuiceSize).min; - -} - - -function getEnumMax() public view returns (FreshJuiceSize) { -return type(FreshJuiceSize).max; - -} - - -function testFunction() external {} - -function testYul1() public view returns (address adr) { -function() external fp = this.testFunction; - -assembly { -adr := fp.address -} -} -function testGetAddress() public view returns (address) { -return this.testFunction.address; -} -function testYul2() public view returns (uint32) { -function() external fp = this.testFunction; -uint selectorValue = 0; - -assembly { -selectorValue := fp.selector -} - -// Value is right-aligned, we shift it so it can be compared -return uint32(bytes4(bytes32(selectorValue << (256 - 32)))); -} -function testGetSelector() public view returns (uint32) { -return uint32(this.testFunction.selector); -} - - - -int8 immutable bugValue = -4; -function fixBugTest() public view returns (bytes32 r) { -int8 y = bugValue; -assembly { r := y } -} - - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/NewFeature086.sol b/framework/src/test/resources/soliditycode/NewFeature086.sol deleted file mode 100644 index f898fadde3e..00000000000 --- a/framework/src/test/resources/soliditycode/NewFeature086.sol +++ /dev/null @@ -1,121 +0,0 @@ -contract C { - constructor() public payable{} - - function catchAssertFail() external view returns(uint) { - try this.assertFail() { - return 0; - } catch Panic(uint _code) { - if (_code == 0x01) { - return 0x01; - } - return 2; - } - return 3; - } - function assertFail() external pure { - assert(0 == 1); - } - function catchUnderFlow() external view returns(uint) { - try this.underflow() { - return 44; - } catch Panic(uint _code) { - if (_code == 0x11) { - return 0x11; - } - return 22; - } - return 33; - } - function underflow() public pure { - uint x = 0; - x--; - } - - function catchDivideZero() external view returns(uint) { - try this.divideZero() { - return 14; - } catch Panic(uint _code) { - if (_code == 0x12) { - return 0x12; - } - return 11; - } - return 13; - } - function divideZero() public pure { - uint8 x = 0; - uint8 y = 1; - uint8 z = y/x; - } - - function convertUint2Int() public pure { - uint16 a = 1; -// int32 b = int32(a); -// int32 b = a; - } - - function getAddressCodeLength() public returns(uint) { - return address(this).code.length; - } - - function keccak256Bug(string memory s) public returns (bool ret) { - assembly { - let a := keccak256(s, 32) - let b := keccak256(s, 8) - ret := eq(a, b) - } - } - - error InsufficientBalance(uint256 available, uint256 required); - mapping(address => uint) balance; - function transfer(address to, uint256 amount) public { - if (amount > balance[msg.sender]) - revert InsufficientBalance({available: balance[msg.sender], required: amount}); - balance[msg.sender] -= amount; - balance[to] += amount; - } - - error Unauthorized(); - function withdraw() public { - address payable owner; - if (msg.sender != owner) - revert Unauthorized(); - owner.transfer(address(this).balance); - } - - bytes s = "Storage"; - function bytesConcat(bytes calldata c, string memory m, bytes16 b) public view returns(uint256) { - bytes memory a = bytes.concat(s, c, c[:2], "Literal", bytes(m), b); - assert((s.length + c.length + 2 + 7 + bytes(m).length + 16) == a.length); - return a.length; - } - - bytes p = "hihello"; - function bytesConcatWithEmptyStr() public view { - bytes memory a = bytes.concat("hi", "", "hello"); - assert(p.length == a.length); - } - - event ssoo(uint256); - function testEmitEvent() public payable { - emit ssoo(6); - } - - function bytes2BytesN(bytes memory c) public returns (bytes8) { - // If c is longer than 8 bytes, truncation happens - return bytes3(c); - } - - function getContractAddress() public view returns (address a1, address a2) { - a1 = address(this); - this.getContractAddress.address; - [this.getContractAddress.address][0]; - a2 = [this.getContractAddress.address][0]; - } - -} - - - - - diff --git a/framework/src/test/resources/soliditycode/NoAbi001.sol b/framework/src/test/resources/soliditycode/NoAbi001.sol deleted file mode 100644 index 8f919cbb153..00000000000 --- a/framework/src/test/resources/soliditycode/NoAbi001.sol +++ /dev/null @@ -1,10 +0,0 @@ -contract testNoABiContract{ - uint public i = 2; - event trigger(uint256 i, address sender); - - function testTrigger() public returns (uint) { - i++; - emit trigger(i, msg.sender); - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/NoAbi002.sol b/framework/src/test/resources/soliditycode/NoAbi002.sol deleted file mode 100644 index 0bb30e78443..00000000000 --- a/framework/src/test/resources/soliditycode/NoAbi002.sol +++ /dev/null @@ -1,29 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract testNoABiContract { - uint public i=0; - event trigger(uint256 i, address sender); - - constructor () public {} - - function plusOne() public returns(uint){ - i++; - emit trigger(i, msg.sender); - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ParentTypeBug.sol b/framework/src/test/resources/soliditycode/ParentTypeBug.sol deleted file mode 100644 index 897c843ae24..00000000000 --- a/framework/src/test/resources/soliditycode/ParentTypeBug.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract Parent { - uint256 public m_aMember; - address public m_bMember; -} -contract Child is Parent { - function foo() public view returns (uint256) { return Parent.m_aMember; } - function bar() public view returns (address) { return Parent.m_bMember; } - - // complie failed - // function foo() public pure returns (uint256) { return Parent.m_aMember; } - // function bar() public pure returns (address) { return Parent.m_bMember; } - -} diff --git a/framework/src/test/resources/soliditycode/SafeMath.sol b/framework/src/test/resources/soliditycode/SafeMath.sol deleted file mode 100644 index 1a7f1be2b8e..00000000000 --- a/framework/src/test/resources/soliditycode/SafeMath.sol +++ /dev/null @@ -1,149 +0,0 @@ - - -/** - * @dev Wrappers over Solidity's arithmetic operations with added overflow - * checks. - * - * Arithmetic operations in Solidity wrap on overflow. This can easily result - * in bugs, because programmers usually assume that an overflow raises an - * error, which is the standard behavior in high level programming languages. - * `SafeMath` restores this intuition by reverting the transaction when an - * operation overflows. - * - * Using this library instead of the unchecked operations eliminates an entire - * class of bugs, so it's recommended to use it always. - */ -library SafeMath { - /** - * @dev Returns the addition of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - Addition cannot overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 c = a + b; - require(c >= a, "SafeMath: addition overflow"); - - return c; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - return sub(a, b, "SafeMath: subtraction overflow"); - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting with custom message on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b <= a, errorMessage); - uint256 c = a - b; - - return c; - } - - /** - * @dev Returns the multiplication of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - Multiplication cannot overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) { - return 0; - } - - uint256 c = a * b; - require(c / a == b, "SafeMath: multiplication overflow"); - - return c; - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - return div(a, b, "SafeMath: division by zero"); - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts with custom message on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b > 0, errorMessage); - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - - return c; - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b) internal pure returns (uint256) { - return mod(a, b, "SafeMath: modulo by zero"); - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts with custom message when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b != 0, errorMessage); - return a % b; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/ShiftCommand001.sol b/framework/src/test/resources/soliditycode/ShiftCommand001.sol deleted file mode 100644 index 574ee2b571b..00000000000 --- a/framework/src/test/resources/soliditycode/ShiftCommand001.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/SolidityMappingFix.sol b/framework/src/test/resources/soliditycode/SolidityMappingFix.sol deleted file mode 100644 index 98f9752e4b3..00000000000 --- a/framework/src/test/resources/soliditycode/SolidityMappingFix.sol +++ /dev/null @@ -1,9 +0,0 @@ -//pragma experimental ABIEncoderV2; -contract Tests { - mapping(address => uint) public balances; - function update(uint256 amount) public returns (address addr) - { - balances[msg.sender] = amount; - return msg.sender; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol b/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol deleted file mode 100644 index 0d5c4bb7013..00000000000 --- a/framework/src/test/resources/soliditycode/TestMappings_array_pop.sol +++ /dev/null @@ -1,19 +0,0 @@ -contract C { - mapping (uint256 => uint256)[] a; - - function n1(uint256 key, uint256 value) public { - a.push(); - a[a.length - 1][key] = value; - } - - - - function map(uint256 key) public view returns (uint) { - return a[a.length - 1][key]; - } - - function p() public { - a.pop(); - } -} - diff --git a/framework/src/test/resources/soliditycode/TransferFailed001.sol b/framework/src/test/resources/soliditycode/TransferFailed001.sol deleted file mode 100644 index 538a07fdf5c..00000000000 --- a/framework/src/test/resources/soliditycode/TransferFailed001.sol +++ /dev/null @@ -1,147 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - - function testTransferTokenCompiledLongMax() payable public{ - payable(address(0x1)).transferToken(1,9223372036855775827); - } - - function testTransferTokenCompiled() payable public{ - payable(address(0x1)).transferToken(1,1); - } - - function testTransferTokenCompiledLongMin() payable public{ - //address(0x1).transferToken(1,-9223372036855775828); - } - - function testTransferTokenCompiledLongMin1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(uint256(int256(-9223372036855775828)))); - } - - function testTransferTokenCompiled1() payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(1)); - } - - function testTransferTokenCompiledLongMax1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(9223372036855775827)); - } - - function testTransferTokenCompiledTokenId(uint256 tokenid) payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(tokenid)); - } - - function testTransferTokenTest(address addr ,uint256 tokenid) payable public returns(uint256){ - return addr.tokenBalance(trcToken(tokenid)); - } - - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public { - caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - } - - function testSendTrxRevert(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - revert(); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.transfer(i); - } - - function testTransferTrxrevert(uint256 i,address payable nonexistentTarget) payable public{ - nonexistentTarget.transfer(i); - revert(); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - } - - function testTransferTokenRevert(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - revert(); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - function testSuicideRevert(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - revert(); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - address payable self = payable(address(uint160(address(this)))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - address payable self = payable(address(uint160(address(this)))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - address payable self = payable(address(uint160(address(this)))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - function deploy2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(300, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TransferFailed005.sol b/framework/src/test/resources/soliditycode/TransferFailed005.sol deleted file mode 100644 index 66b946199c2..00000000000 --- a/framework/src/test/resources/soliditycode/TransferFailed005.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TransferFailed006.sol b/framework/src/test/resources/soliditycode/TransferFailed006.sol deleted file mode 100644 index 66b946199c2..00000000000 --- a/framework/src/test/resources/soliditycode/TransferFailed006.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TransferFailed007.sol b/framework/src/test/resources/soliditycode/TransferFailed007.sol deleted file mode 100644 index 66b946199c2..00000000000 --- a/framework/src/test/resources/soliditycode/TransferFailed007.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - payable(msg.sender).send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = payable(address(uint160(address(this)))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant001.sol b/framework/src/test/resources/soliditycode/TriggerConstant001.sol deleted file mode 100644 index b385850577d..00000000000 --- a/framework/src/test/resources/soliditycode/TriggerConstant001.sol +++ /dev/null @@ -1,28 +0,0 @@ - - -contract testConstantContract{ - uint256 public i; - function testPayable() public payable returns (uint256 z) { - i=1; - z=i; - return z; - } - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - function testView2() public view returns (uint256 z) { - uint256 i=1; - revert(); - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant002.sol b/framework/src/test/resources/soliditycode/TriggerConstant002.sol deleted file mode 100644 index 7708d81792a..00000000000 --- a/framework/src/test/resources/soliditycode/TriggerConstant002.sol +++ /dev/null @@ -1,10 +0,0 @@ - - -contract testConstantContract{ - uint256 public i; - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant003.sol b/framework/src/test/resources/soliditycode/TriggerConstant003.sol deleted file mode 100644 index 947b3f610e6..00000000000 --- a/framework/src/test/resources/soliditycode/TriggerConstant003.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -contract testConstantContract{ - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPayable() public payable returns (uint256 z) { - uint256 i=1; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant004.sol b/framework/src/test/resources/soliditycode/TriggerConstant004.sol deleted file mode 100644 index 7fcb44950e7..00000000000 --- a/framework/src/test/resources/soliditycode/TriggerConstant004.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testPure() public pure returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant015.sol b/framework/src/test/resources/soliditycode/TriggerConstant015.sol deleted file mode 100644 index d926c43c824..00000000000 --- a/framework/src/test/resources/soliditycode/TriggerConstant015.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - constructor () public { - } - function plusOne() public returns(uint){ - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TriggerConstant024.sol b/framework/src/test/resources/soliditycode/TriggerConstant024.sol deleted file mode 100644 index 69ad3a2d5b5..00000000000 --- a/framework/src/test/resources/soliditycode/TriggerConstant024.sol +++ /dev/null @@ -1,9 +0,0 @@ - - -contract testConstantContract{ -function testView() public view returns (uint256 z) { -uint256 i=1; -revert(); -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TvmIsContract.sol b/framework/src/test/resources/soliditycode/TvmIsContract.sol deleted file mode 100644 index 4266b9e92ca..00000000000 --- a/framework/src/test/resources/soliditycode/TvmIsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode/TvmIsContract001.sol b/framework/src/test/resources/soliditycode/TvmIsContract001.sol deleted file mode 100644 index 77aae930b59..00000000000 --- a/framework/src/test/resources/soliditycode/TvmIsContract001.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} - -function testIsContractView(address a) view public returns (bool) { -return (a.isContract); -} - -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} - -function testConstructorView() public view returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode/TvmIsContract002.sol b/framework/src/test/resources/soliditycode/TvmIsContract002.sol deleted file mode 100644 index 2fe474fd98c..00000000000 --- a/framework/src/test/resources/soliditycode/TvmIsContract002.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract testIsContract{ -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -} diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand043.sol b/framework/src/test/resources/soliditycode/TvmNewCommand043.sol deleted file mode 100644 index 04d9f7dde28..00000000000 --- a/framework/src/test/resources/soliditycode/TvmNewCommand043.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand103.sol b/framework/src/test/resources/soliditycode/TvmNewCommand103.sol deleted file mode 100644 index dbc7fd0f0f4..00000000000 --- a/framework/src/test/resources/soliditycode/TvmNewCommand103.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testView() public constant returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand107.sol b/framework/src/test/resources/soliditycode/TvmNewCommand107.sol deleted file mode 100644 index 5b51cd1842c..00000000000 --- a/framework/src/test/resources/soliditycode/TvmNewCommand107.sol +++ /dev/null @@ -1,9 +0,0 @@ - - - contract testConstantContract{ - int256 public i; - function testPayable() public returns (int z) { - z=1+1; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand108.sol b/framework/src/test/resources/soliditycode/TvmNewCommand108.sol deleted file mode 100644 index 0088054faf9..00000000000 --- a/framework/src/test/resources/soliditycode/TvmNewCommand108.sol +++ /dev/null @@ -1,7 +0,0 @@ - - - contract testConstantContract{ - function test() pure public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TvmNewCommand109.sol b/framework/src/test/resources/soliditycode/TvmNewCommand109.sol deleted file mode 100644 index dc8dd1e8399..00000000000 --- a/framework/src/test/resources/soliditycode/TvmNewCommand109.sol +++ /dev/null @@ -1,7 +0,0 @@ - - - contract testConstantContract{ - function test() view public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/TvmOldCommand001.sol b/framework/src/test/resources/soliditycode/TvmOldCommand001.sol deleted file mode 100644 index f2927bd8e45..00000000000 --- a/framework/src/test/resources/soliditycode/TvmOldCommand001.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract binaryRightContract{ - function binaryMoveR(uint i)public returns (uint z) { - return z = 5 >> i; - } - function binaryLiftR(uint i)public returns (uint z) { - return z = 5 << i; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/VerifyBurnProof001.sol b/framework/src/test/resources/soliditycode/VerifyBurnProof001.sol deleted file mode 100644 index 4173e84de23..00000000000 --- a/framework/src/test/resources/soliditycode/VerifyBurnProof001.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract VerifyBurnProof001Test { - // verifyBurnProof(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32) - // size = 512 - // - - function VerifyBurnProofSize001(bytes32[10] memory output, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature,bytes32 signHash) public returns (bool){ - return verifyBurnProof(output, spendAuthoritySignature, value, bindingSignature, signHash); - } - - function VerifyBurnProofSize002(bytes memory data) public returns (bool, bytes memory){ - // bytes memory empty = ""; - return address(0x1000003).delegatecall(data); - } - - function VerifyBurnProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000003).delegatecall(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/VerifyMintProof001.sol b/framework/src/test/resources/soliditycode/VerifyMintProof001.sol deleted file mode 100644 index cb0812c2ef5..00000000000 --- a/framework/src/test/resources/soliditycode/VerifyMintProof001.sol +++ /dev/null @@ -1,33 +0,0 @@ - -contract VerifyMintProof001Test { - // verifyMintProof(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256) - - function VerifyMintProofSize001(bytes32[9] memory output, bytes32[2] memory bindingSignature, uint64 value, bytes32 signHash, bytes32[33] memory frontier,uint256 leafCount) public returns (bytes32[] memory){ - return verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - } - - function VerifyMintProofSize002(bytes memory data) public returns (bool, bytes memory){ -// address verifyMint = address (0x1000001); -// -// assembly { -// let succeeded := delegatecall(sub(gas, 5000), verifyMint, add(data, 0x20), mload(data), 0, 0) -// let size := returndatasize -// let response := mload(0x40) -// mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) -// mstore(response, size) -// returndatacopy(add(response, 0x20), 0, size) -// switch iszero(succeeded) -// case 1 { -// // throw if delegatecall failed -// revert(add(response, 0x20), size) -// } -// } - - return address(0x1000001).delegatecall(data); - } - - function VerifyMintProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000001).call(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/abiencode.sol b/framework/src/test/resources/soliditycode/abiencode.sol deleted file mode 100644 index 38fad3454d6..00000000000 --- a/framework/src/test/resources/soliditycode/abiencode.sol +++ /dev/null @@ -1,16 +0,0 @@ -pragma experimental ABIEncoderV2; - -// tests encoding from storage arrays - -contract AbiEncode { - int256[2][] tmp_h; - function h(int256[2][] calldata s) external returns (bytes memory) { - tmp_h = s; - return abi.encode(tmp_h); - } - int256[2][2] tmp_i; - function i(int256[2][2] calldata s) external returns (bytes memory) { - tmp_i = s; - return abi.encode(tmp_i); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/abstract001.sol b/framework/src/test/resources/soliditycode/abstract001.sol deleted file mode 100644 index 741f236925d..00000000000 --- a/framework/src/test/resources/soliditycode/abstract001.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.6.0; - -interface X { - function setValue(uint _x) external; - function setBalance(uint _x) external; -} - -abstract contract abstract001 is X { - uint x; - function setX(uint _x) public { x = _x; } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/abstract002.sol b/framework/src/test/resources/soliditycode/abstract002.sol deleted file mode 100644 index 7358fc8e163..00000000000 --- a/framework/src/test/resources/soliditycode/abstract002.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.6.0; - -interface X { - function setValue(uint _x) external; - function setBalance(uint _x) external; -} - -abstract contract abstract002 is X { - uint x; - function setX(uint _x) public { x = _x; } - function setValue(uint _x) external override{ x = _x; } - function setBalance(uint _x) external override{ x = _x; } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/abstractContractWithMapParamsConstructor.sol b/framework/src/test/resources/soliditycode/abstractContractWithMapParamsConstructor.sol deleted file mode 100644 index 380c57180b8..00000000000 --- a/framework/src/test/resources/soliditycode/abstractContractWithMapParamsConstructor.sol +++ /dev/null @@ -1,23 +0,0 @@ -abstract contract Feline { - - constructor (mapping (uint => uint) storage m) { - m[5] = 20; - } - - function utterance() public virtual returns (bytes32); - - function getContractName() public returns (string memory){ - return "Feline"; - } -} - - -contract Cat is Feline { - mapping (uint => uint) public m; - - constructor() Feline(m) { - } - function utterance() public override returns (bytes32) { return "miaow"; } - function getMapValue() public returns (uint) { return m[5]; } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/accountAssert.sol b/framework/src/test/resources/soliditycode/accountAssert.sol deleted file mode 100644 index ef10d5fedd8..00000000000 --- a/framework/src/test/resources/soliditycode/accountAssert.sol +++ /dev/null @@ -1,94 +0,0 @@ -//pragma solidity ^0.6.0; - -contract transferTokenTestA { - - // transfer trc10 to a new address or exist address in constructor - constructor(address payable toAddress, uint256 tokenValue, trcToken id) payable public{ - toAddress.transferToken(tokenValue, id); - require(toAddress.tokenBalance(id) > 0, "tokenBalance should not be 0"); - } - - fallback() payable external{} - - function transferTest(address payable toAddress, uint256 tokenValue) payable public { - toAddress.transfer(tokenValue); - } - - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - // suicide to a new address - function selfdestructTest(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - // transfer to a new contract - function createContractTest(uint256 tokenValue, trcToken id) payable public returns(address){ - Simple s = new Simple(); - require(address(s).tokenBalance(id)==0, "tokenBalance should be 0"); - payable(address(s)).transferToken(tokenValue, id); - require(address(s).tokenBalance(id)==tokenValue, "tokenBalance should not be 0"); - return address(s); - } - - // revert transfer to a new contract - function revertCreateContractTest(uint256 tokenValue, trcToken id) payable public { - Simple s = new Simple(); - payable(address(s)).transferToken(tokenValue, id); - revert(); - } -} - -contract transferTokenTestB { - - constructor() payable public{ - } - - fallback() payable external{} - - function transferTest(address payable toAddress, uint256 tokenValue) payable public { - toAddress.transfer(tokenValue); - } - - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - // suicide to a new address - function selfdestructTest(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - // transfer to a new contract - function createContractTest(uint256 tokenValue, trcToken id) payable public returns(address){ - Simple s = new Simple(); - require(address(s).tokenBalance(id)==0, "tokenBalance should be 0"); - payable(address(s)).transferToken(tokenValue, id); - require(address(s).tokenBalance(id)==tokenValue, "tokenBalance should not be 0"); - return address(s); - } - - // revert transfer to a new contract - function revertCreateContractTest(uint256 tokenValue, trcToken id) payable public { - Simple s = new Simple(); - payable(address(s)).transferToken(tokenValue, id); - revert(); - } -} - -contract transferTokenTestC { - Simple public s; - - // transfer to a new address in constructor - constructor(trcToken id) payable public{ - s = new Simple(); - require(address(s).tokenBalance(id)==0, "new contract tokenBalance should be 0"); - require(address(this).tokenBalance(id)==0, "this.tokenBalance should be 0"); - } -} - -contract Simple { - constructor() payable public{} - fallback() payable external{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol deleted file mode 100644 index fcd40cdb521..00000000000 --- a/framework/src/test/resources/soliditycode/addMsg001Nonpayable.sol +++ /dev/null @@ -1,20 +0,0 @@ - - -contract IllegalDecorate { - -event log(uint256); -constructor() payable public{} - -fallback() payable external{} - -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue)public { -// function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addMsg002View.sol b/framework/src/test/resources/soliditycode/addMsg002View.sol deleted file mode 100644 index 0c04b5c0b8a..00000000000 --- a/framework/src/test/resources/soliditycode/addMsg002View.sol +++ /dev/null @@ -1,20 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} - diff --git a/framework/src/test/resources/soliditycode/addMsg003Constant.sol b/framework/src/test/resources/soliditycode/addMsg003Constant.sol deleted file mode 100644 index 2065802bed1..00000000000 --- a/framework/src/test/resources/soliditycode/addMsg003Constant.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addMsg004Pure.sol b/framework/src/test/resources/soliditycode/addMsg004Pure.sol deleted file mode 100644 index 25f1a36d8b7..00000000000 --- a/framework/src/test/resources/soliditycode/addMsg004Pure.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol deleted file mode 100644 index 039b341b6ac..00000000000 --- a/framework/src/test/resources/soliditycode/addTransferToken001Nonpayable.sol +++ /dev/null @@ -1,13 +0,0 @@ - - - contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue)public { - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTransferToken001payable.sol b/framework/src/test/resources/soliditycode/addTransferToken001payable.sol deleted file mode 100644 index 17078e30189..00000000000 --- a/framework/src/test/resources/soliditycode/addTransferToken001payable.sol +++ /dev/null @@ -1,13 +0,0 @@ - - - contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue) public payable{ - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTransferToken002View.sol b/framework/src/test/resources/soliditycode/addTransferToken002View.sol deleted file mode 100644 index c50a16390f5..00000000000 --- a/framework/src/test/resources/soliditycode/addTransferToken002View.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithView(address payable toAddress,trcToken id, uint256 tokenValue) public view{ - - toAddress.transferToken(tokenValue, id); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol deleted file mode 100644 index 18721d9b94c..00000000000 --- a/framework/src/test/resources/soliditycode/addTransferToken003Constant.sol +++ /dev/null @@ -1,14 +0,0 @@ - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol deleted file mode 100644 index f7716ee3874..00000000000 --- a/framework/src/test/resources/soliditycode/addTransferToken004Pure.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol deleted file mode 100644 index fe7a7f4cef8..00000000000 --- a/framework/src/test/resources/soliditycode/addTrcToken001Assemble.sol +++ /dev/null @@ -1,62 +0,0 @@ - - -contract InAssemble { - -mapping(trcToken => uint256) tokenCnt; -mapping(uint256 => mapping(trcToken => trcToken)) cntTokenToken; -constructor () payable public {} -function getBalance (address addr) view public returns(uint256 r) { -assembly{ -r := balance(addr) -} -} - -function getTokenBalanceConstant (address addr, trcToken tokenId) view public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function getTokenBalance (address addr, trcToken tokenId) public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function transferTokenInAssembly(address addr, trcToken tokenId, uint256 tokenValue) public payable { -bytes4 sig = bytes4(keccak256("()")); // function signature - -assembly { -let x := mload(0x40) // get empty storage location -mstore(x,sig) // 4 bytes - place signature in empty storage - -let ret := calltoken(gas, addr, tokenValue, tokenId, -x, // input -0x04, // input size = 4 bytes -x, // output stored at input location, save space -0x0 // output size = 0 bytes -) - -// let ret := calltoken(gas, addr, tokenValue, -// x, // input -// 0x04, // input size = 4 bytes -// x, // output stored at input location, save space -// 0x0 // output size = 0 bytes -// ) // ERROR - - -mstore(0x40, add(x,0x20)) // update free memory pointer -} - -} - -function trcTokenInMap(trcToken tokenId, uint256 tokenValue) public returns(uint256 r) { -tokenCnt[tokenId] += tokenValue; -r = tokenCnt[tokenId]; -} - -function cntTokenTokenInMap(trcToken tokenId1, trcToken tokenId2, uint256 tokenValue) public returns(trcToken r) { -cntTokenToken[tokenValue][tokenId1] = tokenId2; -r = cntTokenToken[tokenValue][tokenId1]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol deleted file mode 100644 index 0cd407079ba..00000000000 --- a/framework/src/test/resources/soliditycode/addTrcToken002Cat.sol +++ /dev/null @@ -1,2051 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol deleted file mode 100644 index 24117bc5e6b..00000000000 --- a/framework/src/test/resources/soliditycode/addTrcToken002Cat_withFinny.sol +++ /dev/null @@ -1,2051 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 finney; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 finney; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode/addressCheckNew.sol b/framework/src/test/resources/soliditycode/addressCheckNew.sol deleted file mode 100644 index 3c10b8c680d..00000000000 --- a/framework/src/test/resources/soliditycode/addressCheckNew.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns(address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/addressCheckOld.sol b/framework/src/test/resources/soliditycode/addressCheckOld.sol deleted file mode 100644 index 6c6b15d1736..00000000000 --- a/framework/src/test/resources/soliditycode/addressCheckOld.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns (address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/altbn.sol b/framework/src/test/resources/soliditycode/altbn.sol deleted file mode 100644 index c3cfcdbe2b9..00000000000 --- a/framework/src/test/resources/soliditycode/altbn.sol +++ /dev/null @@ -1,61 +0,0 @@ -contract AltBn128 { - constructor() public payable {} - function callBn256Add(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas(), 0x06, 0, input, 0x80, result, 0x40) - } - - } - - function callBn256AddNoValue(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns - (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas(), 0xac, 0, input, 0x80, result, 0x40) - } - } - - function callBn256ScalarMul(bytes32 x, bytes32 y, bytes32 scalar) public returns (bytes32[2] memory result) { - bytes32[3] memory input; - input[0] = x; - input[1] = y; - input[2] = scalar; - assembly { - let success := call(gas(), 0x07, 0, input, 0x60, result, 0x40) - switch success - case 0 { - revert(0,0) - } - } - } - - function callBn256Pairing(bytes memory input) public returns (bytes32 result) { - // input is a serialized bytes stream of (a1, b1, a2, b2, ..., ak, bk) from (G_1 x G_2)^k - uint256 len = input.length; - require(len % 192 == 0); - assembly { - let memPtr := mload(0x40) - let success := call(gas(), 0x08, 0, add(input, 0x20), len, memPtr, 0x20) - switch success - case 0 { - revert(0,0) - } default { - result := mload(memPtr) - } - } - } - - function convert(uint256 num) public view returns(bytes32) { - return bytes32(num); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/arrayLength001.sol b/framework/src/test/resources/soliditycode/arrayLength001.sol deleted file mode 100644 index 81a779f059d..00000000000 --- a/framework/src/test/resources/soliditycode/arrayLength001.sol +++ /dev/null @@ -1,64 +0,0 @@ - - -contract arrayLength { - bytes1[] a; - uint256[] IntergerArray; - bytes bs; - - // arrary length - function arrayPushValue() public returns (bytes1[] memory){ - a = new bytes1[](1); - a.push(0x01); - return a; - } - - function arrayPush() public returns(bytes1[] memory){ - a = new bytes1[](1); - a.push(); - return a; - } - - function arrayPop() public returns(bytes1[] memory){ - a = new bytes1[](1); - a.pop(); - return a; - } - - // arrary push/pop return Value - function arrayPushValueReturn() public { - a = new bytes1[](1); - return a.push(0x01); - } - - function arrayPushReturn() public returns (bytes1){ - a = new bytes1[](1); - return a.push(); - } - - function arrayPopReturn() public{ - a = new bytes1[](1); - return a.pop(); - } - - function uint256ArrayPushValue() public returns (bytes1[] memory){ - IntergerArray = [1,2,3]; - IntergerArray.push(); - return a; - } - - - // bytes - function bytesPushValue() public { - - return bs.push(0x01); - } - - function bytesPush() public returns (bytes1){ - return bs.push(); - } - - function bytesPop() public { - return bs.pop(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assemblyTest.sol b/framework/src/test/resources/soliditycode/assemblyTest.sol deleted file mode 100644 index 519a5a85fa3..00000000000 --- a/framework/src/test/resources/soliditycode/assemblyTest.sol +++ /dev/null @@ -1,61 +0,0 @@ - -contract assemblyTest { - - uint constant x = 1; - uint constant y = x; - function getZuint() public view returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - function getZuint2() public returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - bool constant bool1 = true; - bool constant bool2 = bool1; - function getZbool() public view returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - function getZbool2() public returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - -// string constant string1 = "abc"; -// string constant string2 = string1; -// function getZstring() public view returns (string memory) { -// string memory z; -// assembly { -// z := string2 -// } -// return z; -// } - - -// address origin1 = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; -// address origin2 = origin1; -// function getZaddress() public view returns (address) { -// address z; -// assembly { -// z := origin2 -// } -// return z; -// } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest1DivideInt.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol deleted file mode 100644 index 75436287805..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest2FindArgsContractMinTest.sol +++ /dev/null @@ -1,10 +0,0 @@ - -contract findArgsIContract{ -function findArgsByIndex1(uint i) public returns (uint z) { -uint[] memory a = new uint[](3); -a[0]=1; -a[1]=2; -a[2]=3; -return a[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol deleted file mode 100644 index c8a2e5e363b..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest3ByteMinContract.sol +++ /dev/null @@ -1,11 +0,0 @@ - -contract byteContract{ -bytes b; -function testBytesGet(uint i) public returns (bytes1){ -b = new bytes(3); -b[0]=0x0b; -b[1]=0x0c; -b[2]=0x0d; -return b[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol deleted file mode 100644 index 6bd2ade2eea..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest4Enum.sol +++ /dev/null @@ -1,13 +0,0 @@ - - -contract enumContract { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices _choice; - function setGoStraight(ActionChoices choice) public { - _choice = choice; - } - - function getChoice() public returns (ActionChoices) { - return _choice; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol deleted file mode 100644 index ad8f6f0f173..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest5MoveRight.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract binaryRightContract{ - function binaryMoveR(uint i)public returns (uint z) { - return z = 5 >> i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol deleted file mode 100644 index c82e0f5806c..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest6UninitializedContract.sol +++ /dev/null @@ -1,27 +0,0 @@ - -contract uni { -function b(int x, int y) internal returns (int) -{ - return x * y; -} - -function test1() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - funcPtr = b; - - // This call to funcPtr will succeed - return funcPtr(4, 5); -} - -function test2() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - // This call will fail because funcPtr is still a zero-initialized function pointer - return funcPtr(4, 5); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol deleted file mode 100644 index 05b592e0682..00000000000 --- a/framework/src/test/resources/soliditycode/assertExceptiontest7TestAssertContract.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract TestThrowsContract{ - function testAssert() public{ - assert(1==2); - } - function testRequire() public{ - require(2==1); - } - function testRevert() public{ - revert(); - } - function testThrow() public{ - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign.sol b/framework/src/test/resources/soliditycode/batchvalidatesign.sol deleted file mode 100644 index 9e1c1b289b5..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - //function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - //} -} diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign001.sol b/framework/src/test/resources/soliditycode/batchvalidatesign001.sol deleted file mode 100644 index 57e051ce415..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign001.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testPure(bytes32 hash, bytes[] memory signatures, address[] memory addresses) pure public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign002.sol b/framework/src/test/resources/soliditycode/batchvalidatesign002.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign002.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign003.sol b/framework/src/test/resources/soliditycode/batchvalidatesign003.sol deleted file mode 100644 index c43536af499..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign003.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { -bytes32 public result; -constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); -} -function testConstructor() public returns(bytes32){ - return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign005.sol b/framework/src/test/resources/soliditycode/batchvalidatesign005.sol deleted file mode 100644 index 3a6ca362973..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign005.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign007.sol b/framework/src/test/resources/soliditycode/batchvalidatesign007.sol deleted file mode 100644 index 974ffb34efe..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign007.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { - bytes32 public result; - - constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); - } - - function testConstructor() public returns(bytes32){ - return result; - } - - function testConstructorPure() public view returns(bytes32){ - return result; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/batchvalidatesign02.sol b/framework/src/test/resources/soliditycode/batchvalidatesign02.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode/batchvalidatesign02.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/callValueGasPure.sol b/framework/src/test/resources/soliditycode/callValueGasPure.sol deleted file mode 100644 index 6aab49bab84..00000000000 --- a/framework/src/test/resources/soliditycode/callValueGasPure.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract C { -function check(address a) external pure returns (bool success) { - a.call{value:42,gas:42}; - a.call{gas:42}; - //a.call.value(1).gas(42)("fwefewf"); -} -} diff --git a/framework/src/test/resources/soliditycode/calldata.sol b/framework/src/test/resources/soliditycode/calldata.sol deleted file mode 100644 index 6e877ac1b2f..00000000000 --- a/framework/src/test/resources/soliditycode/calldata.sol +++ /dev/null @@ -1,33 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract C { - struct S { uint256 a; } - - function f(S calldata s) external returns (bytes memory) { - return abi.encode(s); - } - - function g(S calldata s) external returns (bytes memory) { - return this.f(s); - } - - function m(uint256[] calldata) external pure returns (bytes memory) { - return msg.data; - } - function h(uint8[] calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function i(uint8[][2] calldata s, uint256 which) external view returns (bytes memory) { - return this.h(s[which]); - } - function j(bytes calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function k(bytes[2] calldata s, uint256 which) external view returns (bytes memory) { - return this.j(s[which]); - } - function l(function() external returns (uint)[] calldata s) external returns (uint, uint, uint) { - assert(s.length == 3); - return (s[0](), s[1](), s[2]()); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/callvalue.sol b/framework/src/test/resources/soliditycode/callvalue.sol deleted file mode 100644 index f01dcf2b52f..00000000000 --- a/framework/src/test/resources/soliditycode/callvalue.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract Callvalue { -function check() public payable returns(uint) { - uint256 wad; - assembly { - wad := callvalue() - } - return wad; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/chainid001.sol b/framework/src/test/resources/soliditycode/chainid001.sol deleted file mode 100644 index 9cf24077dfb..00000000000 --- a/framework/src/test/resources/soliditycode/chainid001.sol +++ /dev/null @@ -1,19 +0,0 @@ - -contract IstanbulTest { - constructor() public payable {} - function getId() public view returns(uint256){ - uint256 id; - assembly { - id := chainid() - } - return id; - } - - function getBalance(address src) public view returns(uint256){ - return address(src).balance; - } - - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/codeSaftySupport.sol b/framework/src/test/resources/soliditycode/codeSaftySupport.sol deleted file mode 100644 index 1cee8e4646c..00000000000 --- a/framework/src/test/resources/soliditycode/codeSaftySupport.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferToken(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol deleted file mode 100644 index fa65a134001..00000000000 --- a/framework/src/test/resources/soliditycode/codeSaftyUnsupport.sol +++ /dev/null @@ -1,56 +0,0 @@ - - -contract SubC { - -event log(string); - -fallback() payable external{} - -function receiveToken() payable public{} - -function getBalance() view public returns (uint256 r) { -r = address(this).balance; -} -} - -contract UseDot { -constructor() payable public{} -fallback() payable external{} -mapping(address => mapping(trcToken => uint256)) sender_tokens; - -function trigger1(address payable addr, trcToken tokenInputId) payable public { - //address(SubC(addr)).call.value(1000).tokenId(tokenInputId)(abi.encodeWithSignature("receiveToken()")); // ERROR -} - -function trigger2(address payable addr) payable public { -// addr.transferToken.value(10)(10, 0x6e6d62); // ERROR -} - -function trigger3(address payable addr) payable public { - // address(SubC(addr)).receiveToken.tokenvalue(10)(); // ERROR -} - -function trigger4(address payable addr) payable public { - //SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR -} - -function trigger5(address payable addr) payable public { - SubC(addr).receiveToken{value:10}(); -} - -function trigger6(address payable addr, trcToken tokenId) payable public { -address(SubC(addr)).call{value:1000}(abi.encodeWithSignature("transferToken(uint256, trcToken)", 10, tokenId)); -} - -function trigger7(address addr) payable public { - //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger -} - -function trigger8(address addr) public payable returns(bytes memory r){ -// r = msg.data; // compile success, no necessary to trigger -} - -function getBalance() public returns (uint256 r){ -r = address(this).balance; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/constantCallStorage001.sol b/framework/src/test/resources/soliditycode/constantCallStorage001.sol deleted file mode 100644 index 1f584923a55..00000000000 --- a/framework/src/test/resources/soliditycode/constantCallStorage001.sol +++ /dev/null @@ -1,159 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} -contract viewCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = bytes32(uint256(0xdCad3a6d3569DF655070DEd0)); - bytes bs = new bytes(3); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.GoRight; - int64[] b = [-1, 2, -3]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - constructor() payable public{ - mapa[address(0x00)] = 34; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - function changeBool(bool param) public returns (bool){ - stopped = param; - emit log(stopped); - return stopped; - } - function getBool() public returns (bool){ - emit log(stopped); - return stopped; - } - function changeInt(int param) public returns (int){ - i = param; - emit log(i); - return i; - } - function getInt() public returns (int){ - emit log(i); - return i; - } - function changeNegativeInt(int param) public returns (int){ - i2 = param; - emit log(i2); - return i2; - } - function getNegativeInt() public returns (int){ - emit log(i2); - return i2; - } - function changeUint(uint param) public returns (uint){ - ui = param; - emit log(ui); - return ui; - } - function getUint() public returns (uint){ - emit log(ui); - return ui; - } - function changeAddress(address param) public returns (address){ - origin = param; - emit log(origin); - return origin; - } - function getAddress() public returns (address){ - emit log(origin); - return origin; - } - function changeBytes32(bytes32 param) public returns (bytes32){ - b32 = param; - emit log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - emit log(b32); - return b32; - } - function changeBytes(bytes memory param) public returns (bytes memory){ - bs = param; - emit log(bs); - return bs; - } - function getBytes() public returns (bytes memory){ - emit log(bs); - return bs; - } - function changeString(string memory param) public returns (string memory){ - s = param; - emit log(s); - return s; - } - function getString() public returns (string memory){ - emit log(s); - return s; - } - function changeActionChoices(ActionChoices param) public returns (ActionChoices){ - choice = param; - emit log(choice); - return choice; - } - function getActionChoices() public returns (ActionChoices){ - emit log(choice); - return choice; - } - function changeInt64NegativeArray(int64[] memory param) public returns (int64[] memory){ - b = param; - emit log(b); - return b; - } - function getInt64NegativeArray() public returns (int64[] memory){ - emit log(b); - return b; - } - function changeInt32Array(int32[2][] memory param) public returns (int32[2][] memory){ - tmp_h = param; - emit log(tmp_h); - return tmp_h; - } - function getInt32Array() public returns (int32[2][] memory){ - emit log(tmp_h); - return tmp_h; - } - function changeInt256Array(int256[2][2] memory param) public returns (int256[2][2] memory){ - tmp_i = param; - emit log(tmp_i); - return tmp_i; - } - function getInt256Array() public returns (int256[2][2] memory){ - emit log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/constantCallStorage002.sol b/framework/src/test/resources/soliditycode/constantCallStorage002.sol deleted file mode 100644 index 1ceba5e87d2..00000000000 --- a/framework/src/test/resources/soliditycode/constantCallStorage002.sol +++ /dev/null @@ -1,16 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public view returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public view returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/constantCallStorage0425.sol b/framework/src/test/resources/soliditycode/constantCallStorage0425.sol deleted file mode 100644 index 8ecf771626d..00000000000 --- a/framework/src/test/resources/soliditycode/constantCallStorage0425.sol +++ /dev/null @@ -1,156 +0,0 @@ -contract constantCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - bytes bs = new bytes(9); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.SitStill; - int64[] b = [91, 2, 333]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - - constructor() payable public{ - mapa[address(0x00)] = 88; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - - function changeBool(bool param) public constant returns (bool){ - stopped = param; - log(stopped); - return stopped; - } - function getBool() public constant returns (bool){ - log(stopped); - return stopped; - } - - function changeInt(int param) public returns (int){ - i = param; - log(i); - return i; - } - function getInt() public returns (int){ - log(i); - return i; - } - - function changeNegativeInt(int param) public constant returns (int){ - i2 = param; - log(i2); - return i2; - } - function getNegativeInt() public constant returns (int){ - log(i2); - return i2; - } - - function changeUint(uint param) public returns (uint){ - ui = param; - log(ui); - return ui; - } - function getUint() public returns (uint){ - log(ui); - return ui; - } - - function changeAddress(address param) public constant returns (address){ - origin = param; - log(origin); - return origin; - } - function getAddress() public constant returns (address){ - log(origin); - return origin; - } - - function changeBytes32(bytes32 param) public constant returns (bytes32){ - b32 = param; - log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - log(b32); - return b32; - } - - function changeBytes(bytes param) public constant returns (bytes){ - bs = param; - log(bs); - return bs; - } - function getBytes() public constant returns (bytes){ - log(bs); - return bs; - } - - function changeString(string param) public constant returns (string){ - s = param; - log(s); - return s; - } - function getString() public returns (string){ - log(s); - return s; - } - - function changeActionChoices(ActionChoices param) public constant returns (ActionChoices){ - choice = param; - log(choice); - return choice; - } - function getActionChoices() public constant returns (ActionChoices){ - log(choice); - return choice; - } - - function changeInt64NegativeArray(int64[] param) public constant returns (int64[]){ - b = param; - log(b); - return b; - } - function getInt64NegativeArray() public constant returns (int64[]){ - log(b); - return b; - } - - function changeInt32Array(int32[2][] param) public returns (int32[2][]){ - tmp_h = param; - log(tmp_h); - return tmp_h; - } - function getInt32Array() public constant returns (int32[2][]){ - log(tmp_h); - return tmp_h; - } - - function changeInt256Array(int256[2][2] param) public returns (int256[2][2]){ - tmp_i = param; - log(tmp_i); - return tmp_i; - } - function getInt256Array() public constant returns (int256[2][2]){ - log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} diff --git a/framework/src/test/resources/soliditycode/constantContract001.sol b/framework/src/test/resources/soliditycode/constantContract001.sol deleted file mode 100644 index 7d574c5a008..00000000000 --- a/framework/src/test/resources/soliditycode/constantContract001.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testPure(uint256 x,uint256 y) public pure returns (uint256 z) { -uint256 i=1; -return i + x + y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGetterContract.sol b/framework/src/test/resources/soliditycode/contractGetterContract.sol deleted file mode 100644 index 365b53ebf1a..00000000000 --- a/framework/src/test/resources/soliditycode/contractGetterContract.sol +++ /dev/null @@ -1,17 +0,0 @@ - - - -contract getterContract { - -constructor() public payable{} -fallback() external payable{} - -uint public c = msg.value; - -function getDataUsingAccessor() public payable returns (uint){ - -return c; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol deleted file mode 100644 index 659e56c9150..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar001test1Grammar001.sol +++ /dev/null @@ -1,18 +0,0 @@ - -contract FunctionSelector { - function select(bool useB, uint x) public returns (uint z) { - //var f = a; - //if (useB) f = b; - //return f(x); - if (useB) - return b(x); - else - return a(x); - } -function a(uint x) public returns (uint z) { - return x * x; - } -function b(uint x) public returns (uint z) { - return 2 * x; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol deleted file mode 100644 index 744b17e9585..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar001test2Grammar002.sol +++ /dev/null @@ -1,44 +0,0 @@ - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert(Data storage self, uint value) public returns (bool) { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public returns (bool) { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public returns (bool) { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register (uint value) public{ - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol deleted file mode 100644 index 140ba2a8f56..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar001test3Grammar003.sol +++ /dev/null @@ -1,44 +0,0 @@ - - -library Set { - struct Data { mapping(uint => bool) flags; } - - function insert(Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - using Set for Set.Data; // this is the crucial change - Set.Data knownValues; - - function register(uint value) public{ - // Here, all variables of type Set.Data have - // corresponding member functions. - // The following function call is identical to - // Set.insert(knownValues, value) - if (!knownValues.insert(value)) - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol deleted file mode 100644 index bd7ffbc8360..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar001test4Grammar004.sol +++ /dev/null @@ -1,31 +0,0 @@ - - -library Search { - function indexOf(uint[] storage self, uint value) public returns (uint) { - for (uint i = 0; i < self.length; i++) - if (self[i] == value) return i; - return uint(int256(-1)); - } -} - - -contract C { - using Search for uint[]; - uint[] public data; - - function append(uint value) public{ - data.push(value); - } - - function replace(uint _old, uint _new) public{ - // This performs the library function call - uint index = data.indexOf(_old); - if (index == uint(int256(-1))) - data.push(_new); - else - data[index] = _new; - } - function getData(uint256 index) public returns(uint256){ - return data[index]; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol deleted file mode 100644 index 275d42d1e71..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar001test5Grammar006.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract InfoFeed { -function d1(uint x1) public{ - - assembly{ - function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } } - } - } - function d2(uint x1) public{ - assembly { - let x:=1 - x := mul(1, add(2, 3))} - } - function f(uint x) public{ - assembly { x := sub(x, 1) } - - } - // 0.6.0 Variable declarations cannot shadow declarations outside the assembly block. - function d(uint x1) public returns(uint256){ - uint256 x; - assembly{ - x := add(2, 3) - let y := mload(0x40) - x := add(x, y) - } - return x; - } - function d4(uint x) public{ - // Error: The labels 'repeat' is disallowed. Please use "if", "switch", "for" or function calls instead - //assembly{let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0)) - x = x; - //} - } - function d5(uint x1) public{ - assembly{ - function f(x) -> y { switch x case 0 { y := mul(x, 2) } default { y := 0 } } - - } - } - - function d6(uint x1) public{ - assembly{ - function f(x) -> y { for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) } } - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol deleted file mode 100644 index 020c2a38ca4..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_1.sol +++ /dev/null @@ -1,60 +0,0 @@ -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -// -abstract contract DogInterface { - function getDougAge(uint _age) public virtual returns (uint); - function contracts(bytes32 name) public virtual returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol deleted file mode 100644 index 8945b566543..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test1Grammar007_2.sol +++ /dev/null @@ -1,60 +0,0 @@ - -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -abstract contract DogInterface { - function getDougAge(uint _age) public virtual returns (uint); - function contracts(bytes32 name) public virtual returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol deleted file mode 100644 index 956623c3103..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test2Grammar008.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -// version 0.6.0 change -// add abstract and override -abstract contract Feline { - - function utterance() public virtual returns (bytes32); - - function getContractName() public returns (string memory){ - return "Feline"; - } -} - - -contract Cat is Feline { - function utterance() public override returns (bytes32) { return "miaow"; } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol deleted file mode 100644 index 617f96cb4e5..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test3Grammar010.sol +++ /dev/null @@ -1,10 +0,0 @@ - -contract InfoFeed { -function info() public payable returns (uint ret) { return 42; } -} -contract Consumer { -constructor() payable public{} -InfoFeed feed; -function setFeed(address addr) public { feed = InfoFeed(addr); } -function callFeed() public payable { feed.info{value:10,gas:800}(); } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol deleted file mode 100644 index fcd18f438ef..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar011.sol +++ /dev/null @@ -1,11 +0,0 @@ - -contract C { -function f(uint key, uint value) public returns(uint) { -return key; -// do something -} -function g() public { -// named arguments -f({value: 2, key: 3}); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol deleted file mode 100644 index cb81d8810cd..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test4Grammar012.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract rTest { -function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { -//function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { -//var a = block.coinbase ; -//var b = block.difficulty; -//var c = block.gaslimit; -//var d = block.number; -//var e = block.blockhash(0); -//var e = d; -//var f = block.timestamp; -//bytes memory g = msg.data; -uint256 h = gasleft(); -address payable i = payable(msg.sender); -bytes4 j = msg.sig; -uint256 k = msg.value; -uint256 l = block.timestamp; -uint256 m = tx.gasprice; -address payable n = payable(tx.origin); -uint256 o = address(this).balance; -return (h,i,j,k,l,m,n,o); -//return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol deleted file mode 100644 index be863303a3d..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar002test6Grammar013.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract Counter { -uint count = 0; -address payable owner; -//function Counter() public{ -constructor() public{ -owner = payable(msg.sender); -} -function increment() public { -uint step = 10; -if (owner == msg.sender) { -count = count + step; -} -} -function getCount() public returns (uint){ -return count; -} -function kill() public{ -if (owner == msg.sender) { -selfdestruct(owner); -//selfdestruct(address(owner)); -} -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol deleted file mode 100644 index b2d70b3741c..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test1Grammar014.sol +++ /dev/null @@ -1,67 +0,0 @@ -contract A { -uint256 public numberForB; -address public senderForB; -function callTest(address bAddress, uint256 _number) public{ - -//bAddress.call(bytes4(sha3("setValue(uint256)")), _number); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("setValue(uint256)",_number)); // B's storage is set, A is not modified -} -function callcodeTest(address bAddress, uint256 _number) public{ -//bAddress.callcode(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} -function delegatecallTest(address bAddress, uint256 _number) public{ -//bAddress.delegatecall(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} - -function callAddTest(address bAddress) public{ -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract B { -uint256 public numberForB; -address public senderForB; -address public addr11; -mapping(uint256=>address) public addr1; -mapping(uint256=>address) public addr2; -event ssss(uint256); -function setValue(uint256 _number) public{ - -emit ssss(_number); -numberForB = _number; -senderForB = msg.sender; -// senderForB is A if invoked by A's callTest. B's storage will be updated -// senderForB is A if invoked by A's callcodeTest. None of B's storage is updated -// senderForB is OWNER if invoked by A's delegatecallTest. None of B's storage is updated -} - -function add() public{ -numberForB=numberForB+1; -C c1 = new C(); -addr1[numberForB]=c1.getAddress(); -addr11 = c1.getAddress(); -C c2 = new C(); -addr2[numberForB] = c2.getAddress(); -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract C { -function getAddress() public view returns(address){ -return address(this); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol deleted file mode 100644 index 0aa93e5e94f..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test2Grammar015.sol +++ /dev/null @@ -1,40 +0,0 @@ - - -contract ExecuteFallback{ - - //回退事件,会把调用的数据打印出来 - event FallbackCalled(bytes data); - //fallback函数,注意是没有名字的,没有参数,没有返回值的 - // 0.6.0 Split unnamed fallback functions into two cases defined using fallback() and receive() - fallback() external{ - emit FallbackCalled(msg.data); - } - - //调用已存在函数的事件,会把调用的原始数据,请求参数打印出来 - event ExistFuncCalled(bytes data, uint256 para); - //一个存在的函数 - function existFunc(uint256 para) public{ - emit ExistFuncCalled(msg.data, para); - } - - // 模拟从外部对一个存在的函数发起一个调用,将直接调用函数 - function callExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("existFunc(uint256)")); - //this.call(funcIdentifier, uint256(1)); - address(this).call(abi.encode(funcIdentifier, uint256(1))); - } - - //模拟从外部对一个不存在的函数发起一个调用,由于匹配不到函数,将调用回退函数 - function callNonExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("functionNotExist()")); - //this.call(funcIdentifier); - address(this).call(abi.encode(funcIdentifier)); - } - - function ExistFuncCalledTopic() view public returns(bytes32){ - return keccak256("ExistFuncCalled(bytes,uint256)"); - } - function FallbackCalledTopic() view public returns(bytes32){ - return keccak256("FallbackCalled(bytes)"); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol deleted file mode 100644 index 6a73d7a8d7e..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test3Grammar016.sol +++ /dev/null @@ -1,23 +0,0 @@ - -contract C { -uint private data; -function f(uint a) private returns(uint b) { return a + 1; } -function setData(uint a) public { data = a; } -function getData() public returns(uint) { return data; } -function compute(uint a, uint b) internal returns (uint) { return a+b; } -} -contract D { -function readData() public{ -C c = new C(); -//uint local = c.f(7); // error: member "f" is not visible -c.setData(3); -uint local = c.getData(); -// local = c.compute(3, 5); // error: member "compute" is not visible -} -} -contract E is C { -function g() public { -C c = new C(); -uint val = compute(3, 5); // access to internal member (from derived to parent contract) -} -} diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol deleted file mode 100644 index 38746d90734..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test4Grammar017.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract CrowdFunding{ - struct Funder{ - address addr; - uint amount; - } - - struct Campaign{ - address payable beneficiary; - uint goal; - uint amount; - uint funderNum; - mapping(uint => Funder) funders; - } - - uint compaingnID; - mapping (uint => Campaign) campaigns; - - function candidate(address payable beneficiary, uint goal) public payable returns (uint compaingnID){ - // initialize - Campaign storage c = campaigns[compaingnID++]; - c.beneficiary = beneficiary; - c.goal = goal; - } - - function vote(uint compaingnID) payable public { - Campaign storage c = campaigns[compaingnID]; - - //another way to initialize - c.funders[c.funderNum++] = Funder({addr: msg.sender, amount: msg.value}); - c.amount += msg.value; - } - - function check(uint comapingnId) public payable returns (bool){ - Campaign storage c = campaigns[comapingnId]; - - if(c.amount < c.goal){ - return false; - } - - uint amount = c.amount; - // incase send much more - c.amount = 0; - // address payable addr = address(uint160(c.beneficiary)); - //if(! addr.send(amount)){ - - if (! c.beneficiary.send(amount)){ - revert(); - } - return true; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol deleted file mode 100644 index ec241f3eae9..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test5Grammar018.sol +++ /dev/null @@ -1,37 +0,0 @@ - - - -contract Grammar18{ - function testAddmod() public returns (uint z) { - //计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕 - z=addmod(2, 2, 3); - return z; - } - function testMulmod() public returns (uint z) { -//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。 - z=mulmod(2, 3, 4); - return z; - } - - function testKeccak256() public returns(bytes32){ - //计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 - return keccak256("11"); - } - - function testSha256() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - return sha256("11"); - } - function testSha3() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - //return sha3("11"); - return keccak256("11"); - } - - function testRipemd160() public returns(bytes32){ - //计算(紧密包装)参数的RIPEMD-160哈希值 - return ripemd160("11"); - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol deleted file mode 100644 index 727ef7091e7..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test6Grammar019.sol +++ /dev/null @@ -1,12 +0,0 @@ - -contract timetest { - -constructor() public { -require( 1 == 1 seconds); -require(1 minutes == 60 seconds); -require(1 hours == 60 minutes); -require(1 days == 24 hours); -require(1 weeks == 7 days); -//require(1 years == 365 days); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol deleted file mode 100644 index 39a7fddcb7e..00000000000 --- a/framework/src/test/resources/soliditycode/contractGrammar003test7Grammar020.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract trxtest { - -function test() public { -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInnerContract.sol b/framework/src/test/resources/soliditycode/contractInnerContract.sol deleted file mode 100644 index 5e6addef105..00000000000 --- a/framework/src/test/resources/soliditycode/contractInnerContract.sol +++ /dev/null @@ -1,32 +0,0 @@ - - - - -contract InnerContract { - - constructor() public payable{} - fallback() external payable{} - - function messageI() payable public returns (uint ret) { - - - - } - -} - - - -contract OuterContract { - - - constructor() public payable{} - fallback() external payable{} - - function callInner(address payable addr) payable public returns (uint) { - - return InnerContract(addr).messageI{value:1}(); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol deleted file mode 100644 index 52dcfb16fc3..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction001.sol +++ /dev/null @@ -1,41 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address payable cAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - B b2 = new B();//1.2 - payable(address(b2)).transfer(5);//1.3 - b2.callCGetZero(cAddr, 1);//1.4 - b2.callCGetZero(cAddr,2);//1.6 - } - function test2(address payable cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - cAddress.call{value:amount + 1}(abi.encodeWithSignature("newBAndTransfer()"));//2.6 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(address payable cAddress,uint256 amount) public{ - cAddress.call{value:amount}(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - B b1 = (new B){value:7}();//2.2,2.7 - b1.getOne();//2.3,2.8 - B b2 = (new B){value:3}();//2.4,2.9 - b2.getOne();//2.5,2.10 - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol deleted file mode 100644 index 502e42d0c7b..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction002.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - - function test2(address cAddress,uint256 amount) public payable{ - //cAddress.call.value(amount)();//2.1 - cAddress.call{value:amount}("");//2.1 - } -} - - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol deleted file mode 100644 index 9d3e38affbd..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction003.sol +++ /dev/null @@ -1,30 +0,0 @@ - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - B b = (new B){value:10}();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol deleted file mode 100644 index e8f32d7bfd9..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction004.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract A{ - constructor () payable public{} - function test(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - fallback() payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} -contract B{ - fallback() external payable{} - function kill(address contractAddres, address toAddress) payable public { - contractAddres.call(abi.encodeWithSignature("test(address)",address(this))); - } - function kill2() public{ - A a = new A(); - a.test(payable(address(this))); - } - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol deleted file mode 100644 index f6bdf294a99..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction005.sol +++ /dev/null @@ -1,53 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1() public payable{ - B b1 = (new B){value:10}();//1.1 - b1.callCGetZero(false); - b1.callCGetZero(true);//1.4 - } - function test2() public payable{ - C c1 = (new C){value:10}();//1.1 - c1.newBAndTransfer(false); - c1.newBAndTransfer(true);//1.4 - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol deleted file mode 100644 index ec574998b29..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction001testInternalTransaction006.sol +++ /dev/null @@ -1,54 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1() public payable{ - B b1 = (new B){value:10}();//1.1 - b1.callCGetZero(true);//1.4 - b1.callCGetZero(false); - } - function test2() public payable{ - C c1 = (new C){value:10}();//1.1 - c1.newBAndTransfer(true);//1.4 - c1.newBAndTransfer(false); - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol deleted file mode 100644 index d14c3d8aa16..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test1InternalTransaction007.sol +++ /dev/null @@ -1,38 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address cAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - B b2 = new B();//1.2 - payable(address(b2)).transfer(5);//1.3 - b2.callCGetZero();//1.4 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero() public{ - assert(1==2); - - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol deleted file mode 100644 index 2e57a0e635c..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test2InternalTransaction008.sol +++ /dev/null @@ -1,60 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - - function testAssert(address bAddress,uint256 amount) public payable{ - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",true)); - } - function testRequire(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - } - function testAssert1(address bAddress,uint256 amount) public payable{ - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",true)); - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - } - function testtRequire2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable public{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol deleted file mode 100644 index d750df65ea4..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test3InternalTransaction009.sol +++ /dev/null @@ -1,47 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address cAddr,address dcontract,address baddress) public payable{ - B b1 = (new B){value:10}();//1.1 - payable(address(b1)).transfer(5);//1.3 - b1.callCGetZero(cAddr, 1);//1.4 - b1.getOne(dcontract,baddress); - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne(address contractAddres, address toAddress) payable public{ - contractAddres.call(abi.encodeWithSignature("suicide1(address)",address(this))); - - } - function callCGetZero(address cAddress,uint256 amount) public{ - cAddress.call{value:amount}(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public{ - B b1 = (new B){value:7}();//2.2,2.7 - B b2 = (new B){value:3}();//2.4,2.9 - } -} - -contract D{ - constructor () payable public{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - fallback() payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol deleted file mode 100644 index ff5817ea173..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010.sol +++ /dev/null @@ -1,186 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - } - function transfer2() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - } - function getBalance() public returns(uint256) { - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol deleted file mode 100644 index d0c80d14ffb..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test4InternalTransaction010_1.sol +++ /dev/null @@ -1,210 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - fallback() payable{} - } - - \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol deleted file mode 100644 index 59ffe9f0fe9..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction002test5InternalTransaction012.sol +++ /dev/null @@ -1,51 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address bAddr,address eAddr) public payable{ - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - } - -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable{ - D d1=(new D){value:1000}(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call{value:1}(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol deleted file mode 100644 index 1dae0beb03c..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction013.sol +++ /dev/null @@ -1,56 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address dAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - b1.testNN(dAddr,2);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount) public payable{ - // D d1=(new D)(); - dAddress.call{value:amount}(abi.encodeWithSignature("getOne()"));//2.1 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - E e = (new E){value:5}(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol deleted file mode 100644 index 0346cec669b..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction014.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract callerContract { - constructor() payable public{} - fallback() payable external{} - function sendToB(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - - contract calledContract { - fallback() payable external {} - constructor() payable public{} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call{value:5}(abi.encodeWithSignature("setI()")); - } - - } - - contract c{ - uint256 public i=0; - constructor() public payable{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } - function setI() payable public{ - i=5; - } - fallback() payable external{} - } diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol deleted file mode 100644 index edeb9488454..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction015.sol +++ /dev/null @@ -1,60 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address dAddr,address eAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - b1.testNN(dAddr,2,eAddr);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount,address eAddress) public payable{ - // D d1=(new D)(); - dAddress.call{value:amount}(abi.encodeWithSignature("getOne(address)",address(this)));//2.1 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } - function suicide(address payable toAddress) public payable{ - selfdestruct(toAddress); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address payable eAddress) payable public{ - E e = (new E){value:5}(); - e.suicide(eAddress); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol deleted file mode 100644 index 9b01c9e0d31..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction016.sol +++ /dev/null @@ -1,174 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - fallback() payable external{} - function transfer() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - B b1=(new B){value:1}();//1 - address payable aaa=payable(address(this)); - b1.suicide1(aaa); - } - function transfer2() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - B b1=(new B){value:1}();//1 - address payable aaa=payable(address(this)); - b1.suicide1(aaa); - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - } - diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol deleted file mode 100644 index 32cf9f2a04d..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction017.sol +++ /dev/null @@ -1,199 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer(address payable Address) payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - B b=(new B){value:1}();//1 - selfdestruct(Address); - } - function transfer2() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol deleted file mode 100644 index fadb5f84b51..00000000000 --- a/framework/src/test/resources/soliditycode/contractInternalTransaction003testInternalTransaction018.sol +++ /dev/null @@ -1,97 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address payable bAddr,address eAddr) public payable{ - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - - } - -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable { - D d1=(new D){value:100}(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call{value:1}(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractLinkage001.sol b/framework/src/test/resources/soliditycode/contractLinkage001.sol deleted file mode 100644 index 8d441fba2da..00000000000 --- a/framework/src/test/resources/soliditycode/contractLinkage001.sol +++ /dev/null @@ -1,9 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -constructor() payable public{} -fallback() payable external{} -function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractLinkage002.sol b/framework/src/test/resources/soliditycode/contractLinkage002.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode/contractLinkage002.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractLinkage003.sol b/framework/src/test/resources/soliditycode/contractLinkage003.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode/contractLinkage003.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractLinkage004.sol b/framework/src/test/resources/soliditycode/contractLinkage004.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode/contractLinkage004.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractLinkage005.sol b/framework/src/test/resources/soliditycode/contractLinkage005.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode/contractLinkage005.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractLinkage006.sol b/framework/src/test/resources/soliditycode/contractLinkage006.sol deleted file mode 100644 index 53449f61ce2..00000000000 --- a/framework/src/test/resources/soliditycode/contractLinkage006.sol +++ /dev/null @@ -1,18 +0,0 @@ - -contract AA{ - uint256 public count=0; - constructor () payable public{} - function init(address payable addr, uint256 max) payable public { - count =0; - this.hack(addr,max); - } - function hack(address payable addr, uint256 max) payable public { - while (count < max) { - count = count +1; - this.hack(addr,max); - } - if (count == max) { - addr.send(20); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol deleted file mode 100644 index 6feb7fff3b8..00000000000 --- a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit001.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol deleted file mode 100644 index 6feb7fff3b8..00000000000 --- a/framework/src/test/resources/soliditycode/contractOriginEnergyLimit004.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol deleted file mode 100644 index c0bb2d7d88e..00000000000 --- a/framework/src/test/resources/soliditycode/contractOtherToTrcToken.sol +++ /dev/null @@ -1,41 +0,0 @@ - - -contract ConvertType { - -constructor() payable public{} - -fallback() payable external{} - -//function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { -// trcToken t = trcToken(tokenStr); // ERROR -// toAddress.transferToken(tokenValue, tokenStr); // ERROR -//} - -function uint256ToTrctoken(address payable toAddress, uint256 tokenValue, uint256 tokenInt) public { - trcToken t = trcToken(tokenInt); // OK - toAddress.transferToken(tokenValue, t); // OK - toAddress.transferToken(tokenValue, tokenInt); // OK -} - -function addressToTrctoken(address payable toAddress, uint256 tokenValue, address adr) public { - trcToken t = trcToken(uint256(uint160(adr))); // OK - toAddress.transferToken(tokenValue, t); // OK -//toAddress.transferToken(tokenValue, adr); // ERROR -} - -//function bytesToTrctoken(address payable toAddress, bytes memory b, uint256 tokenValue) public { - // trcToken t = trcToken(b); // ERROR - // toAddress.transferToken(tokenValue, b); // ERROR -//} - -function bytes32ToTrctoken(address payable toAddress, uint256 tokenValue, bytes32 b32) public { - trcToken t = trcToken(b32); // OK - toAddress.transferToken(tokenValue, t); // OK -// toAddress.transferToken(tokenValue, b32); // ERROR -} - -//function arrayToTrctoken(address payable toAddress, uint256[] memory arr, uint256 tokenValue) public { -//trcToken t = trcToken(arr); // ERROR -// toAddress.transferToken(tokenValue, arr); // ERROR -//} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario001.sol b/framework/src/test/resources/soliditycode/contractScenario001.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario001.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario002.sol b/framework/src/test/resources/soliditycode/contractScenario002.sol deleted file mode 100644 index 5b990fe36e8..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario002.sol +++ /dev/null @@ -1,53 +0,0 @@ - -contract TronNative{ - - address public voteContractAddress= address(0x10001); - address public freezeBalanceAddress = address(0x10002); - address public unFreezeBalanceAddress = address(0x10003); - address public withdrawBalanceAddress = address(0x10004); - address public approveProposalAddress = address(0x10005); - address public createProposalAddress = address(0x10006); - address public deleteProposalAddress = address(0x10007); - constructor () payable public {} - - function voteForSingleWitness (address payable witnessAddr, uint256 voteValue) public{ - // method 1: - voteContractAddress.delegatecall(abi.encode(witnessAddr,voteValue)); - } - - function voteUsingAssembly (address witnessAddr, uint256 voteValue) public{ - // method 2: - assembly{ - mstore(0x80,witnessAddr) - mstore(0xa0,voteValue) - // gas, address, in, size, out, size - if iszero(delegatecall(0, 0x10001, 0x80, 0x40, 0x80, 0x0)) { - revert(0, 0) - } - } - } - - function freezeBalance(uint256 frozen_Balance,uint256 frozen_Duration) public { - freezeBalanceAddress.delegatecall(abi.encode(frozen_Balance,frozen_Duration)); - } - - function unFreezeBalance() public { - unFreezeBalanceAddress.delegatecall(""); - } - - function withdrawBalance() public { - withdrawBalanceAddress.delegatecall(""); - } - - function approveProposal(uint256 id, bool isApprove) public { - approveProposalAddress.delegatecall(abi.encode(id,isApprove)); - } - - function createProposal(bytes32 [] memory data) public { - createProposalAddress.delegatecall(abi.encode(data)); - } - - function deleteProposal(uint256 id) public{ - deleteProposalAddress.delegatecall(abi.encode(id)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario003.sol b/framework/src/test/resources/soliditycode/contractScenario003.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario003.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario004.sol b/framework/src/test/resources/soliditycode/contractScenario004.sol deleted file mode 100644 index f6919502914..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario004.sol +++ /dev/null @@ -1,88 +0,0 @@ - - -contract TronToken { - - string public name = "Tronix"; // token name - string public symbol = "TRX"; // token symbol - uint256 public decimals = 6; // token digit - - mapping (address => uint256) public balanceOf; - mapping (address => mapping (address => uint256)) public allowance; - - uint256 public totalSupply = 0; - bool public stopped = false; - - uint256 constant valueFounder = 100000000000000000; - address owner = address(0x0); - - modifier isOwner { - assert(owner == msg.sender); - _; - } - - modifier isRunning { - assert (!stopped); - _; - } - - modifier validAddress { - assert(address(0x0) != msg.sender); - _; - } - - constructor(address _addressFounder) public { - owner = msg.sender; - totalSupply = valueFounder; - balanceOf[_addressFounder] = valueFounder; - emit Transfer(address(0x0), _addressFounder, valueFounder); - } - - function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[msg.sender] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - balanceOf[msg.sender] -= _value; - balanceOf[_to] += _value; - emit Transfer(msg.sender, _to, _value); - return true; - } - - function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[_from] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - require(allowance[_from][msg.sender] >= _value); - balanceOf[_to] += _value; - balanceOf[_from] -= _value; - allowance[_from][msg.sender] -= _value; - emit Transfer(_from, _to, _value); - return true; - } - - function approve(address _spender, uint256 _value) isRunning validAddress public returns (bool success) { - require(_value == 0 || allowance[msg.sender][_spender] == 0); - allowance[msg.sender][_spender] = _value; - emit Approval(msg.sender, _spender, _value); - return true; - } - - function stop() isOwner public { - stopped = true; - } - - function start() isOwner public { - stopped = false; - } - - function setName(string memory _name) isOwner public { - name = _name; - } - - function burn(uint256 _value) public { - require(balanceOf[msg.sender] >= _value); - balanceOf[msg.sender] -= _value; - balanceOf[address(0x0)] += _value; - emit Transfer(msg.sender, address(0x0), _value); - } - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario005.sol b/framework/src/test/resources/soliditycode/contractScenario005.sol deleted file mode 100644 index 5d20d98c0ba..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario005.sol +++ /dev/null @@ -1,103 +0,0 @@ - - -interface token { - function transfer(address receiver, uint amount) external; -} - -contract Crowdsale { - address payable public beneficiary = payable(address(uint160(0x1b228F5D9f934c7bb18Aaa86F90418932888E7b4))); // 募资成功后的收款方 - uint public fundingGoal = 10000000; // 募资额度 - uint public amountRaised = 1000000; // 参与数量 - uint public deadline; // 募资截止期 - - uint public price; // token 与以太坊的汇率 , token卖多少钱 - token public tokenReward; // 要卖的token - - mapping(address => uint256) public balanceOf; - - bool fundingGoalReached = false; // 众筹是否达到目标 - bool crowdsaleClosed = false; // 众筹是否结束 - - /** - * 事件可以用来跟踪信息 - **/ - event GoalReached(address recipient, uint totalAmountRaised); - event FundTransfer(address backer, uint amount, bool isContribution); - - /** - * 构造函数, 设置相关属性 - */ - constructor( - address payable ifSuccessfulSendTo, - uint fundingGoalInEthers, - uint durationInMinutes, - uint finneyCostOfEachToken, - address addressOfTokenUsedAsReward) public{ - beneficiary = ifSuccessfulSendTo; - fundingGoal = fundingGoalInEthers * 1 sun; - deadline = block.timestamp + durationInMinutes * 1 minutes; - price = finneyCostOfEachToken * 1 trx; - tokenReward = token(addressOfTokenUsedAsReward); // 传入已发布的 token 合约的地址来创建实例 - } - - /** - * 无函数名的Fallback函数, - * 在向合约转账时,这个函数会被调用 - */ - fallback() payable external{ - require(!crowdsaleClosed); - uint amount = msg.value; - balanceOf[msg.sender] += amount; - amountRaised += amount; - tokenReward.transfer(msg.sender, amount / price); - emit FundTransfer(msg.sender, amount, true); - } - - /** - * 定义函数修改器modifier(作用和Python的装饰器很相似) - * 用于在函数执行前检查某种前置条件(判断通过之后才会继续执行该方法) - * _ 表示继续执行之后的代码 - **/ - modifier afterDeadline() { if (block.timestamp >= deadline) _; } - - /** - * 判断众筹是否完成融资目标, 这个方法使用了afterDeadline函数修改器 - * - */ - function checkGoalReached() afterDeadline public{ - if (amountRaised >= fundingGoal) { - fundingGoalReached = true; - emit GoalReached(beneficiary, amountRaised); - } - crowdsaleClosed = true; - } - - - /** - * 完成融资目标时,融资款发送到收款方 - * 未完成融资目标时,执行退款 - * - */ - function safeWithdrawal() afterDeadline public{ - if (!fundingGoalReached) { - uint amount = balanceOf[msg.sender]; - balanceOf[msg.sender] = 0; - if (amount > 0) { - if (payable(msg.sender).send(amount)) { - emit FundTransfer(msg.sender, amount, false); - } else { - balanceOf[msg.sender] = amount; - } - } - } - - if (fundingGoalReached && beneficiary == msg.sender) { - if (payable(beneficiary).send(amountRaised)) { - emit FundTransfer(beneficiary, amountRaised, false); - } else { - //If we fail to send the funds to beneficiary, unlock funders balance - fundingGoalReached = false; - } - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario006.sol b/framework/src/test/resources/soliditycode/contractScenario006.sol deleted file mode 100644 index 15dca03d162..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario006.sol +++ /dev/null @@ -1,1963 +0,0 @@ - - -interface PlayerBookInterface { - function getPlayerID(address _addr) external returns (uint256); - function getPlayerName(uint256 _pID) external view returns (bytes32); - function getPlayerLAff(uint256 _pID) external view returns (uint256); - function getPlayerAddr(uint256 _pID) external view returns (address); - function getNameFee() external view returns (uint256); - function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); - function isDev(address _who) external view returns(bool); -} - - -/** -* @title -Name Filter- v0.1.9 -* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ -* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ -* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ -* _____ _____ -* (, / /) /) /) (, / /) /) -* ┌─┐ / _ (/_ // // / _ // _ __ _(/ -* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ -* ┴ ┴ / / .-/ _____ (__ / -* (__ / (_/ (, / /)™ -* / __ __ __ __ _ __ __ _ _/_ _ _(/ -* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ -* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 -* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ -* _ __ _ ____ ____ _ _ _____ ____ ___ -*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* -*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* -* -* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ -* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ -* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ -*/ - -library NameFilter { - /** - * @dev filters name strings - * -converts uppercase to lower case. - * -makes sure it does not start/end with a space - * -makes sure it does not contain multiple spaces in a row - * -cannot be only numbers - * -cannot start with 0x - * -restricts characters to A-Z, a-z, 0-9, and space. - * @return reprocessed string in bytes32 format - */ - function nameFilter(string memory _input) - internal - pure - returns(bytes32) - { - bytes memory _temp = bytes(_input); - uint256 _length = _temp.length; - - //sorry limited to 32 characters - require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); - // make sure it doesnt start with or end with space - require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); - // make sure first two characters are not 0x - if (_temp[0] == 0x30) - { - require(_temp[1] != 0x78, "string cannot start with 0x"); - require(_temp[1] != 0x58, "string cannot start with 0X"); - } - - // create a bool to track if we have a non number character - bool _hasNonNumber; - - // convert & check - for (uint256 i = 0; i < _length; i++) - { - // if its uppercase A-Z - if (_temp[i] > 0x40 && _temp[i] < 0x5b) - { - // convert to lower case a-z - _temp[i] = bytes1(uint8(_temp[i]) + 32); - - // we have a non number - if (_hasNonNumber == false) - _hasNonNumber = true; - } else { - require - ( - // require character is a space - _temp[i] == 0x20 || - // OR lowercase a-z - (_temp[i] > 0x60 && _temp[i] < 0x7b) || - // or 0-9 - (_temp[i] > 0x2f && _temp[i] < 0x3a), - "string contains invalid characters" - ); - // make sure theres not 2x spaces in a row - if (_temp[i] == 0x20) - require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); - - // see if we have a character other than a number - if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) - _hasNonNumber = true; - } - } - - require(_hasNonNumber == true, "string cannot be only numbers"); - - bytes32 _ret; - assembly { - _ret := mload(add(_temp, 32)) - } - return (_ret); - } -} - - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - if (a == 0) { - return 0; - } - c = a * b; - require(c / a == b, "SafeMath mul failed"); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return c; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { - require(b <= a, "SafeMath sub failed"); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - c = a + b; - require(c >= a, "SafeMath add failed"); - return c; - } - - /** - * @dev gives square root of given x. - */ - function sqrt(uint256 x) - internal - pure - returns (uint256 y) - { - uint256 z = ((add(x,1)) / 2); - y = x; - while (z < y) - { - y = z; - z = ((add((x / z),z)) / 2); - } - } - - /** - * @dev gives square. multiplies x by x - */ - function sq(uint256 x) - internal - pure - returns (uint256) - { - return (mul(x,x)); - } - - /** - * @dev x to the power of y - */ - function pwr(uint256 x, uint256 y) - internal - pure - returns (uint256) - { - if (x==0) - return (0); - else if (y==0) - return (1); - else - { - uint256 z = x; - for (uint256 i=1; i < y; i++) - z = mul(z,x); - return (z); - } - } -} - -//============================================================================== -// | _ _ _ | _ . -// |<(/_\/ (_(_||(_ . -//=======/====================================================================== -library F3DKeysCalcLong { - using SafeMath for *; - /** - * @dev calculates number of keys received given X eth - * @param _curEth current amount of eth in contract - * @param _newEth eth being spent - * @return amount of ticket purchased - */ - function keysRec(uint256 _curEth, uint256 _newEth) - internal - pure - returns (uint256) - { - return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); - } - - /** - * @dev calculates amount of eth received if you sold X keys - * @param _curKeys current amount of keys that exist - * @param _sellKeys amount of keys you wish to sell - * @return amount of eth received - */ - function ethRec(uint256 _curKeys, uint256 _sellKeys) - internal - pure - returns (uint256) - { - return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); - } - - /** - * @dev calculates how many keys would exist with given an amount of eth - * @param _eth eth "in contract" - * @return number of keys that would exist - */ - function keys(uint256 _eth) - internal - pure - returns(uint256) - { - return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); - } - - /** - * @dev calculates how much eth would be in contract given a number of keys - * @param _keys number of keys "in contract" - * @return eth that would exists - */ - function eth(uint256 _keys) - internal - pure - returns(uint256) - { - return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); - } -} - -library F3Ddatasets { - //compressedData key - // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] - // 0 - new player (bool) - // 1 - joined round (bool) - // 2 - new leader (bool) - // 3-5 - air drop tracker (uint 0-999) - // 6-16 - round end time - // 17 - winnerTeam - // 18 - 28 timestamp - // 29 - team - // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) - // 31 - airdrop happened bool - // 32 - airdrop tier - // 33 - airdrop amount won - //compressedIDs key - // [77-52][51-26][25-0] - // 0-25 - pID - // 26-51 - winPID - // 52-77 - rID - struct EventReturns { - uint256 compressedData; - uint256 compressedIDs; - address winnerAddr; // winner address - bytes32 winnerName; // winner name - uint256 amountWon; // amount won - uint256 newPot; // amount in new pot - uint256 P3DAmount; // amount distributed to p3d - uint256 genAmount; // amount distributed to gen - uint256 potAmount; // amount added to pot - } - struct Player { - address payable addr; // player address - bytes32 name; // player name - uint256 win; // winnings vault - uint256 gen; // general vault - uint256 aff; // affiliate vault - uint256 lrnd; // last round played - uint256 laff; // last affiliate id used - } - struct PlayerRounds { - uint256 eth; // eth player has added to round (used for eth limiter) - uint256 keys; // keys - uint256 mask; // player mask - uint256 ico; // ICO phase investment - } - struct Round { - uint256 plyr; // pID of player in lead - uint256 team; // tID of team in lead - uint256 end; // time ends/ended - bool ended; // has round end function been ran - uint256 strt; // time round started - uint256 keys; // keys - uint256 eth; // total eth in - uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) - uint256 mask; // global mask - uint256 ico; // total eth sent in during ICO phase - uint256 icoGen; // total eth for gen during ICO phase - uint256 icoAvg; // average key price for ICO phase - } - struct TeamFee { - uint256 gen; // % of buy in thats paid to key holders of current round - uint256 p3d; // % of buy in thats paid to p3d holders - } - struct PotSplit { - uint256 gen; // % of pot thats paid to key holders of current round - uint256 p3d; // % of pot thats paid to p3d holders - } -} - -contract F3Devents { - // fired whenever a player registers a name - event onNewName - ( - uint256 indexed playerID, - address indexed playerAddress, - bytes32 indexed playerName, - bool isNewPlayer, - uint256 affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 amountPaid, - uint256 timeStamp - ); - - // fired at end of buy or reload - event onEndTx - ( - uint256 compressedData, - uint256 compressedIDs, - bytes32 playerName, - address playerAddress, - uint256 ethIn, - uint256 keysBought, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount, - uint256 potAmount, - uint256 airDropPot - ); - - // fired whenever theres a withdraw - event onWithdraw - ( - uint256 indexed playerID, - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 timeStamp - ); - - // fired whenever a withdraw forces end round to be ran - event onWithdrawAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a buy after round timer - // hit zero, and causes end round to be ran. - event onBuyAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethIn, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a reload after round timer - // hit zero, and causes end round to be ran. - event onReLoadAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // fired whenever an affiliate is paid - event onAffiliatePayout - ( - uint256 indexed affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 indexed roundID, - uint256 indexed buyerID, - uint256 amount, - uint256 timeStamp - ); - - // received pot swap deposit - event onPotSwapDeposit - ( - uint256 roundID, - uint256 amountAddedToPot - ); -} - - - -contract FoMo3Dlong is F3Devents { - using SafeMath for *; - using NameFilter for string; - using F3DKeysCalcLong for uint256; - - address public otherF3D_; - address public Divies; - address public Jekyll_Island_Inc; - PlayerBookInterface public playerBook;// =PlayerBookInterface(0x0dcd2f752394c41875e259e00bb44fd505297caf);//new PlayerBook();// - // TeamJustInterface constant private teamJust = TeamJustInterface(0x3a5f8140b9213a0f733a6a639857c9df43ee3f5a);// new TeamJust();// - - //============================================================================== - // _ _ _ |`. _ _ _ |_ | _ _ . - // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) - //=================_|=========================================================== - string constant public name = "FoMo3D Long Official"; - string constant public symbol = "F3D"; - uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO - uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. - uint256 constant private rndInit_ = 1 hours; // round timer starts at this - uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer - uint256 constant private rndMax_ = 24 hours; // max length a round timer can be - //============================================================================== - // _| _ _|_ _ _ _ _|_ _ . - // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) - //=============================|================================================ - uint256 public airDropPot_; // person who gets the airdrop wins part of this pot - uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop - uint256 public rID_; // round id number / total rounds that have happened - //**************** - // PLAYER DATA - //**************** - mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address - mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name - mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data - mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id - mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) - //**************** - // ROUND DATA - //**************** - mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data - mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id - //**************** - // TEAM FEE DATA - //**************** - mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team - mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team - - function setPlayerBook(address _playerBook) external { - require(msg.sender == owner, 'only dev!'); - require(address(playerBook) == address(0), 'already set!'); - playerBook = PlayerBookInterface(_playerBook); - } - - address public owner; - - //============================================================================== - // _ _ _ __|_ _ __|_ _ _ . - // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) - //============================================================================== - constructor() - public - { - owner = msg.sender; - // Team allocation structures - // 0 = whales - // 1 = bears - // 2 = sneks - // 3 = bulls - - // Team allocation percentages - // (F3D, P3D) + (Pot , Referrals, Community) - // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. - fees_[0] = F3Ddatasets.TeamFee(30, 6); - //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[1] = F3Ddatasets.TeamFee(43, 0); - //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[2] = F3Ddatasets.TeamFee(56, 10); - //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[3] = F3Ddatasets.TeamFee(43, 8); - //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - - // how to split up the final pot based on which team was picked - // (F3D, P3D) - potSplit_[0] = F3Ddatasets.PotSplit(15, 10); - //48% to winner, 25% to next round, 2% to com - potSplit_[1] = F3Ddatasets.PotSplit(25, 0); - //48% to winner, 25% to next round, 2% to com - potSplit_[2] = F3Ddatasets.PotSplit(20, 20); - //48% to winner, 10% to next round, 2% to com - potSplit_[3] = F3Ddatasets.PotSplit(30, 10); - //48% to winner, 10% to next round, 2% to com - } - //============================================================================== - // _ _ _ _|. |`. _ _ _ . - // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) - //============================================================================== - /** - * @dev used to make sure no one can interact with contract until it has - * been activated. - */ - modifier isActivated() { - require(activated_ == true, "its not ready yet. check ?eta in discord"); - _; - } - - /** - * @dev prevents contracts from interacting with fomo3d - */ - modifier isHuman() { - address _addr = msg.sender; - uint256 _codeLength; - - assembly {_codeLength := extcodesize(_addr)} - require(_codeLength == 0, "sorry humans only"); - _; - } - - modifier onlyDevs() - { - require(playerBook.isDev(msg.sender) == true, "msg sender is not a dev"); - _; - } - - /** - * @dev sets boundaries for incoming tx - */ - modifier isWithinLimits(uint256 _eth) { - require(_eth >= 1000000000, "pocket lint: not a valid currency"); - require(_eth <= 100000000000000000000000, "no vitalik, no"); - _; - } - - //============================================================================== - // _ |_ |. _ |` _ __|_. _ _ _ . - // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) - //====|========================================================================= - /** - * @dev emergency buy uses last stored affiliate ID and team snek - */ - fallback() - isActivated() - isHuman() - isWithinLimits(msg.value) - external - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // buy core - buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); - } - - /** - * @dev converts all incoming ethereum to keys. - * -functionhash- 0x8f38f309 (using ID for affiliate) - * -functionhash- 0x98a0871d (using address for affiliate) - * -functionhash- 0xa65b37a1 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - */ - function buyXid(uint256 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affCode, _team, _eventData_); - } - - function buyXaddr(address _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - function buyXname(bytes32 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - /** - * @dev essentially the same as buy, but instead of you sending ether - * from your wallet, it uses your unwithdrawn earnings. - * -functionhash- 0x349cdcac (using ID for affiliate) - * -functionhash- 0x82bfc739 (using address for affiliate) - * -functionhash- 0x079ce327 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - * @param _eth amount of earnings to use (remainder returned to gen vault) - */ - function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affCode, _team, _eth, _eventData_); - } - - function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - /** - * @dev withdraws all of your earnings. - * -functionhash- 0x3ccfd60b - */ - function withdraw() - isActivated() - isHuman() - public - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // setup temp var for player eth - uint256 _eth; - - // check to see if round has ended and no one has run round end yet - if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // end the round (distributes pot) - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire withdraw and distribute event - emit F3Devents.onWithdrawAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eth, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - - // in any other situation - } else { - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // fire withdraw event - emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); - } - } - - /** - * @dev use these to register names. they are just wrappers that will send the - * registration requests to the PlayerBook contract. So registering here is the - * same as registering there. UI will always display the last name you registered. - * but you will still own all previously registered names to use as affiliate - * links. - * - must pay a registration fee. - * - name must be unique - * - names will be converted to lowercase - * - name cannot start or end with a space - * - cannot have more than 1 space in a row - * - cannot be only numbers - * - cannot start with 0x - * - name must be at least 1 char - * - max length of 32 characters long - * - allowed characters: a-z, 0-9, and space - * -functionhash- 0x921dec21 (using ID for affiliate) - * -functionhash- 0x3ddd4698 (using address for affiliate) - * -functionhash- 0x685ffd83 (using name for affiliate) - * @param _nameString players desired name - * @param _affCode affiliate ID, address, or name of who referred you - * @param _all set to true if you want this to push your info to all games - * (this might cost a lot of gas) - */ - function registerNameXID(string memory _nameString, uint256 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXIDFromDapp{value:_paid}(_addr, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, block.timestamp); - } - - function registerNameXaddr(string memory _nameString, address _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXaddrFromDapp{value:msg.value}(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, block.timestamp); - } - - function registerNameXname(string memory _nameString, bytes32 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXnameFromDapp{value:msg.value}(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, block.timestamp); - } - //============================================================================== - // _ _ _|__|_ _ _ _ . - // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) - //=====_|======================================================================= - /** - * @dev return the price buyer will pay for next 1 individual key. - * -functionhash- 0x018a25e8 - * @return price for next key bought (in wei format) - */ - function getBuyPrice() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); - else // rounds over. need price for new round - return (75000000000000); - // init - } - - /** - * @dev returns time left. dont spam this, you'll ddos yourself from your node - * provider - * -functionhash- 0xc7e284b8 - * @return time left in seconds - */ - function getTimeLeft() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - if (_now < round_[_rID].end) - if (_now > round_[_rID].strt + rndGap_) - return ((round_[_rID].end).sub(_now)); - else - return ((round_[_rID].strt + rndGap_).sub(_now)); - else - return (0); - } - - /** - * @dev returns player earnings per vaults - * -functionhash- 0x63066434 - * @return winnings vault - * @return general vault - * @return affiliate vault - */ - function getPlayerVaults(uint256 _pID) - public - view - returns (uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - // if round has ended. but round end has not been run (so contract has not distributed winnings) - if (block.timestamp > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // if player is winner - if (round_[_rID].plyr == _pID) - { - return - ( - (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - // if player is not the winner - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - } - - // if round is still going on, or round has ended and round end has been ran - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), - plyr_[_pID].aff - ); - } - } - - /** - * solidity hates stack limits. this lets us avoid that hate - */ - function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) - private - view - returns (uint256) - { - return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); - } - - /** - * @dev returns all current round info needed for front end - * -functionhash- 0x747dff42 - * @return eth invested during ICO phase - * @return round id - * @return total keys for round - * @return time round ends - * @return time round started - * @return current pot - * @return current team ID & player ID in lead - * @return current player in leads address - * @return current player in leads name - * @return whales eth in for round - * @return bears eth in for round - * @return sneks eth in for round - * @return bulls eth in for round - * @return airdrop tracker # & airdrop pot - */ - function getCurrentRoundInfo() - public - view - returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - return - ( - round_[_rID].ico, //0 - _rID, //1 - round_[_rID].keys, //2 - round_[_rID].end, //3 - round_[_rID].strt, //4 - round_[_rID].pot, //5 - (round_[_rID].team + (round_[_rID].plyr * 10)), //6 - plyr_[round_[_rID].plyr].addr, //7 - plyr_[round_[_rID].plyr].name, //8 - rndTmEth_[_rID][0], //9 - rndTmEth_[_rID][1], //10 - rndTmEth_[_rID][2], //11 - rndTmEth_[_rID][3], //12 - airDropTracker_ + (airDropPot_ * 1000) //13 - ); - } - - /** - * @dev returns player info based on address. if no address is given, it will - * use msg.sender - * -functionhash- 0xee0b5d8b - * @param _addr address of the player you want to lookup - * @return player ID - * @return player name - * @return keys owned (current round) - * @return winnings vault - * @return general vault - * @return affiliate vault - * @return player round eth - */ - function getPlayerInfoByAddress(address _addr) - public - view - returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - if (_addr == address(0)) - { - _addr == msg.sender; - } - uint256 _pID = pIDxAddr_[_addr]; - - return - ( - _pID, //0 - plyr_[_pID].name, //1 - plyrRnds_[_pID][_rID].keys, //2 - plyr_[_pID].win, //3 - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 - plyr_[_pID].aff, //5 - plyrRnds_[_pID][_rID].eth //6 - ); - } - - //============================================================================== - // _ _ _ _ | _ _ . _ . - // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) - //=====================_|======================================================= - /** - * @dev logic runs whenever a buy order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // call core - core(_rID, _pID, msg.value, _affID, _team, _eventData_); - - // if round is not active - } else { - // check to see if end round needs to be ran - if (_now > round_[_rID].end && round_[_rID].ended == false) - { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onBuyAndDistribute - ( - msg.sender, - plyr_[_pID].name, - msg.value, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - - // put eth in players vault - plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); - } - } - - /** - * @dev logic runs whenever a reload order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // get earnings from all vaults and return unused to gen vault - // because we use a custom safemath library. this will throw if player - // tried to spend more eth than they have. - plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); - - // call core - core(_rID, _pID, _eth, _affID, _team, _eventData_); - - // if round is not active and end round needs to be ran - } else if (_now > round_[_rID].end && round_[_rID].ended == false) { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onReLoadAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - } - - /** - * @dev this is the core logic for any buy/reload that happens while a round - * is live. - */ - function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // if player is new to round - if (plyrRnds_[_pID][_rID].keys == 0) - _eventData_ = managePlayer(_pID, _eventData_); - - // early round eth limiter - if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) - { - uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); - uint256 _refund = _eth.sub(_availableLimit); - plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); - _eth = _availableLimit; - } - - // if eth left is greater than min eth allowed (sorry no pocket lint) - if (_eth > 1000000000) - { - - // mint the new keys - uint256 _keys = (round_[_rID].eth).keysRec(_eth); - - // if they bought at least 1 whole key - if (_keys >= 1000000000000000000) - { - updateTimer(_keys, _rID); - - // set new leaders - if (round_[_rID].plyr != _pID) - round_[_rID].plyr = _pID; - if (round_[_rID].team != _team) - round_[_rID].team = _team; - - // set the new leader bool to true - _eventData_.compressedData = _eventData_.compressedData + 100; - } - - // manage airdrops - if (_eth >= 100000000000000000) - { - airDropTracker_++; - if (airdrop() == true) - { - // gib muni - uint256 _prize; - if (_eth >= 10000000000000000000) - { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(75)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(50)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 2 prize was won - _eventData_.compressedData += 200000000000000000000000000000000; - } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(25)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } - // set airdrop happened bool to true - _eventData_.compressedData += 10000000000000000000000000000000; - // let event know how much was won - _eventData_.compressedData += _prize * 1000000000000000000000000000000000; - - // reset air drop tracker - airDropTracker_ = 0; - } - } - - // store the air drop tracker number (number of buys since last airdrop) - _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); - - // update player - plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); - plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); - - // update round - round_[_rID].keys = _keys.add(round_[_rID].keys); - round_[_rID].eth = _eth.add(round_[_rID].eth); - rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); - - // distribute eth - _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); - _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); - - // call end tx function to fire end tx event. - endTx(_pID, _team, _eth, _keys, _eventData_); - } - } - //============================================================================== - // _ _ | _ | _ _|_ _ _ _ . - // (_(_||(_|_||(_| | (_)| _\ . - //============================================================================== - /** - * @dev calculates unmasked earnings (just calculates, does not update mask) - * @return earnings in wei format - */ - function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) - private - view - returns (uint256) - { - return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); - } - - /** - * @dev returns the amount of keys you would get given an amount of eth. - * -functionhash- 0xce89c80c - * @param _rID round ID you want price for - * @param _eth amount of eth sent in - * @return keys received - */ - function calcKeysReceived(uint256 _rID, uint256 _eth) - public - view - returns (uint256) - { - // grab time - uint256 _now = block.timestamp; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].eth).keysRec(_eth)); - else // rounds over. need keys for new round - return ((_eth).keys()); - } - - /** - * @dev returns current eth price for X keys. - * -functionhash- 0xcf808000 - * @param _keys number of keys desired (in 18 decimal format) - * @return amount of eth needed to send - */ - function iWantXKeys(uint256 _keys) - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); - else // rounds over. need price for new round - return ((_keys).eth()); - } - //============================================================================== - // _|_ _ _ | _ . - // | (_)(_)|_\ . - //============================================================================== - /** - * @dev receives name/player info from names contract - */ - function receivePlayerInfo(uint256 _pID, address payable _addr, bytes32 _name, uint256 _laff) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (pIDxAddr_[_addr] != _pID) - pIDxAddr_[_addr] = _pID; - if (pIDxName_[_name] != _pID) - pIDxName_[_name] = _pID; - if (plyr_[_pID].addr != _addr) - plyr_[_pID].addr = _addr; - if (plyr_[_pID].name != _name) - plyr_[_pID].name = _name; - if (plyr_[_pID].laff != _laff) - plyr_[_pID].laff = _laff; - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev receives entire player name list - */ - function receivePlayerNameList(uint256 _pID, bytes32 _name) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev gets existing or registers new pID. use this when a player may be new - * @return pID - */ - function determinePID(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - uint256 _pID = pIDxAddr_[msg.sender]; - // if player is new to this version of fomo3d - if (_pID == 0) - { - // grab their player ID, name and last aff ID, from player names contract - _pID = playerBook.getPlayerID(msg.sender); - bytes32 _name = playerBook.getPlayerName(_pID); - uint256 _laff = playerBook.getPlayerLAff(_pID); - - // set up player account - pIDxAddr_[msg.sender] = _pID; - plyr_[_pID].addr = payable(msg.sender); - - if (_name != "") - { - pIDxName_[_name] = _pID; - plyr_[_pID].name = _name; - plyrNames_[_pID][_name] = true; - } - - if (_laff != 0 && _laff != _pID) - plyr_[_pID].laff = _laff; - - // set the new player bool to true - _eventData_.compressedData = _eventData_.compressedData + 1; - } - return (_eventData_); - } - - /** - * @dev checks to make sure user picked a valid team. if not sets team - * to default (sneks) - */ - function verifyTeam(uint256 _team) - private - pure - returns (uint256) - { - if (_team < 0 || _team > 3) - return (2); - else - return (_team); - } - - /** - * @dev decides if round end needs to be run & new round started. and if - * player unmasked earnings from previously played rounds need to be moved. - */ - function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // if player has played a previous round, move their unmasked earnings - // from that round to gen vault. - if (plyr_[_pID].lrnd != 0) - updateGenVault(_pID, plyr_[_pID].lrnd); - - // update player's last round played - plyr_[_pID].lrnd = rID_; - - // set the joined round bool to true - _eventData_.compressedData = _eventData_.compressedData + 10; - - return (_eventData_); - } - - /** - * @dev ends the round. manages paying out winner/splitting up pot - */ - function endRound(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // setup local rID - uint256 _rID = rID_; - - // grab our winning player and team id's - uint256 _winPID = round_[_rID].plyr; - uint256 _winTID = round_[_rID].team; - - // grab our pot amount - uint256 _pot = round_[_rID].pot; - - // calculate our winner share, community rewards, gen share, - // p3d share, and amount reserved for next pot - uint256 _win = (_pot.mul(48)) / 100; - uint256 _com = (_pot / 50); - uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; - uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; - uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); - - // calculate ppt for round mask - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); - if (_dust > 0) - { - _gen = _gen.sub(_dust); - _res = _res.add(_dust); - } - - // pay our winner - plyr_[_winPID].win = _win.add(plyr_[_winPID].win); - - // community rewards - address payable add = payable(address(uint160(Jekyll_Island_Inc))); - if (!add.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _p3d.add(_com); - _com = 0; - } - - // distribute gen portion to key holders - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // send share for p3d to divies - if (_p3d > 0){ - address payable addr = payable(address(uint160(Divies))); - addr.transfer(_p3d); - } - // prepare event data - _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); - _eventData_.winnerAddr = plyr_[_winPID].addr; - _eventData_.winnerName = plyr_[_winPID].name; - _eventData_.amountWon = _win; - _eventData_.genAmount = _gen; - _eventData_.P3DAmount = _p3d; - _eventData_.newPot = _res; - - // start next round - rID_++; - _rID++; - round_[_rID].strt = block.timestamp; - round_[_rID].end = block.timestamp.add(rndInit_).add(rndGap_); - round_[_rID].pot = _res; - - return (_eventData_); - } - - /** - * @dev moves any unmasked earnings to gen vault. updates earnings mask - */ - function updateGenVault(uint256 _pID, uint256 _rIDlast) - private - { - uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); - if (_earnings > 0) - { - // put in gen vault - plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); - // zero out their earnings by updating mask - plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); - } - } - - /** - * @dev updates round timer based on number of whole keys bought. - */ - function updateTimer(uint256 _keys, uint256 _rID) - private - { - // grab time - uint256 _now = block.timestamp; - - // calculate time based on number of keys bought - uint256 _newTime; - if (_now > round_[_rID].end && round_[_rID].plyr == 0) - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); - else - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); - - // compare to max and set new end time - if (_newTime < (rndMax_).add(_now)) - round_[_rID].end = _newTime; - else - round_[_rID].end = rndMax_.add(_now); - } - - /** - * @dev generates a random number between 0-99 and checks to see if thats - * resulted in an airdrop win - * @return do we have a winner? - */ - function airdrop() - private - view - returns (bool) - { - uint256 seed = uint256(keccak256(abi.encodePacked( - - (block.timestamp).add - (block.difficulty).add - ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)).add - (block.gaslimit).add - ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)).add - (block.number) - - ))); - if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) - return (true); - else - return (false); - } - - /** - * @dev distributes eth based on fees to com, aff, and p3d - */ - function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // pay 2% out to community rewards - uint256 _com = _eth / 50; - uint256 _p3d; - address payable addr = payable(address(uint160(Jekyll_Island_Inc))); - if (!addr.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _com; - _com = 0; - } - - // pay 1% out to FoMo3D short - _com = _eth / 100; - address payable add = payable(address(uint160(otherF3D_))); - add.transfer(_com); - - // distribute share to affiliate - _com = _eth / 10; - - // decide what to do with affiliate share of fees - // affiliate must not be self, and must have a name registered - if (_affID != _pID && plyr_[_affID].name != '') { - plyr_[_affID].aff = _com.add(plyr_[_affID].aff); - emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _com, block.timestamp); - } else { - _p3d = _com; - } - - // pay out p3d - _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); - if (_p3d > 0) - { - // deposit to divies contract - address payable add = payable(address(uint160(Divies))); - add.transfer(_p3d); - - // set up event data - _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); - } - - return (_eventData_); - } - - function potSwap() - external - payable - { - // setup local rID - uint256 _rID = rID_ + 1; - - round_[_rID].pot = round_[_rID].pot.add(msg.value); - emit F3Devents.onPotSwapDeposit(_rID, msg.value); - } - - /** - * @dev distributes eth based on fees to gen and pot - */ - function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // calculate gen share - uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; - - // toss 1% into airdrop pot - uint256 _air = (_eth / 100); - airDropPot_ = airDropPot_.add(_air); - - // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); - - // calculate pot - uint256 _pot = _eth.sub(_gen); - - // distribute gen share (thats what updateMasks() does) and adjust - // balances for dust. - uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); - if (_dust > 0) - _gen = _gen.sub(_dust); - - // add eth to pot - round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); - - // set up event data - _eventData_.genAmount = _gen.add(_eventData_.genAmount); - _eventData_.potAmount = _pot; - - return (_eventData_); - } - - /** - * @dev updates masks for round and player when keys are bought - * @return dust left over - */ - function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) - private - returns (uint256) - { - /* MASKING NOTES - earnings masks are a tricky thing for people to wrap their minds around. - the basic thing to understand here. is were going to have a global - tracker based on profit per share for each round, that increases in - relevant proportion to the increase in share supply. - - the player will have an additional mask that basically says "based - on the rounds mask, my shares, and how much i've already withdrawn, - how much is still owed to me?" - */ - - // calc profit per key & round mask based on this buy: (dust goes to pot) - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // calculate player earning from their own buy (only based on the keys - // they just bought). & update player earnings mask - uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); - plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); - - // calculate & return dust - return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); - } - - /** - * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 - * @return earnings in wei format - */ - function withdrawEarnings(uint256 _pID) - private - returns (uint256) - { - // update gen vault - updateGenVault(_pID, plyr_[_pID].lrnd); - - // from vaults - uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); - if (_earnings > 0) - { - plyr_[_pID].win = 0; - plyr_[_pID].gen = 0; - plyr_[_pID].aff = 0; - } - - return (_earnings); - } - - /** - * @dev prepares compression data and fires event for buy or reload tx's - */ - function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - { - _eventData_.compressedData = _eventData_.compressedData + (block.timestamp * 1000000000000000000) + (_team * 100000000000000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); - - emit F3Devents.onEndTx - ( - _eventData_.compressedData, - _eventData_.compressedIDs, - plyr_[_pID].name, - msg.sender, - _eth, - _keys, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount, - _eventData_.potAmount, - airDropPot_ - ); - } - //============================================================================== - // (~ _ _ _._|_ . - // _)(/_(_|_|| | | \/ . - //====================/========================================================= - /** upon contract deploy, it will be deactivated. this is a one time - * use function that will activate the contract. we do this so devs - * have time to set things up on the web end **/ - bool public activated_ = false; - - function activate() - public - onlyDevs - { - - // can only be ran once - require(activated_ == false, "fomo3d already activated"); - - // activate the contract - activated_ = true; - - otherF3D_ = msg.sender; - Divies = msg.sender; - Jekyll_Island_Inc = msg.sender; - - // lets start first round - rID_ = 1; - round_[1].strt = block.timestamp + rndExtra_ - rndGap_; - round_[1].end = block.timestamp + rndInit_ + rndExtra_; - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario007.sol b/framework/src/test/resources/soliditycode/contractScenario007.sol deleted file mode 100644 index a6fa095860f..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario007.sol +++ /dev/null @@ -1,1432 +0,0 @@ - -/** - * @title ERC165 - * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md - */ -interface ERC165 { - - /** - * @notice Query if a contract implements an interface - * @param _interfaceId The interface identifier, as specified in ERC-165 - * @dev Interface identification is specified in ERC-165. This function - * uses less than 30,000 gas. - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool); - -} - -contract ERC721Basic is ERC165 { - - event Transfer( - address indexed _from, - address indexed _to, - uint256 indexed _tokenId - ); - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); - - function balanceOf(address _owner) public view returns (uint256 _balance); - function ownerOf(uint256 _tokenId) public view returns (address _owner); - function exists(uint256 _tokenId) public view returns (bool _exists); - - function approve(address _to, uint256 _tokenId) public; - function getApproved(uint256 _tokenId) - public view returns (address _operator); - - function setApprovalForAll(address _operator, bool _approved) public; - function isApprovedForAll(address _owner, address _operator) - public view returns (bool); - - function transferFrom(address _from, address _to, uint256 _tokenId) public; - function safeTransferFrom(address _from, address _to, uint256 _tokenId) - public; - - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public; -} - - -/** - * @title SupportsInterfaceWithLookup - * @author Matt Condon (@shrugs) - * @dev Implements ERC165 using a lookup table. - */ -contract SupportsInterfaceWithLookup is ERC165 { - bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; - /** - * 0x01ffc9a7 === - * bytes4(keccak256('supportsInterface(bytes4)')) - */ - - /** - * @dev a mapping of interface id to whether or not it's supported - */ - mapping(bytes4 => bool) internal supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself - */ - constructor() public { - _registerInterface(InterfaceId_ERC165); - } - - /** - * @dev implement supportsInterface(bytes4) using a lookup table - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool) { - return supportedInterfaces[_interfaceId]; - } - - /** - * @dev private method for registering an interface - */ - function _registerInterface(bytes4 _interfaceId) internal { - require(_interfaceId != 0xffffffff); - supportedInterfaces[_interfaceId] = true; - } -} - -contract Governable { - - event Pause(); - event Unpause(); - - address public governor; - bool public paused = false; - - constructor() public { - governor = msg.sender; - } - - function setGovernor(address _gov) public onlyGovernor { - governor = _gov; - } - - modifier onlyGovernor { - require(msg.sender == governor); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - */ - modifier whenPaused() { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyGovernor whenNotPaused public { - paused = true; - emit Pause(); - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyGovernor whenPaused public { - paused = false; - emit Unpause(); - } - -} - -contract CardBase is Governable { - - struct Card { - uint16 proto; - uint16 purity; - } - - function getCard(uint id) public view returns (uint16 proto, uint16 purity) { - Card memory card = cards[id]; - return (card.proto, card.purity); - } - - function getShine(uint16 purity) public pure returns (uint8) { - return uint8(purity / 1000); - } - - Card[] public cards; - -} - -contract CardProto is CardBase { - - event NewProtoCard( - uint16 id, uint8 season, uint8 god, - Rarity rarity, uint8 mana, uint8 attack, - uint8 health, uint8 cardType, uint8 tribe, bool packable - ); - - struct Limit { - uint64 limit; - bool exists; - } - - // limits for mythic cards - mapping(uint16 => Limit) public limits; - - // can only set limits once - function setLimit(uint16 id, uint64 limit) public onlyGovernor { - Limit memory l = limits[id]; - require(!l.exists); - limits[id] = Limit({ - limit: limit, - exists: true - }); - } - - function getLimit(uint16 id) public view returns (uint64 limit, bool set) { - Limit memory l = limits[id]; - return (l.limit, l.exists); - } - - // could make these arrays to save gas - // not really necessary - will be update a very limited no of times - mapping(uint8 => bool) public seasonTradable; - mapping(uint8 => bool) public seasonTradabilityLocked; - uint8 public currentSeason; - - function makeTradable(uint8 season) public onlyGovernor { - seasonTradable[season] = true; - } - - function makeUntradable(uint8 season) public onlyGovernor { - require(!seasonTradabilityLocked[season]); - seasonTradable[season] = false; - } - - function makePermanantlyTradable(uint8 season) public onlyGovernor { - require(seasonTradable[season]); - seasonTradabilityLocked[season] = true; - } - - function isTradable(uint16 proto) public view returns (bool) { - return seasonTradable[protos[proto].season]; - } - - function nextSeason() public onlyGovernor { - //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M - require(currentSeason <= 255); - - currentSeason++; - mythic.length = 0; - legendary.length = 0; - epic.length = 0; - rare.length = 0; - common.length = 0; - } - - enum Rarity { - Common, - Rare, - Epic, - Legendary, - Mythic - } - - uint8 constant SPELL = 1; - uint8 constant MINION = 2; - uint8 constant WEAPON = 3; - uint8 constant HERO = 4; - - struct ProtoCard { - bool exists; - uint8 god; - uint8 season; - uint8 cardType; - Rarity rarity; - uint8 mana; - uint8 attack; - uint8 health; - uint8 tribe; - } - - // there is a particular design decision driving this: - // need to be able to iterate over mythics only for card generation - // don't store 5 different arrays: have to use 2 ids - // better to bear this cost (2 bytes per proto card) - // rather than 1 byte per instance - - uint16 public protoCount; - - mapping(uint16 => ProtoCard) protos; - - uint16[] public mythic; - uint16[] public legendary; - uint16[] public epic; - uint16[] public rare; - uint16[] public common; - - function addProtos( - uint16[] memory externalIDs, uint8[] memory gods, Rarity[] memory rarities, uint8[] memory manas, uint8[] memory attacks, - uint8[] memory healths, uint8[] memory cardTypes, uint8[] memory tribes, bool[] memory packable - ) public onlyGovernor returns(uint16) { - - for (uint i = 0; i < externalIDs.length; i++) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: gods[i], - season: currentSeason, - cardType: cardTypes[i], - rarity: rarities[i], - mana: manas[i], - attack: attacks[i], - health: healths[i], - tribe: tribes[i] - }); - - _addProto(externalIDs[i], card, packable[i]); - } - - } - - function addProto( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: cardType, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function addWeapon( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: WEAPON, - rarity: rarity, - mana: mana, - attack: attack, - health: durability, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: SPELL, - rarity: rarity, - mana: mana, - attack: 0, - health: 0, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addMinion( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: MINION, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { - - require(!protos[externalID].exists); - - card.exists = true; - - protos[externalID] = card; - - protoCount++; - - emit NewProtoCard( - externalID, currentSeason, card.god, - card.rarity, card.mana, card.attack, - card.health, card.cardType, card.tribe, packable - ); - - if (packable) { - Rarity rarity = card.rarity; - if (rarity == Rarity.Common) { - common.push(externalID); - } else if (rarity == Rarity.Rare) { - rare.push(externalID); - } else if (rarity == Rarity.Epic) { - epic.push(externalID); - } else if (rarity == Rarity.Legendary) { - legendary.push(externalID); - } else if (rarity == Rarity.Mythic) { - mythic.push(externalID); - } else { - require(false); - } - } - } - - function getProto(uint16 id) public view returns( - bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) { - ProtoCard memory proto = protos[id]; - return ( - proto.exists, - proto.god, - proto.season, - proto.cardType, - proto.rarity, - proto.mana, - proto.attack, - proto.health, - proto.tribe - ); - } - - function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { - // modulo bias is fine - creates rarity tiers etc - // will obviously revert is there are no cards of that type: this is expected - should never happen - if (rarity == Rarity.Common) { - return common[random % common.length]; - } else if (rarity == Rarity.Rare) { - return rare[random % rare.length]; - } else if (rarity == Rarity.Epic) { - return epic[random % epic.length]; - } else if (rarity == Rarity.Legendary) { - return legendary[random % legendary.length]; - } else if (rarity == Rarity.Mythic) { - // make sure a mythic is available - uint16 id; - uint64 limit; - bool set; - for (uint i = 0; i < mythic.length; i++) { - id = mythic[(random + i) % mythic.length]; - (limit, set) = getLimit(id); - if (set && limit > 0){ - return id; - } - } - // if not, they get a legendary :( - return legendary[random % legendary.length]; - } - require(false); - return 0; - } - - // can never adjust tradable cards - // each season gets a 'balancing beta' - // totally immutable: season, rarity - function replaceProto( - uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) public onlyGovernor { - ProtoCard memory pc = protos[index]; - require(!seasonTradable[pc.season]); - protos[index] = ProtoCard({ - exists: true, - god: god, - season: pc.season, - cardType: cardType, - rarity: pc.rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - } - -} - -contract ERC721Receiver { - /** - * @dev Magic value to be returned upon successful reception of an NFT - * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, - * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - */ - bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; - - /** - * @notice Handle the receipt of an NFT - * @dev The ERC721 smart contract calls this function on the recipient - * after a `safetransfer`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the contract address is always the message sender. - * @param _operator The address which called `safeTransferFrom` function - * @param _from The address which previously owned the token - * @param _tokenId The NFT identifier which is being transfered - * @param _data Additional data with no specified format - * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - */ - function onERC721Received( - address _operator, - address _from, - uint256 _tokenId, - bytes memory _data - ) - public - returns(bytes4); -} - -library AddressUtils { - - /** - * Returns whether the target address is a contract - * @dev This function will return false if invoked during the constructor of a contract, - * as the code is not actually created until after the constructor finishes. - * @param addr address to check - * @return whether the target address is a contract - */ - function isContract1(address addr) internal view returns (bool) { - uint256 size; - // XXX Currently there is no better way to check if there is a contract in an address - // than to check the size of the code at that address. - // See https://ethereum.stackexchange.com/a/14016/36603 - // for more details about how this works. - // TODO Check this again before the Serenity release, because all addresses will be - // contracts then. - // solium-disable-next-line security/no-inline-assembly - assembly { size := extcodesize(addr) } - return size > 0; - } - -} - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { - // Gas optimization: this is cheaper than asserting 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 - if (a == 0) { - return 0; - } - - c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - // uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return a / b; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256 c) { - c = a + b; - assert(c >= a); - return c; - } -} - -contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic { - - bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; - /* - * 0x80ac58cd === - * bytes4(keccak256('balanceOf(address)')) ^ - * bytes4(keccak256('ownerOf(uint256)')) ^ - * bytes4(keccak256('approve(address,uint256)')) ^ - * bytes4(keccak256('getApproved(uint256)')) ^ - * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ - * bytes4(keccak256('isApprovedForAll(address,address)')) ^ - * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) - */ - - bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; - /* - * 0x4f558e79 === - * bytes4(keccak256('exists(uint256)')) - */ - - using SafeMath for uint256; - using AddressUtils for address; - - // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - bytes4 private constant ERC721_RECEIVED = 0x150b7a02; - - // Mapping from token ID to owner - mapping (uint256 => address) internal tokenOwner; - - // Mapping from token ID to approved address - mapping (uint256 => address) internal tokenApprovals; - - // Mapping from owner to number of owned token - // mapping (address => uint256) internal ownedTokensCount; - - // Mapping from owner to operator approvals - mapping (address => mapping (address => bool)) internal operatorApprovals; - - /** - * @dev Guarantees msg.sender is owner of the given token - * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender - */ - modifier onlyOwnerOf(uint256 _tokenId) { - require(ownerOf(_tokenId) == msg.sender); - _; - } - - /** - * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator - * @param _tokenId uint256 ID of the token to validate - */ - modifier canTransfer(uint256 _tokenId) { - require(isApprovedOrOwner(msg.sender, _tokenId)); - _; - } - - constructor() - public - { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721); - _registerInterface(InterfaceId_ERC721Exists); - } - - /** - * @dev Gets the balance of the specified address - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256); - - /** - * @dev Gets the owner of the specified token ID - * @param _tokenId uint256 ID of the token to query the owner of - * @return owner address currently marked as the owner of the given token ID - */ - function ownerOf(uint256 _tokenId) public view returns (address) { - address owner = tokenOwner[_tokenId]; - require(owner != address(0)); - return owner; - } - - /** - * @dev Returns whether the specified token exists - * @param _tokenId uint256 ID of the token to query the existence of - * @return whether the token exists - */ - function exists(uint256 _tokenId) public view returns (bool) { - address owner = tokenOwner[_tokenId]; - return owner != address(0); - } - - /** - * @dev Approves another address to transfer the given token ID - * The zero address indicates there is no approved address. - * There can only be one approved address per token at a given time. - * Can only be called by the token owner or an approved operator. - * @param _to address to be approved for the given token ID - * @param _tokenId uint256 ID of the token to be approved - */ - function approve(address _to, uint256 _tokenId) public { - address owner = ownerOf(_tokenId); - require(_to != owner); - require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); - - tokenApprovals[_tokenId] = _to; - emit Approval(owner, _to, _tokenId); - } - - /** - * @dev Gets the approved address for a token ID, or zero if no address set - * @param _tokenId uint256 ID of the token to query the approval of - * @return address currently approved for the given token ID - */ - function getApproved(uint256 _tokenId) public view returns (address) { - return tokenApprovals[_tokenId]; - } - - /** - * @dev Sets or unsets the approval of a given operator - * An operator is allowed to transfer all tokens of the sender on their behalf - * @param _to operator address to set the approval - * @param _approved representing the status of the approval to be set - */ - function setApprovalForAll(address _to, bool _approved) public { - require(_to != msg.sender); - operatorApprovals[msg.sender][_to] = _approved; - emit ApprovalForAll(msg.sender, _to, _approved); - } - - /** - * @dev Tells whether an operator is approved by a given owner - * @param _owner owner address which you want to query the approval of - * @param _operator operator address which you want to query the approval of - * @return bool whether the given operator is approved by the given owner - */ - function isApprovedForAll( - address _owner, - address _operator - ) - public - view - returns (bool) - { - return operatorApprovals[_owner][_operator]; - } - - /** - * @dev Transfers the ownership of a given token ID to another address - * Usage of this method is discouraged, use `safeTransferFrom` whenever possible - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - require(_from != address(0)); - require(_to != address(0)); - - clearApproval(_from, _tokenId); - removeTokenFrom(_from, _tokenId); - addTokenTo(_to, _tokenId); - - emit Transfer(_from, _to, _tokenId); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - // solium-disable-next-line arg-overflow - safeTransferFrom(_from, _to, _tokenId, ""); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes data to send along with a safe transfer check - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public - canTransfer(_tokenId) - { - transferFrom(_from, _to, _tokenId); - // solium-disable-next-line arg-overflow - require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); - } - - /** - * @dev Returns whether the given spender can transfer a given token ID - * @param _spender address of the spender to query - * @param _tokenId uint256 ID of the token to be transferred - * @return bool whether the msg.sender is approved for the given token ID, - * is an operator of the owner, or is the owner of the token - */ - function isApprovedOrOwner( - address _spender, - uint256 _tokenId - ) - internal - view - returns (bool) - { - address owner = ownerOf(_tokenId); - // Disable solium check because of - // https://github.com/duaraghav8/Solium/issues/175 - // solium-disable-next-line operator-whitespace - return ( - _spender == owner || - getApproved(_tokenId) == _spender || - isApprovedForAll(owner, _spender) - ); - } - - /** - * @dev Internal function to clear current approval of a given token ID - * Reverts if the given address is not indeed the owner of the token - * @param _owner owner of the token - * @param _tokenId uint256 ID of the token to be transferred - */ - function clearApproval(address _owner, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _owner); - if (tokenApprovals[_tokenId] != address(0)) { - tokenApprovals[_tokenId] = address(0); - } - } - - /** - * @dev Internal function to mint a new token - * Reverts if the given token ID already exists - * @param _to The address that will own the minted token - * @param _tokenId uint256 ID of the token to be minted by the msg.sender - */ - function _mint(address _to, uint256 _tokenId) internal { - require(_to != address(0)); - addNewTokenTo(_to, _tokenId); - emit Transfer(address(0), _to, _tokenId); - } - - - /** - * @dev Internal function to burn a specific token - * Reverts if the token does not exist - * @param _tokenId uint256 ID of the token being burned by the msg.sender - */ - function _burn(address _owner, uint256 _tokenId) internal { - clearApproval(_owner, _tokenId); - removeTokenFrom(_owner, _tokenId); - emit Transfer(_owner, address(0), _tokenId); - } - - function addNewTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - // ownedTokensCount[_to] = ownedTokensCount[_to].add(1); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _from); - // ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); - tokenOwner[_tokenId] = address(0); - } - - /** - * @dev Internal function to invoke `onERC721Received` on a target address - * The call is not executed if the target address is not a contract - * @param _from address representing the previous owner of the given token ID - * @param _to target address that will receive the tokens - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes optional data to send along with the call - * @return whether the call correctly returned the expected magic value - */ - function checkAndCallSafeTransfer( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - internal - returns (bool) - { - if (!_to.isContract1()) { - return true; - } - bytes4 retval = ERC721Receiver(_to).onERC721Received( - msg.sender, _from, _tokenId, _data); - return (retval == ERC721_RECEIVED); - } - -} - - - -contract ERC721Enumerable is ERC721Basic { - function totalSupply() public view returns (uint256); - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256 _tokenId); - - function tokenByIndex(uint256 _index) public view returns (uint256); -} - -contract ERC721Metadata is ERC721Basic { - function name() external view returns (string memory _name); - function symbol() external view returns (string memory _symbol); - function tokenURI(uint256 _tokenId) public view returns (string memory); -} - -contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { - -} - - - - -library Strings { - - // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory ) { - bytes memory _ba = bytes(_a); - bytes memory _bb = bytes(_b); - bytes memory _bc = bytes(_c); - bytes memory _bd = bytes(_d); - bytes memory _be = bytes(_e); - string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); - bytes memory babcde = bytes(abcde); - uint k = 0; - for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; - for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; - for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; - for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; - for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; - return string(babcde); - } - - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, _d, ""); - } - - function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, "", ""); - } - - function strConcat(string memory _a, string memory _b) internal pure returns (string memory ) { - return strConcat(_a, _b, "", "", ""); - } - - function uint2str(uint i) internal pure returns (string memory ) { - if (i == 0) return "0"; - uint j = i; - uint len; - while (j != 0){ - len++; - j /= 10; - } - bytes memory bstr = new bytes(len); - uint k = len - 1; - while (i != 0){ - bstr[k--] = byte(uint8(48 + i % 10)); - i /= 10; - } - return string(bstr); - } -} - -contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { - - using Strings for string; - - bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; - /** - * 0x780e9d63 === - * bytes4(keccak256('totalSupply()')) ^ - * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ - * bytes4(keccak256('tokenByIndex(uint256)')) - */ - - bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; - /** - * 0x5b5e139f === - * bytes4(keccak256('name()')) ^ - * bytes4(keccak256('symbol()')) ^ - * bytes4(keccak256('tokenURI(uint256)')) - */ - - /*** Constants ***/ - // Configure these for your own deployment - string public constant NAME = "Gods Unchained"; - string public constant SYMBOL = "GODS"; - string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/"; - - // Mapping from owner to list of owned token IDs - // EDITED: limit to 2^40 (around 1T) - mapping(address => uint40[]) internal ownedTokens; - - uint32[] ownedTokensIndex; - - /** - * @dev Constructor function - */ - constructor() public { - - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721Enumerable); - _registerInterface(InterfaceId_ERC721Metadata); - } - - /** - * @dev Gets the token name - * @return string representing the token name - */ - function name() external view returns (string memory) { - return NAME; - } - - /** - * @dev Gets the token symbol - * @return string representing the token symbol - */ - function symbol() external view returns (string memory) { - return SYMBOL; - } - - /** - * @dev Returns an URI for a given token ID - * Throws if the token ID does not exist. May return an empty string. - * @param _tokenId uint256 ID of the token to query - */ - function tokenURI(uint256 _tokenId) public view returns (string memory) { - return Strings.strConcat( - tokenMetadataBaseURI, - Strings.uint2str(_tokenId) - ); - } - - /** - * @dev Gets the token ID at a given index of the tokens list of the requested owner - * @param _owner address owning the tokens list to be accessed - * @param _index uint256 representing the index to be accessed of the requested tokens list - * @return uint256 token ID at the given index of the tokens list owned by the requested address - */ - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256) - { - require(_index < balanceOf(_owner)); - return ownedTokens[_owner][_index]; - } - - /** - * @dev Gets the total amount of tokens stored by the contract - * @return uint256 representing the total amount of tokens - */ - function totalSupply() public view returns (uint256) { - return cards.length; - } - - /** - * @dev Gets the token ID at a given index of all the tokens in this contract - * Reverts if the index is greater or equal to the total number of tokens - * @param _index uint256 representing the index to be accessed of the tokens list - * @return uint256 token ID at the given index of the tokens list - */ - function tokenByIndex(uint256 _index) public view returns (uint256) { - require(_index < totalSupply()); - return _index; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - super.addTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - - ownedTokensIndex[_tokenId] = uint32(length); - } - - // EDITED - // have to have in order to use array rather than mapping - function addNewTokenTo(address _to, uint256 _tokenId) internal { - super.addNewTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - ownedTokensIndex.push(uint32(length)); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - super.removeTokenFrom(_from, _tokenId); - - uint32 tokenIndex = ownedTokensIndex[_tokenId]; - uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); - uint40 lastToken = ownedTokens[_from][lastTokenIndex]; - - ownedTokens[_from][tokenIndex] = lastToken; - ownedTokens[_from][lastTokenIndex] = 0; - // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to - // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping - // the lastToken to the first position, and then dropping the element placed in the last position of the list - - ownedTokens[_from].length--; - ownedTokensIndex[_tokenId] = 0; - ownedTokensIndex[lastToken] = tokenIndex; - } - - /** - * @dev Gets the balance of the specified address - overrriden from previous to save gas - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256) { - return ownedTokens[_owner].length; - } - -} - -contract CardOwnershipTwo is ERC721Token { - - uint public burnCount; - - function getActiveCards() public view returns (uint) { - return totalSupply() - burnCount; - } - - /** - * @param to : the address to which the card will be transferred - * @param id : the id of the card to be transferred - */ - function transfer(address to, uint id) public payable onlyOwnerOf(id) { - require(isTradable(cards[id].proto)); - require(to != address(0)); - - _transfer(msg.sender, to, id); - } - - function _transfer(address from, address to, uint id) internal { - - clearApproval(from, id); - - removeTokenFrom(from, id); - - addTokenTo(to, id); - - emit Transfer(from, to, id); - } - - /** - * @param to : the address to which the cards will be transferred - * @param ids : the ids of the cards to be transferred - */ - function transferAll(address to, uint[] memory ids) public payable { - for (uint i = 0; i < ids.length; i++) { - transfer(to, ids[i]); - } - } - - /** - * @param proposed : the claimed owner of the cards - * @param ids : the ids of the cards to check - * @return whether proposed owns all of the cards - */ - function ownsAll(address proposed, uint[] memory ids) public view returns (bool) { - require(ids.length > 0); - for (uint i = 0; i < ids.length; i++) { - if (!owns(proposed, ids[i])) { - return false; - } - } - return true; - } - - /** - * @param proposed : the claimed owner of the card - * @param id : the id of the card to check - * @return whether proposed owns the card - */ - function owns(address proposed, uint id) public view returns (bool) { - return ownerOf(id) == proposed; - } - - function burn(uint id) public onlyOwnerOf(id) { - burnCount++; - _burn(msg.sender, id); - } - - /** - * @param ids : the indices of the tokens to burn - */ - function burnAll(uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++){ - burn(ids[i]); - } - } - - /** - * @param to : the address to approve for transfer - * @param id : the index of the card to be approved - */ - function approve(address to, uint id) public { - require(isTradable(cards[id].proto)); - super.approve(to, id); - } - - /** - * @param to : the address to approve for transfer - * @param ids : the indices of the cards to be approved - */ - function approveAll(address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - approve(to, ids[i]); - } - } - - /** - * @param to : the address to which the token should be transferred - * @param id : the index of the token to transfer - */ - function transferFrom(address from, address to, uint id) public { - require(isTradable(cards[id].proto)); - super.transferFrom(from, to, id); - } - - /** - * @param to : the address to which the tokens should be transferred - * @param ids : the indices of the tokens to transfer - */ - function transferAllFrom(address from, address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - transferFrom(from, to, ids[i]); - } - } - - /** - * @return the number of cards which have been burned - */ - function getBurnCount() public view returns (uint) { - return burnCount; - } - -} - -contract CardIntegrationTwo is CardOwnershipTwo { - - address[] public packs; - - event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); - - function addPack(address approved) public onlyGovernor { - packs.push(approved); - } - - modifier onlyApprovedPacks { - require(_isApprovedPack()); - _; - } - - function _isApprovedPack() private view returns (bool) { - for (uint i = 0; i < packs.length; i++) { - if (msg.sender == address(packs[i])) { - return true; - } - } - return false; - } - - function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { - ProtoCard memory card = protos[proto]; - require(card.season == currentSeason); - if (card.rarity == Rarity.Mythic) { - uint64 limit; - bool exists; - (limit, exists) = getLimit(proto); - require(!exists || limit > 0); - limits[proto].limit--; - } - return _createCard(owner, proto, purity); - } - - function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { - Card memory card = Card({ - proto: proto, - purity: purity - }); - - uint id = cards.push(card) - 1; - - _mint(owner, id); - - emit CardCreated(id, proto, purity, owner); - - return id; - } - - /*function combineCards(uint[] ids) public whenNotPaused { - require(ids.length == 5); - require(ownsAll(msg.sender, ids)); - Card memory first = cards[ids[0]]; - uint16 proto = first.proto; - uint8 shine = _getShine(first.purity); - require(shine < shineLimit); - uint16 puritySum = first.purity - (shine * 1000); - burn(ids[0]); - for (uint i = 1; i < ids.length; i++) { - Card memory next = cards[ids[i]]; - require(next.proto == proto); - require(_getShine(next.purity) == shine); - puritySum += (next.purity - (shine * 1000)); - burn(ids[i]); - } - uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); - _createCard(msg.sender, proto, newPurity); - }*/ - - - // PURITY NOTES - // currently, we only - // however, to protect rarity, you'll never be abl - // this is enforced by the restriction in the create-card function - // no cards above this point can be found in packs - - - -} - -contract PreviousInterface { - - function ownerOf(uint id) public view returns (address); - - function getCard(uint id) public view returns (uint16, uint16); - - function totalSupply() public view returns (uint); - - function burnCount() public view returns (uint); - -} - -contract CardMigration is CardIntegrationTwo { - - constructor(PreviousInterface previous) public { - old = previous; - } - - // use interface to lower deployment cost - PreviousInterface old; - - mapping(uint => bool) public migrated; - - function migrate(uint id) public { - - require(!migrated[id]); - - migrated[id] = true; - - address owner = old.ownerOf(id); - - uint16 proto; - uint16 purity; - - (proto, purity) = old.getCard(id); - - _createCard(owner, proto, purity); - } - - function migrateAll(uint[] memory ids) public { - - for (uint i = 0; i < ids.length; i++){ - migrate(ids[i]); - } - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario008.sol b/framework/src/test/resources/soliditycode/contractScenario008.sol deleted file mode 100644 index 0dbed350e4c..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario008.sol +++ /dev/null @@ -1,2061 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() virtual public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer1(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer1(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(block.timestamp), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - kitties.push(_kitty); - uint256 newKittenId = kitties.length - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -abstract contract ERC721 { - // Required methods - function totalSupply() virtual public view returns (uint256 total); - function balanceOf(address _owner) virtual public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) virtual external view returns (address owner); - function approve(address _to, uint256 _tokenId) virtual external; - function transfer(address _to, uint256 _tokenId) virtual external; - function transferFrom(address _from, address _to, uint256 _tokenId) virtual external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) virtual external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external override view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public override view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() override public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - override - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - payable(msg.sender).transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - payable(msg.sender) - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - payable(msg.sender) - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid{value:(msg.value - autoBirthFee)}(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - payable(address(uint160(address(this)))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(int256(-1)), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - -/// @notice No tipping! -/// @dev Reject all Ether from being sent here, unless it's from one of the -/// two auction contracts. (Hopefully, we can prevent user accidents.) -fallback() external payable { -require( -msg.sender == address(saleAuction) || -msg.sender == address(siringAuction) -); -} - -/// @notice Returns all the relevant information about a specific kitty. -/// @param _id The ID of the kitty of interest. -function getKitty(uint256 _id) -external -view -returns ( -bool isGestating, -bool isReady, -uint256 cooldownIndex, -uint256 nextActionAt, -uint256 siringWithId, -uint256 birthTime, -uint256 matronId, -uint256 sireId, -uint256 generation, -uint256 genes -) { -Kitty storage kit = kitties[_id]; - -// if this variable is 0 then it's not gestating -isGestating = (kit.siringWithId != 0); -isReady = (kit.cooldownEndBlock <= block.number); -cooldownIndex = uint256(kit.cooldownIndex); -nextActionAt = uint256(kit.cooldownEndBlock); -siringWithId = uint256(kit.siringWithId); -birthTime = uint256(kit.birthTime); -matronId = uint256(kit.matronId); -sireId = uint256(kit.sireId); -generation = uint256(kit.generation); -genes = kit.genes; -} - -/// @dev Override unpause so it requires all external contract addresses -/// to be set before contract can be unpaused. Also, we can't have -/// newContractAddress set either, because then the contract was upgraded. -/// @notice This is public rather than external so we can call super.unpause -/// without using an expensive CALL. - -function unpause() override public onlyCEO whenPaused { -require(address(saleAuction) != address(0)); -require(address(siringAuction) != address(0)); -require(address(geneScience) != address(0)); -require(newContractAddress == address(0)); - -// Actually unpause the contract. -super.unpause(); -} - -// @dev Allows the CFO to capture the balance available to the contract. -function withdrawBalance() external onlyCFO { -uint256 balance = address(this).balance; -// Subtract all the currently pregnant kittens we have, plus 1 of margin. -uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - -if (balance > subtractFees) { -cfoAddress.transfer(balance - subtractFees); -} -} -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - -function isGeneScience() public pure returns (bool){ -return true; -} - -/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor -/// @param genes1 genes of mom -/// @param genes2 genes of sire -/// @return the genes that are supposed to be passed down the child -function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - -return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { -/// @dev Given a token Id, returns a byte array that is supposed to be converted into string. -function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { -if (_tokenId == 1) { -buffer[0] = "Hello World! :D"; -count = 15; -} else if (_tokenId == 2) { -buffer[0] = "I would definitely choose a medi"; -buffer[1] = "um length string."; -count = 49; -} else if (_tokenId == 3) { -buffer[0] = "Lorem ipsum dolor sit amet, mi e"; -buffer[1] = "st accumsan dapibus augue lorem,"; -buffer[2] = " tristique vestibulum id, libero"; -buffer[3] = " suscipit varius sapien aliquam."; -count = 128; -} -} -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - -// Represents an auction on an NFT -struct Auction { -// Current owner of NFT -address payable seller; -// Price (in wei) at beginning of auction -uint128 startingPrice; -// Price (in wei) at end of auction -uint128 endingPrice; -// Duration (in seconds) of auction -uint64 duration; -// Time when auction started -// NOTE: 0 if this auction has been concluded -uint64 startedAt; -} - -// Reference to contract tracking NFT ownership -ERC721 public nonFungibleContract; - -// Cut owner takes on each auction, measured in basis points (1/100 of a percent). -// Values 0-10,000 map to 0%-100% -uint256 public ownerCut; - -// Map from token ID to their corresponding auction. -mapping (uint256 => Auction) tokenIdToAuction; - -event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); -event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); -event AuctionCancelled(uint256 tokenId); - -/// @dev Returns true if the claimant owns the token. -/// @param _claimant - Address claiming to own the token. -/// @param _tokenId - ID of token whose ownership to verify. -function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { -return (nonFungibleContract.ownerOf(_tokenId) == _claimant); -} - -/// @dev Escrows the NFT, assigning ownership to this contract. -/// Throws if the escrow fails. -/// @param _owner - Current owner address of token to escrow. -/// @param _tokenId - ID of token whose approval to verify. -function _escrow(address _owner, uint256 _tokenId) internal { -// it will throw if transfer fails -nonFungibleContract.transferFrom(_owner, address(this), _tokenId); -} - -/// @dev Transfers an NFT owned by this contract to another address. -/// Returns true if the transfer succeeds. -/// @param _receiver - Address to transfer NFT to. -/// @param _tokenId - ID of token to transfer. -function _transfer(address _receiver, uint256 _tokenId) internal { -// it will throw if transfer fails -nonFungibleContract.transfer(_receiver, _tokenId); -} - -/// @dev Adds an auction to the list of open auctions. Also fires the -/// AuctionCreated event. -/// @param _tokenId The ID of the token to be put on auction. -/// @param _auction Auction to add. -function _addAuction(uint256 _tokenId, Auction memory _auction) internal { -// Require that all auctions have a duration of -// at least one minute. (Keeps our math from getting hairy!) -require(_auction.duration >= 1 minutes); - -tokenIdToAuction[_tokenId] = _auction; - -emit AuctionCreated( -uint256(_tokenId), -uint256(_auction.startingPrice), -uint256(_auction.endingPrice), -uint256(_auction.duration) -); -} - -/// @dev Cancels an auction unconditionally. -function _cancelAuction(uint256 _tokenId, address _seller) internal { -_removeAuction(_tokenId); -_transfer(_seller, _tokenId); -emit AuctionCancelled(_tokenId); -} - -/// @dev Computes the price and transfers winnings. -/// Does NOT transfer ownership of token. -function _bid(uint256 _tokenId, uint256 _bidAmount) -internal -returns (uint256) -{ -// Get a reference to the auction struct -Auction storage auction = tokenIdToAuction[_tokenId]; - -// Explicitly check that this auction is currently live. -// (Because of how Ethereum mappings work, we can't just count -// on the lookup above failing. An invalid _tokenId will just -// return an auction object that is all zeros.) -require(_isOnAuction(auction)); - -// Check that the bid is greater than or equal to the current price -uint256 price = _currentPrice(auction); -require(_bidAmount >= price); - -// Grab a reference to the seller before the auction struct -// gets deleted. -address payable seller = auction.seller; - -// The bid is good! Remove the auction before sending the fees -// to the sender so we can't have a reentrancy attack. -_removeAuction(_tokenId); - -// Transfer proceeds to seller (if there are any!) -if (price > 0) { -// Calculate the auctioneer's cut. -// (NOTE: _computeCut() is guaranteed to return a -// value <= price, so this subtraction can't go negative.) -uint256 auctioneerCut = _computeCut(price); -uint256 sellerProceeds = price - auctioneerCut; - -// NOTE: Doing a transfer() in the middle of a complex -// method like this is generally discouraged because of -// reentrancy attacks and DoS attacks if the seller is -// a contract with an invalid fallback function. We explicitly -// guard against reentrancy attacks by removing the auction -// before calling transfer(), and the only thing the seller -// can DoS is the sale of their own asset! (And if it's an -// accident, they can call cancelAuction(). ) -seller.transfer(sellerProceeds); -} - -// Calculate any excess funds included with the bid. If the excess -// is anything worth worrying about, transfer it back to bidder. -// NOTE: We checked above that the bid amount is greater than or -// equal to the price so this cannot underflow. -uint256 bidExcess = _bidAmount - price; - -// Return the funds. Similar to the previous transfer, this is -// not susceptible to a re-entry attack because the auction is -// removed before any transfers occur. - payable(msg.sender).transfer(bidExcess); - -// Tell the world! -emit AuctionSuccessful(_tokenId, price, msg.sender); - -return price; -} - -/// @dev Removes an auction from the list of open auctions. -/// @param _tokenId - ID of NFT on auction. -function _removeAuction(uint256 _tokenId) internal { -delete tokenIdToAuction[_tokenId]; -} - -/// @dev Returns true if the NFT is on auction. -/// @param _auction - Auction to check. -function _isOnAuction(Auction storage _auction) internal view returns (bool) { -return (_auction.startedAt > 0); -} - -/// @dev Returns current price of an NFT on auction. Broken into two -/// functions (this one, that computes the duration from the auction -/// structure, and the other that does the price computation) so we -/// can easily test that the price computation works correctly. -function _currentPrice(Auction storage _auction) -internal -view -returns (uint256) -{ -uint256 secondsPassed = 0; - -// A bit of insurance against negative values (or wraparound). -// Probably not necessary (since Ethereum guarnatees that the -// now variable doesn't ever go backwards). -if (block.timestamp > _auction.startedAt) { -secondsPassed = block.timestamp - _auction.startedAt; -} - -return _computeCurrentPrice( -_auction.startingPrice, -_auction.endingPrice, -_auction.duration, -secondsPassed -); -} - -/// @dev Computes the current price of an auction. Factored out -/// from _currentPrice so we can run extensive unit tests. -/// When testing, make this function public and turn on -/// `Current price computation` test suite. -function _computeCurrentPrice( -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -uint256 _secondsPassed -) -internal -pure -returns (uint256) -{ -// NOTE: We don't use SafeMath (or similar) in this function because -// all of our public functions carefully cap the maximum values for -// time (at 64-bits) and currency (at 128-bits). _duration is -// also known to be non-zero (see the require() statement in -// _addAuction()) -if (_secondsPassed >= _duration) { -// We've reached the end of the dynamic pricing portion -// of the auction, just return the end price. -return _endingPrice; -} else { -// Starting price can be higher than ending price (and often is!), so -// this delta can be negative. -int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - -// This multiplication can't overflow, _secondsPassed will easily fit within -// 64-bits, and totalPriceChange will easily fit within 128-bits, their product -// will always fit within 256-bits. -int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - -// currentPriceChange can be negative, but if so, will have a magnitude -// less that _startingPrice. Thus, this result will always end up positive. -int256 currentPrice = int256(_startingPrice) + currentPriceChange; - -return uint256(currentPrice); -} -} - -/// @dev Computes owner's cut of a sale. -/// @param _price - Sale price of NFT. -function _computeCut(uint256 _price) internal view returns (uint256) { -// NOTE: We don't use SafeMath (or similar) in this function because -// all of our entry functions carefully cap the maximum values for -// currency (at 128-bits), and ownerCut <= 10000 (see the require() -// statement in the ClockAuction constructor). The result of this -// function is always guaranteed to be <= _price. -return _price * ownerCut / 10000; -} - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { -event Pause(); -event Unpause(); - -bool public paused = false; - - -/** - * @dev modifier to allow actions only when the contract IS paused - */ -modifier whenNotPaused() { -require(!paused); -_; -} - -/** - * @dev modifier to allow actions only when the contract IS NOT paused - */ -modifier whenPaused { -require(paused); -_; -} - -/** - * @dev called by the owner to pause, triggers stopped state - */ -function pause() onlyOwner whenNotPaused public returns (bool) { -paused = true; -emit Pause(); -return true; -} - -/** - * @dev called by the owner to unpause, returns to normal state - */ -function unpause() onlyOwner whenPaused public returns (bool) { -paused = false; -emit Unpause(); -return true; -} -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - -/// @dev The ERC-165 interface signature for ERC-721. -/// Ref: https://github.com/ethereum/EIPs/issues/165 -/// Ref: https://github.com/ethereum/EIPs/issues/721 -bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - -/// @dev Constructor creates a reference to the NFT ownership contract -/// and verifies the owner cut is in the valid range. -/// @param _nftAddress - address of a deployed contract implementing -/// the Nonfungible Interface. -/// @param _cut - percent cut the owner takes on each auction, must be -/// between 0-10,000. -constructor(address _nftAddress, uint256 _cut) public { -require(_cut <= 10000); -ownerCut = _cut; - -ERC721 candidateContract = ERC721(_nftAddress); -require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); -nonFungibleContract = candidateContract; -} - -/// @dev Remove all Ether from the contract, which is the owner's cuts -/// as well as any Ether sent directly to the contract address. -/// Always transfers to the NFT contract, but can be called either by -/// the owner or the NFT contract. -function withdrawBalance() external { -address payable nftAddress = payable(address(uint160(address(nonFungibleContract)))); - -require( -msg.sender == owner || -msg.sender == nftAddress -); -// We are using this boolean method to make sure that even if one fails it will still work -bool res = nftAddress.send(address(this).balance); -} - -/// @dev Creates and begins a new auction. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of time to move between starting -/// price and ending price (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -virtual -external -whenNotPaused -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(_owns(msg.sender, _tokenId)); -_escrow(msg.sender, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(block.timestamp) -); -_addAuction(_tokenId, auction); -} - -/// @dev Bids on an open auction, completing the auction and transferring -/// ownership of the NFT if enough Ether is supplied. -/// @param _tokenId - ID of token to bid on. -function bid(uint256 _tokenId) -external -payable -whenNotPaused -virtual -{ -// _bid will throw if the bid or funds transfer fails -_bid(_tokenId, msg.value); -_transfer(msg.sender, _tokenId); -} - -/// @dev Cancels an auction that hasn't been won yet. -/// Returns the NFT to original owner. -/// @notice This is a state-modifying function that can -/// be called while the contract is paused. -/// @param _tokenId - ID of token on auction -function cancelAuction(uint256 _tokenId) -external -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -address seller = auction.seller; -require(msg.sender == seller); -_cancelAuction(_tokenId, seller); -} - -/// @dev Cancels an auction when the contract is paused. -/// Only the owner may do this, and NFTs are returned to -/// the seller. This should only be used in emergencies. -/// @param _tokenId - ID of the NFT on auction to cancel. -function cancelAuctionWhenPaused(uint256 _tokenId) -whenPaused -onlyOwner -external -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -_cancelAuction(_tokenId, auction.seller); -} - -/// @dev Returns auction info for an NFT on auction. -/// @param _tokenId - ID of NFT on auction. -function getAuction(uint256 _tokenId) -external -view -returns -( -address seller, -uint256 startingPrice, -uint256 endingPrice, -uint256 duration, -uint256 startedAt -) { -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -return ( -auction.seller, -auction.startingPrice, -auction.endingPrice, -auction.duration, -auction.startedAt -); -} - -/// @dev Returns the current price of an auction. -/// @param _tokenId - ID of the token price we are checking. -function getCurrentPrice(uint256 _tokenId) -external -view -returns (uint256) -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -return _currentPrice(auction); -} - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - -// @dev Sanity check that allows us to ensure that we are pointing to the -// right auction in our setSiringAuctionAddress() call. -bool public isSiringClockAuction = true; - -// Delegate constructor -constructor(address _nftAddr, uint256 _cut) public -ClockAuction(_nftAddr, _cut) {} - -/// @dev Creates and begins a new auction. Since this function is wrapped, -/// require sender to be KittyCore contract. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of auction (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -override -external -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(msg.sender == address(nonFungibleContract)); -_escrow(_seller, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(block.timestamp) -); -_addAuction(_tokenId, auction); -} - -/// @dev Places a bid for siring. Requires the sender -/// is the KittyCore contract because all bid methods -/// should be wrapped. Also returns the kitty to the -/// seller rather than the winner. -function bid(uint256 _tokenId) -external -payable -override -{ -require(msg.sender == address(nonFungibleContract)); -address seller = tokenIdToAuction[_tokenId].seller; -// _bid checks that token ID is valid and will throw if bid fails -_bid(_tokenId, msg.value); -// We transfer the kitty back to the seller, the winner will get -// the offspring -_transfer(seller, _tokenId); -} - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - -// @dev Sanity check that allows us to ensure that we are pointing to the -// right auction in our setSaleAuctionAddress() call. -bool public isSaleClockAuction = true; - -// Tracks last 5 sale price of gen0 kitty sales -uint256 public gen0SaleCount; -uint256[5] public lastGen0SalePrices; - -// Delegate constructor -constructor(address _nftAddr, uint256 _cut) public -ClockAuction(_nftAddr, _cut) {} - -/// @dev Creates and begins a new auction. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of auction (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -override -external -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(msg.sender == address(nonFungibleContract)); -_escrow(_seller, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(block.timestamp) -); -_addAuction(_tokenId, auction); -} - -/// @dev Updates lastSalePrice if seller is the nft contract -/// Otherwise, works the same as default bid method. -function bid(uint256 _tokenId) -external -override -payable -{ -// _bid verifies token ID size -address seller = tokenIdToAuction[_tokenId].seller; -uint256 price = _bid(_tokenId, msg.value); -_transfer(msg.sender, _tokenId); - -// If not a gen0 auction, exit -if (seller == address(nonFungibleContract)) { -// Track gen0 sale prices -lastGen0SalePrices[gen0SaleCount % 5] = price; -gen0SaleCount++; -} -} - -function averageGen0SalePrice() external view returns (uint256) { -uint256 sum = 0; -for (uint256 i = 0; i < 5; i++) { -sum += lastGen0SalePrices[i]; -} -return sum / 5; -} - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode/contractScenario009.sol b/framework/src/test/resources/soliditycode/contractScenario009.sol deleted file mode 100644 index 52fa63e90ac..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario009.sol +++ /dev/null @@ -1,51 +0,0 @@ - - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert (Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register(uint value) public { - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario010.sol b/framework/src/test/resources/soliditycode/contractScenario010.sol deleted file mode 100644 index 4e299efecad..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario010.sol +++ /dev/null @@ -1,107 +0,0 @@ - - -contract TRON_ERC721 { - //name - function name() view public returns (string memory name){ - return "Tron ERC721 Token"; - } - //symbol - function symbol() view public returns (string memory symbol){ - return "T721T"; - } - - //totalSupply - - function totalSupply() view public returns (uint256 supply){ - uint256 totalSupply = 1000000000000; - return totalSupply; - } - - mapping(address => uint) private balances; - function balanceOf(address _owner) view public returns (uint balance) - { - return balances[_owner]; - } - - - mapping(uint256 => address) private tokenOwners; - mapping(uint256 => bool) private tokenExists; - function ownerOf(uint256 _tokenId) view public returns (address owner) { - require(tokenExists[_tokenId]); - return tokenOwners[_tokenId]; - } - - - mapping(address => mapping (address => uint256)) allowed; - function approve(address _to, uint256 _tokenId) public{ - require(msg.sender == ownerOf(_tokenId)); - require(msg.sender != _to); - allowed[msg.sender][_to] = _tokenId; - emit Approval(msg.sender, _to, _tokenId); - } - - - function takeOwnership(uint256 _tokenId) public { - require(tokenExists[_tokenId]); - address oldOwner = ownerOf(_tokenId); - address newOwner = msg.sender; - require(newOwner != oldOwner); - require(allowed[oldOwner][newOwner] == _tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - mapping(address => mapping(uint256 => uint256)) private ownerTokens; - function removeFromTokenList(address owner, uint256 _tokenId) private { - for(uint256 i = 0;ownerTokens[owner][i] != _tokenId;i++){ - ownerTokens[owner][i] = 0; - } - } - - function transfer(address _to, uint256 _tokenId) public{ - address currentOwner = msg.sender; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - function transferFrom(address _from,address _to, uint256 _tokenId) public{ - address currentOwner = _from; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - function tokenOfOwnerByIndex(address _owner, uint256 _index) view public returns (uint tokenId){ - return ownerTokens[_owner][_index]; - } - - - mapping(uint256 => string) tokenLinks; - function tokenMetadata(uint256 _tokenId) view public returns (string memory infoUrl) { - return tokenLinks[_tokenId]; - } - // Events - event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); - event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario011.sol b/framework/src/test/resources/soliditycode/contractScenario011.sol deleted file mode 100644 index c0d30e8ebab..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario011.sol +++ /dev/null @@ -1,2060 +0,0 @@ - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public virtual onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer1(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer1(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(block.timestamp), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - kitties.push(_kitty); - uint256 newKittenId = kitties.length - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -abstract contract ERC721 { - // Required methods - function totalSupply() public virtual view returns (uint256 total); - function balanceOf(address _owner) public virtual view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external virtual view returns (address owner); - function approve(address _to, uint256 _tokenId) external virtual; - function transfer(address _to, uint256 _tokenId) external virtual; - function transferFrom(address _from, address _to, uint256 _tokenId) external virtual; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external virtual view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external override view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view override returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - override - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - override - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public override view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - override - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 ; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - payable(msg.sender).transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - payable(msg.sender) - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - payable(msg.sender) - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid{value : (msg.value - autoBirthFee)}(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 ; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - payable(address(uint160(address(this)))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(int256(-1)), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause() public override onlyCEO whenPaused { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - - } -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - payable(msg.sender).transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (block.timestamp > _auction.startedAt) { - secondsPassed = block.timestamp - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = payable(address(uint160(address(nonFungibleContract)))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - virtual - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(block.timestamp) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - virtual - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - override - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(block.timestamp) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - override - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - override - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(block.timestamp) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - override - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode/contractScenario012.sol b/framework/src/test/resources/soliditycode/contractScenario012.sol deleted file mode 100644 index ae6882685a8..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario012.sol +++ /dev/null @@ -1,57 +0,0 @@ - -contract PayTest { - -uint256 public n; -constructor() payable public{ -n = 0; -} - -function nPlusOne() public{ -n = n+1; -} - -//get current contract balance -function getBalance() payable public returns (uint) { -return address(this).balance; -} - -function getSenderBalance() public view returns(address, uint) { -return (msg.sender, msg.sender.balance); -} - -address public user; - -//deposit 1 coin to msg.sender -function depositOneCoin() payable public returns(bool success){ -return payable(msg.sender).send(1); -} - -// function transferOneCoin() payable public returns(){ -// address(msg.sender).transfer(1); -// } - -// function depositOneCoin() payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(1)); -// } - -//deposit coin to msg.sender -function deposit(uint256 money) payable public returns(bool success){ -return payable(msg.sender).send(money); -} -// function deposit(uint money) payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(money)); -// } - -// fallback() payable { -// msg.sender.send(1); -// } - -function sendToAddress(address payable _receiver) payable public{ -_receiver.transfer(msg.value); -} - -function sendToAddress2(address payable _receiver) payable public{ -_receiver.transfer(5); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario013.sol b/framework/src/test/resources/soliditycode/contractScenario013.sol deleted file mode 100644 index 93b7905679b..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario013.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract timetest { - -function time() public{ -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractScenario014.sol b/framework/src/test/resources/soliditycode/contractScenario014.sol deleted file mode 100644 index 9f423d1b1ab..00000000000 --- a/framework/src/test/resources/soliditycode/contractScenario014.sol +++ /dev/null @@ -1,34 +0,0 @@ - -contract Contract1 { - constructor() public payable{} - function send5SunToReceiver(address payable _receiver) payable public{ - _receiver.transfer(5); - } -} -contract contract2 { - address public payContract; - - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract1(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - } - - function triggerContract1ButRevert(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - require(1 == 2); - } - -} -contract contract3 { - address public payContract; - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract2(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("triggerContract1(address)",_receiver)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTest.sol b/framework/src/test/resources/soliditycode/contractTest.sol deleted file mode 100644 index 9a72b4a53b4..00000000000 --- a/framework/src/test/resources/soliditycode/contractTest.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract Test{ - -function a() public returns (uint){ - -uint256 count = 0; - -for (uint256 i = 1; i > 0; i++) { - -count++; - -} - -return count; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode/contractToMathedFeed.sol deleted file mode 100644 index d9df9d9c10d..00000000000 --- a/framework/src/test/resources/soliditycode/contractToMathedFeed.sol +++ /dev/null @@ -1,21 +0,0 @@ - - -contract ToMathedFeed { - uint public i=1; - function ToMathed (uint value) public { - i=value; - } -} - -contract ToMathedUseINContract { - function ToMathedIUseNR(address a,uint256 n) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathedNot(uint256)",n)); - return success; - } - function ToMathedIUseNRE(address a,uint256 value) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathed(uint256)",value)); - return success; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTransferToken001.sol b/framework/src/test/resources/soliditycode/contractTransferToken001.sol deleted file mode 100644 index 0edbbfbb44a..00000000000 --- a/framework/src/test/resources/soliditycode/contractTransferToken001.sol +++ /dev/null @@ -1,22 +0,0 @@ -contract A { - address public a; - constructor() public payable{} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - function newB() public payable returns(address){ - B bAddress=new B(); - a= address(bAddress); - return a; - - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrc1155.sol b/framework/src/test/resources/soliditycode/contractTrc1155.sol deleted file mode 100644 index c33d07b3dfc..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrc1155.sol +++ /dev/null @@ -1,612 +0,0 @@ -pragma solidity ^0.8.0; - -interface IERC165 { - - function supportsInterface(bytes4 interfaceId) external view returns (bool); -} - - - -abstract contract ERC165 is IERC165 { - - function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { - return interfaceId == type(IERC165).interfaceId; - } -} - -interface IERC1155 is IERC165 { - - event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); - - - event TransferBatch( - address indexed operator, - address indexed from, - address indexed to, - uint256[] ids, - uint256[] values - ); - - - event ApprovalForAll(address indexed account, address indexed operator, bool approved); - - - event URI(string value, uint256 indexed id); - - - function balanceOf(address account, uint256 id) external view returns (uint256); - - - function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) - external - view - returns (uint256[] memory); - - - function setApprovalForAll(address operator, bool approved) external; - - - function isApprovedForAll(address account, address operator) external view returns (bool); - - - function safeTransferFrom( - address from, - address to, - uint256 id, - uint256 amount, - bytes calldata data - ) external; - - function safeBatchTransferFrom( - address from, - address to, - uint256[] calldata ids, - uint256[] calldata amounts, - bytes calldata data - ) external; -} - - -abstract contract Context { - function _msgSender() internal view virtual returns (address) { - return msg.sender; - } - - function _msgData() internal view virtual returns (bytes calldata) { - return msg.data; - } -} - - -library Address { - - - function isAContract(address account) internal view returns (bool) { - // This method relies on extcodesize, which returns 0 for contracts in - // construction, since the code is only stored at the end of the - // constructor execution. - - uint256 size; - assembly { - size := extcodesize(account) - } - return size > 0; - } - - - function sendValue(address payable recipient, uint256 amount) internal { - require(address(this).balance >= amount, "Address: insufficient balance"); - - (bool success, ) = recipient.call{value: amount}(""); - require(success, "Address: unable to send value, recipient may have reverted"); - } - - - function functionCall(address target, bytes memory data) internal returns (bytes memory) { - return functionCall(target, data, "Address: low-level call failed"); - } - - - function functionCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - return functionCallWithValue(target, data, 0, errorMessage); - } - - - function functionCallWithValue( - address target, - bytes memory data, - uint256 value - ) internal returns (bytes memory) { - return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); - } - - function functionCallWithValue( - address target, - bytes memory data, - uint256 value, - string memory errorMessage - ) internal returns (bytes memory) { - require(address(this).balance >= value, "Address: insufficient balance for call"); - require(isAContract(target), "Address: call to non-contract"); - - (bool success, bytes memory returndata) = target.call{value: value}(data); - return verifyCallResult(success, returndata, errorMessage); - } - - - function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { - return functionStaticCall(target, data, "Address: low-level static call failed"); - } - - - function functionStaticCall( - address target, - bytes memory data, - string memory errorMessage - ) internal view returns (bytes memory) { - require(isAContract(target), "Address: static call to non-contract"); - - (bool success, bytes memory returndata) = target.staticcall(data); - return verifyCallResult(success, returndata, errorMessage); - } - - - function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { - return functionDelegateCall(target, data, "Address: low-level delegate call failed"); - } - - - function functionDelegateCall( - address target, - bytes memory data, - string memory errorMessage - ) internal returns (bytes memory) { - require(isAContract(target), "Address: delegate call to non-contract"); - - (bool success, bytes memory returndata) = target.delegatecall(data); - return verifyCallResult(success, returndata, errorMessage); - } - - function verifyCallResult( - bool success, - bytes memory returndata, - string memory errorMessage - ) internal pure returns (bytes memory) { - if (success) { - return returndata; - } else { - // Look for revert reason and bubble it up if present - if (returndata.length > 0) { - // The easiest way to bubble the revert reason is using memory via assembly - - assembly { - let returndata_size := mload(returndata) - revert(add(32, returndata), returndata_size) - } - } else { - revert(errorMessage); - } - } - } -} - - -interface IERC1155MetadataURI is IERC1155 { - - function uri(uint256 id) external view returns (string memory); -} - - - - -interface IERC1155Receiver is IERC165 { - - function onERC1155Received( - address operator, - address from, - uint256 id, - uint256 value, - bytes calldata data - ) external returns (bytes4); - - - function onERC1155BatchReceived( - address operator, - address from, - uint256[] calldata ids, - uint256[] calldata values, - bytes calldata data - ) external returns (bytes4); -} - - -contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI { - using Address for address; - - // Mapping from token ID to account balances - mapping(uint256 => mapping(address => uint256)) private _balances; - - // Mapping from account to operator approvals - mapping(address => mapping(address => bool)) private _operatorApprovals; - - // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json - string private _uri; - - /** - * @dev See {_setURI}. - */ - constructor(string memory uri_) { - _setURI(uri_); - } - - /** - * @dev See {IERC165-supportsInterface}. - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return - interfaceId == type(IERC1155).interfaceId || - interfaceId == type(IERC1155MetadataURI).interfaceId || - super.supportsInterface(interfaceId); - } - - - function uri(uint256 id) public view virtual override returns (string memory) { - return _uri; - } - - function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { - require(account != address(0), "ERC1155: balance query for the zero address"); - return _balances[id][account]; - } - - - function balanceOfBatch(address[] memory accounts, uint256[] memory ids) - public - view - virtual - override - returns (uint256[] memory) - { - require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); - - uint256[] memory batchBalances = new uint256[](accounts.length); - - for (uint256 i = 0; i < accounts.length; ++i) { - batchBalances[i] = balanceOf(accounts[i], ids[i]); - } - - return batchBalances; - } - - - function setApprovalForAll(address operator, bool approved) public virtual override { - _setApprovalForAll(_msgSender(), operator, approved); - } - - - function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { - return _operatorApprovals[account][operator]; - } - - - function safeTransferFrom( - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) public virtual override { - require( - from == _msgSender() || isApprovedForAll(from, _msgSender()), - "ERC1155: caller is not owner nor approved" - ); - _safeTransferFrom(from, to, id, amount, data); - } - - - function safeBatchTransferFrom( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) public virtual override { - require( - from == _msgSender() || isApprovedForAll(from, _msgSender()), - "ERC1155: transfer caller is not owner nor approved" - ); - _safeBatchTransferFrom(from, to, ids, amounts, data); - } - - - function _safeTransferFrom( - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) internal virtual { - require(to != address(0), "ERC1155: transfer to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - _balances[id][to] += amount; - - emit TransferSingle(operator, from, to, id, amount); - - _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); - } - - - function _safeBatchTransferFrom( - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual { - require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); - require(to != address(0), "ERC1155: transfer to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, to, ids, amounts, data); - - for (uint256 i = 0; i < ids.length; ++i) { - uint256 id = ids[i]; - uint256 amount = amounts[i]; - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - _balances[id][to] += amount; - } - - emit TransferBatch(operator, from, to, ids, amounts); - - _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); - } - - - function _setURI(string memory newuri) internal virtual { - _uri = newuri; - } - - - function _mint( - address to, - uint256 id, - uint256 amount, - bytes memory data - ) internal virtual { - require(to != address(0), "ERC1155: mint to the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); - - _balances[id][to] += amount; - emit TransferSingle(operator, address(0), to, id, amount); - - _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); - } - - - function _mintBatch( - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual { - require(to != address(0), "ERC1155: mint to the zero address"); - require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); - - for (uint256 i = 0; i < ids.length; i++) { - _balances[ids[i]][to] += amounts[i]; - } - - emit TransferBatch(operator, address(0), to, ids, amounts); - - _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); - } - - - function _burn( - address from, - uint256 id, - uint256 amount - ) internal virtual { - require(from != address(0), "ERC1155: burn from the zero address"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - - emit TransferSingle(operator, from, address(0), id, amount); - } - - - function _burnBatch( - address from, - uint256[] memory ids, - uint256[] memory amounts - ) internal virtual { - require(from != address(0), "ERC1155: burn from the zero address"); - require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); - - address operator = _msgSender(); - - _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); - - for (uint256 i = 0; i < ids.length; i++) { - uint256 id = ids[i]; - uint256 amount = amounts[i]; - - uint256 fromBalance = _balances[id][from]; - require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); - unchecked { - _balances[id][from] = fromBalance - amount; - } - } - - emit TransferBatch(operator, from, address(0), ids, amounts); - } - - - function _setApprovalForAll( - address owner, - address operator, - bool approved - ) internal virtual { - require(owner != operator, "ERC1155: setting approval status for self"); - _operatorApprovals[owner][operator] = approved; - emit ApprovalForAll(owner, operator, approved); - } - - - function _beforeTokenTransfer( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) internal virtual {} - - function _doSafeTransferAcceptanceCheck( - address operator, - address from, - address to, - uint256 id, - uint256 amount, - bytes memory data - ) private { - if (to.isAContract()) { - try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { - if (response != IERC1155Receiver.onERC1155Received.selector) { - revert("ERC1155: ERC1155Receiver rejected tokens"); - } - } catch Error(string memory reason) { - revert(reason); - } catch { - revert("ERC1155: transfer to non ERC1155Receiver implementer"); - } - } - } - - function _doSafeBatchTransferAcceptanceCheck( - address operator, - address from, - address to, - uint256[] memory ids, - uint256[] memory amounts, - bytes memory data - ) private { - if (to.isAContract()) { - try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( - bytes4 response - ) { - if (response != IERC1155Receiver.onERC1155BatchReceived.selector) { - revert("ERC1155: ERC1155Receiver rejected tokens"); - } - } catch Error(string memory reason) { - revert(reason); - } catch { - revert("ERC1155: transfer to non ERC1155Receiver implementer"); - } - } - } - - function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { - uint256[] memory array = new uint256[](1); - array[0] = element; - - return array; - } - - -} - - -contract TronCoins is ERC1155 { - uint256 public constant TRX = 0; - uint256 public constant BTT = 1; - uint256 public constant WIN = 2; - uint256 public constant SUN = 3; - uint256 public constant APENFT = 4; - uint256 public constant APENFT1 = 5; - - constructor() public ERC1155("https://game.example/api/item/%7Bid%7D.json") { - _mint(msg.sender, TRX, 10**3, ""); - _mint(msg.sender, BTT, 10**2, ""); - _mint(msg.sender, WIN, 10**5, ""); - _mint(msg.sender, SUN, 10**4, ""); - _mint(msg.sender, APENFT, 1, ""); - _mint(msg.sender, APENFT1, 1, ""); - } -} - - -abstract contract ERC1155Receiver is ERC165, IERC1155Receiver { - /** - * @dev See {IERC165-supportsInterface} - */ - function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { - return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); - } -} - - -contract ERC1155Holder is ERC1155Receiver { - function onERC1155Received( - address, - address, - uint256, - uint256, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC1155Received.selector; - } - - function onERC1155BatchReceived( - address, - address, - uint256[] memory, - uint256[] memory, - bytes memory - ) public virtual override returns (bytes4) { - return this.onERC1155BatchReceived.selector; - } -} - - -contract MyContractCanReceiver is ERC1155Holder { -} - - - -contract MyContractCanNotReceiver { -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken001.sol b/framework/src/test/resources/soliditycode/contractTrcToken001.sol deleted file mode 100644 index 4bd83e30229..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken001.sol +++ /dev/null @@ -1,41 +0,0 @@ - - - contract tokenTest{ - - uint pos0; - mapping(address => uint) pos1; - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - Storage(); - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - - - function Storage() public { - pos0 = 1234; - pos1[msg.sender] = 5678; - } - - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken002.sol b/framework/src/test/resources/soliditycode/contractTrcToken002.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken002.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken003.sol b/framework/src/test/resources/soliditycode/contractTrcToken003.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken003.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken005.sol b/framework/src/test/resources/soliditycode/contractTrcToken005.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken005.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken011.sol b/framework/src/test/resources/soliditycode/contractTrcToken011.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken011.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken012.sol b/framework/src/test/resources/soliditycode/contractTrcToken012.sol deleted file mode 100644 index ab0c19767e7..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken012.sol +++ /dev/null @@ -1,26 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken014.sol b/framework/src/test/resources/soliditycode/contractTrcToken014.sol deleted file mode 100644 index 589406c47c6..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken014.sol +++ /dev/null @@ -1,34 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken018.sol b/framework/src/test/resources/soliditycode/contractTrcToken018.sol deleted file mode 100644 index ab0c19767e7..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken018.sol +++ /dev/null @@ -1,26 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken023.sol b/framework/src/test/resources/soliditycode/contractTrcToken023.sol deleted file mode 100644 index 070acb201ff..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken023.sol +++ /dev/null @@ -1,26 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external { - flag = 1; -} - -} - -contract C{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable { - //flag = 1; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken026.sol b/framework/src/test/resources/soliditycode/contractTrcToken026.sol deleted file mode 100644 index 5464265d81f..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken026.sol +++ /dev/null @@ -1,31 +0,0 @@ - - -contract token{ - constructor() payable public{} - fallback() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - //callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - fallback() external payable{} - function transC(address payable callCAddress,address payable toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - fallback() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken027.sol b/framework/src/test/resources/soliditycode/contractTrcToken027.sol deleted file mode 100644 index e7d6ee768f3..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken027.sol +++ /dev/null @@ -1,30 +0,0 @@ - - -contract token{ - constructor() payable public{} - fallback() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - fallback() external payable{} - function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - fallback() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken028.sol b/framework/src/test/resources/soliditycode/contractTrcToken028.sol deleted file mode 100644 index 0f27d89c819..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken028.sol +++ /dev/null @@ -1,25 +0,0 @@ - - -contract token{ - uint256 public a=1; - constructor() public payable{} - function tokenBalanceWithSameName(trcToken id) public payable{ - B b= new B(); - a= b.tokenBalance(id); - } - function getA() public returns(uint256){ - return a; - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - fallback() external payable{} - function tokenBalance(trcToken id) payable public returns(uint256){ - flag =9; - return flag; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken029.sol b/framework/src/test/resources/soliditycode/contractTrcToken029.sol deleted file mode 100644 index 8480cf6f19d..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken029.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract token{ - address public a; - constructor() public payable{} - function transferTokenWithSameName(trcToken id,uint256 amount) public payable{ - B b= new B(); - b.transferToken(amount,id); - a= address(b); - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - fallback() external payable{} - function transferToken(uint256 amount, trcToken id) payable public returns(bool){ - flag =9; - } - function getFlag() public view returns (uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken030.sol b/framework/src/test/resources/soliditycode/contractTrcToken030.sol deleted file mode 100644 index 06b8201979c..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken030.sol +++ /dev/null @@ -1,17 +0,0 @@ - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken031.sol b/framework/src/test/resources/soliditycode/contractTrcToken031.sol deleted file mode 100644 index 65ec394e8da..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken031.sol +++ /dev/null @@ -1,18 +0,0 @@ - - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken034.sol b/framework/src/test/resources/soliditycode/contractTrcToken034.sol deleted file mode 100644 index 32c55f8c84b..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken034.sol +++ /dev/null @@ -1,25 +0,0 @@ - - - contract token{ - - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken035.sol b/framework/src/test/resources/soliditycode/contractTrcToken035.sol deleted file mode 100644 index ca45dde790d..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken035.sol +++ /dev/null @@ -1,24 +0,0 @@ - - - contract token{ - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036.sol b/framework/src/test/resources/soliditycode/contractTrcToken036.sol deleted file mode 100644 index c1da2f7555e..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken036.sol +++ /dev/null @@ -1,52 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate1 { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -fallback() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol deleted file mode 100644 index 327ab5a756e..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_1.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol deleted file mode 100644 index 817a96e3c80..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_2.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol deleted file mode 100644 index 67400c2e8ad..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_3.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol deleted file mode 100644 index cbaca0d4b38..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_4.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -event log(uint256); -constructor() payable public{} -fallback() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol b/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol deleted file mode 100644 index 1f03afb7636..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken036_old.sol +++ /dev/null @@ -1,41 +0,0 @@ - - - -contract IllegalDecorate1 { -constructor() payable public{} -fallback() payable public{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -fallback() payable public{} -event log(uint256); -function transferTokenWithView(address toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -fallback() payable public{} -function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken037.sol b/framework/src/test/resources/soliditycode/contractTrcToken037.sol deleted file mode 100644 index 7cdd91702e8..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken037.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - require(0==address(this).tokenBalance(msg.tokenid)); - require(bamount+aamount==rec.tokenBalance(msg.tokenid)); - (bool success, bytes memory data) =rec.call(abi.encodeWithSignature("checkTrc10(uint256,trcToken,uint256)",bamount+aamount,msg.tokenid,0)); - require(success); - - } -} - -contract receiveTrc10 { - fallback() external payable {} - function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ - require(amount==address(this).tokenBalance(tid)); - require(meamount==msg.sender.tokenBalance(tid)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken038.sol b/framework/src/test/resources/soliditycode/contractTrcToken038.sol deleted file mode 100644 index eeb5ae744cf..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken038.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - //require(rec.call(abi.encode(bytes4(keccak256("AssertError()"))))); - (bool suc, bytes memory data) = rec.call(abi.encodeWithSignature("AssertError()")); - require(suc); - require(aamount==address(this).tokenBalance(msg.tokenid)); - require(bamount==rec.tokenBalance(msg.tokenid)); - } -} - -contract receiveTrc10 { - fallback() external payable { - } - function AssertError() public{ - assert(1==2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken039.sol b/framework/src/test/resources/soliditycode/contractTrcToken039.sol deleted file mode 100644 index ebf6fb932ed..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken039.sol +++ /dev/null @@ -1,44 +0,0 @@ - -/* - * 1. caller账户issue一个token - * 2. caller部署proxy, 传入1000 token,1000 trx - * 3. caller部署A - * 4. caller部署B - * 5. caller调用proxy中upgradetTo函数,传入A的地址 - * 6. caller调用proxy中不存在的trans(uint256,address,trcToken)函数,注意这时trcToken是无意义的,但也带上tokenid。address是任意另外某账户的地址 - * 7. 可以看到目标地址trx增长5,caller账户trx减少5 - * 8. caller调用proxy中upgradeTo函数,传入B的地址 - * 9. caller调用proxy中不存在的trans(uint256,address,trcToken)函数。 - * 10. 可以看到目标地址token增长5,caller账户token减少5 -*/ -contract Proxy { - constructor() payable public{} - address public implementation; - function upgradeTo(address _address) public { - implementation = _address; - } - fallback() payable external{ - address addr = implementation; - require(addr != address(0)); - assembly { - let freememstart := mload(0x40) - calldatacopy(freememstart, 0, calldatasize()) - let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 0) - returndatacopy(freememstart, 0, returndatasize()) - switch success - case 0 { revert(freememstart, returndatasize()) } - default { return(freememstart, returndatasize()) } - } - } -} - -contract A { - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transfer(amount); - } -} -contract B{ - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transferToken(amount,id); - } -} diff --git a/framework/src/test/resources/soliditycode/contractTrcToken041.sol b/framework/src/test/resources/soliditycode/contractTrcToken041.sol deleted file mode 100644 index 6284253d1d5..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken041.sol +++ /dev/null @@ -1,20 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} - - function setFlag() public payable{ - flag = 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken043.sol b/framework/src/test/resources/soliditycode/contractTrcToken043.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken043.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken048.sol b/framework/src/test/resources/soliditycode/contractTrcToken048.sol deleted file mode 100644 index e705f696c1d..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken048.sol +++ /dev/null @@ -1,14 +0,0 @@ - - - contract Test { - event log(uint256); - function testMsgTokenValue() payable public returns(uint256 value) { - emit log(msg.tokenvalue); - return msg.tokenvalue; - } - - function testMsgValue() payable public returns(uint256 value) { - emit log(msg.value); - return msg.value; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken049.sol b/framework/src/test/resources/soliditycode/contractTrcToken049.sol deleted file mode 100644 index d40480720df..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken049.sol +++ /dev/null @@ -1,9 +0,0 @@ - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken050.sol b/framework/src/test/resources/soliditycode/contractTrcToken050.sol deleted file mode 100644 index 6bc6d956898..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken050.sol +++ /dev/null @@ -1,10 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken051.sol b/framework/src/test/resources/soliditycode/contractTrcToken051.sol deleted file mode 100644 index 493016b777f..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken051.sol +++ /dev/null @@ -1,11 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - fallback() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken052.sol b/framework/src/test/resources/soliditycode/contractTrcToken052.sol deleted file mode 100644 index 6bc6d956898..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken052.sol +++ /dev/null @@ -1,10 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken054.sol b/framework/src/test/resources/soliditycode/contractTrcToken054.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken054.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken055.sol b/framework/src/test/resources/soliditycode/contractTrcToken055.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken055.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken060.sol b/framework/src/test/resources/soliditycode/contractTrcToken060.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken060.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken061.sol b/framework/src/test/resources/soliditycode/contractTrcToken061.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken061.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken064.sol b/framework/src/test/resources/soliditycode/contractTrcToken064.sol deleted file mode 100644 index 43e0da8a510..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken064.sol +++ /dev/null @@ -1,49 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } - function transferTokenTestValueMaxBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0); - } - function transferTokenTestValueOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775808, 1000001); - } - function transferTokenTestValueMaxLong(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775807, 1000001); - } - function transferTokenTestValue0IdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0, 9223372036854775809); - } -} - - - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken066.sol b/framework/src/test/resources/soliditycode/contractTrcToken066.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken066.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken067.sol b/framework/src/test/resources/soliditycode/contractTrcToken067.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken067.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken073.sol b/framework/src/test/resources/soliditycode/contractTrcToken073.sol deleted file mode 100644 index a9ee8ea412b..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken073.sol +++ /dev/null @@ -1,16 +0,0 @@ - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - fallback() payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken075.sol b/framework/src/test/resources/soliditycode/contractTrcToken075.sol deleted file mode 100644 index c90f8dcbee3..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken075.sol +++ /dev/null @@ -1,26 +0,0 @@ - - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMin() payable public{ - // long.min - 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(uint256(int256(-9223372036855775828)))), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMax() payable public{ - // long.max + 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); - } - - fallback() payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken076.sol b/framework/src/test/resources/soliditycode/contractTrcToken076.sol deleted file mode 100644 index a9decbee320..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken076.sol +++ /dev/null @@ -1,19 +0,0 @@ - -contract Test { - address public origin; - address public sender; - bool public result1; - bool public result2; - function test() external { - origin = tx.origin; - sender = msg.sender; - result1 = msg.sender == tx.origin; // true - result2 = origin == sender; // true - } -function getResult1() public returns(bool){ - return result1; -} -function getResult2() public returns(bool){ - return result2; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken077.sol b/framework/src/test/resources/soliditycode/contractTrcToken077.sol deleted file mode 100644 index aeecf9cb9a5..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken077.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract trcToken077 { -function addressTest() public returns(bytes32 addressValue) { - assembly{ - let x := mload(0x40) //Find empty storage location using "free memory pointer" - mstore(x,address) //Place current contract address - addressValue := mload(x) - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken078.sol b/framework/src/test/resources/soliditycode/contractTrcToken078.sol deleted file mode 100644 index 8d10d25312d..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken078.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract callerContract { - constructor() public payable{} - fallback() external payable{} - function sendToB(address called_address, address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - contract calledContract { - fallback() external payable{} - constructor() public payable {} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call{value:5}(abi.encode(bytes4(keccak256("setI()")))); - } - - } - contract c{ - address public origin; - address public sender; - constructor() public payable{} - event log(address,address); - fallback() payable external{ - emit log(tx.origin,msg.sender); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken079.sol b/framework/src/test/resources/soliditycode/contractTrcToken079.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken079.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken080.sol b/framework/src/test/resources/soliditycode/contractTrcToken080.sol deleted file mode 100644 index 2d2688b74a4..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken080.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - fallback() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcToken081.sol b/framework/src/test/resources/soliditycode/contractTrcToken081.sol deleted file mode 100644 index b69ecde68b2..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcToken081.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract TokenSender { - constructor() payable public{} - function sendTRC10(address target) public payable { - trcToken tokenId = msg.tokenid; - bytes memory callData = abi.encodeWithSignature("receiveTRC10(address,uint256,trcToken)", msg.sender, 1, tokenId); - assembly { - let ret := calltoken( - gas(), - target, - 1, - tokenId, - add(callData, 0x20), - mload(callData), - 0, - 0) - if iszero(ret) { - revert(0, 0) - } - } - } - - function sendTRC10NoMethod(address target) public payable { - trcToken tokenId = msg.tokenid; - bytes4 sig = bytes4(keccak256("()")); // function signature - assembly { - let x := mload(0x40) // get empty storage location - mstore(x,sig) - let ret := calltoken( - gas(), - target, - 1, //token value - tokenId, //token id - x, // input - 0x04, // input size = 4 bytes - x, // output stored at input location, save space - 0x04) - if iszero(ret) { - revert(0, 0) - } - } - } -} - -contract TokenReceiver { - constructor() payable public{} - event Received(address, address, uint256, trcToken); - - function receiveTRC10(address origin, uint256 value, trcToken id) external payable { - emit Received(msg.sender, origin, value, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol deleted file mode 100644 index 6a18fac311a..00000000000 --- a/framework/src/test/resources/soliditycode/contractTrcTokenToOther.sol +++ /dev/null @@ -1,44 +0,0 @@ - - -contract ConvertType { - -constructor() payable public{} - -fallback() payable external{} - -//function trcTokenOnStorage(trcToken storage token) internal { // ERROR: Data location can only be specified for array, struct or mapping types, but "storage" was given. -//} - -function trcTokenToString(trcToken token) public pure returns(string memory s){ -// s = token; // ERROR -// s = string(token); // ERROR -} - -function trcTokenToUint256(trcToken token) public pure returns(uint256 r){ -uint256 u = token; // OK -uint256 u2 = uint256(token); // OK -r = u2; -} - -function trcTokenToAddress(trcToken token) public pure returns(address r){ -//r = token; // ERROR -token = 1000001; -address a2 = address(uint160(token)); // OK -r = a2; -} - -function trcTokenToBytes(trcToken token) public pure returns(bytes memory r){ -//r = token; // ERROR -// r = bytes(token); // ERROR -} - -function trcTokenToBytes32(trcToken token) public pure returns(bytes32 r){ -// r = token; // ERROR -bytes32 b2 = bytes32(token); // OK -r = b2; -} - -function trcTokenToArray(trcToken token) public pure returns(uint[] memory r){ -//r = token; // ERROR -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/contractUnknownException.sol b/framework/src/test/resources/soliditycode/contractUnknownException.sol deleted file mode 100644 index d2d37364a0e..00000000000 --- a/framework/src/test/resources/soliditycode/contractUnknownException.sol +++ /dev/null @@ -1,64 +0,0 @@ - -contract testA { - constructor() public payable { - A a = (new A){value:10}(); - a.fun(); - } -} - -contract testB { - constructor() public payable { - B b = (new B){value:10}(); - b.fun(); - } -} - - -contract testC { - constructor() public payable{ - C c = (new C){value:10}(); - c.fun(); - } -} - -contract testD { - constructor() public payable{ - D d = (new D){value:10}(); - d.fun(); - } -} - - -contract A { - constructor() public payable{ - selfdestruct(payable(msg.sender)); - } - function fun() public { - } - -} - -contract B { - constructor() public payable { - revert(); - } - function fun() public { - } -} - - -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} - -contract D { - constructor() public payable { - require(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/create2CallContract.sol b/framework/src/test/resources/soliditycode/create2CallContract.sol deleted file mode 100644 index 046706ebd9e..00000000000 --- a/framework/src/test/resources/soliditycode/create2CallContract.sol +++ /dev/null @@ -1,37 +0,0 @@ -contract callerContract { - constructor() payable public{} - fallback() payable external{} - function delegateCallCreate2(address called_address, bytes memory code, uint256 salt) public { - called_address.delegatecall(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } - function callCreate2(address called_address,bytes memory code, uint256 salt) public returns(bool,bytes memory){ - return called_address.call(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } -} - - -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/create2Istanbul.sol b/framework/src/test/resources/soliditycode/create2Istanbul.sol deleted file mode 100644 index c2ef8f3236b..00000000000 --- a/framework/src/test/resources/soliditycode/create2Istanbul.sol +++ /dev/null @@ -1,28 +0,0 @@ - - -contract create2Istanbul { - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - - } - return addr; - } - - // prefix in main net is 0x41, testnet config is 0xa0 - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } - -} - -contract B { - constructor() public payable{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/create2contract.sol b/framework/src/test/resources/soliditycode/create2contract.sol deleted file mode 100644 index 0171f4d5486..00000000000 --- a/framework/src/test/resources/soliditycode/create2contract.sol +++ /dev/null @@ -1,52 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract FactoryBytes { - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/create2contract22.sol b/framework/src/test/resources/soliditycode/create2contract22.sol deleted file mode 100644 index cfad7c815fb..00000000000 --- a/framework/src/test/resources/soliditycode/create2contract22.sol +++ /dev/null @@ -1,109 +0,0 @@ -contract Factory { - event Deployed(address addr, trcToken salt, address sender); - event Deployed1(address addr, uint256 salt, address sender); - event Deployed2(address addr, address salt, address sender); - event Deployed3(address addr, string salt, address sender); - - - function deploy(bytes memory code, trcToken salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function deploy1(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed1(addr, salt, msg.sender); - return addr; - } - - function deploy2(bytes memory code, address salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed2(addr, salt, msg.sender); - return addr; - } - - function deploy3(bytes memory code, string memory salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed3(addr, salt, msg.sender); - return addr; - } - -} - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract1 { - uint public i=2; - function testTransfer(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract2 { - uint public i=3; - function testTransfer(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract3 { - uint public i=4; - function testTransfer(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/create2contractn.sol b/framework/src/test/resources/soliditycode/create2contractn.sol deleted file mode 100644 index 4ecf7bc16b4..00000000000 --- a/framework/src/test/resources/soliditycode/create2contractn.sol +++ /dev/null @@ -1,29 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - payable(msg.sender).transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - payable(msg.sender).transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/create2contractn2.sol b/framework/src/test/resources/soliditycode/create2contractn2.sol deleted file mode 100644 index 626988c4e04..00000000000 --- a/framework/src/test/resources/soliditycode/create2contractn2.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function set() payable public { - i=5; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/demo.sol b/framework/src/test/resources/soliditycode/demo.sol deleted file mode 100644 index 06bf15387fc..00000000000 --- a/framework/src/test/resources/soliditycode/demo.sol +++ /dev/null @@ -1,73 +0,0 @@ - - - contract tokenTest{ - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - } - codesize = m; - } - - // positive case - function pulsone() public payable{ - uint256 j = 0; - uint i = 100; - for (; i < i; i++) { - j++; - } - } - - - function getCodeSize() public returns (uint256){ - return codesize; - } - - } - - contract confirmTest{ - - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - - } - codesize = m; - } - - function getCodeSize() public returns (uint256){ - return codesize; - } - - function confirm(address addr) public returns (uint256){ - uint256 j; - assembly { - j := extcodesize(addr) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return j; - } - - function at(address _addr) public returns (bytes memory o_code) { - assembly { - // retrieve the size of the code, this needs assembly - let size := extcodesize(_addr) - // allocate output byte array - this could also be done without assembly - // by using o_code = new bytes(size) - o_code := mload(0x40) - // new "memory end" including padding - mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) - // store length in memory - mstore(o_code, size) - // actually retrieve the code, this needs assembly - extcodecopy(_addr, add(o_code, 0x20), 0, size) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/enumAndStruct.sol b/framework/src/test/resources/soliditycode/enumAndStruct.sol deleted file mode 100644 index 836a4ac850e..00000000000 --- a/framework/src/test/resources/soliditycode/enumAndStruct.sol +++ /dev/null @@ -1,43 +0,0 @@ - - -struct S_out { -uint x; -} - -enum ErrorType { -Revert_Error, //0 -RevertWithMsg_Error, //1 -Require_Error, //2 -RequirewithMsg_Error, //3 -Assert_Error, //4 -Tansfer_Error, //5 -Send_Error, //6 -Math_Error, //7 -ArrayOverFlow_Error //8 -} - -contract enumAndStructTest { - -struct S_inner { -int x; -} - -enum ErrorType_inner { -Revert_Error, //0 -RevertWithMsg_Error, //1 -Require_Error, //2 -RequirewithMsg_Error, //3 -Assert_Error, //4 -Tansfer_Error, //5 -Send_Error, //6 -Math_Error, //7 -ArrayOverFlow_Error //8 -} - -function getvalue() public returns(uint) { - require(ErrorType.Require_Error == ErrorType(2)); - S_out memory s = S_out(1); - return s.x; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/event001.sol b/framework/src/test/resources/soliditycode/event001.sol deleted file mode 100644 index 7662df3a5c6..00000000000 --- a/framework/src/test/resources/soliditycode/event001.sol +++ /dev/null @@ -1,10 +0,0 @@ -contract Event { - event xixi(uint256 id) ; - event log2(uint256,uint256,uint256); - constructor() public payable{} - function messageI() payable public returns (uint ret) { - //emit log2(1,2,3); - emit xixi(1); - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/event002.sol b/framework/src/test/resources/soliditycode/event002.sol deleted file mode 100644 index a61f834e1b5..00000000000 --- a/framework/src/test/resources/soliditycode/event002.sol +++ /dev/null @@ -1,52 +0,0 @@ - - -contract Event { - - event _0(); - event a_0() anonymous; - event a_4i(uint256 indexed x1, uint256 indexed x2 , uint256 indexed x3, uint256 indexed x4, uint256 x5)anonymous ; - event _3i(uint256 x1, uint256 indexed x2 , uint256 indexed x3, uint256 x4, uint256 x5) ; - event _1i(uint256 indexed x1, uint256, uint256 indexed, uint256 x4) ; - event a_1i(uint256) anonymous; - event _ai(uint8[2], uint8) ; - event a_ai(uint8[2], uint8) anonymous; - event _a1i(uint8[2] indexed, uint8) ; - event a_a1i(uint8[2] indexed, uint8) anonymous; - - constructor () public { - // emit a_0(); - // emit a_1i(123); - // emit a_4i(1,2,3,5,16); - // emit _0(); - emit _3i(1,2,3,5,16); - // emit _1i(1,2,3,5); - // emit _ai([1,2], 3); - // emit a_ai([3,4], 5); - // emit _a1i([1,2], 3); - // emit a_a1i([3,4], 5); - } - - function e() public { - emit _1i(1,2,3,4); - } - - function l() public { - emit a_1i(1); - } - - function k() public{ - emit a_4i(2,3,4,5,17); - emit _3i(2,3,4,5,16); - emit _1i(2,3,4,5); - emit a_1i(128); - emit _0(); - emit a_0(); - //selfdestruct(msg.sender); - //emit a_4i(1,2,3,5,16); - //emit _3i(1,2,3,5,16); - //emit _1i(1,2,3,5); - //emit a_1i(123); - //emit _0(); - //emit a_0(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/eventLog2.sol b/framework/src/test/resources/soliditycode/eventLog2.sol deleted file mode 100644 index 0ad82f6dd1f..00000000000 --- a/framework/src/test/resources/soliditycode/eventLog2.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract Event { - event log2(uint256,uint256,uint256); - constructor() public payable{} - function messageI() payable public returns (uint ret) { - emit log2(1,1,1); - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/extCodeHash.sol b/framework/src/test/resources/soliditycode/extCodeHash.sol deleted file mode 100644 index d6209770682..00000000000 --- a/framework/src/test/resources/soliditycode/extCodeHash.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract TestExtCodeHash { - - function getCodeHashByAddr(address _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } - function getCodeHashByUint(uint256 _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } -} diff --git a/framework/src/test/resources/soliditycode/extCodeHash11.sol b/framework/src/test/resources/soliditycode/extCodeHash11.sol deleted file mode 100644 index 961941c7d20..00000000000 --- a/framework/src/test/resources/soliditycode/extCodeHash11.sol +++ /dev/null @@ -1,103 +0,0 @@ -contract Counter { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = payable(msg.sender); -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} -revert(); -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract Counter1 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = payable(msg.sender); -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter2 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = payable(msg.sender); -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} - addr.call(abi.encodeWithSignature("testSuicideNonexistentTarget(address)",c)); - - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter3 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = payable(msg.sender); -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract TestConstract { - uint public i=1; - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/extCodeHashConstruct.sol b/framework/src/test/resources/soliditycode/extCodeHashConstruct.sol deleted file mode 100644 index 6d640ad7a23..00000000000 --- a/framework/src/test/resources/soliditycode/extCodeHashConstruct.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract CounterConstruct { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore); - constructor() public{ - owner = payable(msg.sender); - address addr = address(this); - bytes32 _hashBefore; - assembly { - _hashBefore := extcodehash(addr) - } - emit LogResult(_hashBefore); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/extCodeHashStress.sol b/framework/src/test/resources/soliditycode/extCodeHashStress.sol deleted file mode 100644 index cf41f3c8106..00000000000 --- a/framework/src/test/resources/soliditycode/extCodeHashStress.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract Trigger { - function test(address addr) public returns(uint i) { - bytes32 hash; - while (gasleft() > 1000) { - assembly { - hash := extcodehash(addr) - } - i++; - } - } - - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - assembly { - hash := extcodehash(addr) - } - } - return i; - } - } - - - - contract TriggerNormal { - function test(address addr) public returns(uint i) { - i = 0; - while (gasleft() > 100000) { - i++; - } - } - } - - contract TriggerNormal1 { - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - addr.balance; - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/extCodeHashTestNoPayable.sol b/framework/src/test/resources/soliditycode/extCodeHashTestNoPayable.sol deleted file mode 100644 index c3a2ad8c6ae..00000000000 --- a/framework/src/test/resources/soliditycode/extCodeHashTestNoPayable.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testConstantContract{ -uint256 public i; -function testNoPayable() public returns (uint256 z) { -i=1; -z=i; -return z; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/fallbackUpgrade.sol b/framework/src/test/resources/soliditycode/fallbackUpgrade.sol deleted file mode 100644 index 6751858c65e..00000000000 --- a/framework/src/test/resources/soliditycode/fallbackUpgrade.sol +++ /dev/null @@ -1,83 +0,0 @@ -contract Test0{ - event FuncCalled(bytes data,uint a); -} - -contract Test1 { - - event FuncCalled(string a); - fallback() external { - x = "fallback"; - emit FuncCalled(x); - } - string x; -} -//含有payable的fallback,无receice -contract Test2 { - - event FuncCalled(string data); - fallback() external payable{ - x = "fallback"; - emit FuncCalled(x); - } - string x; -} - -contract TestPayable { - event FuncCalled(string a); - - fallback() external payable { - x = "fallback"; - emit FuncCalled(x); - } - - receive() external payable { - x = "receive"; - emit FuncCalled(x); - } - string x; -} - -contract Caller { - function callTest0(Test0 test) public{ - (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - } - function callTest1(address test) public returns (bool) { - (bool success,) = test.call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - (success,) = address(test).call(""); - require(success); - return true; - } - function callTest2(address test) public payable returns (bool) { - (bool success,) = test.call{value:1000}(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - return true; - } - function callTestPayable1(TestPayable test) public payable returns (bool) { - (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - (success,) = address(test).call(""); - require(success); - return true; - } -} - - -//contract Test0 { -// event FallbackCall(string data,bytes msg); -// //event FuncCalled(string a,bytes data); -// function() external payable{ -// x = "fallback"; -// emit FallbackCall(x,msg.data); -// } -// string x; -//} -//contract Caller{ -// function call(Test0 test) public payable returns(bool){ -// (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); -// require(success); -// return true; -// } -//} - diff --git a/framework/src/test/resources/soliditycode/freezeContract001.sol b/framework/src/test/resources/soliditycode/freezeContract001.sol deleted file mode 100644 index f8522c4166e..00000000000 --- a/framework/src/test/resources/soliditycode/freezeContract001.sol +++ /dev/null @@ -1,63 +0,0 @@ - -contract TestFreeze { - constructor() public payable {} - - function freeze(address payable receiver, uint amount, uint res) external payable{ - receiver.freeze(amount, res); - } - - function unfreeze(address payable receiver, uint res) external { - receiver.unfreeze(res); - } - - function destroy(address payable inheritor) external { - selfdestruct(inheritor); - } - - function send(address payable A) external { - A.transfer(10); - } - - function send(address payable A, uint256 value) external { - A.transfer(value); - } - - function getExpireTime(address payable target, uint res) external view returns(uint) { - return target.freezeExpireTime(res); - } - - function deploy(uint256 salt) public returns(address){ - address addr; - bytes memory code = type(C).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - - function freezeAndSend(address payable receiver, uint amount, uint res) external { - receiver.transfer(amount); - receiver.freeze(amount, res); - } - - -} - - -contract C { - constructor() public payable {} - - function destroy(address payable inheritor) external { - selfdestruct(inheritor); - } -} - -contract D { - constructor() public payable { - payable(msg.sender).freeze(msg.value, 1); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/function_type_array_to_storage.sol b/framework/src/test/resources/soliditycode/function_type_array_to_storage.sol deleted file mode 100644 index a2093023d6a..00000000000 --- a/framework/src/test/resources/soliditycode/function_type_array_to_storage.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract C { - constructor() public payable{} - function () external returns(uint)[1] externalDefaultArray; - function () external view returns(uint)[1] externalViewArray; - function () external pure returns(uint)[1] externalPureArray; - - function () internal returns(uint)[1] internalDefaultArray; - function () internal view returns(uint)[1] internalViewArray; - function () internal pure returns(uint)[1] internalPureArray; - - function externalDefault() external returns(uint) { return 11; } - function externalView() external view returns(uint) { return 12; } - function externalPure() external pure returns(uint) { return 13; } - - function internalDefault() internal returns(uint) { return 21; } - function internalView() internal view returns(uint) { return 22; } - function internalPure() internal pure returns(uint) { return 23; } - - function testViewToDefault() public returns (uint, uint) { - externalDefaultArray = [this.externalView]; - internalDefaultArray = [internalView]; - - return (externalDefaultArray[0](), internalDefaultArray[0]()); - } - - function testPureToDefault() public returns (uint, uint) { - externalDefaultArray = [this.externalPure]; - internalDefaultArray = [internalPure]; - - return (externalDefaultArray[0](), internalDefaultArray[0]()); - } - - function testPureToView() public returns (uint, uint) { - externalViewArray = [this.externalPure]; - internalViewArray = [internalPure]; - - return (externalViewArray[0](), internalViewArray[0]()); - } -} -// ==== -// compileViaYul: also -// ---- -// testViewToDefault() -> 12, 22 -// testPureToDefault() -> 13, 23 -// testPureToView() -> 13, 23 diff --git a/framework/src/test/resources/soliditycode/getAddressChange.sol b/framework/src/test/resources/soliditycode/getAddressChange.sol deleted file mode 100644 index 2796da68770..00000000000 --- a/framework/src/test/resources/soliditycode/getAddressChange.sol +++ /dev/null @@ -1,12 +0,0 @@ -contract getAddressChange { - constructor() public payable {} - // testaddress1函数新增了一个address属性。0.6.0之前 external函数可以通过address(x)来转化为地址,6.0将其禁止,可以通过函数address属性直接获取 - function testaddress1() public view returns(address) { - //return address(this.getamount); //0.6.0之前可以使用 - return this.getamount.address; //0.6.0 - - } - function getamount(address) external view returns(uint256) { - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/isSRCandidate.sol b/framework/src/test/resources/soliditycode/isSRCandidate.sol deleted file mode 100644 index e8e9b692dec..00000000000 --- a/framework/src/test/resources/soliditycode/isSRCandidate.sol +++ /dev/null @@ -1,35 +0,0 @@ - - - -contract ContractB{ - address others; -} - -contract TestIsSRCandidate{ - - ContractB contractB = new ContractB(); - - function isSRCandidateTest(address addr) public view returns (bool) { - return address(addr).isSRCandidate; - } - - function zeroAddressTest() public view returns (bool) { - return address(0x0).isSRCandidate; - } - - function localContractAddrTest() public view returns (bool) { - return address(this).isSRCandidate; - } - - function otherContractAddrTest() public view returns (bool) { - return address(contractB).isSRCandidate; - } - - function nonpayableAddrTest(address addr) public view returns (bool) { - return addr.isSRCandidate; - } - - function payableAddrTest(address payable addr) public returns (bool) { - return addr.isSRCandidate; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/mappingGetter.sol b/framework/src/test/resources/soliditycode/mappingGetter.sol deleted file mode 100644 index dbd473717cb..00000000000 --- a/framework/src/test/resources/soliditycode/mappingGetter.sol +++ /dev/null @@ -1,4 +0,0 @@ -contract mappingGetter { - mapping(bytes => uint256) public balances1; - mapping(string => uint256) public balances2; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/multiValiSignPerformance01.sol b/framework/src/test/resources/soliditycode/multiValiSignPerformance01.sol deleted file mode 100644 index 74baa963366..00000000000 --- a/framework/src/test/resources/soliditycode/multiValiSignPerformance01.sol +++ /dev/null @@ -1,37 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract ecrecoverValidateSign { - - using ECVerify for bytes32; - - function validateSign(bytes32 hash,bytes[] memory sig,address[] memory signer) public returns (bool) { - for(uint256 i=0;i=0.5.0 <0.7.0; - -contract A { - uint public x; - function setValue(uint _x) public { - x = _x; - } -} -contract B is A {} -contract C is A {} -// No explicit override required -contract D is B, C {} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/override003.sol b/framework/src/test/resources/soliditycode/override003.sol deleted file mode 100644 index 0ca6a2663d1..00000000000 --- a/framework/src/test/resources/soliditycode/override003.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.6.0; -contract A { - uint public x; - function setValue(uint _x) public virtual { - x = _x; - } -} - -contract B { - uint public y; - function setValue(uint _y) public virtual { - y = _y; - } -} - -contract C is A, B { - function setValue(uint _x) public override(B,A) { - A.setValue(_x); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/override004.sol b/framework/src/test/resources/soliditycode/override004.sol deleted file mode 100644 index d0cf20525d5..00000000000 --- a/framework/src/test/resources/soliditycode/override004.sol +++ /dev/null @@ -1,25 +0,0 @@ -//pragma solidity >=0.5.0 <0.7.0; - -contract A { - uint public x = 4; - function setValue(uint _x) public notZero { - x = _x; - } - modifier notZero() virtual { - require(x >= 5,"x must >= 5"); - _; - } -} - -contract B is A { - function setValue2(uint _x) public { - x = _x; - } -} - -contract C is A,B { - modifier notZero override { - require(x >= 6,"x must >= 6"); - _; - } -} diff --git a/framework/src/test/resources/soliditycode/override005.sol b/framework/src/test/resources/soliditycode/override005.sol deleted file mode 100644 index 0ea485ae0a2..00000000000 --- a/framework/src/test/resources/soliditycode/override005.sol +++ /dev/null @@ -1,39 +0,0 @@ -pragma solidity >= 0.6.0; - -contract Base { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices public choice2 = ActionChoices.GoRight; - - function stopped() virtual external view returns (bool) { - return true; - } - function i() virtual external view returns (int) { - return 32482980; - } - function i2() virtual external view returns (int) { - return -32482980; - } - function ui() virtual external view returns (uint) { - return 23487820; - } - function origin() virtual external view returns (address) { - return 0x3b0E4a6EdEE231CE0c3433F00F1bbc5FeD409c0B; - } - function b32() virtual external view returns (bytes32) { - return 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd231050; - } - function choice() virtual external returns (ActionChoices) { - return choice2; - } -} - -contract Test is Base { - - bool override public stopped = false; - int override public i = 32482989; - int override public i2 = -32482989; - uint override public ui = 23487823; - address override public origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 override public b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - ActionChoices override public choice = ActionChoices.SitStill; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/overridePrivateFunction.sol b/framework/src/test/resources/soliditycode/overridePrivateFunction.sol deleted file mode 100644 index b0b4d679620..00000000000 --- a/framework/src/test/resources/soliditycode/overridePrivateFunction.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.5.17; - -contract A { - - function test() private pure returns(uint) { - return 1; - } - -} - -contract B is A { - - function basic() private pure returns(uint) { - return 2; - } - function testOverridePrivate() external payable returns(uint) { - return basic(); - } - - constructor() public payable {} -} - diff --git a/framework/src/test/resources/soliditycode/payable001.sol b/framework/src/test/resources/soliditycode/payable001.sol deleted file mode 100644 index 4fe7b20921f..00000000000 --- a/framework/src/test/resources/soliditycode/payable001.sol +++ /dev/null @@ -1,31 +0,0 @@ - - - -contract A { - constructor() public payable{ - } - - fallback() external payable { - } -} - -contract PayableTest { - -address payable a1; -function receiveMoneyTransfer(address a, uint256 _x) public { -a1 = payable(a); -a1.transfer(_x); -} - -function receiveMoneySend(address a, uint256 x) public { -address payable a2 = payable(a); -a2.send(x); -} - -function receiveMoneyTransferWithContract(A PayableTest, uint256 x) public { -payable(address(PayableTest)).transfer(x); -} - -constructor() public payable{ -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/pedersenHash001.sol b/framework/src/test/resources/soliditycode/pedersenHash001.sol deleted file mode 100644 index 6cad7cb9855..00000000000 --- a/framework/src/test/resources/soliditycode/pedersenHash001.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract pedersenHashTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000004).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000004).delegatecall(data); - } - - function test3(uint32 hash, bytes32 left, bytes32 right) public returns (bytes32){ - return pedersenHash(hash, left, right); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/pedersenHash002.sol b/framework/src/test/resources/soliditycode/pedersenHash002.sol deleted file mode 100644 index b0a78973ef2..00000000000 --- a/framework/src/test/resources/soliditycode/pedersenHash002.sol +++ /dev/null @@ -1,320 +0,0 @@ -pragma experimental ABIEncoderV2; - -import "./SafeMath.sol"; - -abstract contract TokenTRC20 { - function transfer(address _to, uint256 _value) public virtual returns (bool success); - - function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success); -} - -contract ShieldedTRC20 { - using SafeMath for uint256; - - uint256 public scalingFactor; // used when decimals of TRC20 token is too large. - uint256 public leafCount; - uint256 constant INT64_MAX = 2 ** 63 - 1; - bytes32 public latestRoot; - mapping(bytes32 => bytes32) public nullifiers; // store nullifiers of spent commitments - mapping(bytes32 => bytes32) public roots; // store history root - mapping(uint256 => bytes32) public tree; - mapping(bytes32 => bytes32) public noteCommitment; - bytes32[33] frontier; - bytes32[32] zeroes = [bytes32(0x0100000000000000000000000000000000000000000000000000000000000000), bytes32(0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155), bytes32(0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34), bytes32(0xd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c), bytes32(0xe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49), bytes32(0x912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a), bytes32(0x8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613), bytes32(0xd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813), bytes32(0x7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444), bytes32(0x43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b), bytes32(0xba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce72), bytes32(0x4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c), bytes32(0xec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048), bytes32(0x1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651), bytes32(0xbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c), bytes32(0xd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f), bytes32(0x1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451), bytes32(0x6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c), bytes32(0xcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf00), bytes32(0x6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b159216), bytes32(0x8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673), bytes32(0x08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023), bytes32(0x0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49), bytes32(0x4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850), bytes32(0xfee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712), bytes32(0x16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a), bytes32(0xd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb58), bytes32(0xa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a), bytes32(0x28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a), bytes32(0xe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72), bytes32(0x12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d), bytes32(0xb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c53814)]; - address owner; - TokenTRC20 trc20Token; - - event MintNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TransferNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event BurnNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TokenMint(address from, uint256 value); - event TokenBurn(address to, uint256 value, bytes32[3] ciphertext); - event NoteSpent(bytes32 nf); - - constructor (address trc20ContractAddress, uint256 scalingFactorExponent) public { - require(scalingFactorExponent < 77, "The scalingFactorExponent is out of range!"); - scalingFactor = 10 ** scalingFactorExponent; - owner = msg.sender; - trc20Token = TokenTRC20(trc20ContractAddress); - } - // output: cm, cv, epk, proof - function mint(uint256 rawValue, bytes32[9] calldata output, bytes32[2] calldata bindingSignature, bytes32[21] calldata c) external { - address sender = msg.sender; - // transfer the trc20Token from the sender to this contract - bool transferResult = trc20Token.transferFrom(sender, address(this), rawValue); - require(transferResult, "TransferFrom failed!"); - - require(noteCommitment[output[0]] == 0, "Duplicate noteCommitments!"); - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), value, output, c)); - (bytes32[] memory ret) = verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[0]; - if (slot == 0) { - frontier[0] = output[0]; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[output[0]] = output[0]; - leafCount ++; - - emit MintNewLeaf(leafCount - 1, output[0], output[1], output[2], c); - emit TokenMint(sender, rawValue); - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function transfer(bytes32[10][] calldata input, bytes32[2][] calldata spendAuthoritySignature, bytes32[9][] calldata output, bytes32[2] calldata bindingSignature, bytes32[21][] calldata c) external { - require(input.length >= 1 && input.length <= 2, "Input number must be 1 or 2!"); - require(input.length == spendAuthoritySignature.length, "Input number must be equal to spendAuthoritySignature number!"); - require(output.length >= 1 && output.length <= 2, "Output number must be 1 or 2!"); - require(output.length == c.length, "Output number must be equal to c number!"); - - for (uint256 i = 0; i < input.length; i++) { - require(nullifiers[input[i][0]] == 0, "The note has already been spent!"); - require(roots[input[i][1]] != 0, "The anchor must exist!"); - } - for (uint256 i = 0; i < output.length; i++) { - require(noteCommitment[output[i][0]] == 0, "Duplicate noteCommitment!"); - } - - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c)); - (bytes32[] memory ret) = verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, 0, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 offset = 1; - //ret offset - for (uint256 i = 0; i < output.length; i++) { - uint256 slot = uint256(ret[offset++]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[i][0]; - if (slot == 0) { - frontier[0] = output[i][0]; - } - for (uint256 k = 1; k < slot + 1; k++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[offset++]; - if (k == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - leafCount++; - } - latestRoot = ret[offset]; - roots[latestRoot] = latestRoot; - for (uint256 i = 0; i < input.length; i++) { - bytes32 nf = input[i][0]; - nullifiers[nf] = nf; - emit NoteSpent(nf); - } - for (uint256 i = 0; i < output.length; i++) { - noteCommitment[output[i][0]] = output[i][0]; - emit TransferNewLeaf(leafCount - (output.length - i), output[i][0], output[i][1], output[i][2], c[i]); - } - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function burn(bytes32[10] calldata input, bytes32[2] calldata spendAuthoritySignature, uint256 rawValue, bytes32[2] calldata bindingSignature, address payTo, bytes32[3] calldata burnCipher, bytes32[9][] calldata output, bytes32[21][] calldata c) external { - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c, payTo, value)); - - bytes32 nf = input[0]; - bytes32 anchor = input[1]; - require(nullifiers[nf] == 0, "The note has already been spent!"); - require(roots[anchor] != 0, "The anchor must exist!"); - - require(output.length <= 1, "Output number cannot exceed 1!"); - require(output.length == c.length, "Output number must be equal to length of c!"); - - // bytes32 signHash = sha256(abi.encodePacked(address(this), input, payTo, value, output, c)); - if (output.length == 0) { - (bool result) = verifyBurnProof(input, spendAuthoritySignature, value, bindingSignature, signHash); - require(result, "The proof and signature have not been verified by the contract!"); - } else { - transferInBurn(input, spendAuthoritySignature, value, bindingSignature, signHash, output, c); - } - - nullifiers[nf] = nf; - emit NoteSpent(nf); - //Finally, transfer trc20Token from this contract to the nominated address - bool transferResult = trc20Token.transfer(payTo, rawValue); - require(transferResult, "Transfer failed!"); - - emit TokenBurn(payTo, rawValue, burnCipher); - } - - function transferInBurn(bytes32[10] memory input, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature, bytes32 signHash, bytes32[9][] memory output, bytes32[21][] memory c) private { - bytes32 cm = output[0][0]; - require(noteCommitment[cm] == 0, "Duplicate noteCommitment!"); - bytes32[10][] memory inputs = new bytes32[10][](1); - inputs[0] = input; - bytes32[2][] memory spendAuthoritySignatures = new bytes32[2][](1); - spendAuthoritySignatures[0] = spendAuthoritySignature; - (bytes32[] memory ret) = verifyTransferProof(inputs, spendAuthoritySignatures, output, bindingSignature, signHash, value, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = cm; - if (slot == 0) { - frontier[0] = cm; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[cm] = cm; - leafCount ++; - - emit BurnNewLeaf(leafCount - 1, cm, output[0][1], output[0][2], c[0]); - } - - //position: index of leafnode, start from 0 - function getPath(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValue(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - //position: index of leafnode, start from 0 - function getPathByValueIsZero(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValueByValueIsZero(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - function ancestorLevel(uint256 leafIndex) private view returns (uint32) { - uint256 nodeIndex1 = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex2 = leafCount + 2 ** 32 - 2; - uint32 level = 0; - while (((nodeIndex1 - 1) / 2) != ((nodeIndex2 - 1) / 2)) { - nodeIndex1 = (nodeIndex1 - 1) / 2; - nodeIndex2 = (nodeIndex2 - 1) / 2; - level = level + 1; - } - return level; - } - - function getTargetNodeValue(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function getTargetNodeValueByValueIsZero(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - left = bytes32(0x0); - right = bytes32(0x0); - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function rawValueToValue(uint256 rawValue) private view returns (uint64) { - require(rawValue > 0, "Value must be positive!"); - require(rawValue.mod(scalingFactor) == 0, "Value must be integer multiples of scalingFactor!"); - uint256 value = rawValue.div(scalingFactor); - require(value < INT64_MAX); - return uint64(value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol deleted file mode 100644 index 16d01911d35..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest1TestRequireContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - //function testThrow(){ - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol deleted file mode 100644 index 1ff73ad6460..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest2TestThrowsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow() public { - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol deleted file mode 100644 index b42a8c3fb23..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest3TestRevertContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow(){ - // throw; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol deleted file mode 100644 index 35f89631e7d..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract noPayableContract { - -function noPayable() public payable returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol b/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol deleted file mode 100644 index 35f89631e7d..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest4noPayableContract_1.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract noPayableContract { - -function noPayable() public payable returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol deleted file mode 100644 index 097594ab7c9..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public payable{ - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol b/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol deleted file mode 100644 index 5008ec5c9bf..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest5noPayableConstructor_1.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public { - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol deleted file mode 100644 index 4f171aebb9a..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest6transferTestContract.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract transferTestContract { - function tranferTest(address payable addr) public payable{ - addr.transfer(10); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol deleted file mode 100644 index 534726cb1b4..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest7payableFallbakContract.sol +++ /dev/null @@ -1,14 +0,0 @@ - - -contract Test { - fallback() external { x = 1; } - uint x; -} - - -contract Caller { - function callTest(Test test) public { - //test.call(0xabcdef01); // hash does not exist - address(test).call(abi.encode(0xabcdef01)); // hash does not exist - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol deleted file mode 100644 index b8743e8231a..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest8newContractGasNoenough.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract Account{ - uint256 public accId; - - // function Account(uint accountId) payable{ - constructor(uint accountId) payable public { - accId = accountId; - } -} - -contract Initialize{ - // Account public account = new Account(10); - - function newAccount() public { - Account account = new Account(1); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol deleted file mode 100644 index 18142d20ee8..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontest9MessageUsedErrorFeed.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -contract MathedFeed { - - function divideMathed() public returns (uint ret) { - uint x=1; - uint y=0; - return x/y; - } -} - - -contract MathedUseContract { - - function MathedUse(address addr) public returns (uint) { - return MathedFeed(addr).divideMathed(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol deleted file mode 100644 index 64243dffd7c..00000000000 --- a/framework/src/test/resources/soliditycode/requireExceptiontestFunctionUsedErrorFeed.sol +++ /dev/null @@ -1,17 +0,0 @@ - - -contract MessageFeed { - - function mValue() payable public returns (uint ret) { - return msg.value; - } -} - -contract MessageUseContract { - function inputValue() payable public returns (uint){ - return msg.value; - } - function messageUse(address addr) payable public returns (uint) { - return MessageFeed(addr).mValue{value:1}(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/selector.sol b/framework/src/test/resources/soliditycode/selector.sol deleted file mode 100644 index 5805a6e8d22..00000000000 --- a/framework/src/test/resources/soliditycode/selector.sol +++ /dev/null @@ -1,21 +0,0 @@ - - -library A { - function getBalance(address) public view returns (uint256) { - return address(this).balance; - } - - function getamount(address) external view returns (uint256) { - return address(this).balance; - } -} - -contract testSelector { - using A for address; - - - function getselector2() public view returns (bytes4, bytes4) { - return (A.getBalance.selector, A.getamount.selector); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/slotAndOffsetNewGrammer.sol b/framework/src/test/resources/soliditycode/slotAndOffsetNewGrammer.sol deleted file mode 100644 index b4c2b0ed516..00000000000 --- a/framework/src/test/resources/soliditycode/slotAndOffsetNewGrammer.sol +++ /dev/null @@ -1,32 +0,0 @@ -contract A { - uint b; - uint a; - uint c; - uint d; - uint e; - - function getA() external returns(uint,uint) { - uint slot; - uint offset; - assembly { -// old grammer -// slot := a_slot -// offset := a_offset - slot := a.slot - offset := a.offset - } - return (slot, offset); - } - - function getE() external returns(uint,uint) { - uint slot; - uint offset; - assembly { -// slot := e_slot -// offset := e_offset - slot := e.slot - offset := e.offset - } - return (slot, offset); - } -} diff --git a/framework/src/test/resources/soliditycode/stackContract001.sol b/framework/src/test/resources/soliditycode/stackContract001.sol deleted file mode 100644 index c2e8f2f7611..00000000000 --- a/framework/src/test/resources/soliditycode/stackContract001.sol +++ /dev/null @@ -1,61 +0,0 @@ - - -contract A{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function test() public{ - emit log(123); - } -} - -contract B{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function rewardBalance(address addr) public view returns (uint256){ - return addr.rewardbalance; - } - - function nullAddressTest() public view returns (uint256) { - return address(0x0).rewardbalance; - } - - function localContractAddrTest() public view returns (uint256) { - address payable localContract = address(uint160(address(this))); - return localContract.rewardbalance; - } - - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function contractBWithdrawRewardTest(address contractB) public returns (uint) { - return B(contractB).withdrawRewardTest(); - } - - function createA() public returns (address){ - return address(new A()); - } - - function callA(address Addr) public{ - A(Addr).test(); - } -} diff --git a/framework/src/test/resources/soliditycode/stackSuicide001.sol b/framework/src/test/resources/soliditycode/stackSuicide001.sol deleted file mode 100644 index d1fc520ddb2..00000000000 --- a/framework/src/test/resources/soliditycode/stackSuicide001.sol +++ /dev/null @@ -1,84 +0,0 @@ - -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public payable returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function transfer(address payable add,uint256 num) public { - return add.transfer(num); - } -} - -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/stateVariableShadowing.sol b/framework/src/test/resources/soliditycode/stateVariableShadowing.sol deleted file mode 100644 index a9109ee296c..00000000000 --- a/framework/src/test/resources/soliditycode/stateVariableShadowing.sol +++ /dev/null @@ -1,21 +0,0 @@ -contract test { -// uint public x; -// function setValue1(uint _x) public returns (uint){ -// x = _x; -// return x; -// } - uint public y; - function setValue3(uint _x) public returns (uint){ - y = _x; - return y; - } -} - -contract stateVariableShadowing is test { - uint public x; - function setValue2(uint _x) public returns (uint){ - x = _x; - return x; - } -} - diff --git a/framework/src/test/resources/soliditycode/stringSplit.sol b/framework/src/test/resources/soliditycode/stringSplit.sol deleted file mode 100644 index 84231f2d1fe..00000000000 --- a/framework/src/test/resources/soliditycode/stringSplit.sol +++ /dev/null @@ -1,45 +0,0 @@ - - -contract testStringSplit { -string s1 = "s""1""2"",./"; -string s2 = "s123?\\'."; -string s3 = hex"41"hex"42"; -string s4 = hex"4142"; - -function getS1() public view returns (string memory) { -return s1; -} - -function getS1N1() public pure returns (string memory) { -string memory n1 = "s""1""2"",./"; -return n1; -} - -function getS2() public view returns (string memory) { -return s2; -} - -function getS2N2() public pure returns (string memory) { -string memory n2 = "s123?\'."; -return n2; -} - -function getS3() public view returns (string memory) { -return s3; -} - -function getS3N3() public pure returns (string memory) { -string memory n3 = hex"41"hex"42"; -return n3; -} - -function getS4() public view returns (string memory) { -return s4; -} - -function getS4N4() public pure returns (string memory) { -string memory n4 = hex"4142"; -return n4; -} - -} diff --git a/framework/src/test/resources/soliditycode/suicide001.sol b/framework/src/test/resources/soliditycode/suicide001.sol deleted file mode 100644 index cb4690e1043..00000000000 --- a/framework/src/test/resources/soliditycode/suicide001.sol +++ /dev/null @@ -1,32 +0,0 @@ -contract factory { - constructor() payable public { - } - - function create1() payable public returns (address){ - Caller add = (new Caller){value:0}(); - return address(add); - } - - function kill() payable public{ - selfdestruct(payable(msg.sender)); - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - Caller addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/suicide002.sol b/framework/src/test/resources/soliditycode/suicide002.sol deleted file mode 100644 index bb845f8e0d6..00000000000 --- a/framework/src/test/resources/soliditycode/suicide002.sol +++ /dev/null @@ -1,43 +0,0 @@ -contract Factory { - uint256 public num; - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(payable(msg.sender)); - addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/super_skip_unimplemented_in_abstract_contract.sol b/framework/src/test/resources/soliditycode/super_skip_unimplemented_in_abstract_contract.sol deleted file mode 100644 index 82dc5d513f7..00000000000 --- a/framework/src/test/resources/soliditycode/super_skip_unimplemented_in_abstract_contract.sol +++ /dev/null @@ -1,22 +0,0 @@ -contract A { - function f() public virtual returns (uint) { - return 42; - } -} - -abstract contract I { - function f() external virtual returns (uint); -} - -contract B is A, I { - function f() override(A, I) public returns (uint) { - // I.f() is before A.f() in the C3 linearized order - // but it has no implementation. - return super.f(); - } -} -// ==== -// compileToEwasm: also -// compileViaYul: also -// ---- -// f() -> 42 diff --git a/framework/src/test/resources/soliditycode/testGetFilterChange.sol b/framework/src/test/resources/soliditycode/testGetFilterChange.sol deleted file mode 100644 index 8a922031c2f..00000000000 --- a/framework/src/test/resources/soliditycode/testGetFilterChange.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.8.0; -contract SolidityTest { - event Deployed(address sender, uint256 a, uint256 num); - function getResult(uint256 num) public payable returns(uint256) { - uint256 a=0; - for(a=0;a1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - return "success"; - - } - - function callFun(string memory functionStr, string memory argsStr) public{ - address(this).call(abi.encodeWithSignature(functionStr, argsStr)); - } - -} - -contract NewContract { - uint256[] arraryUint ; - - constructor(uint256 errorType) public payable{ - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - } -} - -contract tryTest { - function getData(errorContract inter, string memory functionStr, string memory argsStr) public payable returns(string memory) { - try inter.callFun(functionStr,argsStr) { - return "123"; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "3"; - } - } - - function getErrorSwitch(errorContract add, uint256 errorType ) public payable returns(string memory) { - try add.errorSwitch(errorType) returns (string memory Msg) { - return Msg; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "NoErrorMsg"; - } - } - - function catchNewErrorSwitch(uint256 errorType) public returns (address nc){ - try new NewContract(errorType) returns (NewContract nc){ - return address(nc); - }catch { - return address(0x00); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue001.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue001.sol deleted file mode 100644 index 5388ed68473..00000000000 --- a/framework/src/test/resources/soliditycode/tvmAssetIssue001.sol +++ /dev/null @@ -1,25 +0,0 @@ - -contract tvmAssetIssue001 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateOtherAccountAsset(string memory url, string memory desc) public returns (bool) { - trcToken tokenId = trcToken(1000004); - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue002.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue002.sol deleted file mode 100644 index 87c1206b778..00000000000 --- a/framework/src/test/resources/soliditycode/tvmAssetIssue002.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract tvmAssetIssue002 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - assetissue(name, abbr, totalSupply, precision); - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url1, string memory desc1, string memory url2, string memory desc2) public returns (bool) { - updateasset(tokenId, bytes(url1), bytes(desc1)); - return updateasset(tokenId, bytes(url2), bytes(desc2)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue003.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue003.sol deleted file mode 100644 index f5ce5e0dc3e..00000000000 --- a/framework/src/test/resources/soliditycode/tvmAssetIssue003.sol +++ /dev/null @@ -1,23 +0,0 @@ - - -contract tvmAssetIssue003 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function tokenIssueAndTransfer(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - assetissue(name, abbr, totalSupply, precision); - newaddress.transfer(100000000); - } - - function updateAssetAndTransfer(trcToken tokenId, string memory url, string memory desc, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - updateasset(tokenId, bytes(url), bytes(desc)); - newaddress.transfer(100000000); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue004.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue004.sol deleted file mode 100644 index c8332de8f45..00000000000 --- a/framework/src/test/resources/soliditycode/tvmAssetIssue004.sol +++ /dev/null @@ -1,39 +0,0 @@ - - -contract A { - - constructor() payable public{} - fallback() payable external {} - - function tokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint){ - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAssetA(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} - -contract tvmAssetIssue004 { - - A a; - - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return a.tokenIssueA(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return a.updateAssetA(tokenId, url, desc); - } - - function getContractAddress() public payable returns (address) { - a = (new A).value(1024000000)(); - return address(a); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmAssetIssue005.sol b/framework/src/test/resources/soliditycode/tvmAssetIssue005.sol deleted file mode 100644 index 8c36d050ff8..00000000000 --- a/framework/src/test/resources/soliditycode/tvmAssetIssue005.sol +++ /dev/null @@ -1,45 +0,0 @@ - - -contract tvmAssetIssue005 { - constructor() payable public{} - - fallback() external payable { - } - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} - -contract B { - event Deployed(address addr, uint256 salt); - - function deploy(uint256 salt) public returns (address) { - address addr; - bytes memory code = type(tvmAssetIssue005).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt); - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/tvmVote.sol b/framework/src/test/resources/soliditycode/tvmVote.sol deleted file mode 100644 index 214c7c6b10c..00000000000 --- a/framework/src/test/resources/soliditycode/tvmVote.sol +++ /dev/null @@ -1,89 +0,0 @@ -contract TestVote { - - /** - * @dev Contract can accept value while creating. - */ - constructor() public payable {} - - /** - * @dev Freeze `amount` balance of contract to get resource for `receiver` - * which type is `res` (0 for bandwidth, 1 for energy). - */ - function freeze(address payable receiver, uint amount, uint res) external { - receiver.freeze(amount, res); - } - - /** - * @dev Unfreeze specific balance to get corresponding balance.You can use - * `receiver' and 'res' (0 for bandwidth, 1 for energy) parameters to - * unfreeze specific balance. - */ - function unfreeze(address payable receiver, uint res) external { - receiver.unfreeze(res); - } - - /** - * @dev Vote witness in `srList` array and every witness will get correspond - * tron power in `tpList` array. - */ - function voteWitness(address[] calldata srList, uint[] calldata tpList) external { - vote(srList, tpList); - } - - /** - * @dev Withdraw all allowance and reward to contract balance. Return actually withdraw amount. - */ - function withdrawReward() external returns(uint) { - return withdrawreward(); - } - - /** - * @dev query all allowance and reward of contract account. Return contract's all allowance. - */ - function queryRewardBalance() external view returns(uint) { - return rewardBalance(); - } - - /** - * @dev Judge whether the address is a candidate address.If the address is a candidate address, - * return `true`, or return `false`. - */ - function isWitness(address sr) external view returns(bool) { - return isSrCandidate(sr); - } - - /** - * @dev Query vote count of `from` votes for `to`. Return corresponding vote count. - */ - function queryVoteCount(address from, address to) external view returns(uint) { - return voteCount(from, to); - } - - /** - * @dev Query total vote count of `owner`. Return owner's total vote count. - */ - function queryTotalVoteCount(address owner) external view returns(uint) { - return totalVoteCount(owner); - } - - /** - * @dev Query `owner` recevied vote count. Return owner's received vote count. - */ - function queryReceivedVoteCount(address owner) external view returns(uint) { - return receivedVoteCount(owner); - } - - /** - * @dev Query `owner` used vote count. Return owner's used vote count. - */ - function queryUsedVoteCount(address owner) external view returns(uint) { - return usedVoteCount(owner); - } - - /** - * @dev Execute self destruct and transfer all balance and asset of contract to target address. - */ - function killme(address payable target) external { - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/typeName.sol b/framework/src/test/resources/soliditycode/typeName.sol deleted file mode 100644 index 5b44abd1bbb..00000000000 --- a/framework/src/test/resources/soliditycode/typeName.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract TypeName { - function testTypeName() public returns (string memory){ - return type(TypeName).name; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/unStake001.sol b/framework/src/test/resources/soliditycode/unStake001.sol deleted file mode 100644 index 03734fecfa5..00000000000 --- a/framework/src/test/resources/soliditycode/unStake001.sol +++ /dev/null @@ -1,90 +0,0 @@ - - -contract unStakeTest { - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - - function selfdestructTest(address payable target) public { - selfdestruct(target); - } - - function selfdestructTest2(address sr, uint256 amount, address payable target) public { - stake(sr, amount); - selfdestruct(target); - } - - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - - function unStake() public returns (bool result){ - return unstake(); - } - - function unStake2() public returns (bool result){ - unstake(); - return unstake(); - } - - function withdrawReward() public returns (uint256 amount) { - return withdrawreward(); - } - - function rewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - - function revertTest1(address sr, uint256 amount, address payable transferAddr) public { - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000); - //stake more than balance to fail - transferAddr.transfer(4000000); - } - - function revertTest2(address payable transferAddr) public { - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake(); - //unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - - function BSelfdestructTest(address payable target) public { - b.SelfdestructTest(target); - } -} - -contract B { - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function UnStake() public returns (bool result){ - return unstake(); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/validatemultisign001.sol b/framework/src/test/resources/soliditycode/validatemultisign001.sol deleted file mode 100644 index cc0a742d0c5..00000000000 --- a/framework/src/test/resources/soliditycode/validatemultisign001.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract validatemultisignTest { - function testmulti(address a, uint256 perid, bytes32 hash, bytes[] memory signatures) public returns (bool){ - return validatemultisign(a, perid, hash, signatures); - } - - function testbatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns (bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testMultiPrecompileContract(bytes memory data) public returns(bool, bytes memory){ - return address(0xa).delegatecall(data); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/verifyTransferProof001.sol b/framework/src/test/resources/soliditycode/verifyTransferProof001.sol deleted file mode 100644 index 587b4defd10..00000000000 --- a/framework/src/test/resources/soliditycode/verifyTransferProof001.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract verifyTransferProofTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000002).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000002).delegatecall(data); - } - - function test3(bytes32[10][] memory input, bytes32[2][] memory spendAuthoritySignature, bytes32[9][] memory output, bytes32[2] memory bindingSignature, bytes32 signHash, uint64 valueBalance, bytes32[33] memory frontier, uint256 leafCount) public returns (bytes32[] memory){ - return verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, valueBalance, frontier, leafCount); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode/virtual001.sol b/framework/src/test/resources/soliditycode/virtual001.sol deleted file mode 100644 index f7967626764..00000000000 --- a/framework/src/test/resources/soliditycode/virtual001.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.6.0; -interface X { - function setValue(uint _x) external; -} -abstract contract Y { - function setBool(bool _y) external virtual ; -} -contract Y2 { - string public z; - function setString(string calldata _z) external virtual { z = "123"; } -} - -contract Z is X,Y,Y2 { - uint public x; - bool public y; - function setValue(uint _x) external override { x = _x; } - function setBool(bool _y) external override { y = _y; } - function setString(string calldata _z) external override { z = _z; } -} diff --git a/framework/src/test/resources/soliditycode/walletTestMutiSign004.sol b/framework/src/test/resources/soliditycode/walletTestMutiSign004.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode/walletTestMutiSign004.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/AssertException002.sol b/framework/src/test/resources/soliditycode_0.5.15/AssertException002.sol deleted file mode 100644 index 2bff1dcec3e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/AssertException002.sol +++ /dev/null @@ -1,17 +0,0 @@ -//pragma solidity ^0.4.0; - -contract AssertException{ - function divideIHaveArgsReturn(int x,int y) public returns (int z) { - return x / y; - } - function testAssert() public { - require(2==1); - } -} -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/AssignToExternal.sol b/framework/src/test/resources/soliditycode_0.5.15/AssignToExternal.sol deleted file mode 100644 index d4f09590a36..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/AssignToExternal.sol +++ /dev/null @@ -1,30 +0,0 @@ -contract AssignToExternal { - // Not allow: - // function f(uint256[] calldata x, uint256[] calldata y) external pure { - // x = y; - // } - - // allow: - - function f(uint256 a) external returns (uint){ - a = a + 1; - return a; - } - - function StringSet(string calldata a) external returns (string memory){ - return a; - } - - function ByteSet(bytes32 a) external returns (bytes32){ - return a; - } - - function UintArraySet(uint256[2] calldata a) external returns (uint256[2] memory){ - return a; - } - - function AddSet(address a) external returns (address){ - return a; - } - -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/BlockHash.sol b/framework/src/test/resources/soliditycode_0.5.15/BlockHash.sol deleted file mode 100644 index 6603da65e44..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/BlockHash.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract TestBlockHash { - - function testOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) | bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) | blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) & bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) & blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) ^ bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) ^ blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ClearAbi001.sol b/framework/src/test/resources/soliditycode_0.5.15/ClearAbi001.sol deleted file mode 100644 index fccc59e14be..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/ClearAbi001.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ -function testPayable() public view returns (int z) { -return 1; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ClearAbi005.sol b/framework/src/test/resources/soliditycode_0.5.15/ClearAbi005.sol deleted file mode 100644 index a3115398386..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/ClearAbi005.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=0; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ConstructorDefaults.sol b/framework/src/test/resources/soliditycode_0.5.15/ConstructorDefaults.sol deleted file mode 100644 index 4b6186ccb95..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/ConstructorDefaults.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract testIsContract{ - bool result; - constructor (bool a) public { - result = a; - } -function test( address a) public returns (bool) { -return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/Create2Test023.sol b/framework/src/test/resources/soliditycode_0.5.15/Create2Test023.sol deleted file mode 100644 index 4c3f8af9f2b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/Create2Test023.sol +++ /dev/null @@ -1,31 +0,0 @@ -contract factory { - constructor() payable public { - } - - function deploy(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } - - function testCreate() payable public returns (address){ - Caller add = (new Caller).value(0)(); - return address(add); - } - - function kill( ) payable public{ - selfdestruct(msg.sender); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/Create2Test024.sol b/framework/src/test/resources/soliditycode_0.5.15/Create2Test024.sol deleted file mode 100644 index f5a9d032cff..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/Create2Test024.sol +++ /dev/null @@ -1,56 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(msg.sender); - addr.set(); - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } - - function deploy2(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - //addr.testSuicideNonexistentTarget(msg.sender); - //addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/Create2Test025.sol b/framework/src/test/resources/soliditycode_0.5.15/Create2Test025.sol deleted file mode 100644 index 895dc43e56f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/Create2Test025.sol +++ /dev/null @@ -1,34 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } -} - -contract TestContract{ - uint256 public num; - constructor(uint256 j) public{ - num = j; - } - function getNum() public returns (uint256){ - return num; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ExtCodeHashTest010.sol b/framework/src/test/resources/soliditycode_0.5.15/ExtCodeHashTest010.sol deleted file mode 100644 index bfa8a7fa0d8..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/ExtCodeHashTest010.sol +++ /dev/null @@ -1,46 +0,0 @@ -contract Counter { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); - constructor() public{ - owner = msg.sender; - } - function getCodeHashSuicide(address addr) public returns (bytes32 _hashBefore){ - assembly{ - _hashBefore := extcodehash(addr) - } - selfdestruct(owner); - return _hashBefore; - } - - function getCodeHashRevert() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - address addr = address(this); - assembly { - _hashBefore := extcodehash(addr) - } - if (owner == msg.sender) { - selfdestruct(owner); - } - assembly { - _hashAfter := extcodehash(addr) - } - revert(); - emit LogResult(_hashBefore, _hashAfter); - } - - function getCodeHashCreate() public returns (bytes32 _hashBefore){ - TestContract A = (new TestContract).value(0)(); - address addr = address(A); - assembly{ - _hashBefore := extcodehash(addr) - } - revert(); - return _hashBefore; - } -} - -contract TestContract{ - uint256 count = 1; - constructor() public payable{ - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ParentTypeBug.sol b/framework/src/test/resources/soliditycode_0.5.15/ParentTypeBug.sol deleted file mode 100644 index 897c843ae24..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/ParentTypeBug.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract Parent { - uint256 public m_aMember; - address public m_bMember; -} -contract Child is Parent { - function foo() public view returns (uint256) { return Parent.m_aMember; } - function bar() public view returns (address) { return Parent.m_bMember; } - - // complie failed - // function foo() public pure returns (uint256) { return Parent.m_aMember; } - // function bar() public pure returns (address) { return Parent.m_bMember; } - -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/SafeMath.sol b/framework/src/test/resources/soliditycode_0.5.15/SafeMath.sol deleted file mode 100644 index b154b8b81b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/SafeMath.sol +++ /dev/null @@ -1,149 +0,0 @@ -pragma solidity ^0.5.8; - -/** - * @dev Wrappers over Solidity's arithmetic operations with added overflow - * checks. - * - * Arithmetic operations in Solidity wrap on overflow. This can easily result - * in bugs, because programmers usually assume that an overflow raises an - * error, which is the standard behavior in high level programming languages. - * `SafeMath` restores this intuition by reverting the transaction when an - * operation overflows. - * - * Using this library instead of the unchecked operations eliminates an entire - * class of bugs, so it's recommended to use it always. - */ -library SafeMath { - /** - * @dev Returns the addition of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - Addition cannot overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 c = a + b; - require(c >= a, "SafeMath: addition overflow"); - - return c; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - return sub(a, b, "SafeMath: subtraction overflow"); - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting with custom message on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b <= a, errorMessage); - uint256 c = a - b; - - return c; - } - - /** - * @dev Returns the multiplication of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - Multiplication cannot overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) { - return 0; - } - - uint256 c = a * b; - require(c / a == b, "SafeMath: multiplication overflow"); - - return c; - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - return div(a, b, "SafeMath: division by zero"); - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts with custom message on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b > 0, errorMessage); - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - - return c; - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b) internal pure returns (uint256) { - return mod(a, b, "SafeMath: modulo by zero"); - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts with custom message when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b != 0, errorMessage); - return a % b; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/ShiftCommand001.sol b/framework/src/test/resources/soliditycode_0.5.15/ShiftCommand001.sol deleted file mode 100644 index 574ee2b571b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/ShiftCommand001.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/SolidityMappingFix.sol b/framework/src/test/resources/soliditycode_0.5.15/SolidityMappingFix.sol deleted file mode 100644 index 67692d3b4ae..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/SolidityMappingFix.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Tests { - mapping(address => uint) public balances; - function update(uint256 amount) public returns (address addr) - { - balances[msg.sender] = amount; - return msg.sender; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TestMappings_array_pop.sol b/framework/src/test/resources/soliditycode_0.5.15/TestMappings_array_pop.sol deleted file mode 100644 index 3ceac916049..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TestMappings_array_pop.sol +++ /dev/null @@ -1,19 +0,0 @@ -contract C { - mapping (uint256 => uint256)[] a; - - function n1(uint256 key, uint256 value) public { - a.length++; - a[a.length - 1][key] = value; - } - - - - function map(uint256 key) public view returns (uint) { - return a[a.length - 1][key]; - } - - function p() public { - a.pop(); - } -} - diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed001.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed001.sol deleted file mode 100644 index dba043edcb3..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed001.sol +++ /dev/null @@ -1,147 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - - function testTransferTokenCompiledLongMax() payable public{ - address(0x1).transferToken(1,9223372036855775827); - } - - function testTransferTokenCompiled() payable public{ - address(0x1).transferToken(1,1); - } - - function testTransferTokenCompiledLongMin() payable public{ - //address(0x1).transferToken(1,-9223372036855775828); - } - - function testTransferTokenCompiledLongMin1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(-9223372036855775828)); - } - - function testTransferTokenCompiled1() payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(1)); - } - - function testTransferTokenCompiledLongMax1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(9223372036855775827)); - } - - function testTransferTokenCompiledTokenId(uint256 tokenid) payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(tokenid)); - } - - function testTransferTokenTest(address addr ,uint256 tokenid) payable public returns(uint256){ - return addr.tokenBalance(trcToken(tokenid)); - } - - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public { - caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - } - - function testSendTrxRevert(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - revert(); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.transfer(i); - } - - function testTransferTrxrevert(uint256 i,address payable nonexistentTarget) payable public{ - nonexistentTarget.transfer(i); - revert(); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - } - - function testTransferTokenRevert(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - revert(); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - function testSuicideRevert(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - revert(); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - function deploy2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(300, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed005.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed005.sol deleted file mode 100644 index aa39aafa152..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed005.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed006.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed006.sol deleted file mode 100644 index aa39aafa152..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed006.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed007.sol b/framework/src/test/resources/soliditycode_0.5.15/TransferFailed007.sol deleted file mode 100644 index aa39aafa152..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TransferFailed007.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant001.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant001.sol deleted file mode 100644 index 515b9e07724..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant001.sol +++ /dev/null @@ -1,28 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ - uint256 public i; - function testPayable() public payable returns (uint256 z) { - i=1; - z=i; - return z; - } - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - function testView2() public view returns (uint256 z) { - uint256 i=1; - revert(); - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant002.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant002.sol deleted file mode 100644 index 44332e58c51..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant002.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ - uint256 public i; - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant003.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant003.sol deleted file mode 100644 index 03e29fb76b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant003.sol +++ /dev/null @@ -1,18 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPayable() public payable returns (uint256 z) { - uint256 i=1; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant004.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant004.sol deleted file mode 100644 index fce77178ca7..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant004.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ -function testPure() public pure returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant015.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant015.sol deleted file mode 100644 index d926c43c824..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant015.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - constructor () public { - } - function plusOne() public returns(uint){ - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant024.sol b/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant024.sol deleted file mode 100644 index 287b0fc9782..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TriggerConstant024.sol +++ /dev/null @@ -1,9 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ -function testView() public view returns (uint256 z) { -uint256 i=1; -revert(); -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract.sol deleted file mode 100644 index 4266b9e92ca..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract001.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract001.sol deleted file mode 100644 index 77aae930b59..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract001.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} - -function testIsContractView(address a) view public returns (bool) { -return (a.isContract); -} - -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} - -function testConstructorView() public view returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract002.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract002.sol deleted file mode 100644 index 2fe474fd98c..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmIsContract002.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract testIsContract{ -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand043.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand043.sol deleted file mode 100644 index 04d9f7dde28..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand043.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand103.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand103.sol deleted file mode 100644 index 7ad130c87c6..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand103.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ -function testView() public constant returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand107.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand107.sol deleted file mode 100644 index 4dcd33ad7b0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand107.sol +++ /dev/null @@ -1,9 +0,0 @@ -//pragma solidity ^0.4.0; - - contract testConstantContract{ - int256 public i; - function testPayable() public returns (int z) { - z=1+1; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand108.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand108.sol deleted file mode 100644 index b44d5c82731..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand108.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - - contract testConstantContract{ - function test() pure public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand109.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand109.sol deleted file mode 100644 index 864f01f7fb4..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmNewCommand109.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - - contract testConstantContract{ - function test() view public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/TvmOldCommand001.sol b/framework/src/test/resources/soliditycode_0.5.15/TvmOldCommand001.sol deleted file mode 100644 index 9f3cf079ea1..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/TvmOldCommand001.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.0; - -contract binaryRightContract{ - function binaryMoveR(int i)public returns (int z) { - return z = 5 >> i; - } - function binaryLiftR(int i)public returns (int z) { - return z = 5 << i; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/VerifyBurnProof001.sol b/framework/src/test/resources/soliditycode_0.5.15/VerifyBurnProof001.sol deleted file mode 100644 index 4173e84de23..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/VerifyBurnProof001.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract VerifyBurnProof001Test { - // verifyBurnProof(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32) - // size = 512 - // - - function VerifyBurnProofSize001(bytes32[10] memory output, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature,bytes32 signHash) public returns (bool){ - return verifyBurnProof(output, spendAuthoritySignature, value, bindingSignature, signHash); - } - - function VerifyBurnProofSize002(bytes memory data) public returns (bool, bytes memory){ - // bytes memory empty = ""; - return address(0x1000003).delegatecall(data); - } - - function VerifyBurnProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000003).delegatecall(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/VerifyMintProof001.sol b/framework/src/test/resources/soliditycode_0.5.15/VerifyMintProof001.sol deleted file mode 100644 index cb0812c2ef5..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/VerifyMintProof001.sol +++ /dev/null @@ -1,33 +0,0 @@ - -contract VerifyMintProof001Test { - // verifyMintProof(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256) - - function VerifyMintProofSize001(bytes32[9] memory output, bytes32[2] memory bindingSignature, uint64 value, bytes32 signHash, bytes32[33] memory frontier,uint256 leafCount) public returns (bytes32[] memory){ - return verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - } - - function VerifyMintProofSize002(bytes memory data) public returns (bool, bytes memory){ -// address verifyMint = address (0x1000001); -// -// assembly { -// let succeeded := delegatecall(sub(gas, 5000), verifyMint, add(data, 0x20), mload(data), 0, 0) -// let size := returndatasize -// let response := mload(0x40) -// mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) -// mstore(response, size) -// returndatacopy(add(response, 0x20), 0, size) -// switch iszero(succeeded) -// case 1 { -// // throw if delegatecall failed -// revert(add(response, 0x20), size) -// } -// } - - return address(0x1000001).delegatecall(data); - } - - function VerifyMintProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000001).call(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/abiencode.sol b/framework/src/test/resources/soliditycode_0.5.15/abiencode.sol deleted file mode 100644 index 38fad3454d6..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/abiencode.sol +++ /dev/null @@ -1,16 +0,0 @@ -pragma experimental ABIEncoderV2; - -// tests encoding from storage arrays - -contract AbiEncode { - int256[2][] tmp_h; - function h(int256[2][] calldata s) external returns (bytes memory) { - tmp_h = s; - return abi.encode(tmp_h); - } - int256[2][2] tmp_i; - function i(int256[2][2] calldata s) external returns (bytes memory) { - tmp_i = s; - return abi.encode(tmp_i); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg001Nonpayable.sol deleted file mode 100644 index d1294f2336a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addMsg001Nonpayable.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -event log(uint256); -constructor() payable public{} - -function() payable external{} - -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue)public { -// function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg002View.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg002View.sol deleted file mode 100644 index 423bb68e3ed..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addMsg002View.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable external{} - -event log(uint256); - -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} - diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg003Constant.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg003Constant.sol deleted file mode 100644 index 0f0ab7553e0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addMsg003Constant.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable external{} - -event log(uint256); - -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addMsg004Pure.sol b/framework/src/test/resources/soliditycode_0.5.15/addMsg004Pure.sol deleted file mode 100644 index b5d3a4e4aee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addMsg004Pure.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable external{} - -event log(uint256); - -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001Nonpayable.sol deleted file mode 100644 index c8d0dcc7560..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001Nonpayable.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.24; - - contract IllegalDecorate { - - constructor() payable public{} - - function() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue)public { - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001payable.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001payable.sol deleted file mode 100644 index 803d66ad75e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken001payable.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.24; - - contract IllegalDecorate { - - constructor() payable public{} - - function() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue) public payable{ - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken002View.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken002View.sol deleted file mode 100644 index 109f46386ce..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken002View.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - - constructor() payable public{} - - function() payable external{} - - function transferTokenWithView(address payable toAddress,trcToken id, uint256 tokenValue) public view{ - - toAddress.transferToken(tokenValue, id); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken003Constant.sol deleted file mode 100644 index fb1a2cbbbb4..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken003Constant.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - - constructor() payable public{} - - function() payable external{} - - function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode_0.5.15/addTransferToken004Pure.sol deleted file mode 100644 index 7ea2bf0a40b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTransferToken004Pure.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - - constructor() payable public{} - - function() payable external{} - - function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken001Assemble.sol deleted file mode 100644 index a93d9046a3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken001Assemble.sol +++ /dev/null @@ -1,62 +0,0 @@ -//pragma solidity ^0.4.24; - -contract InAssemble { - -mapping(trcToken => uint256) tokenCnt; -mapping(uint256 => mapping(trcToken => trcToken)) cntTokenToken; -constructor () payable public {} -function getBalance (address addr) view public returns(uint256 r) { -assembly{ -r := balance(addr) -} -} - -function getTokenBalanceConstant (address addr, trcToken tokenId) view public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function getTokenBalance (address addr, trcToken tokenId) public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function transferTokenInAssembly(address addr, trcToken tokenId, uint256 tokenValue) public payable { -bytes4 sig = bytes4(keccak256("()")); // function signature - -assembly { -let x := mload(0x40) // get empty storage location -mstore(x,sig) // 4 bytes - place signature in empty storage - -let ret := calltoken(gas, addr, tokenValue, tokenId, -x, // input -0x04, // input size = 4 bytes -x, // output stored at input location, save space -0x0 // output size = 0 bytes -) - -// let ret := calltoken(gas, addr, tokenValue, -// x, // input -// 0x04, // input size = 4 bytes -// x, // output stored at input location, save space -// 0x0 // output size = 0 bytes -// ) // ERROR - - -mstore(0x40, add(x,0x20)) // update free memory pointer -} - -} - -function trcTokenInMap(trcToken tokenId, uint256 tokenValue) public returns(uint256 r) { -tokenCnt[tokenId] += tokenValue; -r = tokenCnt[tokenId]; -} - -function cntTokenTokenInMap(trcToken tokenId1, trcToken tokenId2, uint256 tokenValue) public returns(trcToken r) { -cntTokenToken[tokenValue][tokenId1] = tokenId2; -r = cntTokenToken[tokenValue][tokenId1]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat.sol deleted file mode 100644 index 6d9c169330d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat.sol +++ /dev/null @@ -1,2051 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat_withFinny.sol deleted file mode 100644 index 2acebceddda..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addTrcToken002Cat_withFinny.sol +++ /dev/null @@ -1,2051 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 finney; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 finney; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.5.15/addressCheckNew.sol b/framework/src/test/resources/soliditycode_0.5.15/addressCheckNew.sol deleted file mode 100644 index 3c10b8c680d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addressCheckNew.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns(address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/addressCheckOld.sol b/framework/src/test/resources/soliditycode_0.5.15/addressCheckOld.sol deleted file mode 100644 index 6c6b15d1736..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/addressCheckOld.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns (address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/altbn.sol b/framework/src/test/resources/soliditycode_0.5.15/altbn.sol deleted file mode 100644 index ee6ca1a98c9..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/altbn.sol +++ /dev/null @@ -1,63 +0,0 @@ -pragma solidity ^0.5.12; - -contract AltBn128 { - constructor() public payable {} - function callBn256Add(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas, 0x06, 0, input, 0x80, result, 0x40) - } - - } - - function callBn256AddNoValue(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns - (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas, 0xac, 0, input, 0x80, result, 0x40) - } - } - - function callBn256ScalarMul(bytes32 x, bytes32 y, bytes32 scalar) public returns (bytes32[2] memory result) { - bytes32[3] memory input; - input[0] = x; - input[1] = y; - input[2] = scalar; - assembly { - let success := call(gas, 0x07, 0, input, 0x60, result, 0x40) - switch success - case 0 { - revert(0,0) - } - } - } - - function callBn256Pairing(bytes memory input) public returns (bytes32 result) { - // input is a serialized bytes stream of (a1, b1, a2, b2, ..., ak, bk) from (G_1 x G_2)^k - uint256 len = input.length; - require(len % 192 == 0); - assembly { - let memPtr := mload(0x40) - let success := call(gas, 0x08, 0, add(input, 0x20), len, memPtr, 0x20) - switch success - case 0 { - revert(0,0) - } default { - result := mload(memPtr) - } - } - } - - function convert(uint256 num) public view returns(bytes32) { - return bytes32(num); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/arrayLength001.sol b/framework/src/test/resources/soliditycode_0.5.15/arrayLength001.sol deleted file mode 100644 index 1c7e4e9dac2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/arrayLength001.sol +++ /dev/null @@ -1,16 +0,0 @@ - -contract Test { - byte[] a; - - function ChangeSize() external returns(byte[] memory) { - a.push(0x01); - a.length = 3; - - a.length ++; - a.length --; - a.length --; - - a.pop(); - return a; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assemblyTest.sol b/framework/src/test/resources/soliditycode_0.5.15/assemblyTest.sol deleted file mode 100644 index 6da31ff7b6f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assemblyTest.sol +++ /dev/null @@ -1,62 +0,0 @@ -pragma solidity ^0.5.12; - -contract assemblyTest { - - uint constant x = 1; - uint constant y = x; - function getZuint() public view returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - function getZuint2() public returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - bool constant bool1 = true; - bool constant bool2 = bool1; - function getZbool() public view returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - function getZbool2() public returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - -// string constant string1 = "abc"; -// string constant string2 = string1; -// function getZstring() public view returns (string memory) { -// string memory z; -// assembly { -// z := string2 -// } -// return z; -// } - - -// address origin1 = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; -// address origin2 = origin1; -// function getZaddress() public view returns (address) { -// address z; -// assembly { -// z := origin2 -// } -// return z; -// } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest1DivideInt.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest1DivideInt.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest2FindArgsContractMinTest.sol deleted file mode 100644 index b8565d2578e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest2FindArgsContractMinTest.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.0; -contract findArgsIContract{ -function findArgsByIndex1(uint i) public returns (uint z) { -uint[] memory a = new uint[](3); -a[0]=1; -a[1]=2; -a[2]=3; -return a[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest3ByteMinContract.sol deleted file mode 100644 index 6d846fad7f4..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest3ByteMinContract.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity >0.5.0; -contract byteContract{ -bytes b; -function testBytesGet(uint i) public returns (bytes1){ -b = new bytes(3); -b[0]=0x0b; -b[1]=0x0c; -b[2]=0x0d; -return b[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest4Enum.sol deleted file mode 100644 index 4a740d4a089..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest4Enum.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.4; - -contract enumContract { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices _choice; - function setGoStraight(ActionChoices choice) public { - _choice = choice; - } - - function getChoice() public returns (ActionChoices) { - return _choice; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest5MoveRight.sol deleted file mode 100644 index 7194520fb09..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest5MoveRight.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract binaryRightContract{ - function binaryMoveR(int i)public returns (int z) { - return z = 5 >> i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest6UninitializedContract.sol deleted file mode 100644 index 1ff2215abdb..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest6UninitializedContract.sol +++ /dev/null @@ -1,27 +0,0 @@ -//pragma solidity ^0.4.0; -contract uni { -function b(int x, int y) internal returns (int) -{ - return x * y; -} - -function test1() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - funcPtr = b; - - // This call to funcPtr will succeed - return funcPtr(4, 5); -} - -function test2() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - // This call will fail because funcPtr is still a zero-initialized function pointer - return funcPtr(4, 5); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest7TestAssertContract.sol deleted file mode 100644 index 0bfd6fbd04e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/assertExceptiontest7TestAssertContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma solidity >0.5.0; -contract TestThrowsContract{ - function testAssert() public{ - assert(1==2); - } - function testRequire() public{ - require(2==1); - } - function testRevert() public{ - revert(); - } - function testThrow() public{ - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign.sol deleted file mode 100644 index 9e1c1b289b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - //function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - //} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign001.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign001.sol deleted file mode 100644 index 57e051ce415..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign001.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testPure(bytes32 hash, bytes[] memory signatures, address[] memory addresses) pure public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign002.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign002.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign002.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign003.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign003.sol deleted file mode 100644 index c43536af499..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign003.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { -bytes32 public result; -constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); -} -function testConstructor() public returns(bytes32){ - return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign005.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign005.sol deleted file mode 100644 index 3a6ca362973..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign005.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign007.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign007.sol deleted file mode 100644 index 974ffb34efe..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign007.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { - bytes32 public result; - - constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); - } - - function testConstructor() public returns(bytes32){ - return result; - } - - function testConstructorPure() public view returns(bytes32){ - return result; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign02.sol b/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign02.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/batchvalidatesign02.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/callValueGasPure.sol b/framework/src/test/resources/soliditycode_0.5.15/callValueGasPure.sol deleted file mode 100644 index ed4877e1ce4..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/callValueGasPure.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract C { -function check(address a) external pure returns (bool success) { - a.call.value(42).gas(42); - a.call.gas(42); - //a.call.value(1).gas(42)("fwefewf"); -} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/calldata.sol b/framework/src/test/resources/soliditycode_0.5.15/calldata.sol deleted file mode 100644 index 6e877ac1b2f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/calldata.sol +++ /dev/null @@ -1,33 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract C { - struct S { uint256 a; } - - function f(S calldata s) external returns (bytes memory) { - return abi.encode(s); - } - - function g(S calldata s) external returns (bytes memory) { - return this.f(s); - } - - function m(uint256[] calldata) external pure returns (bytes memory) { - return msg.data; - } - function h(uint8[] calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function i(uint8[][2] calldata s, uint256 which) external view returns (bytes memory) { - return this.h(s[which]); - } - function j(bytes calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function k(bytes[2] calldata s, uint256 which) external view returns (bytes memory) { - return this.j(s[which]); - } - function l(function() external returns (uint)[] calldata s) external returns (uint, uint, uint) { - assert(s.length == 3); - return (s[0](), s[1](), s[2]()); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/callvalue.sol b/framework/src/test/resources/soliditycode_0.5.15/callvalue.sol deleted file mode 100644 index ee2a30342c5..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/callvalue.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract Callvalue { -function check() public payable returns(uint) { - uint256 wad; - assembly { - wad := callvalue - } - return wad; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/chainid001.sol b/framework/src/test/resources/soliditycode_0.5.15/chainid001.sol deleted file mode 100644 index c057a83b325..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/chainid001.sol +++ /dev/null @@ -1,20 +0,0 @@ -pragma solidity ^0.5.12; - -contract IstanbulTest { - constructor() public payable {} - function getId() public view returns(uint256){ - uint256 id; - assembly { - id := chainid() - } - return id; - } - - function getBalance(address src) public view returns(uint256){ - return address(src).balance; - } - - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/codeSaftySupport.sol b/framework/src/test/resources/soliditycode_0.5.15/codeSaftySupport.sol deleted file mode 100644 index 45a4beee384..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/codeSaftySupport.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable external{} - -event log(uint256); - -function transferToken(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode_0.5.15/codeSaftyUnsupport.sol deleted file mode 100644 index 220d66b2257..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/codeSaftyUnsupport.sol +++ /dev/null @@ -1,56 +0,0 @@ -//pragma solidity ^0.4.24; - -contract SubC { - -event log(string); - -function () payable external{} - -function receiveToken() payable public{} - -function getBalance() view public returns (uint256 r) { -r = address(this).balance; -} -} - -contract UseDot { -constructor() payable public{} -function() payable external{} -mapping(address => mapping(trcToken => uint256)) sender_tokens; - -function trigger1(address payable addr, trcToken tokenInputId) payable public { - //address(SubC(addr)).call.value(1000).tokenId(tokenInputId)(abi.encodeWithSignature("receiveToken()")); // ERROR -} - -function trigger2(address payable addr) payable public { -// addr.transferToken.value(10)(10, 0x6e6d62); // ERROR -} - -function trigger3(address payable addr) payable public { - // address(SubC(addr)).receiveToken.tokenvalue(10)(); // ERROR -} - -function trigger4(address payable addr) payable public { - //SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR -} - -function trigger5(address payable addr) payable public { - SubC(addr).receiveToken.value(10)(); -} - -function trigger6(address payable addr, trcToken tokenId) payable public { -address(SubC(addr)).call.value(1000)(abi.encodeWithSignature("transferToken(uint256, trcToken)", 10, tokenId)); -} - -function trigger7(address addr) payable public { - //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger -} - -function trigger8(address addr) public payable returns(bytes memory r){ -// r = msg.data; // compile success, no necessary to trigger -} - -function getBalance() public returns (uint256 r){ -r = address(this).balance; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage001.sol b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage001.sol deleted file mode 100644 index 1f584923a55..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage001.sol +++ /dev/null @@ -1,159 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} -contract viewCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = bytes32(uint256(0xdCad3a6d3569DF655070DEd0)); - bytes bs = new bytes(3); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.GoRight; - int64[] b = [-1, 2, -3]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - constructor() payable public{ - mapa[address(0x00)] = 34; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - function changeBool(bool param) public returns (bool){ - stopped = param; - emit log(stopped); - return stopped; - } - function getBool() public returns (bool){ - emit log(stopped); - return stopped; - } - function changeInt(int param) public returns (int){ - i = param; - emit log(i); - return i; - } - function getInt() public returns (int){ - emit log(i); - return i; - } - function changeNegativeInt(int param) public returns (int){ - i2 = param; - emit log(i2); - return i2; - } - function getNegativeInt() public returns (int){ - emit log(i2); - return i2; - } - function changeUint(uint param) public returns (uint){ - ui = param; - emit log(ui); - return ui; - } - function getUint() public returns (uint){ - emit log(ui); - return ui; - } - function changeAddress(address param) public returns (address){ - origin = param; - emit log(origin); - return origin; - } - function getAddress() public returns (address){ - emit log(origin); - return origin; - } - function changeBytes32(bytes32 param) public returns (bytes32){ - b32 = param; - emit log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - emit log(b32); - return b32; - } - function changeBytes(bytes memory param) public returns (bytes memory){ - bs = param; - emit log(bs); - return bs; - } - function getBytes() public returns (bytes memory){ - emit log(bs); - return bs; - } - function changeString(string memory param) public returns (string memory){ - s = param; - emit log(s); - return s; - } - function getString() public returns (string memory){ - emit log(s); - return s; - } - function changeActionChoices(ActionChoices param) public returns (ActionChoices){ - choice = param; - emit log(choice); - return choice; - } - function getActionChoices() public returns (ActionChoices){ - emit log(choice); - return choice; - } - function changeInt64NegativeArray(int64[] memory param) public returns (int64[] memory){ - b = param; - emit log(b); - return b; - } - function getInt64NegativeArray() public returns (int64[] memory){ - emit log(b); - return b; - } - function changeInt32Array(int32[2][] memory param) public returns (int32[2][] memory){ - tmp_h = param; - emit log(tmp_h); - return tmp_h; - } - function getInt32Array() public returns (int32[2][] memory){ - emit log(tmp_h); - return tmp_h; - } - function changeInt256Array(int256[2][2] memory param) public returns (int256[2][2] memory){ - tmp_i = param; - emit log(tmp_i); - return tmp_i; - } - function getInt256Array() public returns (int256[2][2] memory){ - emit log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage002.sol b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage002.sol deleted file mode 100644 index 1ceba5e87d2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage002.sol +++ /dev/null @@ -1,16 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public view returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public view returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage0425.sol b/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage0425.sol deleted file mode 100644 index 8ecf771626d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/constantCallStorage0425.sol +++ /dev/null @@ -1,156 +0,0 @@ -contract constantCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - bytes bs = new bytes(9); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.SitStill; - int64[] b = [91, 2, 333]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - - constructor() payable public{ - mapa[address(0x00)] = 88; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - - function changeBool(bool param) public constant returns (bool){ - stopped = param; - log(stopped); - return stopped; - } - function getBool() public constant returns (bool){ - log(stopped); - return stopped; - } - - function changeInt(int param) public returns (int){ - i = param; - log(i); - return i; - } - function getInt() public returns (int){ - log(i); - return i; - } - - function changeNegativeInt(int param) public constant returns (int){ - i2 = param; - log(i2); - return i2; - } - function getNegativeInt() public constant returns (int){ - log(i2); - return i2; - } - - function changeUint(uint param) public returns (uint){ - ui = param; - log(ui); - return ui; - } - function getUint() public returns (uint){ - log(ui); - return ui; - } - - function changeAddress(address param) public constant returns (address){ - origin = param; - log(origin); - return origin; - } - function getAddress() public constant returns (address){ - log(origin); - return origin; - } - - function changeBytes32(bytes32 param) public constant returns (bytes32){ - b32 = param; - log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - log(b32); - return b32; - } - - function changeBytes(bytes param) public constant returns (bytes){ - bs = param; - log(bs); - return bs; - } - function getBytes() public constant returns (bytes){ - log(bs); - return bs; - } - - function changeString(string param) public constant returns (string){ - s = param; - log(s); - return s; - } - function getString() public returns (string){ - log(s); - return s; - } - - function changeActionChoices(ActionChoices param) public constant returns (ActionChoices){ - choice = param; - log(choice); - return choice; - } - function getActionChoices() public constant returns (ActionChoices){ - log(choice); - return choice; - } - - function changeInt64NegativeArray(int64[] param) public constant returns (int64[]){ - b = param; - log(b); - return b; - } - function getInt64NegativeArray() public constant returns (int64[]){ - log(b); - return b; - } - - function changeInt32Array(int32[2][] param) public returns (int32[2][]){ - tmp_h = param; - log(tmp_h); - return tmp_h; - } - function getInt32Array() public constant returns (int32[2][]){ - log(tmp_h); - return tmp_h; - } - - function changeInt256Array(int256[2][2] param) public returns (int256[2][2]){ - tmp_i = param; - log(tmp_i); - return tmp_i; - } - function getInt256Array() public constant returns (int256[2][2]){ - log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/constantContract001.sol b/framework/src/test/resources/soliditycode_0.5.15/constantContract001.sol deleted file mode 100644 index ab97b450235..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/constantContract001.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; - -contract testConstantContract{ -function testPure(uint256 x,uint256 y) public pure returns (uint256 z) { -uint256 i=1; -return i + x + y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGetterContract.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGetterContract.sol deleted file mode 100644 index ba090f061dd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGetterContract.sol +++ /dev/null @@ -1,17 +0,0 @@ -//pragma solidity ^0.4.0; - - -contract getterContract { - -constructor() public payable{} -function() external payable{} - -uint public c = msg.value; - -function getDataUsingAccessor() public payable returns (uint){ - -return c; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test1Grammar001.sol deleted file mode 100644 index 1d0ad6e3d3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test1Grammar001.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma solidity >0.5.0; -contract FunctionSelector { - function select(bool useB, uint x) public returns (uint z) { - //var f = a; - //if (useB) f = b; - //return f(x); - if (useB) - return b(x); - else - return a(x); - } -function a(uint x) public returns (uint z) { - return x * x; - } -function b(uint x) public returns (uint z) { - return 2 * x; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test2Grammar002.sol deleted file mode 100644 index df9d5c88839..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test2Grammar002.sol +++ /dev/null @@ -1,44 +0,0 @@ -//pragma solidity ^0.4.16; -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert(Data storage self, uint value) public returns (bool) { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public returns (bool) { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public returns (bool) { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register (uint value) public{ - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test3Grammar003.sol deleted file mode 100644 index ce56f5c9912..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test3Grammar003.sol +++ /dev/null @@ -1,44 +0,0 @@ -//pragma solidity ^0.4.11; - -library Set { - struct Data { mapping(uint => bool) flags; } - - function insert(Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - using Set for Set.Data; // this is the crucial change - Set.Data knownValues; - - function register(uint value) public{ - // Here, all variables of type Set.Data have - // corresponding member functions. - // The following function call is identical to - // Set.insert(knownValues, value) - if (!knownValues.insert(value)) - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test4Grammar004.sol deleted file mode 100644 index b36d171a912..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test4Grammar004.sol +++ /dev/null @@ -1,31 +0,0 @@ -//pragma solidity ^0.4.0; - -library Search { - function indexOf(uint[] storage self, uint value) public returns (uint) { - for (uint i = 0; i < self.length; i++) - if (self[i] == value) return i; - return uint(-1); - } -} - - -contract C { - using Search for uint[]; - uint[] public data; - - function append(uint value) public{ - data.push(value); - } - - function replace(uint _old, uint _new) public{ - // This performs the library function call - uint index = data.indexOf(_old); - if (index == uint(-1)) - data.push(_new); - else - data[index] = _new; - } - function getData(uint256 index) public returns(uint256){ - return data[index]; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test5Grammar006.sol deleted file mode 100644 index 805476a9e4a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar001test5Grammar006.sol +++ /dev/null @@ -1,38 +0,0 @@ -// pragma solidity ^0.4.0; -contract InfoFeed { -function d1(uint x) public{ - assembly{ - function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } } - } - } - function d2(uint x) public{ - assembly { x := mul(1, add(2, 3))} - } - function f(uint x) public{ - assembly { x := sub(x, 1) } - - } - function d(uint x) public{ - assembly{ - let x := add(2, 3) let y := mload(0x40) x := add(x, y) - } - } - function d4(uint x) public{ - // Error: The labels 'repeat' is disallowed. Please use "if", "switch", "for" or function calls instead - //assembly{let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0)) - x = x; - //} - } - function d5(uint x) public{ - assembly{ - function f(x) -> y { switch x case 0 { y := mul(x, 2) } default { y := 0 } } - - } - } - - function d6(uint x) public{ - assembly{ - function f(x) -> y { for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) } } - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_1.sol deleted file mode 100644 index 6e3ac0bfd1e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_1.sol +++ /dev/null @@ -1,60 +0,0 @@ -//pragma solidity ^0.4.19; -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -contract DogInterface { - function getDougAge(uint _age) public returns (uint); - function contracts(bytes32 name) public returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_2.sol deleted file mode 100644 index 6e3ac0bfd1e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test1Grammar007_2.sol +++ /dev/null @@ -1,60 +0,0 @@ -//pragma solidity ^0.4.19; -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -contract DogInterface { - function getDougAge(uint _age) public returns (uint); - function contracts(bytes32 name) public returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test2Grammar008.sol deleted file mode 100644 index c9c5d614d2d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test2Grammar008.sol +++ /dev/null @@ -1,14 +0,0 @@ -//pragma solidity ^0.4.19; -contract Feline { - function utterance() public returns (bytes32); - - function getContractName() public returns (string memory){ - return "Feline"; - } -} - - -contract Cat is Feline { - function utterance() public returns (bytes32) { return "miaow"; } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test3Grammar010.sol deleted file mode 100644 index a7749dfcc71..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test3Grammar010.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.0; -contract InfoFeed { -function info() public payable returns (uint ret) { return 42; } -} -contract Consumer { -constructor() payable public{} -InfoFeed feed; -function setFeed(address addr) public { feed = InfoFeed(addr); } -function callFeed() public payable { feed.info.value(10).gas(800)(); } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar011.sol deleted file mode 100644 index 921b52a6080..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar011.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.0; -contract C { -function f(uint key, uint value) public returns(uint) { -return key; -// do something -} -function g() public { -// named arguments -f({value: 2, key: 3}); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar012.sol deleted file mode 100644 index 45e6d3aaf6e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test4Grammar012.sol +++ /dev/null @@ -1,24 +0,0 @@ -//pragma solidity ^0.4.24; -contract rTest { -function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { -//function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { -//var a = block.coinbase ; -//var b = block.difficulty; -//var c = block.gaslimit; -//var d = block.number; -//var e = block.blockhash(0); -//var e = d; -//var f = block.timestamp; -//bytes memory g = msg.data; -uint256 h = gasleft(); -address payable i = msg.sender; -bytes4 j = msg.sig; -uint256 k = msg.value; -uint256 l = now; -uint256 m = tx.gasprice; -address payable n = tx.origin; -uint256 o = address(this).balance; -return (h,i,j,k,l,m,n,o); -//return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test6Grammar013.sol deleted file mode 100644 index 56f97191ea0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar002test6Grammar013.sol +++ /dev/null @@ -1,24 +0,0 @@ -//pragma solidity ^0.4.4; -contract Counter { -uint count = 0; -address payable owner; -//function Counter() public{ -constructor() public{ -owner = msg.sender; -} -function increment() public { -uint step = 10; -if (owner == msg.sender) { -count = count + step; -} -} -function getCount() public returns (uint){ -return count; -} -function kill() public{ -if (owner == msg.sender) { -selfdestruct(owner); -//selfdestruct(address(owner)); -} -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test1Grammar014.sol deleted file mode 100644 index 9190e902056..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test1Grammar014.sol +++ /dev/null @@ -1,68 +0,0 @@ -//pragma solidity ^0.4.4; -contract A { -uint256 public numberForB; -address public senderForB; -function callTest(address bAddress, uint256 _number) public{ - -//bAddress.call(bytes4(sha3("setValue(uint256)")), _number); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("setValue(uint256)",_number)); // B's storage is set, A is not modified -} -function callcodeTest(address bAddress, uint256 _number) public{ -//bAddress.callcode(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} -function delegatecallTest(address bAddress, uint256 _number) public{ -//bAddress.delegatecall(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} - -function callAddTest(address bAddress) public{ -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract B { -uint256 public numberForB; -address public senderForB; -address public addr11; -mapping(uint256=>address) public addr1; -mapping(uint256=>address) public addr2; -event ssss(uint256); -function setValue(uint256 _number) public{ - -emit ssss(_number); -numberForB = _number; -senderForB = msg.sender; -// senderForB is A if invoked by A's callTest. B's storage will be updated -// senderForB is A if invoked by A's callcodeTest. None of B's storage is updated -// senderForB is OWNER if invoked by A's delegatecallTest. None of B's storage is updated -} - -function add() public{ -numberForB=numberForB+1; -C c1 = new C(); -addr1[numberForB]=c1.getAddress(); -addr11 = c1.getAddress(); -C c2 = new C(); -addr2[numberForB] = c2.getAddress(); -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract C { -function getAddress() public view returns(address){ -return address(this); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test2Grammar015.sol deleted file mode 100644 index 51aa0843890..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test2Grammar015.sol +++ /dev/null @@ -1,39 +0,0 @@ -//pragma solidity ^0.4.0; - -contract ExecuteFallback{ - - //回退事件,会把调用的数据打印出来 - event FallbackCalled(bytes data); - //fallback函数,注意是没有名字的,没有参数,没有返回值的 - function() external{ - emit FallbackCalled(msg.data); - } - - //调用已存在函数的事件,会把调用的原始数据,请求参数打印出来 - event ExistFuncCalled(bytes data, uint256 para); - //一个存在的函数 - function existFunc(uint256 para) public{ - emit ExistFuncCalled(msg.data, para); - } - - // 模拟从外部对一个存在的函数发起一个调用,将直接调用函数 - function callExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("existFunc(uint256)")); - //this.call(funcIdentifier, uint256(1)); - address(this).call(abi.encode(funcIdentifier, uint256(1))); - } - - //模拟从外部对一个不存在的函数发起一个调用,由于匹配不到函数,将调用回退函数 - function callNonExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("functionNotExist()")); - //this.call(funcIdentifier); - address(this).call(abi.encode(funcIdentifier)); - } - - function ExistFuncCalledTopic() view public returns(bytes32){ - return keccak256("ExistFuncCalled(bytes,uint256)"); - } - function FallbackCalledTopic() view public returns(bytes32){ - return keccak256("FallbackCalled(bytes)"); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test3Grammar016.sol deleted file mode 100644 index 11eb8f9cc70..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test3Grammar016.sol +++ /dev/null @@ -1,23 +0,0 @@ -//pragma solidity ^0.4.0; -contract C { -uint private data; -function f(uint a) private returns(uint b) { return a + 1; } -function setData(uint a) public { data = a; } -function getData() public returns(uint) { return data; } -function compute(uint a, uint b) internal returns (uint) { return a+b; } -} -contract D { -function readData() public{ -C c = new C(); -//uint local = c.f(7); // error: member "f" is not visible -c.setData(3); -uint local = c.getData(); -// local = c.compute(3, 5); // error: member "compute" is not visible -} -} -contract E is C { -function g() public { -C c = new C(); -uint val = compute(3, 5); // access to internal member (from derived to parent contract) -} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test4Grammar017.sol deleted file mode 100644 index 23fcdec76f0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test4Grammar017.sol +++ /dev/null @@ -1,50 +0,0 @@ -//pragma solidity ^0.4.0; -contract CrowdFunding{ -struct Funder{ -address addr; -uint amount; -} - -struct Campaign{ -address payable beneficiary; -uint goal; -uint amount; -uint funderNum; -mapping(uint => Funder) funders; -} - -uint compaingnID; -mapping (uint => Campaign) campaigns; - -function candidate(address payable beneficiary, uint goal) public payable returns (uint compaingnID){ -// initialize -campaigns[compaingnID++] = Campaign(beneficiary, goal, 0, 0); -} - -function vote(uint compaingnID) payable public { -Campaign storage c = campaigns[compaingnID]; - -//another way to initialize -c.funders[c.funderNum++] = Funder({addr: msg.sender, amount: msg.value}); -c.amount += msg.value; -} - -function check(uint comapingnId) public payable returns (bool){ - Campaign memory c = campaigns[comapingnId]; - - if(c.amount < c.goal){ - return false; - } - - uint amount = c.amount; - // incase send much more - c.amount = 0; - // address payable addr = address(uint160(c.beneficiary)); - //if(! addr.send(amount)){ - - if (! c.beneficiary.send(amount)){ - revert(); - } - return true; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test5Grammar018.sol deleted file mode 100644 index ddd6deb040f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test5Grammar018.sol +++ /dev/null @@ -1,37 +0,0 @@ -//pragma solidity ^0.4.0; - - -contract Grammar18{ - function testAddmod() public returns (uint z) { - //计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕 - z=addmod(2, 2, 3); - return z; - } - function testMulmod() public returns (uint z) { -//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。 - z=mulmod(2, 3, 4); - return z; - } - - function testKeccak256() public returns(bytes32){ - //计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 - return keccak256("11"); - } - - function testSha256() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - return sha256("11"); - } - function testSha3() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - //return sha3("11"); - return keccak256("11"); - } - - function testRipemd160() public returns(bytes32){ - //计算(紧密包装)参数的RIPEMD-160哈希值 - return ripemd160("11"); - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test6Grammar019.sol deleted file mode 100644 index 30418539865..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test6Grammar019.sol +++ /dev/null @@ -1,12 +0,0 @@ -//pragma solidity ^0.4.0; -contract timetest { - -constructor() public { -require( 1 == 1 seconds); -require(1 minutes == 60 seconds); -require(1 hours == 60 minutes); -require(1 days == 24 hours); -require(1 weeks == 7 days); -//require(1 years == 365 days); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test7Grammar020.sol deleted file mode 100644 index 1b960e6e313..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractGrammar003test7Grammar020.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; -contract trxtest { - -function test() public { -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInnerContract.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInnerContract.sol deleted file mode 100644 index bc183931c88..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInnerContract.sol +++ /dev/null @@ -1,32 +0,0 @@ -//pragma solidity ^0.4.0; - - - -contract InnerContract { - - constructor() public payable{} - function() external payable{} - - function messageI() payable public returns (uint ret) { - - - - } - -} - - - -contract OuterContract { - - - constructor() public payable{} - function() external payable{} - - function callInner(address payable addr) payable public returns (uint) { - - return InnerContract(addr).messageI.value(1)(); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction001.sol deleted file mode 100644 index 8baba262e87..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction001.sol +++ /dev/null @@ -1,42 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address payable cAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - B b2 = new B();//1.2 - address(b2).transfer(5);//1.3 - b2.callCGetZero(cAddr, 1);//1.4 - b2.callCGetZero(cAddr,2);//1.6 - } - function test2(address payable cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - cAddress.call.value(amount + 1)(abi.encodeWithSignature("newBAndTransfer()"));//2.6 - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(address payable cAddress,uint256 amount) public{ - cAddress.call.value(amount)(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - B b1 = (new B).value(7)();//2.2,2.7 - b1.getOne();//2.3,2.8 - B b2 = (new B).value(3)();//2.4,2.9 - b2.getOne();//2.5,2.10 - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction002.sol deleted file mode 100644 index 42231b7c960..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction002.sol +++ /dev/null @@ -1,21 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - - function test2(address cAddress,uint256 amount) public payable{ - //cAddress.call.value(amount)();//2.1 - cAddress.call.value(amount)("");//2.1 - } -} - - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction003.sol deleted file mode 100644 index 0910a0c4a2b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction003.sol +++ /dev/null @@ -1,31 +0,0 @@ -//pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - B b = (new B).value(10)();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - function () payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction004.sol deleted file mode 100644 index c7866dddb58..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction004.sol +++ /dev/null @@ -1,25 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor () payable public{} - function test(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - function () payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} -contract B{ - function() external payable{} - function kill(address contractAddres, address toAddress) payable public { - contractAddres.call(abi.encodeWithSignature("test(address)",address(this))); - } - function kill2() public{ - A a = new A(); - a.test(address(this)); - } - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction005.sol deleted file mode 100644 index 6e83c423b38..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction005.sol +++ /dev/null @@ -1,54 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1() public payable{ - B b1 = (new B).value(10)();//1.1 - b1.callCGetZero(false); - b1.callCGetZero(true);//1.4 - } - function test2() public payable{ - C c1 = (new C).value(10)();//1.1 - c1.newBAndTransfer(false); - c1.newBAndTransfer(true);//1.4 - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction006.sol deleted file mode 100644 index 6bc548690a5..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction001testInternalTransaction006.sol +++ /dev/null @@ -1,54 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1() public payable{ - B b1 = (new B).value(10)();//1.1 - b1.callCGetZero(true);//1.4 - b1.callCGetZero(false); - } - function test2() public payable{ - C c1 = (new C).value(10)();//1.1 - c1.newBAndTransfer(true);//1.4 - c1.newBAndTransfer(false); - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test1InternalTransaction007.sol deleted file mode 100644 index 229bf82fa2d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test1InternalTransaction007.sol +++ /dev/null @@ -1,38 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address cAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - B b2 = new B();//1.2 - address(b2).transfer(5);//1.3 - b2.callCGetZero();//1.4 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero() public{ - assert(1==2); - - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test2InternalTransaction008.sol deleted file mode 100644 index a75fba4f14b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test2InternalTransaction008.sol +++ /dev/null @@ -1,60 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - - function testAssert(address bAddress,uint256 amount) public payable{ - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",true)); - } - function testRequire(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - } - function testAssert1(address bAddress,uint256 amount) public payable{ - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",true)); - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - } - function testtRequire2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable public{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test3InternalTransaction009.sol deleted file mode 100644 index 1a7df822511..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test3InternalTransaction009.sol +++ /dev/null @@ -1,47 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address cAddr,address dcontract,address baddress) public payable{ - B b1 = (new B).value(10)();//1.1 - address(b1).transfer(5);//1.3 - b1.callCGetZero(cAddr, 1);//1.4 - b1.getOne(dcontract,baddress); - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne(address contractAddres, address toAddress) payable public{ - contractAddres.call(abi.encodeWithSignature("suicide1(address)",address(this))); - - } - function callCGetZero(address cAddress,uint256 amount) public{ - cAddress.call.value(amount)(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public{ - B b1 = (new B).value(7)();//2.2,2.7 - B b2 = (new B).value(3)();//2.4,2.9 - } -} - -contract D{ - constructor () payable public{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - function () payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010.sol deleted file mode 100644 index 7f34b2bfe08..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010.sol +++ /dev/null @@ -1,186 +0,0 @@ -//pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() public returns(uint256) { - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - function () payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010_1.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010_1.sol deleted file mode 100644 index c77fe76f5fa..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test4InternalTransaction010_1.sol +++ /dev/null @@ -1,210 +0,0 @@ -pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - function () payable{} - } - - \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test5InternalTransaction012.sol deleted file mode 100644 index ce2798888fe..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction002test5InternalTransaction012.sol +++ /dev/null @@ -1,51 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address bAddr,address eAddr) public payable{ - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - } - -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable{ - D d1=(new D).value(1000)(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - function() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction013.sol deleted file mode 100644 index bc1d3dbe6cd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction013.sol +++ /dev/null @@ -1,56 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address dAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.testNN(dAddr,2);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount) public payable{ - // D d1=(new D)(); - dAddress.call.value(amount)(abi.encodeWithSignature("getOne()"));//2.1 - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - E e = (new E).value(5)(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction014.sol deleted file mode 100644 index b3bbfc9a7db..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction014.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract callerContract { - constructor() payable public{} - function() payable external{} - function sendToB(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - - contract calledContract { - function() payable external {} - constructor() payable public{} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call.value(5)(abi.encodeWithSignature("setI()")); - } - - } - - contract c{ - uint256 public i=0; - constructor() public payable{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } - function setI() payable public{ - i=5; - } - function() payable external{} - } diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction015.sol deleted file mode 100644 index 0426d650da4..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction015.sol +++ /dev/null @@ -1,60 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address dAddr,address eAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.testNN(dAddr,2,eAddr);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount,address eAddress) public payable{ - // D d1=(new D)(); - dAddress.call.value(amount)(abi.encodeWithSignature("getOne(address)",address(this)));//2.1 - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } - function suicide(address payable toAddress) public payable{ - selfdestruct(toAddress); - } -} -contract D{ - constructor() payable public{} - function() payable external{} - function getOne(address payable eAddress) payable public{ - E e = (new E).value(5)(); - e.suicide(eAddress); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction016.sol deleted file mode 100644 index f97217fe169..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction016.sol +++ /dev/null @@ -1,174 +0,0 @@ -//pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function () payable external{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - B b1=(new B).value(1)();//1 - address payable aaa=address(this); - b1.suicide1(aaa); - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - B b1=(new B).value(1)();//1 - address payable aaa=address(this); - b1.suicide1(aaa); - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - function () payable external{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - } - diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction017.sol deleted file mode 100644 index ebe570fd8af..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction017.sol +++ /dev/null @@ -1,199 +0,0 @@ -//pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer(address payable Address) payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - B b=(new B).value(1)();//1 - selfdestruct(Address); - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - function () payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction018.sol deleted file mode 100644 index a59c587b233..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractInternalTransaction003testInternalTransaction018.sol +++ /dev/null @@ -1,97 +0,0 @@ -//pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable external{} - function test1(address payable bAddr,address eAddr) public payable{ - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - - } - -} - -contract B{ - constructor() payable public{} - function() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable { - D d1=(new D).value(100)(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - function() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage001.sol deleted file mode 100644 index 4c04cf5c6fb..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage001.sol +++ /dev/null @@ -1,9 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -constructor() payable public{} -function() payable external{} -function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage002.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage002.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage003.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage003.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage004.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage004.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage005.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage005.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractLinkage006.sol deleted file mode 100644 index 9c20c82dc02..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractLinkage006.sol +++ /dev/null @@ -1,18 +0,0 @@ -//pragma solidity ^0.4.0; -contract AA{ - uint256 public count=0; - constructor () payable public{} - function init(address payable addr, uint256 max) payable public { - count =0; - this.hack(addr,max); - } - function hack(address payable addr, uint256 max) payable public { - while (count < max) { - count = count +1; - this.hack(addr,max); - } - if (count == max) { - addr.send(20); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit001.sol deleted file mode 100644 index 212614935f6..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit001.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.0; - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit004.sol deleted file mode 100644 index 212614935f6..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractOriginEnergyLimit004.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.0; - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode_0.5.15/contractOtherToTrcToken.sol deleted file mode 100644 index 74afd5d0e54..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractOtherToTrcToken.sol +++ /dev/null @@ -1,41 +0,0 @@ -//pragma solidity ^0.4.24; - -contract ConvertType { - -constructor() payable public{} - -function() payable external{} - -//function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { -// trcToken t = trcToken(tokenStr); // ERROR -// toAddress.transferToken(tokenValue, tokenStr); // ERROR -//} - -function uint256ToTrctoken(address payable toAddress, uint256 tokenValue, uint256 tokenInt) public { - trcToken t = trcToken(tokenInt); // OK - toAddress.transferToken(tokenValue, t); // OK - toAddress.transferToken(tokenValue, tokenInt); // OK -} - -function addressToTrctoken(address payable toAddress, uint256 tokenValue, address adr) public { - trcToken t = trcToken(adr); // OK - toAddress.transferToken(tokenValue, t); // OK -//toAddress.transferToken(tokenValue, adr); // ERROR -} - -//function bytesToTrctoken(address payable toAddress, bytes memory b, uint256 tokenValue) public { - // trcToken t = trcToken(b); // ERROR - // toAddress.transferToken(tokenValue, b); // ERROR -//} - -function bytes32ToTrctoken(address payable toAddress, uint256 tokenValue, bytes32 b32) public { - trcToken t = trcToken(b32); // OK - toAddress.transferToken(tokenValue, t); // OK -// toAddress.transferToken(tokenValue, b32); // ERROR -} - -//function arrayToTrctoken(address payable toAddress, uint256[] memory arr, uint256 tokenValue) public { -//trcToken t = trcToken(arr); // ERROR -// toAddress.transferToken(tokenValue, arr); // ERROR -//} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario001.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario001.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario002.sol deleted file mode 100644 index aa9deda79ef..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario002.sol +++ /dev/null @@ -1,53 +0,0 @@ -//pragma solidity ^0.4.0; -contract TronNative{ - - address public voteContractAddress= address(0x10001); - address public freezeBalanceAddress = address(0x10002); - address public unFreezeBalanceAddress = address(0x10003); - address public withdrawBalanceAddress = address(0x10004); - address public approveProposalAddress = address(0x10005); - address public createProposalAddress = address(0x10006); - address public deleteProposalAddress = address(0x10007); - constructor () payable public {} - - function voteForSingleWitness (address payable witnessAddr, uint256 voteValue) public{ - // method 1: - voteContractAddress.delegatecall(abi.encode(witnessAddr,voteValue)); - } - - function voteUsingAssembly (address witnessAddr, uint256 voteValue) public{ - // method 2: - assembly{ - mstore(0x80,witnessAddr) - mstore(0xa0,voteValue) - // gas, address, in, size, out, size - if iszero(delegatecall(0, 0x10001, 0x80, 0x40, 0x80, 0x0)) { - revert(0, 0) - } - } - } - - function freezeBalance(uint256 frozen_Balance,uint256 frozen_Duration) public { - freezeBalanceAddress.delegatecall(abi.encode(frozen_Balance,frozen_Duration)); - } - - function unFreezeBalance() public { - unFreezeBalanceAddress.delegatecall(""); - } - - function withdrawBalance() public { - withdrawBalanceAddress.delegatecall(""); - } - - function approveProposal(uint256 id, bool isApprove) public { - approveProposalAddress.delegatecall(abi.encode(id,isApprove)); - } - - function createProposal(bytes32 [] memory data) public { - createProposalAddress.delegatecall(abi.encode(data)); - } - - function deleteProposal(uint256 id) public{ - deleteProposalAddress.delegatecall(abi.encode(id)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario003.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario003.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario004.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario004.sol deleted file mode 100644 index b3ca2687b4c..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario004.sol +++ /dev/null @@ -1,88 +0,0 @@ -//pragma solidity ^0.4.11; - -contract TronToken { - - string public name = "Tronix"; // token name - string public symbol = "TRX"; // token symbol - uint256 public decimals = 6; // token digit - - mapping (address => uint256) public balanceOf; - mapping (address => mapping (address => uint256)) public allowance; - - uint256 public totalSupply = 0; - bool public stopped = false; - - uint256 constant valueFounder = 100000000000000000; - address owner = address(0x0); - - modifier isOwner { - assert(owner == msg.sender); - _; - } - - modifier isRunning { - assert (!stopped); - _; - } - - modifier validAddress { - assert(address(0x0) != msg.sender); - _; - } - - constructor(address _addressFounder) public { - owner = msg.sender; - totalSupply = valueFounder; - balanceOf[_addressFounder] = valueFounder; - emit Transfer(address(0x0), _addressFounder, valueFounder); - } - - function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[msg.sender] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - balanceOf[msg.sender] -= _value; - balanceOf[_to] += _value; - emit Transfer(msg.sender, _to, _value); - return true; - } - - function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[_from] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - require(allowance[_from][msg.sender] >= _value); - balanceOf[_to] += _value; - balanceOf[_from] -= _value; - allowance[_from][msg.sender] -= _value; - emit Transfer(_from, _to, _value); - return true; - } - - function approve(address _spender, uint256 _value) isRunning validAddress public returns (bool success) { - require(_value == 0 || allowance[msg.sender][_spender] == 0); - allowance[msg.sender][_spender] = _value; - emit Approval(msg.sender, _spender, _value); - return true; - } - - function stop() isOwner public { - stopped = true; - } - - function start() isOwner public { - stopped = false; - } - - function setName(string memory _name) isOwner public { - name = _name; - } - - function burn(uint256 _value) public { - require(balanceOf[msg.sender] >= _value); - balanceOf[msg.sender] -= _value; - balanceOf[address(0x0)] += _value; - emit Transfer(msg.sender, address(0x0), _value); - } - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario005.sol deleted file mode 100644 index d46098cd410..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario005.sol +++ /dev/null @@ -1,103 +0,0 @@ -//pragma solidity ^0.4.16; - -interface token { - function transfer(address receiver, uint amount) external; -} - -contract Crowdsale { - address payable public beneficiary = 0x1b228F5D9f934c7bb18Aaa86F90418932888E7b4; // 募资成功后的收款方 - uint public fundingGoal = 10000000; // 募资额度 - uint public amountRaised = 1000000; // 参与数量 - uint public deadline; // 募资截止期 - - uint public price; // token 与以太坊的汇率 , token卖多少钱 - token public tokenReward; // 要卖的token - - mapping(address => uint256) public balanceOf; - - bool fundingGoalReached = false; // 众筹是否达到目标 - bool crowdsaleClosed = false; // 众筹是否结束 - - /** - * 事件可以用来跟踪信息 - **/ - event GoalReached(address recipient, uint totalAmountRaised); - event FundTransfer(address backer, uint amount, bool isContribution); - - /** - * 构造函数, 设置相关属性 - */ - constructor( - address payable ifSuccessfulSendTo, - uint fundingGoalInEthers, - uint durationInMinutes, - uint finneyCostOfEachToken, - address addressOfTokenUsedAsReward) public{ - beneficiary = ifSuccessfulSendTo; - fundingGoal = fundingGoalInEthers * 1 sun; - deadline = now + durationInMinutes * 1 minutes; - price = finneyCostOfEachToken * 1 trx; - tokenReward = token(addressOfTokenUsedAsReward); // 传入已发布的 token 合约的地址来创建实例 - } - - /** - * 无函数名的Fallback函数, - * 在向合约转账时,这个函数会被调用 - */ - function () payable external{ - require(!crowdsaleClosed); - uint amount = msg.value; - balanceOf[msg.sender] += amount; - amountRaised += amount; - tokenReward.transfer(msg.sender, amount / price); - emit FundTransfer(msg.sender, amount, true); - } - - /** - * 定义函数修改器modifier(作用和Python的装饰器很相似) - * 用于在函数执行前检查某种前置条件(判断通过之后才会继续执行该方法) - * _ 表示继续执行之后的代码 - **/ - modifier afterDeadline() { if (now >= deadline) _; } - - /** - * 判断众筹是否完成融资目标, 这个方法使用了afterDeadline函数修改器 - * - */ - function checkGoalReached() afterDeadline public{ - if (amountRaised >= fundingGoal) { - fundingGoalReached = true; - emit GoalReached(beneficiary, amountRaised); - } - crowdsaleClosed = true; - } - - - /** - * 完成融资目标时,融资款发送到收款方 - * 未完成融资目标时,执行退款 - * - */ - function safeWithdrawal() afterDeadline public{ - if (!fundingGoalReached) { - uint amount = balanceOf[msg.sender]; - balanceOf[msg.sender] = 0; - if (amount > 0) { - if (msg.sender.send(amount)) { - emit FundTransfer(msg.sender, amount, false); - } else { - balanceOf[msg.sender] = amount; - } - } - } - - if (fundingGoalReached && beneficiary == msg.sender) { - if (address(beneficiary).send(amountRaised)) { - emit FundTransfer(beneficiary, amountRaised, false); - } else { - //If we fail to send the funds to beneficiary, unlock funders balance - fundingGoalReached = false; - } - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario006.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario006.sol deleted file mode 100644 index 397c62096e0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario006.sol +++ /dev/null @@ -1,1963 +0,0 @@ -//pragma solidity ^0.4.24; - -interface PlayerBookInterface { - function getPlayerID(address _addr) external returns (uint256); - function getPlayerName(uint256 _pID) external view returns (bytes32); - function getPlayerLAff(uint256 _pID) external view returns (uint256); - function getPlayerAddr(uint256 _pID) external view returns (address); - function getNameFee() external view returns (uint256); - function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); - function isDev(address _who) external view returns(bool); -} - - -/** -* @title -Name Filter- v0.1.9 -* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ -* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ -* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ -* _____ _____ -* (, / /) /) /) (, / /) /) -* ┌─┐ / _ (/_ // // / _ // _ __ _(/ -* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ -* ┴ ┴ / / .-/ _____ (__ / -* (__ / (_/ (, / /)™ -* / __ __ __ __ _ __ __ _ _/_ _ _(/ -* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ -* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 -* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ -* _ __ _ ____ ____ _ _ _____ ____ ___ -*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* -*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* -* -* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ -* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ -* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ -*/ - -library NameFilter { - /** - * @dev filters name strings - * -converts uppercase to lower case. - * -makes sure it does not start/end with a space - * -makes sure it does not contain multiple spaces in a row - * -cannot be only numbers - * -cannot start with 0x - * -restricts characters to A-Z, a-z, 0-9, and space. - * @return reprocessed string in bytes32 format - */ - function nameFilter(string memory _input) - internal - pure - returns(bytes32) - { - bytes memory _temp = bytes(_input); - uint256 _length = _temp.length; - - //sorry limited to 32 characters - require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); - // make sure it doesnt start with or end with space - require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); - // make sure first two characters are not 0x - if (_temp[0] == 0x30) - { - require(_temp[1] != 0x78, "string cannot start with 0x"); - require(_temp[1] != 0x58, "string cannot start with 0X"); - } - - // create a bool to track if we have a non number character - bool _hasNonNumber; - - // convert & check - for (uint256 i = 0; i < _length; i++) - { - // if its uppercase A-Z - if (_temp[i] > 0x40 && _temp[i] < 0x5b) - { - // convert to lower case a-z - _temp[i] = byte(uint8(_temp[i]) + 32); - - // we have a non number - if (_hasNonNumber == false) - _hasNonNumber = true; - } else { - require - ( - // require character is a space - _temp[i] == 0x20 || - // OR lowercase a-z - (_temp[i] > 0x60 && _temp[i] < 0x7b) || - // or 0-9 - (_temp[i] > 0x2f && _temp[i] < 0x3a), - "string contains invalid characters" - ); - // make sure theres not 2x spaces in a row - if (_temp[i] == 0x20) - require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); - - // see if we have a character other than a number - if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) - _hasNonNumber = true; - } - } - - require(_hasNonNumber == true, "string cannot be only numbers"); - - bytes32 _ret; - assembly { - _ret := mload(add(_temp, 32)) - } - return (_ret); - } -} - - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - if (a == 0) { - return 0; - } - c = a * b; - require(c / a == b, "SafeMath mul failed"); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return c; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { - require(b <= a, "SafeMath sub failed"); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - c = a + b; - require(c >= a, "SafeMath add failed"); - return c; - } - - /** - * @dev gives square root of given x. - */ - function sqrt(uint256 x) - internal - pure - returns (uint256 y) - { - uint256 z = ((add(x,1)) / 2); - y = x; - while (z < y) - { - y = z; - z = ((add((x / z),z)) / 2); - } - } - - /** - * @dev gives square. multiplies x by x - */ - function sq(uint256 x) - internal - pure - returns (uint256) - { - return (mul(x,x)); - } - - /** - * @dev x to the power of y - */ - function pwr(uint256 x, uint256 y) - internal - pure - returns (uint256) - { - if (x==0) - return (0); - else if (y==0) - return (1); - else - { - uint256 z = x; - for (uint256 i=1; i < y; i++) - z = mul(z,x); - return (z); - } - } -} - -//============================================================================== -// | _ _ _ | _ . -// |<(/_\/ (_(_||(_ . -//=======/====================================================================== -library F3DKeysCalcLong { - using SafeMath for *; - /** - * @dev calculates number of keys received given X eth - * @param _curEth current amount of eth in contract - * @param _newEth eth being spent - * @return amount of ticket purchased - */ - function keysRec(uint256 _curEth, uint256 _newEth) - internal - pure - returns (uint256) - { - return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); - } - - /** - * @dev calculates amount of eth received if you sold X keys - * @param _curKeys current amount of keys that exist - * @param _sellKeys amount of keys you wish to sell - * @return amount of eth received - */ - function ethRec(uint256 _curKeys, uint256 _sellKeys) - internal - pure - returns (uint256) - { - return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); - } - - /** - * @dev calculates how many keys would exist with given an amount of eth - * @param _eth eth "in contract" - * @return number of keys that would exist - */ - function keys(uint256 _eth) - internal - pure - returns(uint256) - { - return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); - } - - /** - * @dev calculates how much eth would be in contract given a number of keys - * @param _keys number of keys "in contract" - * @return eth that would exists - */ - function eth(uint256 _keys) - internal - pure - returns(uint256) - { - return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); - } -} - -library F3Ddatasets { - //compressedData key - // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] - // 0 - new player (bool) - // 1 - joined round (bool) - // 2 - new leader (bool) - // 3-5 - air drop tracker (uint 0-999) - // 6-16 - round end time - // 17 - winnerTeam - // 18 - 28 timestamp - // 29 - team - // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) - // 31 - airdrop happened bool - // 32 - airdrop tier - // 33 - airdrop amount won - //compressedIDs key - // [77-52][51-26][25-0] - // 0-25 - pID - // 26-51 - winPID - // 52-77 - rID - struct EventReturns { - uint256 compressedData; - uint256 compressedIDs; - address winnerAddr; // winner address - bytes32 winnerName; // winner name - uint256 amountWon; // amount won - uint256 newPot; // amount in new pot - uint256 P3DAmount; // amount distributed to p3d - uint256 genAmount; // amount distributed to gen - uint256 potAmount; // amount added to pot - } - struct Player { - address payable addr; // player address - bytes32 name; // player name - uint256 win; // winnings vault - uint256 gen; // general vault - uint256 aff; // affiliate vault - uint256 lrnd; // last round played - uint256 laff; // last affiliate id used - } - struct PlayerRounds { - uint256 eth; // eth player has added to round (used for eth limiter) - uint256 keys; // keys - uint256 mask; // player mask - uint256 ico; // ICO phase investment - } - struct Round { - uint256 plyr; // pID of player in lead - uint256 team; // tID of team in lead - uint256 end; // time ends/ended - bool ended; // has round end function been ran - uint256 strt; // time round started - uint256 keys; // keys - uint256 eth; // total eth in - uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) - uint256 mask; // global mask - uint256 ico; // total eth sent in during ICO phase - uint256 icoGen; // total eth for gen during ICO phase - uint256 icoAvg; // average key price for ICO phase - } - struct TeamFee { - uint256 gen; // % of buy in thats paid to key holders of current round - uint256 p3d; // % of buy in thats paid to p3d holders - } - struct PotSplit { - uint256 gen; // % of pot thats paid to key holders of current round - uint256 p3d; // % of pot thats paid to p3d holders - } -} - -contract F3Devents { - // fired whenever a player registers a name - event onNewName - ( - uint256 indexed playerID, - address indexed playerAddress, - bytes32 indexed playerName, - bool isNewPlayer, - uint256 affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 amountPaid, - uint256 timeStamp - ); - - // fired at end of buy or reload - event onEndTx - ( - uint256 compressedData, - uint256 compressedIDs, - bytes32 playerName, - address playerAddress, - uint256 ethIn, - uint256 keysBought, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount, - uint256 potAmount, - uint256 airDropPot - ); - - // fired whenever theres a withdraw - event onWithdraw - ( - uint256 indexed playerID, - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 timeStamp - ); - - // fired whenever a withdraw forces end round to be ran - event onWithdrawAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a buy after round timer - // hit zero, and causes end round to be ran. - event onBuyAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethIn, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a reload after round timer - // hit zero, and causes end round to be ran. - event onReLoadAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // fired whenever an affiliate is paid - event onAffiliatePayout - ( - uint256 indexed affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 indexed roundID, - uint256 indexed buyerID, - uint256 amount, - uint256 timeStamp - ); - - // received pot swap deposit - event onPotSwapDeposit - ( - uint256 roundID, - uint256 amountAddedToPot - ); -} - - - -contract FoMo3Dlong is F3Devents { - using SafeMath for *; - using NameFilter for string; - using F3DKeysCalcLong for uint256; - - address public otherF3D_; - address public Divies; - address public Jekyll_Island_Inc; - PlayerBookInterface public playerBook;// =PlayerBookInterface(0x0dcd2f752394c41875e259e00bb44fd505297caf);//new PlayerBook();// - // TeamJustInterface constant private teamJust = TeamJustInterface(0x3a5f8140b9213a0f733a6a639857c9df43ee3f5a);// new TeamJust();// - - //============================================================================== - // _ _ _ |`. _ _ _ |_ | _ _ . - // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) - //=================_|=========================================================== - string constant public name = "FoMo3D Long Official"; - string constant public symbol = "F3D"; - uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO - uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. - uint256 constant private rndInit_ = 1 hours; // round timer starts at this - uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer - uint256 constant private rndMax_ = 24 hours; // max length a round timer can be - //============================================================================== - // _| _ _|_ _ _ _ _|_ _ . - // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) - //=============================|================================================ - uint256 public airDropPot_; // person who gets the airdrop wins part of this pot - uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop - uint256 public rID_; // round id number / total rounds that have happened - //**************** - // PLAYER DATA - //**************** - mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address - mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name - mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data - mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id - mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) - //**************** - // ROUND DATA - //**************** - mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data - mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id - //**************** - // TEAM FEE DATA - //**************** - mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team - mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team - - function setPlayerBook(address _playerBook) external { - require(msg.sender == owner, 'only dev!'); - require(address(playerBook) == address(0), 'already set!'); - playerBook = PlayerBookInterface(_playerBook); - } - - address public owner; - - //============================================================================== - // _ _ _ __|_ _ __|_ _ _ . - // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) - //============================================================================== - constructor() - public - { - owner = msg.sender; - // Team allocation structures - // 0 = whales - // 1 = bears - // 2 = sneks - // 3 = bulls - - // Team allocation percentages - // (F3D, P3D) + (Pot , Referrals, Community) - // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. - fees_[0] = F3Ddatasets.TeamFee(30, 6); - //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[1] = F3Ddatasets.TeamFee(43, 0); - //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[2] = F3Ddatasets.TeamFee(56, 10); - //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[3] = F3Ddatasets.TeamFee(43, 8); - //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - - // how to split up the final pot based on which team was picked - // (F3D, P3D) - potSplit_[0] = F3Ddatasets.PotSplit(15, 10); - //48% to winner, 25% to next round, 2% to com - potSplit_[1] = F3Ddatasets.PotSplit(25, 0); - //48% to winner, 25% to next round, 2% to com - potSplit_[2] = F3Ddatasets.PotSplit(20, 20); - //48% to winner, 10% to next round, 2% to com - potSplit_[3] = F3Ddatasets.PotSplit(30, 10); - //48% to winner, 10% to next round, 2% to com - } - //============================================================================== - // _ _ _ _|. |`. _ _ _ . - // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) - //============================================================================== - /** - * @dev used to make sure no one can interact with contract until it has - * been activated. - */ - modifier isActivated() { - require(activated_ == true, "its not ready yet. check ?eta in discord"); - _; - } - - /** - * @dev prevents contracts from interacting with fomo3d - */ - modifier isHuman() { - address _addr = msg.sender; - uint256 _codeLength; - - assembly {_codeLength := extcodesize(_addr)} - require(_codeLength == 0, "sorry humans only"); - _; - } - - modifier onlyDevs() - { - require(playerBook.isDev(msg.sender) == true, "msg sender is not a dev"); - _; - } - - /** - * @dev sets boundaries for incoming tx - */ - modifier isWithinLimits(uint256 _eth) { - require(_eth >= 1000000000, "pocket lint: not a valid currency"); - require(_eth <= 100000000000000000000000, "no vitalik, no"); - _; - } - - //============================================================================== - // _ |_ |. _ |` _ __|_. _ _ _ . - // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) - //====|========================================================================= - /** - * @dev emergency buy uses last stored affiliate ID and team snek - */ - function() - isActivated() - isHuman() - isWithinLimits(msg.value) - external - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // buy core - buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); - } - - /** - * @dev converts all incoming ethereum to keys. - * -functionhash- 0x8f38f309 (using ID for affiliate) - * -functionhash- 0x98a0871d (using address for affiliate) - * -functionhash- 0xa65b37a1 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - */ - function buyXid(uint256 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affCode, _team, _eventData_); - } - - function buyXaddr(address _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - function buyXname(bytes32 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - /** - * @dev essentially the same as buy, but instead of you sending ether - * from your wallet, it uses your unwithdrawn earnings. - * -functionhash- 0x349cdcac (using ID for affiliate) - * -functionhash- 0x82bfc739 (using address for affiliate) - * -functionhash- 0x079ce327 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - * @param _eth amount of earnings to use (remainder returned to gen vault) - */ - function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affCode, _team, _eth, _eventData_); - } - - function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - /** - * @dev withdraws all of your earnings. - * -functionhash- 0x3ccfd60b - */ - function withdraw() - isActivated() - isHuman() - public - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // setup temp var for player eth - uint256 _eth; - - // check to see if round has ended and no one has run round end yet - if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // end the round (distributes pot) - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire withdraw and distribute event - emit F3Devents.onWithdrawAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eth, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - - // in any other situation - } else { - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // fire withdraw event - emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); - } - } - - /** - * @dev use these to register names. they are just wrappers that will send the - * registration requests to the PlayerBook contract. So registering here is the - * same as registering there. UI will always display the last name you registered. - * but you will still own all previously registered names to use as affiliate - * links. - * - must pay a registration fee. - * - name must be unique - * - names will be converted to lowercase - * - name cannot start or end with a space - * - cannot have more than 1 space in a row - * - cannot be only numbers - * - cannot start with 0x - * - name must be at least 1 char - * - max length of 32 characters long - * - allowed characters: a-z, 0-9, and space - * -functionhash- 0x921dec21 (using ID for affiliate) - * -functionhash- 0x3ddd4698 (using address for affiliate) - * -functionhash- 0x685ffd83 (using name for affiliate) - * @param _nameString players desired name - * @param _affCode affiliate ID, address, or name of who referred you - * @param _all set to true if you want this to push your info to all games - * (this might cost a lot of gas) - */ - function registerNameXID(string memory _nameString, uint256 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - - function registerNameXaddr(string memory _nameString, address _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - - function registerNameXname(string memory _nameString, bytes32 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - //============================================================================== - // _ _ _|__|_ _ _ _ . - // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) - //=====_|======================================================================= - /** - * @dev return the price buyer will pay for next 1 individual key. - * -functionhash- 0x018a25e8 - * @return price for next key bought (in wei format) - */ - function getBuyPrice() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); - else // rounds over. need price for new round - return (75000000000000); - // init - } - - /** - * @dev returns time left. dont spam this, you'll ddos yourself from your node - * provider - * -functionhash- 0xc7e284b8 - * @return time left in seconds - */ - function getTimeLeft() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - if (_now < round_[_rID].end) - if (_now > round_[_rID].strt + rndGap_) - return ((round_[_rID].end).sub(_now)); - else - return ((round_[_rID].strt + rndGap_).sub(_now)); - else - return (0); - } - - /** - * @dev returns player earnings per vaults - * -functionhash- 0x63066434 - * @return winnings vault - * @return general vault - * @return affiliate vault - */ - function getPlayerVaults(uint256 _pID) - public - view - returns (uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - // if round has ended. but round end has not been run (so contract has not distributed winnings) - if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // if player is winner - if (round_[_rID].plyr == _pID) - { - return - ( - (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - // if player is not the winner - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - } - - // if round is still going on, or round has ended and round end has been ran - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), - plyr_[_pID].aff - ); - } - } - - /** - * solidity hates stack limits. this lets us avoid that hate - */ - function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) - private - view - returns (uint256) - { - return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); - } - - /** - * @dev returns all current round info needed for front end - * -functionhash- 0x747dff42 - * @return eth invested during ICO phase - * @return round id - * @return total keys for round - * @return time round ends - * @return time round started - * @return current pot - * @return current team ID & player ID in lead - * @return current player in leads address - * @return current player in leads name - * @return whales eth in for round - * @return bears eth in for round - * @return sneks eth in for round - * @return bulls eth in for round - * @return airdrop tracker # & airdrop pot - */ - function getCurrentRoundInfo() - public - view - returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - return - ( - round_[_rID].ico, //0 - _rID, //1 - round_[_rID].keys, //2 - round_[_rID].end, //3 - round_[_rID].strt, //4 - round_[_rID].pot, //5 - (round_[_rID].team + (round_[_rID].plyr * 10)), //6 - plyr_[round_[_rID].plyr].addr, //7 - plyr_[round_[_rID].plyr].name, //8 - rndTmEth_[_rID][0], //9 - rndTmEth_[_rID][1], //10 - rndTmEth_[_rID][2], //11 - rndTmEth_[_rID][3], //12 - airDropTracker_ + (airDropPot_ * 1000) //13 - ); - } - - /** - * @dev returns player info based on address. if no address is given, it will - * use msg.sender - * -functionhash- 0xee0b5d8b - * @param _addr address of the player you want to lookup - * @return player ID - * @return player name - * @return keys owned (current round) - * @return winnings vault - * @return general vault - * @return affiliate vault - * @return player round eth - */ - function getPlayerInfoByAddress(address _addr) - public - view - returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - if (_addr == address(0)) - { - _addr == msg.sender; - } - uint256 _pID = pIDxAddr_[_addr]; - - return - ( - _pID, //0 - plyr_[_pID].name, //1 - plyrRnds_[_pID][_rID].keys, //2 - plyr_[_pID].win, //3 - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 - plyr_[_pID].aff, //5 - plyrRnds_[_pID][_rID].eth //6 - ); - } - - //============================================================================== - // _ _ _ _ | _ _ . _ . - // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) - //=====================_|======================================================= - /** - * @dev logic runs whenever a buy order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // call core - core(_rID, _pID, msg.value, _affID, _team, _eventData_); - - // if round is not active - } else { - // check to see if end round needs to be ran - if (_now > round_[_rID].end && round_[_rID].ended == false) - { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onBuyAndDistribute - ( - msg.sender, - plyr_[_pID].name, - msg.value, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - - // put eth in players vault - plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); - } - } - - /** - * @dev logic runs whenever a reload order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // get earnings from all vaults and return unused to gen vault - // because we use a custom safemath library. this will throw if player - // tried to spend more eth than they have. - plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); - - // call core - core(_rID, _pID, _eth, _affID, _team, _eventData_); - - // if round is not active and end round needs to be ran - } else if (_now > round_[_rID].end && round_[_rID].ended == false) { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onReLoadAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - } - - /** - * @dev this is the core logic for any buy/reload that happens while a round - * is live. - */ - function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // if player is new to round - if (plyrRnds_[_pID][_rID].keys == 0) - _eventData_ = managePlayer(_pID, _eventData_); - - // early round eth limiter - if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) - { - uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); - uint256 _refund = _eth.sub(_availableLimit); - plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); - _eth = _availableLimit; - } - - // if eth left is greater than min eth allowed (sorry no pocket lint) - if (_eth > 1000000000) - { - - // mint the new keys - uint256 _keys = (round_[_rID].eth).keysRec(_eth); - - // if they bought at least 1 whole key - if (_keys >= 1000000000000000000) - { - updateTimer(_keys, _rID); - - // set new leaders - if (round_[_rID].plyr != _pID) - round_[_rID].plyr = _pID; - if (round_[_rID].team != _team) - round_[_rID].team = _team; - - // set the new leader bool to true - _eventData_.compressedData = _eventData_.compressedData + 100; - } - - // manage airdrops - if (_eth >= 100000000000000000) - { - airDropTracker_++; - if (airdrop() == true) - { - // gib muni - uint256 _prize; - if (_eth >= 10000000000000000000) - { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(75)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(50)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 2 prize was won - _eventData_.compressedData += 200000000000000000000000000000000; - } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(25)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } - // set airdrop happened bool to true - _eventData_.compressedData += 10000000000000000000000000000000; - // let event know how much was won - _eventData_.compressedData += _prize * 1000000000000000000000000000000000; - - // reset air drop tracker - airDropTracker_ = 0; - } - } - - // store the air drop tracker number (number of buys since last airdrop) - _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); - - // update player - plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); - plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); - - // update round - round_[_rID].keys = _keys.add(round_[_rID].keys); - round_[_rID].eth = _eth.add(round_[_rID].eth); - rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); - - // distribute eth - _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); - _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); - - // call end tx function to fire end tx event. - endTx(_pID, _team, _eth, _keys, _eventData_); - } - } - //============================================================================== - // _ _ | _ | _ _|_ _ _ _ . - // (_(_||(_|_||(_| | (_)| _\ . - //============================================================================== - /** - * @dev calculates unmasked earnings (just calculates, does not update mask) - * @return earnings in wei format - */ - function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) - private - view - returns (uint256) - { - return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); - } - - /** - * @dev returns the amount of keys you would get given an amount of eth. - * -functionhash- 0xce89c80c - * @param _rID round ID you want price for - * @param _eth amount of eth sent in - * @return keys received - */ - function calcKeysReceived(uint256 _rID, uint256 _eth) - public - view - returns (uint256) - { - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].eth).keysRec(_eth)); - else // rounds over. need keys for new round - return ((_eth).keys()); - } - - /** - * @dev returns current eth price for X keys. - * -functionhash- 0xcf808000 - * @param _keys number of keys desired (in 18 decimal format) - * @return amount of eth needed to send - */ - function iWantXKeys(uint256 _keys) - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); - else // rounds over. need price for new round - return ((_keys).eth()); - } - //============================================================================== - // _|_ _ _ | _ . - // | (_)(_)|_\ . - //============================================================================== - /** - * @dev receives name/player info from names contract - */ - function receivePlayerInfo(uint256 _pID, address payable _addr, bytes32 _name, uint256 _laff) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (pIDxAddr_[_addr] != _pID) - pIDxAddr_[_addr] = _pID; - if (pIDxName_[_name] != _pID) - pIDxName_[_name] = _pID; - if (plyr_[_pID].addr != _addr) - plyr_[_pID].addr = _addr; - if (plyr_[_pID].name != _name) - plyr_[_pID].name = _name; - if (plyr_[_pID].laff != _laff) - plyr_[_pID].laff = _laff; - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev receives entire player name list - */ - function receivePlayerNameList(uint256 _pID, bytes32 _name) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev gets existing or registers new pID. use this when a player may be new - * @return pID - */ - function determinePID(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - uint256 _pID = pIDxAddr_[msg.sender]; - // if player is new to this version of fomo3d - if (_pID == 0) - { - // grab their player ID, name and last aff ID, from player names contract - _pID = playerBook.getPlayerID(msg.sender); - bytes32 _name = playerBook.getPlayerName(_pID); - uint256 _laff = playerBook.getPlayerLAff(_pID); - - // set up player account - pIDxAddr_[msg.sender] = _pID; - plyr_[_pID].addr = msg.sender; - - if (_name != "") - { - pIDxName_[_name] = _pID; - plyr_[_pID].name = _name; - plyrNames_[_pID][_name] = true; - } - - if (_laff != 0 && _laff != _pID) - plyr_[_pID].laff = _laff; - - // set the new player bool to true - _eventData_.compressedData = _eventData_.compressedData + 1; - } - return (_eventData_); - } - - /** - * @dev checks to make sure user picked a valid team. if not sets team - * to default (sneks) - */ - function verifyTeam(uint256 _team) - private - pure - returns (uint256) - { - if (_team < 0 || _team > 3) - return (2); - else - return (_team); - } - - /** - * @dev decides if round end needs to be run & new round started. and if - * player unmasked earnings from previously played rounds need to be moved. - */ - function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // if player has played a previous round, move their unmasked earnings - // from that round to gen vault. - if (plyr_[_pID].lrnd != 0) - updateGenVault(_pID, plyr_[_pID].lrnd); - - // update player's last round played - plyr_[_pID].lrnd = rID_; - - // set the joined round bool to true - _eventData_.compressedData = _eventData_.compressedData + 10; - - return (_eventData_); - } - - /** - * @dev ends the round. manages paying out winner/splitting up pot - */ - function endRound(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // setup local rID - uint256 _rID = rID_; - - // grab our winning player and team id's - uint256 _winPID = round_[_rID].plyr; - uint256 _winTID = round_[_rID].team; - - // grab our pot amount - uint256 _pot = round_[_rID].pot; - - // calculate our winner share, community rewards, gen share, - // p3d share, and amount reserved for next pot - uint256 _win = (_pot.mul(48)) / 100; - uint256 _com = (_pot / 50); - uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; - uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; - uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); - - // calculate ppt for round mask - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); - if (_dust > 0) - { - _gen = _gen.sub(_dust); - _res = _res.add(_dust); - } - - // pay our winner - plyr_[_winPID].win = _win.add(plyr_[_winPID].win); - - // community rewards - address payable add = address(uint160(Jekyll_Island_Inc)); - if (!add.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _p3d.add(_com); - _com = 0; - } - - // distribute gen portion to key holders - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // send share for p3d to divies - if (_p3d > 0){ - address payable addr = address(uint160(Divies)); - addr.transfer(_p3d); - } - // prepare event data - _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); - _eventData_.winnerAddr = plyr_[_winPID].addr; - _eventData_.winnerName = plyr_[_winPID].name; - _eventData_.amountWon = _win; - _eventData_.genAmount = _gen; - _eventData_.P3DAmount = _p3d; - _eventData_.newPot = _res; - - // start next round - rID_++; - _rID++; - round_[_rID].strt = now; - round_[_rID].end = now.add(rndInit_).add(rndGap_); - round_[_rID].pot = _res; - - return (_eventData_); - } - - /** - * @dev moves any unmasked earnings to gen vault. updates earnings mask - */ - function updateGenVault(uint256 _pID, uint256 _rIDlast) - private - { - uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); - if (_earnings > 0) - { - // put in gen vault - plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); - // zero out their earnings by updating mask - plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); - } - } - - /** - * @dev updates round timer based on number of whole keys bought. - */ - function updateTimer(uint256 _keys, uint256 _rID) - private - { - // grab time - uint256 _now = now; - - // calculate time based on number of keys bought - uint256 _newTime; - if (_now > round_[_rID].end && round_[_rID].plyr == 0) - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); - else - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); - - // compare to max and set new end time - if (_newTime < (rndMax_).add(_now)) - round_[_rID].end = _newTime; - else - round_[_rID].end = rndMax_.add(_now); - } - - /** - * @dev generates a random number between 0-99 and checks to see if thats - * resulted in an airdrop win - * @return do we have a winner? - */ - function airdrop() - private - view - returns (bool) - { - uint256 seed = uint256(keccak256(abi.encodePacked( - - (block.timestamp).add - (block.difficulty).add - ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add - (block.gaslimit).add - ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add - (block.number) - - ))); - if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) - return (true); - else - return (false); - } - - /** - * @dev distributes eth based on fees to com, aff, and p3d - */ - function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // pay 2% out to community rewards - uint256 _com = _eth / 50; - uint256 _p3d; - address payable addr = address(uint160(Jekyll_Island_Inc)); - if (!addr.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _com; - _com = 0; - } - - // pay 1% out to FoMo3D short - _com = _eth / 100; - address payable add = address(uint160(otherF3D_)); - add.transfer(_com); - - // distribute share to affiliate - _com = _eth / 10; - - // decide what to do with affiliate share of fees - // affiliate must not be self, and must have a name registered - if (_affID != _pID && plyr_[_affID].name != '') { - plyr_[_affID].aff = _com.add(plyr_[_affID].aff); - emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _com, now); - } else { - _p3d = _com; - } - - // pay out p3d - _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); - if (_p3d > 0) - { - // deposit to divies contract - address payable add = address(uint160(Divies)); - add.transfer(_p3d); - - // set up event data - _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); - } - - return (_eventData_); - } - - function potSwap() - external - payable - { - // setup local rID - uint256 _rID = rID_ + 1; - - round_[_rID].pot = round_[_rID].pot.add(msg.value); - emit F3Devents.onPotSwapDeposit(_rID, msg.value); - } - - /** - * @dev distributes eth based on fees to gen and pot - */ - function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // calculate gen share - uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; - - // toss 1% into airdrop pot - uint256 _air = (_eth / 100); - airDropPot_ = airDropPot_.add(_air); - - // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); - - // calculate pot - uint256 _pot = _eth.sub(_gen); - - // distribute gen share (thats what updateMasks() does) and adjust - // balances for dust. - uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); - if (_dust > 0) - _gen = _gen.sub(_dust); - - // add eth to pot - round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); - - // set up event data - _eventData_.genAmount = _gen.add(_eventData_.genAmount); - _eventData_.potAmount = _pot; - - return (_eventData_); - } - - /** - * @dev updates masks for round and player when keys are bought - * @return dust left over - */ - function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) - private - returns (uint256) - { - /* MASKING NOTES - earnings masks are a tricky thing for people to wrap their minds around. - the basic thing to understand here. is were going to have a global - tracker based on profit per share for each round, that increases in - relevant proportion to the increase in share supply. - - the player will have an additional mask that basically says "based - on the rounds mask, my shares, and how much i've already withdrawn, - how much is still owed to me?" - */ - - // calc profit per key & round mask based on this buy: (dust goes to pot) - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // calculate player earning from their own buy (only based on the keys - // they just bought). & update player earnings mask - uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); - plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); - - // calculate & return dust - return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); - } - - /** - * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 - * @return earnings in wei format - */ - function withdrawEarnings(uint256 _pID) - private - returns (uint256) - { - // update gen vault - updateGenVault(_pID, plyr_[_pID].lrnd); - - // from vaults - uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); - if (_earnings > 0) - { - plyr_[_pID].win = 0; - plyr_[_pID].gen = 0; - plyr_[_pID].aff = 0; - } - - return (_earnings); - } - - /** - * @dev prepares compression data and fires event for buy or reload tx's - */ - function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - { - _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); - - emit F3Devents.onEndTx - ( - _eventData_.compressedData, - _eventData_.compressedIDs, - plyr_[_pID].name, - msg.sender, - _eth, - _keys, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount, - _eventData_.potAmount, - airDropPot_ - ); - } - //============================================================================== - // (~ _ _ _._|_ . - // _)(/_(_|_|| | | \/ . - //====================/========================================================= - /** upon contract deploy, it will be deactivated. this is a one time - * use function that will activate the contract. we do this so devs - * have time to set things up on the web end **/ - bool public activated_ = false; - - function activate() - public - onlyDevs - { - - // can only be ran once - require(activated_ == false, "fomo3d already activated"); - - // activate the contract - activated_ = true; - - otherF3D_ = msg.sender; - Divies = msg.sender; - Jekyll_Island_Inc = msg.sender; - - // lets start first round - rID_ = 1; - round_[1].strt = now + rndExtra_ - rndGap_; - round_[1].end = now + rndInit_ + rndExtra_; - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario007.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario007.sol deleted file mode 100644 index 1e6ff5d7250..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario007.sol +++ /dev/null @@ -1,1433 +0,0 @@ -//pragma solidity 0.4.24; - -/** - * @title ERC165 - * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md - */ -interface ERC165 { - - /** - * @notice Query if a contract implements an interface - * @param _interfaceId The interface identifier, as specified in ERC-165 - * @dev Interface identification is specified in ERC-165. This function - * uses less than 30,000 gas. - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool); - -} - -contract ERC721Basic is ERC165 { - - event Transfer( - address indexed _from, - address indexed _to, - uint256 indexed _tokenId - ); - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); - - function balanceOf(address _owner) public view returns (uint256 _balance); - function ownerOf(uint256 _tokenId) public view returns (address _owner); - function exists(uint256 _tokenId) public view returns (bool _exists); - - function approve(address _to, uint256 _tokenId) public; - function getApproved(uint256 _tokenId) - public view returns (address _operator); - - function setApprovalForAll(address _operator, bool _approved) public; - function isApprovedForAll(address _owner, address _operator) - public view returns (bool); - - function transferFrom(address _from, address _to, uint256 _tokenId) public; - function safeTransferFrom(address _from, address _to, uint256 _tokenId) - public; - - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public; -} - - -/** - * @title SupportsInterfaceWithLookup - * @author Matt Condon (@shrugs) - * @dev Implements ERC165 using a lookup table. - */ -contract SupportsInterfaceWithLookup is ERC165 { - bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; - /** - * 0x01ffc9a7 === - * bytes4(keccak256('supportsInterface(bytes4)')) - */ - - /** - * @dev a mapping of interface id to whether or not it's supported - */ - mapping(bytes4 => bool) internal supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself - */ - constructor() public { - _registerInterface(InterfaceId_ERC165); - } - - /** - * @dev implement supportsInterface(bytes4) using a lookup table - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool) { - return supportedInterfaces[_interfaceId]; - } - - /** - * @dev private method for registering an interface - */ - function _registerInterface(bytes4 _interfaceId) internal { - require(_interfaceId != 0xffffffff); - supportedInterfaces[_interfaceId] = true; - } -} - -contract Governable { - - event Pause(); - event Unpause(); - - address public governor; - bool public paused = false; - - constructor() public { - governor = msg.sender; - } - - function setGovernor(address _gov) public onlyGovernor { - governor = _gov; - } - - modifier onlyGovernor { - require(msg.sender == governor); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - */ - modifier whenPaused() { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyGovernor whenNotPaused public { - paused = true; - emit Pause(); - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyGovernor whenPaused public { - paused = false; - emit Unpause(); - } - -} - -contract CardBase is Governable { - - struct Card { - uint16 proto; - uint16 purity; - } - - function getCard(uint id) public view returns (uint16 proto, uint16 purity) { - Card memory card = cards[id]; - return (card.proto, card.purity); - } - - function getShine(uint16 purity) public pure returns (uint8) { - return uint8(purity / 1000); - } - - Card[] public cards; - -} - -contract CardProto is CardBase { - - event NewProtoCard( - uint16 id, uint8 season, uint8 god, - Rarity rarity, uint8 mana, uint8 attack, - uint8 health, uint8 cardType, uint8 tribe, bool packable - ); - - struct Limit { - uint64 limit; - bool exists; - } - - // limits for mythic cards - mapping(uint16 => Limit) public limits; - - // can only set limits once - function setLimit(uint16 id, uint64 limit) public onlyGovernor { - Limit memory l = limits[id]; - require(!l.exists); - limits[id] = Limit({ - limit: limit, - exists: true - }); - } - - function getLimit(uint16 id) public view returns (uint64 limit, bool set) { - Limit memory l = limits[id]; - return (l.limit, l.exists); - } - - // could make these arrays to save gas - // not really necessary - will be update a very limited no of times - mapping(uint8 => bool) public seasonTradable; - mapping(uint8 => bool) public seasonTradabilityLocked; - uint8 public currentSeason; - - function makeTradable(uint8 season) public onlyGovernor { - seasonTradable[season] = true; - } - - function makeUntradable(uint8 season) public onlyGovernor { - require(!seasonTradabilityLocked[season]); - seasonTradable[season] = false; - } - - function makePermanantlyTradable(uint8 season) public onlyGovernor { - require(seasonTradable[season]); - seasonTradabilityLocked[season] = true; - } - - function isTradable(uint16 proto) public view returns (bool) { - return seasonTradable[protos[proto].season]; - } - - function nextSeason() public onlyGovernor { - //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M - require(currentSeason <= 255); - - currentSeason++; - mythic.length = 0; - legendary.length = 0; - epic.length = 0; - rare.length = 0; - common.length = 0; - } - - enum Rarity { - Common, - Rare, - Epic, - Legendary, - Mythic - } - - uint8 constant SPELL = 1; - uint8 constant MINION = 2; - uint8 constant WEAPON = 3; - uint8 constant HERO = 4; - - struct ProtoCard { - bool exists; - uint8 god; - uint8 season; - uint8 cardType; - Rarity rarity; - uint8 mana; - uint8 attack; - uint8 health; - uint8 tribe; - } - - // there is a particular design decision driving this: - // need to be able to iterate over mythics only for card generation - // don't store 5 different arrays: have to use 2 ids - // better to bear this cost (2 bytes per proto card) - // rather than 1 byte per instance - - uint16 public protoCount; - - mapping(uint16 => ProtoCard) protos; - - uint16[] public mythic; - uint16[] public legendary; - uint16[] public epic; - uint16[] public rare; - uint16[] public common; - - function addProtos( - uint16[] memory externalIDs, uint8[] memory gods, Rarity[] memory rarities, uint8[] memory manas, uint8[] memory attacks, - uint8[] memory healths, uint8[] memory cardTypes, uint8[] memory tribes, bool[] memory packable - ) public onlyGovernor returns(uint16) { - - for (uint i = 0; i < externalIDs.length; i++) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: gods[i], - season: currentSeason, - cardType: cardTypes[i], - rarity: rarities[i], - mana: manas[i], - attack: attacks[i], - health: healths[i], - tribe: tribes[i] - }); - - _addProto(externalIDs[i], card, packable[i]); - } - - } - - function addProto( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: cardType, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function addWeapon( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: WEAPON, - rarity: rarity, - mana: mana, - attack: attack, - health: durability, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: SPELL, - rarity: rarity, - mana: mana, - attack: 0, - health: 0, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addMinion( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: MINION, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { - - require(!protos[externalID].exists); - - card.exists = true; - - protos[externalID] = card; - - protoCount++; - - emit NewProtoCard( - externalID, currentSeason, card.god, - card.rarity, card.mana, card.attack, - card.health, card.cardType, card.tribe, packable - ); - - if (packable) { - Rarity rarity = card.rarity; - if (rarity == Rarity.Common) { - common.push(externalID); - } else if (rarity == Rarity.Rare) { - rare.push(externalID); - } else if (rarity == Rarity.Epic) { - epic.push(externalID); - } else if (rarity == Rarity.Legendary) { - legendary.push(externalID); - } else if (rarity == Rarity.Mythic) { - mythic.push(externalID); - } else { - require(false); - } - } - } - - function getProto(uint16 id) public view returns( - bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) { - ProtoCard memory proto = protos[id]; - return ( - proto.exists, - proto.god, - proto.season, - proto.cardType, - proto.rarity, - proto.mana, - proto.attack, - proto.health, - proto.tribe - ); - } - - function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { - // modulo bias is fine - creates rarity tiers etc - // will obviously revert is there are no cards of that type: this is expected - should never happen - if (rarity == Rarity.Common) { - return common[random % common.length]; - } else if (rarity == Rarity.Rare) { - return rare[random % rare.length]; - } else if (rarity == Rarity.Epic) { - return epic[random % epic.length]; - } else if (rarity == Rarity.Legendary) { - return legendary[random % legendary.length]; - } else if (rarity == Rarity.Mythic) { - // make sure a mythic is available - uint16 id; - uint64 limit; - bool set; - for (uint i = 0; i < mythic.length; i++) { - id = mythic[(random + i) % mythic.length]; - (limit, set) = getLimit(id); - if (set && limit > 0){ - return id; - } - } - // if not, they get a legendary :( - return legendary[random % legendary.length]; - } - require(false); - return 0; - } - - // can never adjust tradable cards - // each season gets a 'balancing beta' - // totally immutable: season, rarity - function replaceProto( - uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) public onlyGovernor { - ProtoCard memory pc = protos[index]; - require(!seasonTradable[pc.season]); - protos[index] = ProtoCard({ - exists: true, - god: god, - season: pc.season, - cardType: cardType, - rarity: pc.rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - } - -} - -contract ERC721Receiver { - /** - * @dev Magic value to be returned upon successful reception of an NFT - * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, - * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - */ - bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; - - /** - * @notice Handle the receipt of an NFT - * @dev The ERC721 smart contract calls this function on the recipient - * after a `safetransfer`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the contract address is always the message sender. - * @param _operator The address which called `safeTransferFrom` function - * @param _from The address which previously owned the token - * @param _tokenId The NFT identifier which is being transfered - * @param _data Additional data with no specified format - * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - */ - function onERC721Received( - address _operator, - address _from, - uint256 _tokenId, - bytes memory _data - ) - public - returns(bytes4); -} - -library AddressUtils { - - /** - * Returns whether the target address is a contract - * @dev This function will return false if invoked during the constructor of a contract, - * as the code is not actually created until after the constructor finishes. - * @param addr address to check - * @return whether the target address is a contract - */ - function isContract1(address addr) internal view returns (bool) { - uint256 size; - // XXX Currently there is no better way to check if there is a contract in an address - // than to check the size of the code at that address. - // See https://ethereum.stackexchange.com/a/14016/36603 - // for more details about how this works. - // TODO Check this again before the Serenity release, because all addresses will be - // contracts then. - // solium-disable-next-line security/no-inline-assembly - assembly { size := extcodesize(addr) } - return size > 0; - } - -} - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { - // Gas optimization: this is cheaper than asserting 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 - if (a == 0) { - return 0; - } - - c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - // uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return a / b; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256 c) { - c = a + b; - assert(c >= a); - return c; - } -} - -contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic { - - bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; - /* - * 0x80ac58cd === - * bytes4(keccak256('balanceOf(address)')) ^ - * bytes4(keccak256('ownerOf(uint256)')) ^ - * bytes4(keccak256('approve(address,uint256)')) ^ - * bytes4(keccak256('getApproved(uint256)')) ^ - * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ - * bytes4(keccak256('isApprovedForAll(address,address)')) ^ - * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) - */ - - bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; - /* - * 0x4f558e79 === - * bytes4(keccak256('exists(uint256)')) - */ - - using SafeMath for uint256; - using AddressUtils for address; - - // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - bytes4 private constant ERC721_RECEIVED = 0x150b7a02; - - // Mapping from token ID to owner - mapping (uint256 => address) internal tokenOwner; - - // Mapping from token ID to approved address - mapping (uint256 => address) internal tokenApprovals; - - // Mapping from owner to number of owned token - // mapping (address => uint256) internal ownedTokensCount; - - // Mapping from owner to operator approvals - mapping (address => mapping (address => bool)) internal operatorApprovals; - - /** - * @dev Guarantees msg.sender is owner of the given token - * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender - */ - modifier onlyOwnerOf(uint256 _tokenId) { - require(ownerOf(_tokenId) == msg.sender); - _; - } - - /** - * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator - * @param _tokenId uint256 ID of the token to validate - */ - modifier canTransfer(uint256 _tokenId) { - require(isApprovedOrOwner(msg.sender, _tokenId)); - _; - } - - constructor() - public - { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721); - _registerInterface(InterfaceId_ERC721Exists); - } - - /** - * @dev Gets the balance of the specified address - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256); - - /** - * @dev Gets the owner of the specified token ID - * @param _tokenId uint256 ID of the token to query the owner of - * @return owner address currently marked as the owner of the given token ID - */ - function ownerOf(uint256 _tokenId) public view returns (address) { - address owner = tokenOwner[_tokenId]; - require(owner != address(0)); - return owner; - } - - /** - * @dev Returns whether the specified token exists - * @param _tokenId uint256 ID of the token to query the existence of - * @return whether the token exists - */ - function exists(uint256 _tokenId) public view returns (bool) { - address owner = tokenOwner[_tokenId]; - return owner != address(0); - } - - /** - * @dev Approves another address to transfer the given token ID - * The zero address indicates there is no approved address. - * There can only be one approved address per token at a given time. - * Can only be called by the token owner or an approved operator. - * @param _to address to be approved for the given token ID - * @param _tokenId uint256 ID of the token to be approved - */ - function approve(address _to, uint256 _tokenId) public { - address owner = ownerOf(_tokenId); - require(_to != owner); - require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); - - tokenApprovals[_tokenId] = _to; - emit Approval(owner, _to, _tokenId); - } - - /** - * @dev Gets the approved address for a token ID, or zero if no address set - * @param _tokenId uint256 ID of the token to query the approval of - * @return address currently approved for the given token ID - */ - function getApproved(uint256 _tokenId) public view returns (address) { - return tokenApprovals[_tokenId]; - } - - /** - * @dev Sets or unsets the approval of a given operator - * An operator is allowed to transfer all tokens of the sender on their behalf - * @param _to operator address to set the approval - * @param _approved representing the status of the approval to be set - */ - function setApprovalForAll(address _to, bool _approved) public { - require(_to != msg.sender); - operatorApprovals[msg.sender][_to] = _approved; - emit ApprovalForAll(msg.sender, _to, _approved); - } - - /** - * @dev Tells whether an operator is approved by a given owner - * @param _owner owner address which you want to query the approval of - * @param _operator operator address which you want to query the approval of - * @return bool whether the given operator is approved by the given owner - */ - function isApprovedForAll( - address _owner, - address _operator - ) - public - view - returns (bool) - { - return operatorApprovals[_owner][_operator]; - } - - /** - * @dev Transfers the ownership of a given token ID to another address - * Usage of this method is discouraged, use `safeTransferFrom` whenever possible - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - require(_from != address(0)); - require(_to != address(0)); - - clearApproval(_from, _tokenId); - removeTokenFrom(_from, _tokenId); - addTokenTo(_to, _tokenId); - - emit Transfer(_from, _to, _tokenId); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - // solium-disable-next-line arg-overflow - safeTransferFrom(_from, _to, _tokenId, ""); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes data to send along with a safe transfer check - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public - canTransfer(_tokenId) - { - transferFrom(_from, _to, _tokenId); - // solium-disable-next-line arg-overflow - require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); - } - - /** - * @dev Returns whether the given spender can transfer a given token ID - * @param _spender address of the spender to query - * @param _tokenId uint256 ID of the token to be transferred - * @return bool whether the msg.sender is approved for the given token ID, - * is an operator of the owner, or is the owner of the token - */ - function isApprovedOrOwner( - address _spender, - uint256 _tokenId - ) - internal - view - returns (bool) - { - address owner = ownerOf(_tokenId); - // Disable solium check because of - // https://github.com/duaraghav8/Solium/issues/175 - // solium-disable-next-line operator-whitespace - return ( - _spender == owner || - getApproved(_tokenId) == _spender || - isApprovedForAll(owner, _spender) - ); - } - - /** - * @dev Internal function to clear current approval of a given token ID - * Reverts if the given address is not indeed the owner of the token - * @param _owner owner of the token - * @param _tokenId uint256 ID of the token to be transferred - */ - function clearApproval(address _owner, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _owner); - if (tokenApprovals[_tokenId] != address(0)) { - tokenApprovals[_tokenId] = address(0); - } - } - - /** - * @dev Internal function to mint a new token - * Reverts if the given token ID already exists - * @param _to The address that will own the minted token - * @param _tokenId uint256 ID of the token to be minted by the msg.sender - */ - function _mint(address _to, uint256 _tokenId) internal { - require(_to != address(0)); - addNewTokenTo(_to, _tokenId); - emit Transfer(address(0), _to, _tokenId); - } - - - /** - * @dev Internal function to burn a specific token - * Reverts if the token does not exist - * @param _tokenId uint256 ID of the token being burned by the msg.sender - */ - function _burn(address _owner, uint256 _tokenId) internal { - clearApproval(_owner, _tokenId); - removeTokenFrom(_owner, _tokenId); - emit Transfer(_owner, address(0), _tokenId); - } - - function addNewTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - // ownedTokensCount[_to] = ownedTokensCount[_to].add(1); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _from); - // ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); - tokenOwner[_tokenId] = address(0); - } - - /** - * @dev Internal function to invoke `onERC721Received` on a target address - * The call is not executed if the target address is not a contract - * @param _from address representing the previous owner of the given token ID - * @param _to target address that will receive the tokens - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes optional data to send along with the call - * @return whether the call correctly returned the expected magic value - */ - function checkAndCallSafeTransfer( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - internal - returns (bool) - { - if (!_to.isContract1()) { - return true; - } - bytes4 retval = ERC721Receiver(_to).onERC721Received( - msg.sender, _from, _tokenId, _data); - return (retval == ERC721_RECEIVED); - } - -} - - - -contract ERC721Enumerable is ERC721Basic { - function totalSupply() public view returns (uint256); - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256 _tokenId); - - function tokenByIndex(uint256 _index) public view returns (uint256); -} - -contract ERC721Metadata is ERC721Basic { - function name() external view returns (string memory _name); - function symbol() external view returns (string memory _symbol); - function tokenURI(uint256 _tokenId) public view returns (string memory); -} - -contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { - -} - - - - -library Strings { - - // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory ) { - bytes memory _ba = bytes(_a); - bytes memory _bb = bytes(_b); - bytes memory _bc = bytes(_c); - bytes memory _bd = bytes(_d); - bytes memory _be = bytes(_e); - string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); - bytes memory babcde = bytes(abcde); - uint k = 0; - for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; - for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; - for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; - for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; - for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; - return string(babcde); - } - - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, _d, ""); - } - - function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, "", ""); - } - - function strConcat(string memory _a, string memory _b) internal pure returns (string memory ) { - return strConcat(_a, _b, "", "", ""); - } - - function uint2str(uint i) internal pure returns (string memory ) { - if (i == 0) return "0"; - uint j = i; - uint len; - while (j != 0){ - len++; - j /= 10; - } - bytes memory bstr = new bytes(len); - uint k = len - 1; - while (i != 0){ - bstr[k--] = byte(uint8(48 + i % 10)); - i /= 10; - } - return string(bstr); - } -} - -contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { - - using Strings for string; - - bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; - /** - * 0x780e9d63 === - * bytes4(keccak256('totalSupply()')) ^ - * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ - * bytes4(keccak256('tokenByIndex(uint256)')) - */ - - bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; - /** - * 0x5b5e139f === - * bytes4(keccak256('name()')) ^ - * bytes4(keccak256('symbol()')) ^ - * bytes4(keccak256('tokenURI(uint256)')) - */ - - /*** Constants ***/ - // Configure these for your own deployment - string public constant NAME = "Gods Unchained"; - string public constant SYMBOL = "GODS"; - string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/"; - - // Mapping from owner to list of owned token IDs - // EDITED: limit to 2^40 (around 1T) - mapping(address => uint40[]) internal ownedTokens; - - uint32[] ownedTokensIndex; - - /** - * @dev Constructor function - */ - constructor() public { - - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721Enumerable); - _registerInterface(InterfaceId_ERC721Metadata); - } - - /** - * @dev Gets the token name - * @return string representing the token name - */ - function name() external view returns (string memory) { - return NAME; - } - - /** - * @dev Gets the token symbol - * @return string representing the token symbol - */ - function symbol() external view returns (string memory) { - return SYMBOL; - } - - /** - * @dev Returns an URI for a given token ID - * Throws if the token ID does not exist. May return an empty string. - * @param _tokenId uint256 ID of the token to query - */ - function tokenURI(uint256 _tokenId) public view returns (string memory) { - return Strings.strConcat( - tokenMetadataBaseURI, - Strings.uint2str(_tokenId) - ); - } - - /** - * @dev Gets the token ID at a given index of the tokens list of the requested owner - * @param _owner address owning the tokens list to be accessed - * @param _index uint256 representing the index to be accessed of the requested tokens list - * @return uint256 token ID at the given index of the tokens list owned by the requested address - */ - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256) - { - require(_index < balanceOf(_owner)); - return ownedTokens[_owner][_index]; - } - - /** - * @dev Gets the total amount of tokens stored by the contract - * @return uint256 representing the total amount of tokens - */ - function totalSupply() public view returns (uint256) { - return cards.length; - } - - /** - * @dev Gets the token ID at a given index of all the tokens in this contract - * Reverts if the index is greater or equal to the total number of tokens - * @param _index uint256 representing the index to be accessed of the tokens list - * @return uint256 token ID at the given index of the tokens list - */ - function tokenByIndex(uint256 _index) public view returns (uint256) { - require(_index < totalSupply()); - return _index; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - super.addTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - - ownedTokensIndex[_tokenId] = uint32(length); - } - - // EDITED - // have to have in order to use array rather than mapping - function addNewTokenTo(address _to, uint256 _tokenId) internal { - super.addNewTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - ownedTokensIndex.push(uint32(length)); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - super.removeTokenFrom(_from, _tokenId); - - uint32 tokenIndex = ownedTokensIndex[_tokenId]; - uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); - uint40 lastToken = ownedTokens[_from][lastTokenIndex]; - - ownedTokens[_from][tokenIndex] = lastToken; - ownedTokens[_from][lastTokenIndex] = 0; - // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to - // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping - // the lastToken to the first position, and then dropping the element placed in the last position of the list - - ownedTokens[_from].length--; - ownedTokensIndex[_tokenId] = 0; - ownedTokensIndex[lastToken] = tokenIndex; - } - - /** - * @dev Gets the balance of the specified address - overrriden from previous to save gas - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256) { - return ownedTokens[_owner].length; - } - -} - -contract CardOwnershipTwo is ERC721Token { - - uint public burnCount; - - function getActiveCards() public view returns (uint) { - return totalSupply() - burnCount; - } - - /** - * @param to : the address to which the card will be transferred - * @param id : the id of the card to be transferred - */ - function transfer(address to, uint id) public payable onlyOwnerOf(id) { - require(isTradable(cards[id].proto)); - require(to != address(0)); - - _transfer(msg.sender, to, id); - } - - function _transfer(address from, address to, uint id) internal { - - clearApproval(from, id); - - removeTokenFrom(from, id); - - addTokenTo(to, id); - - emit Transfer(from, to, id); - } - - /** - * @param to : the address to which the cards will be transferred - * @param ids : the ids of the cards to be transferred - */ - function transferAll(address to, uint[] memory ids) public payable { - for (uint i = 0; i < ids.length; i++) { - transfer(to, ids[i]); - } - } - - /** - * @param proposed : the claimed owner of the cards - * @param ids : the ids of the cards to check - * @return whether proposed owns all of the cards - */ - function ownsAll(address proposed, uint[] memory ids) public view returns (bool) { - require(ids.length > 0); - for (uint i = 0; i < ids.length; i++) { - if (!owns(proposed, ids[i])) { - return false; - } - } - return true; - } - - /** - * @param proposed : the claimed owner of the card - * @param id : the id of the card to check - * @return whether proposed owns the card - */ - function owns(address proposed, uint id) public view returns (bool) { - return ownerOf(id) == proposed; - } - - function burn(uint id) public onlyOwnerOf(id) { - burnCount++; - _burn(msg.sender, id); - } - - /** - * @param ids : the indices of the tokens to burn - */ - function burnAll(uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++){ - burn(ids[i]); - } - } - - /** - * @param to : the address to approve for transfer - * @param id : the index of the card to be approved - */ - function approve(address to, uint id) public { - require(isTradable(cards[id].proto)); - super.approve(to, id); - } - - /** - * @param to : the address to approve for transfer - * @param ids : the indices of the cards to be approved - */ - function approveAll(address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - approve(to, ids[i]); - } - } - - /** - * @param to : the address to which the token should be transferred - * @param id : the index of the token to transfer - */ - function transferFrom(address from, address to, uint id) public { - require(isTradable(cards[id].proto)); - super.transferFrom(from, to, id); - } - - /** - * @param to : the address to which the tokens should be transferred - * @param ids : the indices of the tokens to transfer - */ - function transferAllFrom(address from, address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - transferFrom(from, to, ids[i]); - } - } - - /** - * @return the number of cards which have been burned - */ - function getBurnCount() public view returns (uint) { - return burnCount; - } - -} - -contract CardIntegrationTwo is CardOwnershipTwo { - - address[] public packs; - - event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); - - function addPack(address approved) public onlyGovernor { - packs.push(approved); - } - - modifier onlyApprovedPacks { - require(_isApprovedPack()); - _; - } - - function _isApprovedPack() private view returns (bool) { - for (uint i = 0; i < packs.length; i++) { - if (msg.sender == address(packs[i])) { - return true; - } - } - return false; - } - - function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { - ProtoCard memory card = protos[proto]; - require(card.season == currentSeason); - if (card.rarity == Rarity.Mythic) { - uint64 limit; - bool exists; - (limit, exists) = getLimit(proto); - require(!exists || limit > 0); - limits[proto].limit--; - } - return _createCard(owner, proto, purity); - } - - function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { - Card memory card = Card({ - proto: proto, - purity: purity - }); - - uint id = cards.push(card) - 1; - - _mint(owner, id); - - emit CardCreated(id, proto, purity, owner); - - return id; - } - - /*function combineCards(uint[] ids) public whenNotPaused { - require(ids.length == 5); - require(ownsAll(msg.sender, ids)); - Card memory first = cards[ids[0]]; - uint16 proto = first.proto; - uint8 shine = _getShine(first.purity); - require(shine < shineLimit); - uint16 puritySum = first.purity - (shine * 1000); - burn(ids[0]); - for (uint i = 1; i < ids.length; i++) { - Card memory next = cards[ids[i]]; - require(next.proto == proto); - require(_getShine(next.purity) == shine); - puritySum += (next.purity - (shine * 1000)); - burn(ids[i]); - } - uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); - _createCard(msg.sender, proto, newPurity); - }*/ - - - // PURITY NOTES - // currently, we only - // however, to protect rarity, you'll never be abl - // this is enforced by the restriction in the create-card function - // no cards above this point can be found in packs - - - -} - -contract PreviousInterface { - - function ownerOf(uint id) public view returns (address); - - function getCard(uint id) public view returns (uint16, uint16); - - function totalSupply() public view returns (uint); - - function burnCount() public view returns (uint); - -} - -contract CardMigration is CardIntegrationTwo { - - constructor(PreviousInterface previous) public { - old = previous; - } - - // use interface to lower deployment cost - PreviousInterface old; - - mapping(uint => bool) public migrated; - - function migrate(uint id) public { - - require(!migrated[id]); - - migrated[id] = true; - - address owner = old.ownerOf(id); - - uint16 proto; - uint16 purity; - - (proto, purity) = old.getCard(id); - - _createCard(owner, proto, purity); - } - - function migrateAll(uint[] memory ids) public { - - for (uint i = 0; i < ids.length; i++){ - migrate(ids[i]); - } - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario008.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario008.sol deleted file mode 100644 index 251b41bc6a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario008.sol +++ /dev/null @@ -1,2050 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause() public onlyCEO whenPaused { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario009.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario009.sol deleted file mode 100644 index fb0b76db240..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario009.sol +++ /dev/null @@ -1,51 +0,0 @@ -//pragma solidity ^0.4.0; - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert (Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register(uint value) public { - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario010.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario010.sol deleted file mode 100644 index f665ea9686e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario010.sol +++ /dev/null @@ -1,107 +0,0 @@ -//pragma solidity ^0.4.11; - -contract TRON_ERC721 { - //name - function name() view public returns (string memory name){ - return "Tron ERC721 Token"; - } - //symbol - function symbol() view public returns (string memory symbol){ - return "T721T"; - } - - //totalSupply - - function totalSupply() view public returns (uint256 supply){ - uint256 totalSupply = 1000000000000; - return totalSupply; - } - - mapping(address => uint) private balances; - function balanceOf(address _owner) view public returns (uint balance) - { - return balances[_owner]; - } - - - mapping(uint256 => address) private tokenOwners; - mapping(uint256 => bool) private tokenExists; - function ownerOf(uint256 _tokenId) view public returns (address owner) { - require(tokenExists[_tokenId]); - return tokenOwners[_tokenId]; - } - - - mapping(address => mapping (address => uint256)) allowed; - function approve(address _to, uint256 _tokenId) public{ - require(msg.sender == ownerOf(_tokenId)); - require(msg.sender != _to); - allowed[msg.sender][_to] = _tokenId; - emit Approval(msg.sender, _to, _tokenId); - } - - - function takeOwnership(uint256 _tokenId) public { - require(tokenExists[_tokenId]); - address oldOwner = ownerOf(_tokenId); - address newOwner = msg.sender; - require(newOwner != oldOwner); - require(allowed[oldOwner][newOwner] == _tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - mapping(address => mapping(uint256 => uint256)) private ownerTokens; - function removeFromTokenList(address owner, uint256 _tokenId) private { - for(uint256 i = 0;ownerTokens[owner][i] != _tokenId;i++){ - ownerTokens[owner][i] = 0; - } - } - - function transfer(address _to, uint256 _tokenId) public{ - address currentOwner = msg.sender; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - function transferFrom(address _from,address _to, uint256 _tokenId) public{ - address currentOwner = _from; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - function tokenOfOwnerByIndex(address _owner, uint256 _index) view public returns (uint tokenId){ - return ownerTokens[_owner][_index]; - } - - - mapping(uint256 => string) tokenLinks; - function tokenMetadata(uint256 _tokenId) view public returns (string memory infoUrl) { - return tokenLinks[_tokenId]; - } - // Events - event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); - event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario011.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario011.sol deleted file mode 100644 index 74fe819be31..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario011.sol +++ /dev/null @@ -1,2050 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause() public onlyCEO whenPaused { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario012.sol deleted file mode 100644 index 7bed08dd111..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario012.sol +++ /dev/null @@ -1,57 +0,0 @@ -//pragma solidity ^0.4.0; -contract PayTest { - -uint256 public n; -constructor() payable public{ -n = 0; -} - -function nPlusOne() public{ -n = n+1; -} - -//get current contract balance -function getBalance() payable public returns (uint) { -return address(this).balance; -} - -function getSenderBalance() public view returns(address, uint) { -return (msg.sender, msg.sender.balance); -} - -address public user; - -//deposit 1 coin to msg.sender -function depositOneCoin() payable public returns(bool success){ -return msg.sender.send(1); -} - -// function transferOneCoin() payable public returns(){ -// address(msg.sender).transfer(1); -// } - -// function depositOneCoin() payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(1)); -// } - -//deposit coin to msg.sender -function deposit(uint256 money) payable public returns(bool success){ -return msg.sender.send(money); -} -// function deposit(uint money) payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(money)); -// } - -// function () payable { -// msg.sender.send(1); -// } - -function sendToAddress(address payable _receiver) payable public{ -_receiver.transfer(msg.value); -} - -function sendToAddress2(address payable _receiver) payable public{ -_receiver.transfer(5); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario013.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario013.sol deleted file mode 100644 index b91085d018e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario013.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; -contract timetest { - -function time() public{ -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractScenario014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractScenario014.sol deleted file mode 100644 index 41ea739e231..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractScenario014.sol +++ /dev/null @@ -1,34 +0,0 @@ -//pragma solidity ^0.4.0; -contract Contract1 { - constructor() public payable{} - function send5SunToReceiver(address payable _receiver) payable public{ - _receiver.transfer(5); - } -} -contract contract2 { - address public payContract; - - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract1(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - } - - function triggerContract1ButRevert(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - require(1 == 2); - } - -} -contract contract3 { - address public payContract; - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract2(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("triggerContract1(address)",_receiver)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTest.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTest.sol deleted file mode 100644 index 409545eaabb..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTest.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.4; - -contract Test{ - -function a() public returns (uint){ - -uint256 count = 0; - -for (uint256 i = 1; i > 0; i++) { - -count++; - -} - -return count; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode_0.5.15/contractToMathedFeed.sol deleted file mode 100644 index a5d181ad927..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractToMathedFeed.sol +++ /dev/null @@ -1,21 +0,0 @@ -//pragma solidity ^0.4.0; - -contract ToMathedFeed { - uint public i=1; - function ToMathed (uint value) public { - i=value; - } -} - -contract ToMathedUseINContract { - function ToMathedIUseNR(address a,uint256 n) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathedNot(uint256)",n)); - return success; - } - function ToMathedIUseNRE(address a,uint256 value) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathed(uint256)",value)); - return success; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTransferToken001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTransferToken001.sol deleted file mode 100644 index e91c0d7bf0f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTransferToken001.sol +++ /dev/null @@ -1,22 +0,0 @@ -contract A { - address public a; - constructor() public payable{} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - function newB() public payable returns(address){ - B bAddress=new B(); - a= address(bAddress); - return a; - - } - - } - -contract B{ - constructor() public payable {} - function() external payable {} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken001.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken001.sol deleted file mode 100644 index 0db64f36336..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken001.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken002.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken002.sol deleted file mode 100644 index 0db64f36336..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken002.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken003.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken003.sol deleted file mode 100644 index 48205199eec..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken003.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken005.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken005.sol deleted file mode 100644 index 48205199eec..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken005.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken011.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken011.sol deleted file mode 100644 index f815c26b136..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken011.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken012.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken012.sol deleted file mode 100644 index 668f67ae205..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken012.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken014.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken014.sol deleted file mode 100644 index 3753770398a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken014.sol +++ /dev/null @@ -1,34 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken018.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken018.sol deleted file mode 100644 index 668f67ae205..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken018.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken023.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken023.sol deleted file mode 100644 index 99b19beb107..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken023.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() external { - flag = 1; -} - -} -//pragma solidity ^0.4.24; -contract C{ - uint256 public flag = 0; - constructor() public payable {} - function() external payable { - //flag = 1; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken026.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken026.sol deleted file mode 100644 index 66635521150..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken026.sol +++ /dev/null @@ -1,31 +0,0 @@ -//pragma solidity ^0.4.24; - -contract token{ - constructor() payable public{} - function() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - //callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - function() external payable{} - function transC(address payable callCAddress,address payable toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - function() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken027.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken027.sol deleted file mode 100644 index ee9c1d3eb46..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken027.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - -contract token{ - constructor() payable public{} - function() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - function() external payable{} - function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - function() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken028.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken028.sol deleted file mode 100644 index 957f1c3c60d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken028.sol +++ /dev/null @@ -1,25 +0,0 @@ -//pragma solidity ^0.4.24; - -contract token{ - uint256 public a=1; - constructor() public payable{} - function tokenBalanceWithSameName(trcToken id) public payable{ - B b= new B(); - a= b.tokenBalance(id); - } - function getA() public returns(uint256){ - return a; - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - function() external payable{} - function tokenBalance(trcToken id) payable public returns(uint256){ - flag =9; - return flag; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken029.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken029.sol deleted file mode 100644 index e8f5cbc0988..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken029.sol +++ /dev/null @@ -1,24 +0,0 @@ -//pragma solidity ^0.4.24; - -contract token{ - address public a; - constructor() public payable{} - function transferTokenWithSameName(trcToken id,uint256 amount) public payable{ - B b= new B(); - b.transferToken(amount,id); - a= address(b); - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - function() external payable{} - function transferToken(uint256 amount, trcToken id) payable public returns(bool){ - flag =9; - } - function getFlag() public view returns (uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken030.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken030.sol deleted file mode 100644 index 5693292d127..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken030.sol +++ /dev/null @@ -1,18 +0,0 @@ -//pragma solidity ^0.4.24; - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - function() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken031.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken031.sol deleted file mode 100644 index 5693292d127..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken031.sol +++ /dev/null @@ -1,18 +0,0 @@ -//pragma solidity ^0.4.24; - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - function() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken034.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken034.sol deleted file mode 100644 index 2a3d9e1fa3a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken034.sol +++ /dev/null @@ -1,25 +0,0 @@ -//pragma solidity ^0.4.24; - - contract token{ - - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken035.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken035.sol deleted file mode 100644 index ab53daa704a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken035.sol +++ /dev/null @@ -1,24 +0,0 @@ -//pragma solidity ^0.4.24; - - contract token{ - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036.sol deleted file mode 100644 index 6a4c61d1e07..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036.sol +++ /dev/null @@ -1,52 +0,0 @@ -//pragma solidity ^0.4.24; -contract IllegalDecorate { -constructor() payable public{} -function() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate1 { -constructor() payable public{} -function() payable external{} -event log(uint256); -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -function() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -function() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_1.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_1.sol deleted file mode 100644 index cd039f3e39d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_1.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.24; -contract IllegalDecorate { -constructor() payable public{} -function() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_2.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_2.sol deleted file mode 100644 index 0b4d56e086b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_2.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.24; -contract IllegalDecorate { -constructor() payable public{} -function() payable external{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_3.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_3.sol deleted file mode 100644 index b8c7d750514..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_3.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.24; -contract IllegalDecorate { -constructor() payable public{} -function() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_4.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_4.sol deleted file mode 100644 index 29c1990962b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_4.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.4.24; -contract IllegalDecorate { -event log(uint256); -constructor() payable public{} -function() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_old.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_old.sol deleted file mode 100644 index 7ea2561a1e1..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken036_old.sol +++ /dev/null @@ -1,41 +0,0 @@ -//pragma solidity ^0.4.24; - - -contract IllegalDecorate1 { -constructor() payable public{} -function() payable public{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -function() payable public{} -event log(uint256); -function transferTokenWithView(address toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -function() payable public{} -function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken037.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken037.sol deleted file mode 100644 index 5e3fbcb8270..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken037.sol +++ /dev/null @@ -1,24 +0,0 @@ -//pragma solidity ^0.4.24; - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - require(0==address(this).tokenBalance(msg.tokenid)); - require(bamount+aamount==rec.tokenBalance(msg.tokenid)); - (bool success, bytes memory data) =rec.call(abi.encodeWithSignature("checkTrc10(uint256,trcToken,uint256)",bamount+aamount,msg.tokenid,0)); - require(success); - - } -} - -contract receiveTrc10 { - function() external payable {} - function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ - require(amount==address(this).tokenBalance(tid)); - require(meamount==msg.sender.tokenBalance(tid)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken038.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken038.sol deleted file mode 100644 index 713d7661e84..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken038.sol +++ /dev/null @@ -1,24 +0,0 @@ -//pragma solidity ^0.4.24; - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - //require(rec.call(abi.encode(bytes4(keccak256("AssertError()"))))); - (bool suc, bytes memory data) = rec.call(abi.encodeWithSignature("AssertError()")); - require(suc); - require(aamount==address(this).tokenBalance(msg.tokenid)); - require(bamount==rec.tokenBalance(msg.tokenid)); - } -} - -contract receiveTrc10 { - function() external payable { - } - function AssertError() public{ - assert(1==2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken039.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken039.sol deleted file mode 100644 index e60b3285652..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken039.sol +++ /dev/null @@ -1,44 +0,0 @@ -//pragma solidity ^0.4.24; -/* - * 1. caller账户issue一个token - * 2. caller部署proxy, 传入1000 token,1000 trx - * 3. caller部署A - * 4. caller部署B - * 5. caller调用proxy中upgradetTo函数,传入A的地址 - * 6. caller调用proxy中不存在的trans(uint256,address,trcToken)函数,注意这时trcToken是无意义的,但也带上tokenid。address是任意另外某账户的地址 - * 7. 可以看到目标地址trx增长5,caller账户trx减少5 - * 8. caller调用proxy中upgradeTo函数,传入B的地址 - * 9. caller调用proxy中不存在的trans(uint256,address,trcToken)函数。 - * 10. 可以看到目标地址token增长5,caller账户token减少5 -*/ -contract Proxy { - constructor() payable public{} - address public implementation; - function upgradeTo(address _address) public { - implementation = _address; - } - function() payable external{ - address addr = implementation; - require(addr != address(0)); - assembly { - let freememstart := mload(0x40) - calldatacopy(freememstart, 0, calldatasize()) - let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 0) - returndatacopy(freememstart, 0, returndatasize()) - switch success - case 0 { revert(freememstart, returndatasize()) } - default { return(freememstart, returndatasize()) } - } - } -} - -contract A { - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transfer(amount); - } -} -contract B{ - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transferToken(amount,id); - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken041.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken041.sol deleted file mode 100644 index a6272bc813d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken041.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() external payable {} - - function setFlag() public payable{ - flag = 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken043.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken043.sol deleted file mode 100644 index f815c26b136..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken043.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken048.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken048.sol deleted file mode 100644 index de2844608c0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken048.sol +++ /dev/null @@ -1,14 +0,0 @@ -//pragma solidity ^0.4.24; - - contract Test { - event log(uint256); - function testMsgTokenValue() payable public returns(uint256 value) { - emit log(msg.tokenvalue); - return msg.tokenvalue; - } - - function testMsgValue() payable public returns(uint256 value) { - emit log(msg.value); - return msg.value; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken049.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken049.sol deleted file mode 100644 index 3fd502c89fd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken049.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken050.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken050.sol deleted file mode 100644 index 3fd502c89fd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken050.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken051.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken051.sol deleted file mode 100644 index b5b9efd4817..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken051.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - function() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken052.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken052.sol deleted file mode 100644 index 3fd502c89fd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken052.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken054.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken054.sol deleted file mode 100644 index 48205199eec..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken054.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken055.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken055.sol deleted file mode 100644 index 48205199eec..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken055.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken060.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken060.sol deleted file mode 100644 index 0db64f36336..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken060.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken061.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken061.sol deleted file mode 100644 index 0db64f36336..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken061.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken064.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken064.sol deleted file mode 100644 index cf2a6fe8097..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken064.sol +++ /dev/null @@ -1,49 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } - function transferTokenTestValueMaxBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0); - } - function transferTokenTestValueOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775808, 1000001); - } - function transferTokenTestValueMaxLong(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775807, 1000001); - } - function transferTokenTestValue0IdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0, 9223372036854775809); - } -} - - - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken066.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken066.sol deleted file mode 100644 index f815c26b136..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken066.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken067.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken067.sol deleted file mode 100644 index f815c26b136..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken067.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken073.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken073.sol deleted file mode 100644 index 9cb13ec7268..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken073.sol +++ /dev/null @@ -1,17 +0,0 @@ -//pragma solidity ^0.4.0; - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function () payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken075.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken075.sol deleted file mode 100644 index 2a32fd7e8d3..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken075.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.0; - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMin() payable public{ - // long.min - 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(-9223372036855775828)), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMax() payable public{ - // long.max + 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); - } - - function () payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken076.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken076.sol deleted file mode 100644 index 9de79a327c3..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken076.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; -contract Test { - address public origin; - address public sender; - bool public result1; - bool public result2; - function test() external { - origin = tx.origin; - sender = msg.sender; - result1 = msg.sender == tx.origin; // true - result2 = origin == sender; // true - } -function getResult1() public returns(bool){ - return result1; -} -function getResult2() public returns(bool){ - return result2; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken077.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken077.sol deleted file mode 100644 index e110f24e2fc..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken077.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.24; - -contract trcToken077 { -function addressTest() public returns(bytes32 addressValue) { - assembly{ - let x := mload(0x40) //Find empty storage location using "free memory pointer" - mstore(x,address) //Place current contract address - addressValue := mload(x) - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken078.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken078.sol deleted file mode 100644 index f7504ea55aa..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken078.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract callerContract { - constructor() public payable{} - function() external payable{} - function sendToB(address called_address, address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - contract calledContract { - function() external payable{} - constructor() public payable {} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call.value(5)(abi.encode(bytes4(keccak256("setI()")))); - } - - } - contract c{ - address public origin; - address public sender; - constructor() public payable{} - event log(address,address); - function() payable external{ - emit log(tx.origin,msg.sender); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken079.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken079.sol deleted file mode 100644 index 48205199eec..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken079.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken080.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken080.sol deleted file mode 100644 index 27529ce48e8..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcToken080.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - function() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode_0.5.15/contractTrcTokenToOther.sol deleted file mode 100644 index 22456df9e8e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractTrcTokenToOther.sol +++ /dev/null @@ -1,44 +0,0 @@ -//pragma solidity ^0.4.24; - -contract ConvertType { - -constructor() payable public{} - -function() payable external{} - -//function trcTokenOnStorage(trcToken storage token) internal { // ERROR: Data location can only be specified for array, struct or mapping types, but "storage" was given. -//} - -function trcTokenToString(trcToken token) public pure returns(string memory s){ -// s = token; // ERROR -// s = string(token); // ERROR -} - -function trcTokenToUint256(trcToken token) public pure returns(uint256 r){ -uint256 u = token; // OK -uint256 u2 = uint256(token); // OK -r = u2; -} - -function trcTokenToAddress(trcToken token) public pure returns(address r){ -//r = token; // ERROR -token = 0x1234567812345678123456781234567812345678123456781234567812345678; -address a2 = address(token); // OK -r = a2; -} - -function trcTokenToBytes(trcToken token) public pure returns(bytes memory r){ -//r = token; // ERROR -// r = bytes(token); // ERROR -} - -function trcTokenToBytes32(trcToken token) public pure returns(bytes32 r){ -// r = token; // ERROR -bytes32 b2 = bytes32(token); // OK -r = b2; -} - -function trcTokenToArray(trcToken token) public pure returns(uint[] memory r){ -//r = token; // ERROR -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/contractUnknownException.sol b/framework/src/test/resources/soliditycode_0.5.15/contractUnknownException.sol deleted file mode 100644 index 37c28468be1..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/contractUnknownException.sol +++ /dev/null @@ -1,65 +0,0 @@ -// pragma solidity ^0.4.24; - -contract testA { - constructor() public payable { - A a = (new A).value(10)(); - a.fun(); - } -} - -contract testB { - constructor() public payable { - B b = (new B).value(10)(); - b.fun(); - } -} - - -contract testC { - constructor() public payable{ - C c = (new C).value(10)(); - c.fun(); - } -} - -contract testD { - constructor() public payable{ - D d = (new D).value(10)(); - d.fun(); - } -} - - -contract A { - constructor() public payable{ - selfdestruct(msg.sender); - } - function fun() public { - } - -} - -contract B { - constructor() public payable { - revert(); - } - function fun() public { - } -} - - -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} - -contract D { - constructor() public payable { - require(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2CallContract.sol b/framework/src/test/resources/soliditycode_0.5.15/create2CallContract.sol deleted file mode 100644 index f2de1c7ee13..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/create2CallContract.sol +++ /dev/null @@ -1,37 +0,0 @@ -contract callerContract { - constructor() payable public{} - function() payable external{} - function delegateCallCreate2(address called_address, bytes memory code, uint256 salt) public { - called_address.delegatecall(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } - function callCreate2(address called_address,bytes memory code, uint256 salt) public returns(bool,bytes memory){ - return called_address.call(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } -} - - -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2Istanbul.sol b/framework/src/test/resources/soliditycode_0.5.15/create2Istanbul.sol deleted file mode 100644 index b79db6e4639..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/create2Istanbul.sol +++ /dev/null @@ -1,28 +0,0 @@ -pragma solidity ^0.5.12; - -contract create2Istanbul { - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - - } - return addr; - } - - // prefix in main net is 0x41, testnet config is 0xa0 - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } - -} - -contract B { - constructor() public payable{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contract.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contract.sol deleted file mode 100644 index 0171f4d5486..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/create2contract.sol +++ /dev/null @@ -1,52 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract FactoryBytes { - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contract22.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contract22.sol deleted file mode 100644 index c33cb08edc3..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/create2contract22.sol +++ /dev/null @@ -1,109 +0,0 @@ -contract Factory { - event Deployed(address addr, trcToken salt, address sender); - event Deployed1(address addr, uint8 salt, address sender); - event Deployed2(address addr, address salt, address sender); - event Deployed3(address addr, string salt, address sender); - - - function deploy(bytes memory code, trcToken salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function deploy1(bytes memory code, uint8 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed1(addr, salt, msg.sender); - return addr; - } - - function deploy2(bytes memory code, address salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed2(addr, salt, msg.sender); - return addr; - } - - function deploy3(bytes memory code, string memory salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed3(addr, salt, msg.sender); - return addr; - } - -} - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract1 { - uint public i=2; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract2 { - uint public i=3; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract3 { - uint public i=4; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contractn.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contractn.sol deleted file mode 100644 index e0e3ae64c16..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/create2contractn.sol +++ /dev/null @@ -1,29 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/create2contractn2.sol b/framework/src/test/resources/soliditycode_0.5.15/create2contractn2.sol deleted file mode 100644 index 626988c4e04..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/create2contractn2.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function set() payable public { - i=5; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/demo.sol b/framework/src/test/resources/soliditycode_0.5.15/demo.sol deleted file mode 100644 index c7f6d0d4da9..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/demo.sol +++ /dev/null @@ -1,73 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - } - codesize = m; - } - - // positive case - function pulsone() public payable{ - uint256 j = 0; - uint i = 100; - for (; i < i; i++) { - j++; - } - } - - - function getCodeSize() public returns (uint256){ - return codesize; - } - - } - - contract confirmTest{ - - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - - } - codesize = m; - } - - function getCodeSize() public returns (uint256){ - return codesize; - } - - function confirm(address addr) public returns (uint256){ - uint256 j; - assembly { - j := extcodesize(addr) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return j; - } - - function at(address _addr) public returns (bytes memory o_code) { - assembly { - // retrieve the size of the code, this needs assembly - let size := extcodesize(_addr) - // allocate output byte array - this could also be done without assembly - // by using o_code = new bytes(size) - o_code := mload(0x40) - // new "memory end" including padding - mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) - // store length in memory - mstore(o_code, size) - // actually retrieve the code, this needs assembly - extcodecopy(_addr, add(o_code, 0x20), 0, size) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/event001.sol b/framework/src/test/resources/soliditycode_0.5.15/event001.sol deleted file mode 100644 index 7662df3a5c6..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/event001.sol +++ /dev/null @@ -1,10 +0,0 @@ -contract Event { - event xixi(uint256 id) ; - event log2(uint256,uint256,uint256); - constructor() public payable{} - function messageI() payable public returns (uint ret) { - //emit log2(1,2,3); - emit xixi(1); - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/event002.sol b/framework/src/test/resources/soliditycode_0.5.15/event002.sol deleted file mode 100644 index 70a5275521c..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/event002.sol +++ /dev/null @@ -1,52 +0,0 @@ -pragma solidity >=0.4.0 <0.7.0; - -contract Event { - - event _0(); - event a_0() anonymous; - event a_4i(uint256 indexed x1, uint256 indexed x2 , uint256 indexed x3, uint256 indexed x4, uint256 x5)anonymous ; - event _3i(uint256 x1, uint256 indexed x2 , uint256 indexed x3, uint256 x4, uint256 x5) ; - event _1i(uint256 indexed x1, uint256, uint256 indexed, uint256 x4) ; - event a_1i(uint256) anonymous; - event _ai(uint8[2], uint8) ; - event a_ai(uint8[2], uint8) anonymous; - event _a1i(uint8[2] indexed, uint8) ; - event a_a1i(uint8[2] indexed, uint8) anonymous; - - constructor () public { - // emit a_0(); - // emit a_1i(123); - // emit a_4i(1,2,3,5,16); - // emit _0(); - emit _3i(1,2,3,5,16); - // emit _1i(1,2,3,5); - // emit _ai([1,2], 3); - // emit a_ai([3,4], 5); - // emit _a1i([1,2], 3); - // emit a_a1i([3,4], 5); - } - - function e() public { - emit _1i(1,2,3,4); - } - - function l() public { - emit a_1i(1); - } - - function k() public{ - emit a_4i(2,3,4,5,17); - emit _3i(2,3,4,5,16); - emit _1i(2,3,4,5); - emit a_1i(128); - emit _0(); - emit a_0(); - //selfdestruct(msg.sender); - //emit a_4i(1,2,3,5,16); - //emit _3i(1,2,3,5,16); - //emit _1i(1,2,3,5); - //emit a_1i(123); - //emit _0(); - //emit a_0(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHash.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHash.sol deleted file mode 100644 index d6209770682..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/extCodeHash.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract TestExtCodeHash { - - function getCodeHashByAddr(address _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } - function getCodeHashByUint(uint256 _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHash11.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHash11.sol deleted file mode 100644 index ad59f6cce1c..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/extCodeHash11.sol +++ /dev/null @@ -1,103 +0,0 @@ -contract Counter { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} -revert(); -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract Counter1 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter2 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} - addr.call(abi.encodeWithSignature("testSuicideNonexistentTarget(address)",c)); - - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter3 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract TestConstract { - uint public i=1; - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashConstruct.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashConstruct.sol deleted file mode 100644 index 6bb91b3d3b1..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashConstruct.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract CounterConstruct { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore); - constructor() public{ - owner = msg.sender; - address addr = address(this); - bytes32 _hashBefore; - assembly { - _hashBefore := extcodehash(addr) - } - emit LogResult(_hashBefore); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashStress.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashStress.sol deleted file mode 100644 index cf41f3c8106..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashStress.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract Trigger { - function test(address addr) public returns(uint i) { - bytes32 hash; - while (gasleft() > 1000) { - assembly { - hash := extcodehash(addr) - } - i++; - } - } - - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - assembly { - hash := extcodehash(addr) - } - } - return i; - } - } - - - - contract TriggerNormal { - function test(address addr) public returns(uint i) { - i = 0; - while (gasleft() > 100000) { - i++; - } - } - } - - contract TriggerNormal1 { - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - addr.balance; - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashTestNoPayable.sol b/framework/src/test/resources/soliditycode_0.5.15/extCodeHashTestNoPayable.sol deleted file mode 100644 index c3a2ad8c6ae..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/extCodeHashTestNoPayable.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testConstantContract{ -uint256 public i; -function testNoPayable() public returns (uint256 z) { -i=1; -z=i; -return z; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/isSRCandidate.sol b/framework/src/test/resources/soliditycode_0.5.15/isSRCandidate.sol deleted file mode 100644 index 723e6d0e93a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/isSRCandidate.sol +++ /dev/null @@ -1,35 +0,0 @@ - -pragma solidity ^0.5.0; - -contract ContractB{ - address others; -} - -contract TestIsSRCandidate{ - - ContractB contractB = new ContractB(); - - function isSRCandidateTest(address addr) public view returns (bool) { - return address(addr).isSRCandidate; - } - - function zeroAddressTest() public view returns (bool) { - return address(0x0).isSRCandidate; - } - - function localContractAddrTest() public view returns (bool) { - return address(this).isSRCandidate; - } - - function otherContractAddrTest() public view returns (bool) { - return address(contractB).isSRCandidate; - } - - function nonpayableAddrTest(address addr) public view returns (bool) { - return addr.isSRCandidate; - } - - function payableAddrTest(address payable addr) public returns (bool) { - return addr.isSRCandidate; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/mappingGetter.sol b/framework/src/test/resources/soliditycode_0.5.15/mappingGetter.sol deleted file mode 100644 index dbd473717cb..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/mappingGetter.sol +++ /dev/null @@ -1,4 +0,0 @@ -contract mappingGetter { - mapping(bytes => uint256) public balances1; - mapping(string => uint256) public balances2; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/multiValiSignPerformance01.sol b/framework/src/test/resources/soliditycode_0.5.15/multiValiSignPerformance01.sol deleted file mode 100644 index 74baa963366..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/multiValiSignPerformance01.sol +++ /dev/null @@ -1,37 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract ecrecoverValidateSign { - - using ECVerify for bytes32; - - function validateSign(bytes32 hash,bytes[] memory sig,address[] memory signer) public returns (bool) { - for(uint256 i=0;i bytes32) public nullifiers; // store nullifiers of spent commitments - mapping(bytes32 => bytes32) public roots; // store history root - mapping(uint256 => bytes32) public tree; - mapping(bytes32 => bytes32) public noteCommitment; - bytes32[33] frontier; - bytes32[32] zeroes = [bytes32(0x0100000000000000000000000000000000000000000000000000000000000000), bytes32(0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155), bytes32(0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34), bytes32(0xd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c), bytes32(0xe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49), bytes32(0x912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a), bytes32(0x8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613), bytes32(0xd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813), bytes32(0x7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444), bytes32(0x43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b), bytes32(0xba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce72), bytes32(0x4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c), bytes32(0xec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048), bytes32(0x1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651), bytes32(0xbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c), bytes32(0xd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f), bytes32(0x1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451), bytes32(0x6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c), bytes32(0xcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf00), bytes32(0x6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b159216), bytes32(0x8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673), bytes32(0x08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023), bytes32(0x0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49), bytes32(0x4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850), bytes32(0xfee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712), bytes32(0x16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a), bytes32(0xd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb58), bytes32(0xa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a), bytes32(0x28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a), bytes32(0xe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72), bytes32(0x12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d), bytes32(0xb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c53814)]; - address owner; - TokenTRC20 trc20Token; - - event MintNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TransferNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event BurnNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TokenMint(address from, uint256 value); - event TokenBurn(address to, uint256 value, bytes32[3] ciphertext); - event NoteSpent(bytes32 nf); - - constructor (address trc20ContractAddress, uint256 scalingFactorExponent) public { - require(scalingFactorExponent < 77, "The scalingFactorExponent is out of range!"); - scalingFactor = 10 ** scalingFactorExponent; - owner = msg.sender; - trc20Token = TokenTRC20(trc20ContractAddress); - } - // output: cm, cv, epk, proof - function mint(uint256 rawValue, bytes32[9] calldata output, bytes32[2] calldata bindingSignature, bytes32[21] calldata c) external { - address sender = msg.sender; - // transfer the trc20Token from the sender to this contract - bool transferResult = trc20Token.transferFrom(sender, address(this), rawValue); - require(transferResult, "TransferFrom failed!"); - - require(noteCommitment[output[0]] == 0, "Duplicate noteCommitments!"); - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), value, output, c)); - (bytes32[] memory ret) = verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[0]; - if (slot == 0) { - frontier[0] = output[0]; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[output[0]] = output[0]; - leafCount ++; - - emit MintNewLeaf(leafCount - 1, output[0], output[1], output[2], c); - emit TokenMint(sender, rawValue); - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function transfer(bytes32[10][] calldata input, bytes32[2][] calldata spendAuthoritySignature, bytes32[9][] calldata output, bytes32[2] calldata bindingSignature, bytes32[21][] calldata c) external { - require(input.length >= 1 && input.length <= 2, "Input number must be 1 or 2!"); - require(input.length == spendAuthoritySignature.length, "Input number must be equal to spendAuthoritySignature number!"); - require(output.length >= 1 && output.length <= 2, "Output number must be 1 or 2!"); - require(output.length == c.length, "Output number must be equal to c number!"); - - for (uint256 i = 0; i < input.length; i++) { - require(nullifiers[input[i][0]] == 0, "The note has already been spent!"); - require(roots[input[i][1]] != 0, "The anchor must exist!"); - } - for (uint256 i = 0; i < output.length; i++) { - require(noteCommitment[output[i][0]] == 0, "Duplicate noteCommitment!"); - } - - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c)); - (bytes32[] memory ret) = verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, 0, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 offset = 1; - //ret offset - for (uint256 i = 0; i < output.length; i++) { - uint256 slot = uint256(ret[offset++]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[i][0]; - if (slot == 0) { - frontier[0] = output[i][0]; - } - for (uint256 k = 1; k < slot + 1; k++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[offset++]; - if (k == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - leafCount++; - } - latestRoot = ret[offset]; - roots[latestRoot] = latestRoot; - for (uint256 i = 0; i < input.length; i++) { - bytes32 nf = input[i][0]; - nullifiers[nf] = nf; - emit NoteSpent(nf); - } - for (uint256 i = 0; i < output.length; i++) { - noteCommitment[output[i][0]] = output[i][0]; - emit TransferNewLeaf(leafCount - (output.length - i), output[i][0], output[i][1], output[i][2], c[i]); - } - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function burn(bytes32[10] calldata input, bytes32[2] calldata spendAuthoritySignature, uint256 rawValue, bytes32[2] calldata bindingSignature, address payTo, bytes32[3] calldata burnCipher, bytes32[9][] calldata output, bytes32[21][] calldata c) external { - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c, payTo, value)); - - bytes32 nf = input[0]; - bytes32 anchor = input[1]; - require(nullifiers[nf] == 0, "The note has already been spent!"); - require(roots[anchor] != 0, "The anchor must exist!"); - - require(output.length <= 1, "Output number cannot exceed 1!"); - require(output.length == c.length, "Output number must be equal to length of c!"); - - // bytes32 signHash = sha256(abi.encodePacked(address(this), input, payTo, value, output, c)); - if (output.length == 0) { - (bool result) = verifyBurnProof(input, spendAuthoritySignature, value, bindingSignature, signHash); - require(result, "The proof and signature have not been verified by the contract!"); - } else { - transferInBurn(input, spendAuthoritySignature, value, bindingSignature, signHash, output, c); - } - - nullifiers[nf] = nf; - emit NoteSpent(nf); - //Finally, transfer trc20Token from this contract to the nominated address - bool transferResult = trc20Token.transfer(payTo, rawValue); - require(transferResult, "Transfer failed!"); - - emit TokenBurn(payTo, rawValue, burnCipher); - } - - function transferInBurn(bytes32[10] memory input, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature, bytes32 signHash, bytes32[9][] memory output, bytes32[21][] memory c) private { - bytes32 cm = output[0][0]; - require(noteCommitment[cm] == 0, "Duplicate noteCommitment!"); - bytes32[10][] memory inputs = new bytes32[10][](1); - inputs[0] = input; - bytes32[2][] memory spendAuthoritySignatures = new bytes32[2][](1); - spendAuthoritySignatures[0] = spendAuthoritySignature; - (bytes32[] memory ret) = verifyTransferProof(inputs, spendAuthoritySignatures, output, bindingSignature, signHash, value, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = cm; - if (slot == 0) { - frontier[0] = cm; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[cm] = cm; - leafCount ++; - - emit BurnNewLeaf(leafCount - 1, cm, output[0][1], output[0][2], c[0]); - } - - //position: index of leafnode, start from 0 - function getPath(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValue(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - //position: index of leafnode, start from 0 - function getPathByValueIsZero(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValueByValueIsZero(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - function ancestorLevel(uint256 leafIndex) private view returns (uint32) { - uint256 nodeIndex1 = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex2 = leafCount + 2 ** 32 - 2; - uint32 level = 0; - while (((nodeIndex1 - 1) / 2) != ((nodeIndex2 - 1) / 2)) { - nodeIndex1 = (nodeIndex1 - 1) / 2; - nodeIndex2 = (nodeIndex2 - 1) / 2; - level = level + 1; - } - return level; - } - - function getTargetNodeValue(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function getTargetNodeValueByValueIsZero(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - left = bytes32(0x0); - right = bytes32(0x0); - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function rawValueToValue(uint256 rawValue) private view returns (uint64) { - require(rawValue > 0, "Value must be positive!"); - require(rawValue.mod(scalingFactor) == 0, "Value must be integer multiples of scalingFactor!"); - uint256 value = rawValue.div(scalingFactor); - require(value < INT64_MAX); - return uint64(value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest1TestRequireContract.sol deleted file mode 100644 index dbb97ab4f04..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest1TestRequireContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.0; -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - //function testThrow(){ - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest2TestThrowsContract.sol deleted file mode 100644 index abcc2d84ca2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest2TestThrowsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.0; -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow() public { - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest3TestRevertContract.sol deleted file mode 100644 index 229fa6a74b0..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest3TestRevertContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.0; -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow(){ - // throw; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract.sol deleted file mode 100644 index aa043ad9c3b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; - -contract noPayableContract { - -function noPayable() public payable returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract_1.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract_1.sol deleted file mode 100644 index fe7ba275736..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest4noPayableContract_1.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; - -contract noPayableContract { - -function noPayable() public returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor.sol deleted file mode 100644 index e1733b0562b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.0; - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public payable{ - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor_1.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor_1.sol deleted file mode 100644 index 793b468d4c2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest5noPayableConstructor_1.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.0; - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public { - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest6transferTestContract.sol deleted file mode 100644 index 8c64ff740cd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest6transferTestContract.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; - -contract transferTestContract { - function tranferTest(address payable addr) public payable{ - addr.transfer(10); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest7payableFallbakContract.sol deleted file mode 100644 index 85cf454e08e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest7payableFallbakContract.sol +++ /dev/null @@ -1,14 +0,0 @@ -//pragma solidity ^0.4.0; - -contract Test { - function() external { x = 1; } - uint x; -} - - -contract Caller { - function callTest(Test test) public { - //test.call(0xabcdef01); // hash does not exist - address(test).call(abi.encode(0xabcdef01)); // hash does not exist - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest8newContractGasNoenough.sol deleted file mode 100644 index b322ac68591..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest8newContractGasNoenough.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.0; - -contract Account{ - uint256 public accId; - - // function Account(uint accountId) payable{ - constructor(uint accountId) payable public { - accId = accountId; - } -} - -contract Initialize{ - // Account public account = new Account(10); - - function newAccount() public { - Account account = new Account(1); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest9MessageUsedErrorFeed.sol deleted file mode 100644 index 05448bfd0ac..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontest9MessageUsedErrorFeed.sol +++ /dev/null @@ -1,18 +0,0 @@ -//pragma solidity ^0.4.0; - -contract MathedFeed { - - function divideMathed() public returns (uint ret) { - uint x=1; - uint y=0; - return x/y; - } -} - - -contract MathedUseContract { - - function MathedUse(address addr) public returns (uint) { - return MathedFeed(addr).divideMathed(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontestFunctionUsedErrorFeed.sol deleted file mode 100644 index b7f5244954d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/requireExceptiontestFunctionUsedErrorFeed.sol +++ /dev/null @@ -1,17 +0,0 @@ -//pragma solidity ^0.4.0; - -contract MessageFeed { - - function mValue() payable public returns (uint ret) { - return msg.value; - } -} - -contract MessageUseContract { - function inputValue() payable public returns (uint){ - return msg.value; - } - function messageUse(address addr) payable public returns (uint) { - return MessageFeed(addr).mValue.value(1)(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/selector.sol b/framework/src/test/resources/soliditycode_0.5.15/selector.sol deleted file mode 100644 index 411e36b0b8e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/selector.sol +++ /dev/null @@ -1,21 +0,0 @@ -pragma solidity ^0; - -library A { - function getBalance(address) public view returns (uint256) { - return address(this).balance; - } - - function getamount(address) external view returns (uint256) { - return address(this).balance; - } -} - -contract testSelector { - using A for address; - - - function getselector2() public view returns (bytes4, bytes4) { - return (A.getBalance.selector, A.getamount.selector); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/stackContract001.sol b/framework/src/test/resources/soliditycode_0.5.15/stackContract001.sol deleted file mode 100644 index 19041b1e405..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/stackContract001.sol +++ /dev/null @@ -1,61 +0,0 @@ -pragma solidity ^0.5.0; - -contract A{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function test() public{ - emit log(123); - } -} - -contract B{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function rewardBalance(address addr) public view returns (uint256){ - return addr.rewardbalance; - } - - function nullAddressTest() public view returns (uint256) { - return address(0x0).rewardbalance; - } - - function localContractAddrTest() public view returns (uint256) { - address payable localContract = address(uint160(address(this))); - return localContract.rewardbalance; - } - - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function contractBWithdrawRewardTest(address contractB) public returns (uint) { - return B(contractB).withdrawRewardTest(); - } - - function createA() public returns (address){ - return address(new A()); - } - - function callA(address Addr) public{ - A(Addr).test(); - } -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/stackSuicide001.sol b/framework/src/test/resources/soliditycode_0.5.15/stackSuicide001.sol deleted file mode 100644 index a71816ddabd..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/stackSuicide001.sol +++ /dev/null @@ -1,84 +0,0 @@ -pragma solidity ^0.5.0; -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public payable returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function transfer(address payable add,uint256 num) public { - return add.transfer(num); - } -} - -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/stringSplit.sol b/framework/src/test/resources/soliditycode_0.5.15/stringSplit.sol deleted file mode 100644 index 5a7f5bdd4c9..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/stringSplit.sol +++ /dev/null @@ -1,45 +0,0 @@ -pragma solidity ^0; - -contract testStringSplit { -string s1 = "s""1""2"",./"; -string s2 = "s123?\\'."; -string s3 = hex"41"hex"42"; -string s4 = hex"4142"; - -function getS1() public view returns (string memory) { -return s1; -} - -function getS1N1() public pure returns (string memory) { -string memory n1 = "s""1""2"",./"; -return n1; -} - -function getS2() public view returns (string memory) { -return s2; -} - -function getS2N2() public pure returns (string memory) { -string memory n2 = "s123?\'."; -return n2; -} - -function getS3() public view returns (string memory) { -return s3; -} - -function getS3N3() public pure returns (string memory) { -string memory n3 = hex"41"hex"42"; -return n3; -} - -function getS4() public view returns (string memory) { -return s4; -} - -function getS4N4() public pure returns (string memory) { -string memory n4 = hex"4142"; -return n4; -} - -} diff --git a/framework/src/test/resources/soliditycode_0.5.15/suicide001.sol b/framework/src/test/resources/soliditycode_0.5.15/suicide001.sol deleted file mode 100644 index 3544f8bf84a..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/suicide001.sol +++ /dev/null @@ -1,32 +0,0 @@ -contract factory { - constructor() payable public { - } - - function create1() payable public returns (address){ - Caller add = (new Caller).value(0)(); - return address(add); - } - - function kill() payable public{ - selfdestruct(msg.sender); - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - Caller addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/suicide002.sol b/framework/src/test/resources/soliditycode_0.5.15/suicide002.sol deleted file mode 100644 index 160ab64f320..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/suicide002.sol +++ /dev/null @@ -1,43 +0,0 @@ -contract Factory { - uint256 public num; - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(msg.sender); - addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/testOutOfMem.sol b/framework/src/test/resources/soliditycode_0.5.15/testOutOfMem.sol deleted file mode 100644 index 8d285b28b7d..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/testOutOfMem.sol +++ /dev/null @@ -1,7 +0,0 @@ -contract Test { - function testOutOfMem(uint256 x) public returns(bytes32 r) { - uint[] memory memVar; - memVar = new uint[](x); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/testStakeSuicide.sol b/framework/src/test/resources/soliditycode_0.5.15/testStakeSuicide.sol deleted file mode 100644 index 6f8ddfe0e3e..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/testStakeSuicide.sol +++ /dev/null @@ -1,71 +0,0 @@ -pragma solidity ^0.5.0; -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function BSelfdestructTest(address payable target) public{ - b.SelfdestructTest(target); - } -} -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tryCatch001.sol b/framework/src/test/resources/soliditycode_0.5.15/tryCatch001.sol deleted file mode 100644 index 5692fe84540..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/tryCatch001.sol +++ /dev/null @@ -1,105 +0,0 @@ -pragma solidity ^0.6.0; - -enum ErrorType { - Revert_Error, //0 - RevertWithMsg_Error, //1 - Require_Error, //2 - RequirewithMsg_Error, //3 - Assert_Error, //4 - Tansfer_Error, //5 - Send_Error, //6 - Math_Error, //7 - ArrayOverFlow_Error //8 -} -contract errorContract { - uint256[] arraryUint ; - - function errorSwitch(uint256 errorType) public returns(string memory) { - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - return "success"; - - } - - function callFun(string memory functionStr, string memory argsStr) public{ - address(this).call(abi.encodeWithSignature(functionStr, argsStr)); - } - -} - -contract NewContract { - uint256[] arraryUint ; - - constructor(uint256 errorType) public payable{ - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - } -} - -contract tryTest { - function getData(errorContract inter, string memory functionStr, string memory argsStr) public payable returns(string memory) { - try inter.callFun(functionStr,argsStr) { - return "123"; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "3"; - } - } - - function getErrorSwitch(errorContract add, uint256 errorType ) public payable returns(string memory) { - try add.errorSwitch(errorType) returns (string memory Msg) { - return Msg; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "NoErrorMsg"; - } - } - - function catchNewErrorSwitch(uint256 errorType) public returns (address nc){ - try new NewContract(errorType) returns (NewContract nc){ - return address(nc); - }catch { - return address(0x00); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue001.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue001.sol deleted file mode 100644 index fd3c817421b..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue001.sol +++ /dev/null @@ -1,26 +0,0 @@ -pragma solidity ^0.5.12; - -contract tvmAssetIssue001 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateOtherAccountAsset(string memory url, string memory desc) public returns (bool) { - trcToken tokenId = trcToken(1000004); - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue002.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue002.sol deleted file mode 100644 index b158faf6720..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue002.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma solidity ^0.5.12; - -contract tvmAssetIssue002 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - assetissue(name, abbr, totalSupply, precision); - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url1, string memory desc1, string memory url2, string memory desc2) public returns (bool) { - updateasset(tokenId, bytes(url1), bytes(desc1)); - return updateasset(tokenId, bytes(url2), bytes(desc2)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue003.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue003.sol deleted file mode 100644 index 40390238d8f..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue003.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.5.12; - -contract tvmAssetIssue003 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function tokenIssueAndTransfer(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - assetissue(name, abbr, totalSupply, precision); - newaddress.transfer(100000000); - } - - function updateAssetAndTransfer(trcToken tokenId, string memory url, string memory desc, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - updateasset(tokenId, bytes(url), bytes(desc)); - newaddress.transfer(100000000); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue004.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue004.sol deleted file mode 100644 index fbebdb26e68..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue004.sol +++ /dev/null @@ -1,39 +0,0 @@ -pragma solidity ^0.5.12; - -contract A { - - constructor() payable public{} - function() payable external {} - - function tokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint){ - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAssetA(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} - -contract tvmAssetIssue004 { - - A a; - - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return a.tokenIssueA(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return a.updateAssetA(tokenId, url, desc); - } - - function getContractAddress() public payable returns (address) { - a = (new A).value(1024000000)(); - return address(a); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue005.sol b/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue005.sol deleted file mode 100644 index 20fd14944c2..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/tvmAssetIssue005.sol +++ /dev/null @@ -1,45 +0,0 @@ -pragma solidity ^0.5.12; - -contract tvmAssetIssue005 { - constructor() payable public{} - - function() external payable { - } - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} - -contract B { - event Deployed(address addr, uint256 salt); - - function deploy(uint256 salt) public returns (address) { - address addr; - bytes memory code = type(tvmAssetIssue005).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt); - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/typeName.sol b/framework/src/test/resources/soliditycode_0.5.15/typeName.sol deleted file mode 100644 index 5b44abd1bbb..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/typeName.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract TypeName { - function testTypeName() public returns (string memory){ - return type(TypeName).name; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/unStake001.sol b/framework/src/test/resources/soliditycode_0.5.15/unStake001.sol deleted file mode 100644 index 54a9829cd40..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/unStake001.sol +++ /dev/null @@ -1,90 +0,0 @@ -pragma solidity ^0.5.0; - -contract unStakeTest { - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - - function selfdestructTest(address payable target) public { - selfdestruct(target); - } - - function selfdestructTest2(address sr, uint256 amount, address payable target) public { - stake(sr, amount); - selfdestruct(target); - } - - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - - function unStake() public returns (bool result){ - return unstake(); - } - - function unStake2() public returns (bool result){ - unstake(); - return unstake(); - } - - function withdrawReward() public returns (uint256 amount) { - return withdrawreward(); - } - - function rewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - - function revertTest1(address sr, uint256 amount, address payable transferAddr) public { - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000); - //stake more than balance to fail - transferAddr.transfer(4000000); - } - - function revertTest2(address payable transferAddr) public { - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake(); - //unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - - function BSelfdestructTest(address payable target) public { - b.SelfdestructTest(target); - } -} - -contract B { - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function UnStake() public returns (bool result){ - return unstake(); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/validatemultisign001.sol b/framework/src/test/resources/soliditycode_0.5.15/validatemultisign001.sol deleted file mode 100644 index cc0a742d0c5..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/validatemultisign001.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract validatemultisignTest { - function testmulti(address a, uint256 perid, bytes32 hash, bytes[] memory signatures) public returns (bool){ - return validatemultisign(a, perid, hash, signatures); - } - - function testbatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns (bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testMultiPrecompileContract(bytes memory data) public returns(bool, bytes memory){ - return address(0xa).delegatecall(data); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/verifyTransferProof001.sol b/framework/src/test/resources/soliditycode_0.5.15/verifyTransferProof001.sol deleted file mode 100644 index 587b4defd10..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/verifyTransferProof001.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract verifyTransferProofTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000002).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000002).delegatecall(data); - } - - function test3(bytes32[10][] memory input, bytes32[2][] memory spendAuthoritySignature, bytes32[9][] memory output, bytes32[2] memory bindingSignature, bytes32 signHash, uint64 valueBalance, bytes32[33] memory frontier, uint256 leafCount) public returns (bytes32[] memory){ - return verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, valueBalance, frontier, leafCount); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.5.15/walletTestMutiSign004.sol b/framework/src/test/resources/soliditycode_0.5.15/walletTestMutiSign004.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_0.5.15/walletTestMutiSign004.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/AssertException002.sol b/framework/src/test/resources/soliditycode_0.6.12/AssertException002.sol deleted file mode 100644 index 15cc07ff984..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/AssertException002.sol +++ /dev/null @@ -1,17 +0,0 @@ - - -contract AssertException{ - function divideIHaveArgsReturn(int x,int y) public returns (int z) { - return x / y; - } - function testAssert() public { - require(2==1); - } -} -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/AssignToExternal.sol b/framework/src/test/resources/soliditycode_0.6.12/AssignToExternal.sol deleted file mode 100644 index d4f09590a36..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/AssignToExternal.sol +++ /dev/null @@ -1,30 +0,0 @@ -contract AssignToExternal { - // Not allow: - // function f(uint256[] calldata x, uint256[] calldata y) external pure { - // x = y; - // } - - // allow: - - function f(uint256 a) external returns (uint){ - a = a + 1; - return a; - } - - function StringSet(string calldata a) external returns (string memory){ - return a; - } - - function ByteSet(bytes32 a) external returns (bytes32){ - return a; - } - - function UintArraySet(uint256[2] calldata a) external returns (uint256[2] memory){ - return a; - } - - function AddSet(address a) external returns (address){ - return a; - } - -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/BlockHash.sol b/framework/src/test/resources/soliditycode_0.6.12/BlockHash.sol deleted file mode 100644 index 6603da65e44..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/BlockHash.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract TestBlockHash { - - function testOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) | bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) | blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) & bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) & blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) ^ bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) ^ blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/ClearAbi001.sol b/framework/src/test/resources/soliditycode_0.6.12/ClearAbi001.sol deleted file mode 100644 index 39a8e8cf005..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ClearAbi001.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract testConstantContract{ -function testPayable() public view returns (int z) { -return 1; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/ClearAbi005.sol b/framework/src/test/resources/soliditycode_0.6.12/ClearAbi005.sol deleted file mode 100644 index a3115398386..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ClearAbi005.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=0; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/ConstructorDefaults.sol b/framework/src/test/resources/soliditycode_0.6.12/ConstructorDefaults.sol deleted file mode 100644 index 4b6186ccb95..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ConstructorDefaults.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract testIsContract{ - bool result; - constructor (bool a) public { - result = a; - } -function test( address a) public returns (bool) { -return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/Create2Test023.sol b/framework/src/test/resources/soliditycode_0.6.12/Create2Test023.sol deleted file mode 100644 index 4c3f8af9f2b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/Create2Test023.sol +++ /dev/null @@ -1,31 +0,0 @@ -contract factory { - constructor() payable public { - } - - function deploy(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } - - function testCreate() payable public returns (address){ - Caller add = (new Caller).value(0)(); - return address(add); - } - - function kill( ) payable public{ - selfdestruct(msg.sender); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/Create2Test024.sol b/framework/src/test/resources/soliditycode_0.6.12/Create2Test024.sol deleted file mode 100644 index f5a9d032cff..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/Create2Test024.sol +++ /dev/null @@ -1,56 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(msg.sender); - addr.set(); - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } - - function deploy2(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - //addr.testSuicideNonexistentTarget(msg.sender); - //addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/Create2Test025.sol b/framework/src/test/resources/soliditycode_0.6.12/Create2Test025.sol deleted file mode 100644 index 895dc43e56f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/Create2Test025.sol +++ /dev/null @@ -1,34 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } -} - -contract TestContract{ - uint256 public num; - constructor(uint256 j) public{ - num = j; - } - function getNum() public returns (uint256){ - return num; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/ExtCodeHashTest010.sol b/framework/src/test/resources/soliditycode_0.6.12/ExtCodeHashTest010.sol deleted file mode 100644 index bfa8a7fa0d8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ExtCodeHashTest010.sol +++ /dev/null @@ -1,46 +0,0 @@ -contract Counter { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); - constructor() public{ - owner = msg.sender; - } - function getCodeHashSuicide(address addr) public returns (bytes32 _hashBefore){ - assembly{ - _hashBefore := extcodehash(addr) - } - selfdestruct(owner); - return _hashBefore; - } - - function getCodeHashRevert() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - address addr = address(this); - assembly { - _hashBefore := extcodehash(addr) - } - if (owner == msg.sender) { - selfdestruct(owner); - } - assembly { - _hashAfter := extcodehash(addr) - } - revert(); - emit LogResult(_hashBefore, _hashAfter); - } - - function getCodeHashCreate() public returns (bytes32 _hashBefore){ - TestContract A = (new TestContract).value(0)(); - address addr = address(A); - assembly{ - _hashBefore := extcodehash(addr) - } - revert(); - return _hashBefore; - } -} - -contract TestContract{ - uint256 count = 1; - constructor() public payable{ - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/ExternalSelector.sol b/framework/src/test/resources/soliditycode_0.6.12/ExternalSelector.sol deleted file mode 100644 index 0359813e275..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ExternalSelector.sol +++ /dev/null @@ -1,92 +0,0 @@ -pragma solidity ^0.6.0; - -contract selectorContract { - function testSelectorNoParam() external pure returns(uint) { - return 11; - } - - function testSelectorWithParam(uint x) external pure returns(uint) { - return 22; - } -} - -interface interfaceSelector { - function getSelector() external pure returns(uint); -} - -interface B is interfaceSelector { - // interface现在可以继承自其他interface - function testImplemention() external pure returns(uint); -} - -contract implementContract is B{ - function getSelector() external override pure returns(uint) { - return 66; - } - - function testImplemention() external override pure returns(uint) { - return 77; - } - - constructor() public payable {} -} - -contract basicContract{ - function testNewUse() external payable returns(uint) { - return 345; - } - - constructor() public payable {} -} - -contract TestGasValue{ - constructor() public payable {} - - function testNewUse() external payable returns(uint) { - return 123; - } - basicContract bc = new basicContract(); - // external方法在调用时可以采用c.f{gas: 10000, value: 4 trx}()的形式 - function callWithGasAndValue(uint x,uint y) external returns(uint) { - return bc.testNewUse{gas:x, value:y}(); - } - - function callThisNoGasAnd1Value() external returns(uint) { - return this.testNewUse{gas:0, value:1}(); - } - - // inline assembly中允许true和false字面量 - function testAssemblyTrue() public pure returns(uint x) { - assembly { - x := true - } - } - - // inline assembly中允许true和false字面量 - function testAssemblyFalse() public pure returns(uint x) { - assembly { - x := false - } - } - - // create2的high-level用法new C{salt: 0x1234, value: 1 ether}(arg1, arg2) - function testCreate2() public returns(address) { - basicContract c = new basicContract{salt: bytes32(bytes1(0x01)), value: 1 trx}(); - return address(c); - } - - - function getContractSelectorNoParam() public pure returns(bytes4) { - return selectorContract.testSelectorNoParam.selector; - } - - function getContractSelectorWithParam() public pure returns(bytes4) { - return selectorContract.testSelectorWithParam.selector; - } - - function getInterfaceSelectorNoParam() public pure returns(bytes4) { - return interfaceSelector.getSelector.selector; - } - -} - diff --git a/framework/src/test/resources/soliditycode_0.6.12/NewFeature068.sol b/framework/src/test/resources/soliditycode_0.6.12/NewFeature068.sol deleted file mode 100644 index f5c19435f7c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/NewFeature068.sol +++ /dev/null @@ -1,126 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0 -pragma solidity ^0.6.8; - -abstract contract testModifier { - modifier isOwner() virtual; -} - -abstract contract testInterfaceId { - function getValue() external view virtual returns(uint); - function getOwner() external view virtual returns(uint); - -} - -interface a { - function getValue() external view returns(uint); - function getOwner() external view returns(uint); -} - -contract testMapKey is testModifier{ - - enum size{ - SMALL, - LARGE - } - - mapping(size => uint) public enums; - - mapping(testMapKey => uint) public contracts; - - function setEnumValue(uint value) public { - enums[size.SMALL] = value; - } - - function getEnumValue() public view returns(uint) { - return enums[size.SMALL]; - } - - function setContractValue() public { - contracts[this] = 2; - } - - function getContractValue() public view returns(uint) { - return contracts[this]; - } - - bytes4 constant functionSelector = this.getEnumValue.selector; - - function getfunctionSelector() public pure returns(bytes4) { - return functionSelector; - } - - uint immutable x; - address immutable owner = msg.sender; - - constructor() public { - x = 5; - } - - string b = "test"; - - function testStorage() public view returns(string memory) { - string storage aa; - aa = b; - return aa; - - } - - function getImmutableVal() public view returns(uint) { - return x; - } - - function getOwner() public view returns(address) { - return owner; - } - - function getInterfaceId() public pure returns(bytes4,bytes4) { - return (type(a).interfaceId, type(testInterfaceId).interfaceId); - } - - modifier isOwner() override { - require(msg.sender == owner); - _; - } - - function requireOwner() public view isOwner returns(uint) { - return 6; - } - - - function getUint256MinAndMax() public pure returns(uint, uint) { - return (type(uint).min, type(uint).max); - } - - - function getUint8MinAndMax() public pure returns(uint8, uint8) { - return (type(uint8).min, type(uint8).max); - } - -} - - -abstract contract base { - function abstractfun() virtual public returns(uint); -} - -abstract contract callEmptyFunction is base { - function callfun() public returns(uint) { - return abstractfun(); - } -} - - - - - - - - - - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.6.12/ParentTypeBug.sol b/framework/src/test/resources/soliditycode_0.6.12/ParentTypeBug.sol deleted file mode 100644 index 897c843ae24..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ParentTypeBug.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract Parent { - uint256 public m_aMember; - address public m_bMember; -} -contract Child is Parent { - function foo() public view returns (uint256) { return Parent.m_aMember; } - function bar() public view returns (address) { return Parent.m_bMember; } - - // complie failed - // function foo() public pure returns (uint256) { return Parent.m_aMember; } - // function bar() public pure returns (address) { return Parent.m_bMember; } - -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/SafeMath.sol b/framework/src/test/resources/soliditycode_0.6.12/SafeMath.sol deleted file mode 100644 index 1a7f1be2b8e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/SafeMath.sol +++ /dev/null @@ -1,149 +0,0 @@ - - -/** - * @dev Wrappers over Solidity's arithmetic operations with added overflow - * checks. - * - * Arithmetic operations in Solidity wrap on overflow. This can easily result - * in bugs, because programmers usually assume that an overflow raises an - * error, which is the standard behavior in high level programming languages. - * `SafeMath` restores this intuition by reverting the transaction when an - * operation overflows. - * - * Using this library instead of the unchecked operations eliminates an entire - * class of bugs, so it's recommended to use it always. - */ -library SafeMath { - /** - * @dev Returns the addition of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - Addition cannot overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 c = a + b; - require(c >= a, "SafeMath: addition overflow"); - - return c; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - return sub(a, b, "SafeMath: subtraction overflow"); - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting with custom message on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b <= a, errorMessage); - uint256 c = a - b; - - return c; - } - - /** - * @dev Returns the multiplication of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - Multiplication cannot overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) { - return 0; - } - - uint256 c = a * b; - require(c / a == b, "SafeMath: multiplication overflow"); - - return c; - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - return div(a, b, "SafeMath: division by zero"); - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts with custom message on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b > 0, errorMessage); - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - - return c; - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b) internal pure returns (uint256) { - return mod(a, b, "SafeMath: modulo by zero"); - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts with custom message when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b != 0, errorMessage); - return a % b; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/ShiftCommand001.sol b/framework/src/test/resources/soliditycode_0.6.12/ShiftCommand001.sol deleted file mode 100644 index 574ee2b571b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/ShiftCommand001.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/SolidityMappingFix.sol b/framework/src/test/resources/soliditycode_0.6.12/SolidityMappingFix.sol deleted file mode 100644 index 67692d3b4ae..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/SolidityMappingFix.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Tests { - mapping(address => uint) public balances; - function update(uint256 amount) public returns (address addr) - { - balances[msg.sender] = amount; - return msg.sender; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TestMappings_array_pop.sol b/framework/src/test/resources/soliditycode_0.6.12/TestMappings_array_pop.sol deleted file mode 100644 index 0d5c4bb7013..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TestMappings_array_pop.sol +++ /dev/null @@ -1,19 +0,0 @@ -contract C { - mapping (uint256 => uint256)[] a; - - function n1(uint256 key, uint256 value) public { - a.push(); - a[a.length - 1][key] = value; - } - - - - function map(uint256 key) public view returns (uint) { - return a[a.length - 1][key]; - } - - function p() public { - a.pop(); - } -} - diff --git a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed001.sol b/framework/src/test/resources/soliditycode_0.6.12/TransferFailed001.sol deleted file mode 100644 index dba043edcb3..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed001.sol +++ /dev/null @@ -1,147 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - - function testTransferTokenCompiledLongMax() payable public{ - address(0x1).transferToken(1,9223372036855775827); - } - - function testTransferTokenCompiled() payable public{ - address(0x1).transferToken(1,1); - } - - function testTransferTokenCompiledLongMin() payable public{ - //address(0x1).transferToken(1,-9223372036855775828); - } - - function testTransferTokenCompiledLongMin1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(-9223372036855775828)); - } - - function testTransferTokenCompiled1() payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(1)); - } - - function testTransferTokenCompiledLongMax1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(9223372036855775827)); - } - - function testTransferTokenCompiledTokenId(uint256 tokenid) payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(tokenid)); - } - - function testTransferTokenTest(address addr ,uint256 tokenid) payable public returns(uint256){ - return addr.tokenBalance(trcToken(tokenid)); - } - - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public { - caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - } - - function testSendTrxRevert(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - revert(); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.transfer(i); - } - - function testTransferTrxrevert(uint256 i,address payable nonexistentTarget) payable public{ - nonexistentTarget.transfer(i); - revert(); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - } - - function testTransferTokenRevert(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - revert(); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - function testSuicideRevert(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - revert(); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - function deploy2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(300, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed005.sol b/framework/src/test/resources/soliditycode_0.6.12/TransferFailed005.sol deleted file mode 100644 index aa39aafa152..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed005.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed006.sol b/framework/src/test/resources/soliditycode_0.6.12/TransferFailed006.sol deleted file mode 100644 index aa39aafa152..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed006.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed007.sol b/framework/src/test/resources/soliditycode_0.6.12/TransferFailed007.sol deleted file mode 100644 index aa39aafa152..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TransferFailed007.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant001.sol b/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant001.sol deleted file mode 100644 index b385850577d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant001.sol +++ /dev/null @@ -1,28 +0,0 @@ - - -contract testConstantContract{ - uint256 public i; - function testPayable() public payable returns (uint256 z) { - i=1; - z=i; - return z; - } - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - function testView2() public view returns (uint256 z) { - uint256 i=1; - revert(); - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant002.sol b/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant002.sol deleted file mode 100644 index 7708d81792a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant002.sol +++ /dev/null @@ -1,10 +0,0 @@ - - -contract testConstantContract{ - uint256 public i; - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant003.sol b/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant003.sol deleted file mode 100644 index 947b3f610e6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant003.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -contract testConstantContract{ - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPayable() public payable returns (uint256 z) { - uint256 i=1; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant004.sol b/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant004.sol deleted file mode 100644 index 7fcb44950e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant004.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testPure() public pure returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant015.sol b/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant015.sol deleted file mode 100644 index d926c43c824..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant015.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - constructor () public { - } - function plusOne() public returns(uint){ - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant024.sol b/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant024.sol deleted file mode 100644 index 69ad3a2d5b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TriggerConstant024.sol +++ /dev/null @@ -1,9 +0,0 @@ - - -contract testConstantContract{ -function testView() public view returns (uint256 z) { -uint256 i=1; -revert(); -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract.sol deleted file mode 100644 index 4266b9e92ca..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract001.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract001.sol deleted file mode 100644 index 77aae930b59..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract001.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} - -function testIsContractView(address a) view public returns (bool) { -return (a.isContract); -} - -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} - -function testConstructorView() public view returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract002.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract002.sol deleted file mode 100644 index 2fe474fd98c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmIsContract002.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract testIsContract{ -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand043.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand043.sol deleted file mode 100644 index 04d9f7dde28..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand043.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand103.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand103.sol deleted file mode 100644 index dbc7fd0f0f4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand103.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testView() public constant returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand107.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand107.sol deleted file mode 100644 index 5b51cd1842c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand107.sol +++ /dev/null @@ -1,9 +0,0 @@ - - - contract testConstantContract{ - int256 public i; - function testPayable() public returns (int z) { - z=1+1; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand108.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand108.sol deleted file mode 100644 index 0088054faf9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand108.sol +++ /dev/null @@ -1,7 +0,0 @@ - - - contract testConstantContract{ - function test() pure public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand109.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand109.sol deleted file mode 100644 index dc8dd1e8399..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmNewCommand109.sol +++ /dev/null @@ -1,7 +0,0 @@ - - - contract testConstantContract{ - function test() view public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/TvmOldCommand001.sol b/framework/src/test/resources/soliditycode_0.6.12/TvmOldCommand001.sol deleted file mode 100644 index 1ee046babe0..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/TvmOldCommand001.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract binaryRightContract{ - function binaryMoveR(int i)public returns (int z) { - return z = 5 >> i; - } - function binaryLiftR(int i)public returns (int z) { - return z = 5 << i; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/VerifyBurnProof001.sol b/framework/src/test/resources/soliditycode_0.6.12/VerifyBurnProof001.sol deleted file mode 100644 index 4173e84de23..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/VerifyBurnProof001.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract VerifyBurnProof001Test { - // verifyBurnProof(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32) - // size = 512 - // - - function VerifyBurnProofSize001(bytes32[10] memory output, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature,bytes32 signHash) public returns (bool){ - return verifyBurnProof(output, spendAuthoritySignature, value, bindingSignature, signHash); - } - - function VerifyBurnProofSize002(bytes memory data) public returns (bool, bytes memory){ - // bytes memory empty = ""; - return address(0x1000003).delegatecall(data); - } - - function VerifyBurnProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000003).delegatecall(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/VerifyMintProof001.sol b/framework/src/test/resources/soliditycode_0.6.12/VerifyMintProof001.sol deleted file mode 100644 index cb0812c2ef5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/VerifyMintProof001.sol +++ /dev/null @@ -1,33 +0,0 @@ - -contract VerifyMintProof001Test { - // verifyMintProof(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256) - - function VerifyMintProofSize001(bytes32[9] memory output, bytes32[2] memory bindingSignature, uint64 value, bytes32 signHash, bytes32[33] memory frontier,uint256 leafCount) public returns (bytes32[] memory){ - return verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - } - - function VerifyMintProofSize002(bytes memory data) public returns (bool, bytes memory){ -// address verifyMint = address (0x1000001); -// -// assembly { -// let succeeded := delegatecall(sub(gas, 5000), verifyMint, add(data, 0x20), mload(data), 0, 0) -// let size := returndatasize -// let response := mload(0x40) -// mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) -// mstore(response, size) -// returndatacopy(add(response, 0x20), 0, size) -// switch iszero(succeeded) -// case 1 { -// // throw if delegatecall failed -// revert(add(response, 0x20), size) -// } -// } - - return address(0x1000001).delegatecall(data); - } - - function VerifyMintProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000001).call(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/abiencode.sol b/framework/src/test/resources/soliditycode_0.6.12/abiencode.sol deleted file mode 100644 index 38fad3454d6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/abiencode.sol +++ /dev/null @@ -1,16 +0,0 @@ -pragma experimental ABIEncoderV2; - -// tests encoding from storage arrays - -contract AbiEncode { - int256[2][] tmp_h; - function h(int256[2][] calldata s) external returns (bytes memory) { - tmp_h = s; - return abi.encode(tmp_h); - } - int256[2][2] tmp_i; - function i(int256[2][2] calldata s) external returns (bytes memory) { - tmp_i = s; - return abi.encode(tmp_i); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/abstract001.sol b/framework/src/test/resources/soliditycode_0.6.12/abstract001.sol deleted file mode 100644 index 56bdc38eef4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/abstract001.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.6.0; - -interface X { - function setValue(uint _x) external; - function setBalance(uint _x) external; -} - -abstract contract abstract001 is X { - uint x; - function setX(uint _x) public { x = _x; } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/abstract002.sol b/framework/src/test/resources/soliditycode_0.6.12/abstract002.sol deleted file mode 100644 index 98bcf879f60..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/abstract002.sol +++ /dev/null @@ -1,13 +0,0 @@ -pragma solidity ^0.6.0; - -interface X { - function setValue(uint _x) external; - function setBalance(uint _x) external; -} - -abstract contract abstract002 is X { - uint x; - function setX(uint _x) public { x = _x; } - function setValue(uint _x) external override{ x = _x; } - function setBalance(uint _x) external override{ x = _x; } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/accountAssert.sol b/framework/src/test/resources/soliditycode_0.6.12/accountAssert.sol deleted file mode 100644 index 6d370f56080..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/accountAssert.sol +++ /dev/null @@ -1,94 +0,0 @@ -pragma solidity ^0.6.0; - -contract transferTokenTestA { - - // transfer trc10 to a new address or exist address in constructor - constructor(address payable toAddress, uint256 tokenValue, trcToken id) payable public{ - toAddress.transferToken(tokenValue, id); - require(toAddress.tokenBalance(id) > 0, "tokenBalance should not be 0"); - } - - fallback() payable external{} - - function transferTest(address payable toAddress, uint256 tokenValue) payable public { - toAddress.transfer(tokenValue); - } - - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - // suicide to a new address - function selfdestructTest(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - // transfer to a new contract - function createContractTest(uint256 tokenValue, trcToken id) payable public returns(address){ - Simple s = new Simple(); - require(address(s).tokenBalance(id)==0, "tokenBalance should be 0"); - address(s).transferToken(tokenValue, id); - require(address(s).tokenBalance(id)==tokenValue, "tokenBalance should not be 0"); - return address(s); - } - - // revert transfer to a new contract - function revertCreateContractTest(uint256 tokenValue, trcToken id) payable public { - Simple s = new Simple(); - address(s).transferToken(tokenValue, id); - revert(); - } -} - -contract transferTokenTestB { - - constructor() payable public{ - } - - fallback() payable external{} - - function transferTest(address payable toAddress, uint256 tokenValue) payable public { - toAddress.transfer(tokenValue); - } - - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - // suicide to a new address - function selfdestructTest(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - // transfer to a new contract - function createContractTest(uint256 tokenValue, trcToken id) payable public returns(address){ - Simple s = new Simple(); - require(address(s).tokenBalance(id)==0, "tokenBalance should be 0"); - address(s).transferToken(tokenValue, id); - require(address(s).tokenBalance(id)==tokenValue, "tokenBalance should not be 0"); - return address(s); - } - - // revert transfer to a new contract - function revertCreateContractTest(uint256 tokenValue, trcToken id) payable public { - Simple s = new Simple(); - address(s).transferToken(tokenValue, id); - revert(); - } -} - -contract transferTokenTestC { - Simple public s; - - // transfer to a new address in constructor - constructor(trcToken id) payable public{ - s = new Simple(); - require(address(s).tokenBalance(id)==0, "new contract tokenBalance should be 0"); - require(address(this).tokenBalance(id)==0, "this.tokenBalance should be 0"); - } -} - -contract Simple { - constructor() payable public{} - fallback() payable external{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.6.12/addMsg001Nonpayable.sol deleted file mode 100644 index fcd40cdb521..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addMsg001Nonpayable.sol +++ /dev/null @@ -1,20 +0,0 @@ - - -contract IllegalDecorate { - -event log(uint256); -constructor() payable public{} - -fallback() payable external{} - -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue)public { -// function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addMsg002View.sol b/framework/src/test/resources/soliditycode_0.6.12/addMsg002View.sol deleted file mode 100644 index 0c04b5c0b8a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addMsg002View.sol +++ /dev/null @@ -1,20 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} - diff --git a/framework/src/test/resources/soliditycode_0.6.12/addMsg003Constant.sol b/framework/src/test/resources/soliditycode_0.6.12/addMsg003Constant.sol deleted file mode 100644 index 2065802bed1..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addMsg003Constant.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addMsg004Pure.sol b/framework/src/test/resources/soliditycode_0.6.12/addMsg004Pure.sol deleted file mode 100644 index 25f1a36d8b7..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addMsg004Pure.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.6.12/addTransferToken001Nonpayable.sol deleted file mode 100644 index 039b341b6ac..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken001Nonpayable.sol +++ /dev/null @@ -1,13 +0,0 @@ - - - contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue)public { - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken001payable.sol b/framework/src/test/resources/soliditycode_0.6.12/addTransferToken001payable.sol deleted file mode 100644 index 17078e30189..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken001payable.sol +++ /dev/null @@ -1,13 +0,0 @@ - - - contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue) public payable{ - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken002View.sol b/framework/src/test/resources/soliditycode_0.6.12/addTransferToken002View.sol deleted file mode 100644 index c50a16390f5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken002View.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithView(address payable toAddress,trcToken id, uint256 tokenValue) public view{ - - toAddress.transferToken(tokenValue, id); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode_0.6.12/addTransferToken003Constant.sol deleted file mode 100644 index 18721d9b94c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken003Constant.sol +++ /dev/null @@ -1,14 +0,0 @@ - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode_0.6.12/addTransferToken004Pure.sol deleted file mode 100644 index f7716ee3874..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTransferToken004Pure.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode_0.6.12/addTrcToken001Assemble.sol deleted file mode 100644 index fe7a7f4cef8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTrcToken001Assemble.sol +++ /dev/null @@ -1,62 +0,0 @@ - - -contract InAssemble { - -mapping(trcToken => uint256) tokenCnt; -mapping(uint256 => mapping(trcToken => trcToken)) cntTokenToken; -constructor () payable public {} -function getBalance (address addr) view public returns(uint256 r) { -assembly{ -r := balance(addr) -} -} - -function getTokenBalanceConstant (address addr, trcToken tokenId) view public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function getTokenBalance (address addr, trcToken tokenId) public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function transferTokenInAssembly(address addr, trcToken tokenId, uint256 tokenValue) public payable { -bytes4 sig = bytes4(keccak256("()")); // function signature - -assembly { -let x := mload(0x40) // get empty storage location -mstore(x,sig) // 4 bytes - place signature in empty storage - -let ret := calltoken(gas, addr, tokenValue, tokenId, -x, // input -0x04, // input size = 4 bytes -x, // output stored at input location, save space -0x0 // output size = 0 bytes -) - -// let ret := calltoken(gas, addr, tokenValue, -// x, // input -// 0x04, // input size = 4 bytes -// x, // output stored at input location, save space -// 0x0 // output size = 0 bytes -// ) // ERROR - - -mstore(0x40, add(x,0x20)) // update free memory pointer -} - -} - -function trcTokenInMap(trcToken tokenId, uint256 tokenValue) public returns(uint256 r) { -tokenCnt[tokenId] += tokenValue; -r = tokenCnt[tokenId]; -} - -function cntTokenTokenInMap(trcToken tokenId1, trcToken tokenId2, uint256 tokenValue) public returns(trcToken r) { -cntTokenToken[tokenValue][tokenId1] = tokenId2; -r = cntTokenToken[tokenValue][tokenId1]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode_0.6.12/addTrcToken002Cat.sol deleted file mode 100644 index 0cd407079ba..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTrcToken002Cat.sol +++ /dev/null @@ -1,2051 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.6.12/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode_0.6.12/addTrcToken002Cat_withFinny.sol deleted file mode 100644 index 24117bc5e6b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addTrcToken002Cat_withFinny.sol +++ /dev/null @@ -1,2051 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 finney; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 finney; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.6.12/addressCheckNew.sol b/framework/src/test/resources/soliditycode_0.6.12/addressCheckNew.sol deleted file mode 100644 index 3c10b8c680d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addressCheckNew.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns(address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/addressCheckOld.sol b/framework/src/test/resources/soliditycode_0.6.12/addressCheckOld.sol deleted file mode 100644 index 6c6b15d1736..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/addressCheckOld.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns (address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/altbn.sol b/framework/src/test/resources/soliditycode_0.6.12/altbn.sol deleted file mode 100644 index c3cfcdbe2b9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/altbn.sol +++ /dev/null @@ -1,61 +0,0 @@ -contract AltBn128 { - constructor() public payable {} - function callBn256Add(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas(), 0x06, 0, input, 0x80, result, 0x40) - } - - } - - function callBn256AddNoValue(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns - (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas(), 0xac, 0, input, 0x80, result, 0x40) - } - } - - function callBn256ScalarMul(bytes32 x, bytes32 y, bytes32 scalar) public returns (bytes32[2] memory result) { - bytes32[3] memory input; - input[0] = x; - input[1] = y; - input[2] = scalar; - assembly { - let success := call(gas(), 0x07, 0, input, 0x60, result, 0x40) - switch success - case 0 { - revert(0,0) - } - } - } - - function callBn256Pairing(bytes memory input) public returns (bytes32 result) { - // input is a serialized bytes stream of (a1, b1, a2, b2, ..., ak, bk) from (G_1 x G_2)^k - uint256 len = input.length; - require(len % 192 == 0); - assembly { - let memPtr := mload(0x40) - let success := call(gas(), 0x08, 0, add(input, 0x20), len, memPtr, 0x20) - switch success - case 0 { - revert(0,0) - } default { - result := mload(memPtr) - } - } - } - - function convert(uint256 num) public view returns(bytes32) { - return bytes32(num); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/arrayLength001.sol b/framework/src/test/resources/soliditycode_0.6.12/arrayLength001.sol deleted file mode 100644 index 46b2405a97e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/arrayLength001.sol +++ /dev/null @@ -1,64 +0,0 @@ - - -contract arrayLength { - byte[] a; - uint256[] IntergerArray; - bytes bs; - - // arrary length - function arrayPushValue() public returns (byte[] memory){ - a = new byte[](1); - a.push(0x01); - return a; - } - - function arrayPush() public returns(byte[] memory){ - a = new byte[](1); - a.push(); - return a; - } - - function arrayPop() public returns(byte[] memory){ - a = new byte[](1); - a.pop(); - return a; - } - - // arrary push/pop return Value - function arrayPushValueReturn() public { - a = new byte[](1); - return a.push(0x01); - } - - function arrayPushReturn() public returns (bytes1){ - a = new byte[](1); - return a.push(); - } - - function arrayPopReturn() public{ - a = new byte[](1); - return a.pop(); - } - - function uint256ArrayPushValue() public returns (byte[] memory){ - IntergerArray = [1,2,3]; - IntergerArray.push(); - return a; - } - - - // bytes - function bytesPushValue() public { - - return bs.push(0x01); - } - - function bytesPush() public returns (bytes1){ - return bs.push(); - } - - function bytesPop() public { - return bs.pop(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assemblyTest.sol b/framework/src/test/resources/soliditycode_0.6.12/assemblyTest.sol deleted file mode 100644 index 519a5a85fa3..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assemblyTest.sol +++ /dev/null @@ -1,61 +0,0 @@ - -contract assemblyTest { - - uint constant x = 1; - uint constant y = x; - function getZuint() public view returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - function getZuint2() public returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - bool constant bool1 = true; - bool constant bool2 = bool1; - function getZbool() public view returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - function getZbool2() public returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - -// string constant string1 = "abc"; -// string constant string2 = string1; -// function getZstring() public view returns (string memory) { -// string memory z; -// assembly { -// z := string2 -// } -// return z; -// } - - -// address origin1 = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; -// address origin2 = origin1; -// function getZaddress() public view returns (address) { -// address z; -// assembly { -// z := origin2 -// } -// return z; -// } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest1DivideInt.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest1DivideInt.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest2FindArgsContractMinTest.sol deleted file mode 100644 index 75436287805..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest2FindArgsContractMinTest.sol +++ /dev/null @@ -1,10 +0,0 @@ - -contract findArgsIContract{ -function findArgsByIndex1(uint i) public returns (uint z) { -uint[] memory a = new uint[](3); -a[0]=1; -a[1]=2; -a[2]=3; -return a[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest3ByteMinContract.sol deleted file mode 100644 index c8a2e5e363b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest3ByteMinContract.sol +++ /dev/null @@ -1,11 +0,0 @@ - -contract byteContract{ -bytes b; -function testBytesGet(uint i) public returns (bytes1){ -b = new bytes(3); -b[0]=0x0b; -b[1]=0x0c; -b[2]=0x0d; -return b[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest4Enum.sol deleted file mode 100644 index 6bd2ade2eea..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest4Enum.sol +++ /dev/null @@ -1,13 +0,0 @@ - - -contract enumContract { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices _choice; - function setGoStraight(ActionChoices choice) public { - _choice = choice; - } - - function getChoice() public returns (ActionChoices) { - return _choice; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest5MoveRight.sol deleted file mode 100644 index b83168d5ddc..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest5MoveRight.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract binaryRightContract{ - function binaryMoveR(int i)public returns (int z) { - return z = 5 >> i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest6UninitializedContract.sol deleted file mode 100644 index c82e0f5806c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest6UninitializedContract.sol +++ /dev/null @@ -1,27 +0,0 @@ - -contract uni { -function b(int x, int y) internal returns (int) -{ - return x * y; -} - -function test1() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - funcPtr = b; - - // This call to funcPtr will succeed - return funcPtr(4, 5); -} - -function test2() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - // This call will fail because funcPtr is still a zero-initialized function pointer - return funcPtr(4, 5); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest7TestAssertContract.sol deleted file mode 100644 index 05b592e0682..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/assertExceptiontest7TestAssertContract.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract TestThrowsContract{ - function testAssert() public{ - assert(1==2); - } - function testRequire() public{ - require(2==1); - } - function testRevert() public{ - revert(); - } - function testThrow() public{ - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign.sol deleted file mode 100644 index 9e1c1b289b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - //function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - //} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign001.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign001.sol deleted file mode 100644 index 57e051ce415..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign001.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testPure(bytes32 hash, bytes[] memory signatures, address[] memory addresses) pure public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign002.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign002.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign002.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign003.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign003.sol deleted file mode 100644 index c43536af499..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign003.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { -bytes32 public result; -constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); -} -function testConstructor() public returns(bytes32){ - return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign005.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign005.sol deleted file mode 100644 index 3a6ca362973..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign005.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign007.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign007.sol deleted file mode 100644 index 974ffb34efe..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign007.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { - bytes32 public result; - - constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); - } - - function testConstructor() public returns(bytes32){ - return result; - } - - function testConstructorPure() public view returns(bytes32){ - return result; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign02.sol b/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign02.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/batchvalidatesign02.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/callValueGasPure.sol b/framework/src/test/resources/soliditycode_0.6.12/callValueGasPure.sol deleted file mode 100644 index ed4877e1ce4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/callValueGasPure.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract C { -function check(address a) external pure returns (bool success) { - a.call.value(42).gas(42); - a.call.gas(42); - //a.call.value(1).gas(42)("fwefewf"); -} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/calldata.sol b/framework/src/test/resources/soliditycode_0.6.12/calldata.sol deleted file mode 100644 index 6e877ac1b2f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/calldata.sol +++ /dev/null @@ -1,33 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract C { - struct S { uint256 a; } - - function f(S calldata s) external returns (bytes memory) { - return abi.encode(s); - } - - function g(S calldata s) external returns (bytes memory) { - return this.f(s); - } - - function m(uint256[] calldata) external pure returns (bytes memory) { - return msg.data; - } - function h(uint8[] calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function i(uint8[][2] calldata s, uint256 which) external view returns (bytes memory) { - return this.h(s[which]); - } - function j(bytes calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function k(bytes[2] calldata s, uint256 which) external view returns (bytes memory) { - return this.j(s[which]); - } - function l(function() external returns (uint)[] calldata s) external returns (uint, uint, uint) { - assert(s.length == 3); - return (s[0](), s[1](), s[2]()); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/callvalue.sol b/framework/src/test/resources/soliditycode_0.6.12/callvalue.sol deleted file mode 100644 index f01dcf2b52f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/callvalue.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract Callvalue { -function check() public payable returns(uint) { - uint256 wad; - assembly { - wad := callvalue() - } - return wad; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/chainid001.sol b/framework/src/test/resources/soliditycode_0.6.12/chainid001.sol deleted file mode 100644 index 9cf24077dfb..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/chainid001.sol +++ /dev/null @@ -1,19 +0,0 @@ - -contract IstanbulTest { - constructor() public payable {} - function getId() public view returns(uint256){ - uint256 id; - assembly { - id := chainid() - } - return id; - } - - function getBalance(address src) public view returns(uint256){ - return address(src).balance; - } - - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/codeSaftySupport.sol b/framework/src/test/resources/soliditycode_0.6.12/codeSaftySupport.sol deleted file mode 100644 index 1cee8e4646c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/codeSaftySupport.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferToken(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode_0.6.12/codeSaftyUnsupport.sol deleted file mode 100644 index d448f49d706..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/codeSaftyUnsupport.sol +++ /dev/null @@ -1,56 +0,0 @@ - - -contract SubC { - -event log(string); - -fallback() payable external{} - -function receiveToken() payable public{} - -function getBalance() view public returns (uint256 r) { -r = address(this).balance; -} -} - -contract UseDot { -constructor() payable public{} -fallback() payable external{} -mapping(address => mapping(trcToken => uint256)) sender_tokens; - -function trigger1(address payable addr, trcToken tokenInputId) payable public { - //address(SubC(addr)).call.value(1000).tokenId(tokenInputId)(abi.encodeWithSignature("receiveToken()")); // ERROR -} - -function trigger2(address payable addr) payable public { -// addr.transferToken.value(10)(10, 0x6e6d62); // ERROR -} - -function trigger3(address payable addr) payable public { - // address(SubC(addr)).receiveToken.tokenvalue(10)(); // ERROR -} - -function trigger4(address payable addr) payable public { - //SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR -} - -function trigger5(address payable addr) payable public { - SubC(addr).receiveToken.value(10)(); -} - -function trigger6(address payable addr, trcToken tokenId) payable public { -address(SubC(addr)).call.value(1000)(abi.encodeWithSignature("transferToken(uint256, trcToken)", 10, tokenId)); -} - -function trigger7(address addr) payable public { - //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger -} - -function trigger8(address addr) public payable returns(bytes memory r){ -// r = msg.data; // compile success, no necessary to trigger -} - -function getBalance() public returns (uint256 r){ -r = address(this).balance; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage001.sol b/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage001.sol deleted file mode 100644 index 1f584923a55..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage001.sol +++ /dev/null @@ -1,159 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} -contract viewCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = bytes32(uint256(0xdCad3a6d3569DF655070DEd0)); - bytes bs = new bytes(3); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.GoRight; - int64[] b = [-1, 2, -3]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - constructor() payable public{ - mapa[address(0x00)] = 34; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - function changeBool(bool param) public returns (bool){ - stopped = param; - emit log(stopped); - return stopped; - } - function getBool() public returns (bool){ - emit log(stopped); - return stopped; - } - function changeInt(int param) public returns (int){ - i = param; - emit log(i); - return i; - } - function getInt() public returns (int){ - emit log(i); - return i; - } - function changeNegativeInt(int param) public returns (int){ - i2 = param; - emit log(i2); - return i2; - } - function getNegativeInt() public returns (int){ - emit log(i2); - return i2; - } - function changeUint(uint param) public returns (uint){ - ui = param; - emit log(ui); - return ui; - } - function getUint() public returns (uint){ - emit log(ui); - return ui; - } - function changeAddress(address param) public returns (address){ - origin = param; - emit log(origin); - return origin; - } - function getAddress() public returns (address){ - emit log(origin); - return origin; - } - function changeBytes32(bytes32 param) public returns (bytes32){ - b32 = param; - emit log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - emit log(b32); - return b32; - } - function changeBytes(bytes memory param) public returns (bytes memory){ - bs = param; - emit log(bs); - return bs; - } - function getBytes() public returns (bytes memory){ - emit log(bs); - return bs; - } - function changeString(string memory param) public returns (string memory){ - s = param; - emit log(s); - return s; - } - function getString() public returns (string memory){ - emit log(s); - return s; - } - function changeActionChoices(ActionChoices param) public returns (ActionChoices){ - choice = param; - emit log(choice); - return choice; - } - function getActionChoices() public returns (ActionChoices){ - emit log(choice); - return choice; - } - function changeInt64NegativeArray(int64[] memory param) public returns (int64[] memory){ - b = param; - emit log(b); - return b; - } - function getInt64NegativeArray() public returns (int64[] memory){ - emit log(b); - return b; - } - function changeInt32Array(int32[2][] memory param) public returns (int32[2][] memory){ - tmp_h = param; - emit log(tmp_h); - return tmp_h; - } - function getInt32Array() public returns (int32[2][] memory){ - emit log(tmp_h); - return tmp_h; - } - function changeInt256Array(int256[2][2] memory param) public returns (int256[2][2] memory){ - tmp_i = param; - emit log(tmp_i); - return tmp_i; - } - function getInt256Array() public returns (int256[2][2] memory){ - emit log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage002.sol b/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage002.sol deleted file mode 100644 index 1ceba5e87d2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage002.sol +++ /dev/null @@ -1,16 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public view returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public view returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage0425.sol b/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage0425.sol deleted file mode 100644 index 8ecf771626d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/constantCallStorage0425.sol +++ /dev/null @@ -1,156 +0,0 @@ -contract constantCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - bytes bs = new bytes(9); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.SitStill; - int64[] b = [91, 2, 333]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - - constructor() payable public{ - mapa[address(0x00)] = 88; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - - function changeBool(bool param) public constant returns (bool){ - stopped = param; - log(stopped); - return stopped; - } - function getBool() public constant returns (bool){ - log(stopped); - return stopped; - } - - function changeInt(int param) public returns (int){ - i = param; - log(i); - return i; - } - function getInt() public returns (int){ - log(i); - return i; - } - - function changeNegativeInt(int param) public constant returns (int){ - i2 = param; - log(i2); - return i2; - } - function getNegativeInt() public constant returns (int){ - log(i2); - return i2; - } - - function changeUint(uint param) public returns (uint){ - ui = param; - log(ui); - return ui; - } - function getUint() public returns (uint){ - log(ui); - return ui; - } - - function changeAddress(address param) public constant returns (address){ - origin = param; - log(origin); - return origin; - } - function getAddress() public constant returns (address){ - log(origin); - return origin; - } - - function changeBytes32(bytes32 param) public constant returns (bytes32){ - b32 = param; - log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - log(b32); - return b32; - } - - function changeBytes(bytes param) public constant returns (bytes){ - bs = param; - log(bs); - return bs; - } - function getBytes() public constant returns (bytes){ - log(bs); - return bs; - } - - function changeString(string param) public constant returns (string){ - s = param; - log(s); - return s; - } - function getString() public returns (string){ - log(s); - return s; - } - - function changeActionChoices(ActionChoices param) public constant returns (ActionChoices){ - choice = param; - log(choice); - return choice; - } - function getActionChoices() public constant returns (ActionChoices){ - log(choice); - return choice; - } - - function changeInt64NegativeArray(int64[] param) public constant returns (int64[]){ - b = param; - log(b); - return b; - } - function getInt64NegativeArray() public constant returns (int64[]){ - log(b); - return b; - } - - function changeInt32Array(int32[2][] param) public returns (int32[2][]){ - tmp_h = param; - log(tmp_h); - return tmp_h; - } - function getInt32Array() public constant returns (int32[2][]){ - log(tmp_h); - return tmp_h; - } - - function changeInt256Array(int256[2][2] param) public returns (int256[2][2]){ - tmp_i = param; - log(tmp_i); - return tmp_i; - } - function getInt256Array() public constant returns (int256[2][2]){ - log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/constantContract001.sol b/framework/src/test/resources/soliditycode_0.6.12/constantContract001.sol deleted file mode 100644 index 7d574c5a008..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/constantContract001.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testPure(uint256 x,uint256 y) public pure returns (uint256 z) { -uint256 i=1; -return i + x + y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGetterContract.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGetterContract.sol deleted file mode 100644 index 365b53ebf1a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGetterContract.sol +++ /dev/null @@ -1,17 +0,0 @@ - - - -contract getterContract { - -constructor() public payable{} -fallback() external payable{} - -uint public c = msg.value; - -function getDataUsingAccessor() public payable returns (uint){ - -return c; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test1Grammar001.sol deleted file mode 100644 index 659e56c9150..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test1Grammar001.sol +++ /dev/null @@ -1,18 +0,0 @@ - -contract FunctionSelector { - function select(bool useB, uint x) public returns (uint z) { - //var f = a; - //if (useB) f = b; - //return f(x); - if (useB) - return b(x); - else - return a(x); - } -function a(uint x) public returns (uint z) { - return x * x; - } -function b(uint x) public returns (uint z) { - return 2 * x; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test2Grammar002.sol deleted file mode 100644 index 744b17e9585..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test2Grammar002.sol +++ /dev/null @@ -1,44 +0,0 @@ - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert(Data storage self, uint value) public returns (bool) { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public returns (bool) { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public returns (bool) { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register (uint value) public{ - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test3Grammar003.sol deleted file mode 100644 index 140ba2a8f56..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test3Grammar003.sol +++ /dev/null @@ -1,44 +0,0 @@ - - -library Set { - struct Data { mapping(uint => bool) flags; } - - function insert(Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - using Set for Set.Data; // this is the crucial change - Set.Data knownValues; - - function register(uint value) public{ - // Here, all variables of type Set.Data have - // corresponding member functions. - // The following function call is identical to - // Set.insert(knownValues, value) - if (!knownValues.insert(value)) - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test4Grammar004.sol deleted file mode 100644 index 772691cebc5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test4Grammar004.sol +++ /dev/null @@ -1,31 +0,0 @@ - - -library Search { - function indexOf(uint[] storage self, uint value) public returns (uint) { - for (uint i = 0; i < self.length; i++) - if (self[i] == value) return i; - return uint(-1); - } -} - - -contract C { - using Search for uint[]; - uint[] public data; - - function append(uint value) public{ - data.push(value); - } - - function replace(uint _old, uint _new) public{ - // This performs the library function call - uint index = data.indexOf(_old); - if (index == uint(-1)) - data.push(_new); - else - data[index] = _new; - } - function getData(uint256 index) public returns(uint256){ - return data[index]; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test5Grammar006.sol deleted file mode 100644 index 275d42d1e71..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar001test5Grammar006.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract InfoFeed { -function d1(uint x1) public{ - - assembly{ - function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } } - } - } - function d2(uint x1) public{ - assembly { - let x:=1 - x := mul(1, add(2, 3))} - } - function f(uint x) public{ - assembly { x := sub(x, 1) } - - } - // 0.6.0 Variable declarations cannot shadow declarations outside the assembly block. - function d(uint x1) public returns(uint256){ - uint256 x; - assembly{ - x := add(2, 3) - let y := mload(0x40) - x := add(x, y) - } - return x; - } - function d4(uint x) public{ - // Error: The labels 'repeat' is disallowed. Please use "if", "switch", "for" or function calls instead - //assembly{let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0)) - x = x; - //} - } - function d5(uint x1) public{ - assembly{ - function f(x) -> y { switch x case 0 { y := mul(x, 2) } default { y := 0 } } - - } - } - - function d6(uint x1) public{ - assembly{ - function f(x) -> y { for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) } } - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test1Grammar007_1.sol deleted file mode 100644 index 020c2a38ca4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test1Grammar007_1.sol +++ /dev/null @@ -1,60 +0,0 @@ -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -// -abstract contract DogInterface { - function getDougAge(uint _age) public virtual returns (uint); - function contracts(bytes32 name) public virtual returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test1Grammar007_2.sol deleted file mode 100644 index 8945b566543..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test1Grammar007_2.sol +++ /dev/null @@ -1,60 +0,0 @@ - -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -abstract contract DogInterface { - function getDougAge(uint _age) public virtual returns (uint); - function contracts(bytes32 name) public virtual returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test2Grammar008.sol deleted file mode 100644 index 956623c3103..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test2Grammar008.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -// version 0.6.0 change -// add abstract and override -abstract contract Feline { - - function utterance() public virtual returns (bytes32); - - function getContractName() public returns (string memory){ - return "Feline"; - } -} - - -contract Cat is Feline { - function utterance() public override returns (bytes32) { return "miaow"; } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test3Grammar010.sol deleted file mode 100644 index d6845d2e336..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test3Grammar010.sol +++ /dev/null @@ -1,10 +0,0 @@ - -contract InfoFeed { -function info() public payable returns (uint ret) { return 42; } -} -contract Consumer { -constructor() payable public{} -InfoFeed feed; -function setFeed(address addr) public { feed = InfoFeed(addr); } -function callFeed() public payable { feed.info.value(10).gas(800)(); } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test4Grammar011.sol deleted file mode 100644 index fcd18f438ef..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test4Grammar011.sol +++ /dev/null @@ -1,11 +0,0 @@ - -contract C { -function f(uint key, uint value) public returns(uint) { -return key; -// do something -} -function g() public { -// named arguments -f({value: 2, key: 3}); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test4Grammar012.sol deleted file mode 100644 index 8fb3c750298..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test4Grammar012.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract rTest { -function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { -//function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { -//var a = block.coinbase ; -//var b = block.difficulty; -//var c = block.gaslimit; -//var d = block.number; -//var e = block.blockhash(0); -//var e = d; -//var f = block.timestamp; -//bytes memory g = msg.data; -uint256 h = gasleft(); -address payable i = msg.sender; -bytes4 j = msg.sig; -uint256 k = msg.value; -uint256 l = now; -uint256 m = tx.gasprice; -address payable n = tx.origin; -uint256 o = address(this).balance; -return (h,i,j,k,l,m,n,o); -//return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test6Grammar013.sol deleted file mode 100644 index 53de5def6bc..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar002test6Grammar013.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract Counter { -uint count = 0; -address payable owner; -//function Counter() public{ -constructor() public{ -owner = msg.sender; -} -function increment() public { -uint step = 10; -if (owner == msg.sender) { -count = count + step; -} -} -function getCount() public returns (uint){ -return count; -} -function kill() public{ -if (owner == msg.sender) { -selfdestruct(owner); -//selfdestruct(address(owner)); -} -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test1Grammar014.sol deleted file mode 100644 index b2d70b3741c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test1Grammar014.sol +++ /dev/null @@ -1,67 +0,0 @@ -contract A { -uint256 public numberForB; -address public senderForB; -function callTest(address bAddress, uint256 _number) public{ - -//bAddress.call(bytes4(sha3("setValue(uint256)")), _number); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("setValue(uint256)",_number)); // B's storage is set, A is not modified -} -function callcodeTest(address bAddress, uint256 _number) public{ -//bAddress.callcode(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} -function delegatecallTest(address bAddress, uint256 _number) public{ -//bAddress.delegatecall(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} - -function callAddTest(address bAddress) public{ -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract B { -uint256 public numberForB; -address public senderForB; -address public addr11; -mapping(uint256=>address) public addr1; -mapping(uint256=>address) public addr2; -event ssss(uint256); -function setValue(uint256 _number) public{ - -emit ssss(_number); -numberForB = _number; -senderForB = msg.sender; -// senderForB is A if invoked by A's callTest. B's storage will be updated -// senderForB is A if invoked by A's callcodeTest. None of B's storage is updated -// senderForB is OWNER if invoked by A's delegatecallTest. None of B's storage is updated -} - -function add() public{ -numberForB=numberForB+1; -C c1 = new C(); -addr1[numberForB]=c1.getAddress(); -addr11 = c1.getAddress(); -C c2 = new C(); -addr2[numberForB] = c2.getAddress(); -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract C { -function getAddress() public view returns(address){ -return address(this); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test2Grammar015.sol deleted file mode 100644 index 0aa93e5e94f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test2Grammar015.sol +++ /dev/null @@ -1,40 +0,0 @@ - - -contract ExecuteFallback{ - - //回退事件,会把调用的数据打印出来 - event FallbackCalled(bytes data); - //fallback函数,注意是没有名字的,没有参数,没有返回值的 - // 0.6.0 Split unnamed fallback functions into two cases defined using fallback() and receive() - fallback() external{ - emit FallbackCalled(msg.data); - } - - //调用已存在函数的事件,会把调用的原始数据,请求参数打印出来 - event ExistFuncCalled(bytes data, uint256 para); - //一个存在的函数 - function existFunc(uint256 para) public{ - emit ExistFuncCalled(msg.data, para); - } - - // 模拟从外部对一个存在的函数发起一个调用,将直接调用函数 - function callExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("existFunc(uint256)")); - //this.call(funcIdentifier, uint256(1)); - address(this).call(abi.encode(funcIdentifier, uint256(1))); - } - - //模拟从外部对一个不存在的函数发起一个调用,由于匹配不到函数,将调用回退函数 - function callNonExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("functionNotExist()")); - //this.call(funcIdentifier); - address(this).call(abi.encode(funcIdentifier)); - } - - function ExistFuncCalledTopic() view public returns(bytes32){ - return keccak256("ExistFuncCalled(bytes,uint256)"); - } - function FallbackCalledTopic() view public returns(bytes32){ - return keccak256("FallbackCalled(bytes)"); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test3Grammar016.sol deleted file mode 100644 index 6a73d7a8d7e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test3Grammar016.sol +++ /dev/null @@ -1,23 +0,0 @@ - -contract C { -uint private data; -function f(uint a) private returns(uint b) { return a + 1; } -function setData(uint a) public { data = a; } -function getData() public returns(uint) { return data; } -function compute(uint a, uint b) internal returns (uint) { return a+b; } -} -contract D { -function readData() public{ -C c = new C(); -//uint local = c.f(7); // error: member "f" is not visible -c.setData(3); -uint local = c.getData(); -// local = c.compute(3, 5); // error: member "compute" is not visible -} -} -contract E is C { -function g() public { -C c = new C(); -uint val = compute(3, 5); // access to internal member (from derived to parent contract) -} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test4Grammar017.sol deleted file mode 100644 index fb81b6e529c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test4Grammar017.sol +++ /dev/null @@ -1,50 +0,0 @@ - -contract CrowdFunding{ -struct Funder{ -address addr; -uint amount; -} - -struct Campaign{ -address payable beneficiary; -uint goal; -uint amount; -uint funderNum; -mapping(uint => Funder) funders; -} - -uint compaingnID; -mapping (uint => Campaign) campaigns; - -function candidate(address payable beneficiary, uint goal) public payable returns (uint compaingnID){ -// initialize -campaigns[compaingnID++] = Campaign(beneficiary, goal, 0, 0); -} - -function vote(uint compaingnID) payable public { -Campaign storage c = campaigns[compaingnID]; - -//another way to initialize -c.funders[c.funderNum++] = Funder({addr: msg.sender, amount: msg.value}); -c.amount += msg.value; -} - -function check(uint comapingnId) public payable returns (bool){ - Campaign memory c = campaigns[comapingnId]; - - if(c.amount < c.goal){ - return false; - } - - uint amount = c.amount; - // incase send much more - c.amount = 0; - // address payable addr = address(uint160(c.beneficiary)); - //if(! addr.send(amount)){ - - if (! c.beneficiary.send(amount)){ - revert(); - } - return true; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test5Grammar018.sol deleted file mode 100644 index ec241f3eae9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test5Grammar018.sol +++ /dev/null @@ -1,37 +0,0 @@ - - - -contract Grammar18{ - function testAddmod() public returns (uint z) { - //计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕 - z=addmod(2, 2, 3); - return z; - } - function testMulmod() public returns (uint z) { -//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。 - z=mulmod(2, 3, 4); - return z; - } - - function testKeccak256() public returns(bytes32){ - //计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 - return keccak256("11"); - } - - function testSha256() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - return sha256("11"); - } - function testSha3() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - //return sha3("11"); - return keccak256("11"); - } - - function testRipemd160() public returns(bytes32){ - //计算(紧密包装)参数的RIPEMD-160哈希值 - return ripemd160("11"); - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test6Grammar019.sol deleted file mode 100644 index 727ef7091e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test6Grammar019.sol +++ /dev/null @@ -1,12 +0,0 @@ - -contract timetest { - -constructor() public { -require( 1 == 1 seconds); -require(1 minutes == 60 seconds); -require(1 hours == 60 minutes); -require(1 days == 24 hours); -require(1 weeks == 7 days); -//require(1 years == 365 days); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test7Grammar020.sol deleted file mode 100644 index 39a7fddcb7e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractGrammar003test7Grammar020.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract trxtest { - -function test() public { -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInnerContract.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInnerContract.sol deleted file mode 100644 index 0de68bbf7da..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInnerContract.sol +++ /dev/null @@ -1,32 +0,0 @@ - - - - -contract InnerContract { - - constructor() public payable{} - fallback() external payable{} - - function messageI() payable public returns (uint ret) { - - - - } - -} - - - -contract OuterContract { - - - constructor() public payable{} - fallback() external payable{} - - function callInner(address payable addr) payable public returns (uint) { - - return InnerContract(addr).messageI.value(1)(); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction001.sol deleted file mode 100644 index 02fa51949c3..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction001.sol +++ /dev/null @@ -1,41 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address payable cAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - B b2 = new B();//1.2 - payable(address(b2)).transfer(5);//1.3 - b2.callCGetZero(cAddr, 1);//1.4 - b2.callCGetZero(cAddr,2);//1.6 - } - function test2(address payable cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - cAddress.call.value(amount + 1)(abi.encodeWithSignature("newBAndTransfer()"));//2.6 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(address payable cAddress,uint256 amount) public{ - cAddress.call.value(amount)(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - B b1 = (new B).value(7)();//2.2,2.7 - b1.getOne();//2.3,2.8 - B b2 = (new B).value(3)();//2.4,2.9 - b2.getOne();//2.5,2.10 - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction002.sol deleted file mode 100644 index 92edfeb1157..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction002.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - - function test2(address cAddress,uint256 amount) public payable{ - //cAddress.call.value(amount)();//2.1 - cAddress.call.value(amount)("");//2.1 - } -} - - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction003.sol deleted file mode 100644 index 2e17d6dbc02..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction003.sol +++ /dev/null @@ -1,30 +0,0 @@ - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - B b = (new B).value(10)();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction004.sol deleted file mode 100644 index e8f32d7bfd9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction004.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract A{ - constructor () payable public{} - function test(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - fallback() payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} -contract B{ - fallback() external payable{} - function kill(address contractAddres, address toAddress) payable public { - contractAddres.call(abi.encodeWithSignature("test(address)",address(this))); - } - function kill2() public{ - A a = new A(); - a.test(payable(address(this))); - } - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction005.sol deleted file mode 100644 index b198d260e4d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction005.sol +++ /dev/null @@ -1,53 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1() public payable{ - B b1 = (new B).value(10)();//1.1 - b1.callCGetZero(false); - b1.callCGetZero(true);//1.4 - } - function test2() public payable{ - C c1 = (new C).value(10)();//1.1 - c1.newBAndTransfer(false); - c1.newBAndTransfer(true);//1.4 - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction006.sol deleted file mode 100644 index ca51fda2021..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction001testInternalTransaction006.sol +++ /dev/null @@ -1,54 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1() public payable{ - B b1 = (new B).value(10)();//1.1 - b1.callCGetZero(true);//1.4 - b1.callCGetZero(false); - } - function test2() public payable{ - C c1 = (new C).value(10)();//1.1 - c1.newBAndTransfer(true);//1.4 - c1.newBAndTransfer(false); - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test1InternalTransaction007.sol deleted file mode 100644 index 528fb9fa8a8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test1InternalTransaction007.sol +++ /dev/null @@ -1,38 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address cAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - B b2 = new B();//1.2 - payable(address(b2)).transfer(5);//1.3 - b2.callCGetZero();//1.4 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero() public{ - assert(1==2); - - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test2InternalTransaction008.sol deleted file mode 100644 index c1e9ea0596f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test2InternalTransaction008.sol +++ /dev/null @@ -1,60 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - - function testAssert(address bAddress,uint256 amount) public payable{ - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",true)); - } - function testRequire(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - } - function testAssert1(address bAddress,uint256 amount) public payable{ - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",true)); - bAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - } - function testtRequire2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - cAddress.call.value(amount).gas(1000000)(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable public{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test3InternalTransaction009.sol deleted file mode 100644 index 7c8a1f8c879..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test3InternalTransaction009.sol +++ /dev/null @@ -1,47 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address cAddr,address dcontract,address baddress) public payable{ - B b1 = (new B).value(10)();//1.1 - payable(address(b1)).transfer(5);//1.3 - b1.callCGetZero(cAddr, 1);//1.4 - b1.getOne(dcontract,baddress); - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne(address contractAddres, address toAddress) payable public{ - contractAddres.call(abi.encodeWithSignature("suicide1(address)",address(this))); - - } - function callCGetZero(address cAddress,uint256 amount) public{ - cAddress.call.value(amount)(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public{ - B b1 = (new B).value(7)();//2.2,2.7 - B b2 = (new B).value(3)();//2.4,2.9 - } -} - -contract D{ - constructor () payable public{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - fallback() payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test4InternalTransaction010.sol deleted file mode 100644 index af2b54af172..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test4InternalTransaction010.sol +++ /dev/null @@ -1,186 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() public returns(uint256) { - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test4InternalTransaction010_1.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test4InternalTransaction010_1.sol deleted file mode 100644 index d0c80d14ffb..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test4InternalTransaction010_1.sol +++ /dev/null @@ -1,210 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - fallback() payable{} - } - - \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test5InternalTransaction012.sol deleted file mode 100644 index e9bc38b58d4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction002test5InternalTransaction012.sol +++ /dev/null @@ -1,51 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address bAddr,address eAddr) public payable{ - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - } - -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable{ - D d1=(new D).value(1000)(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction013.sol deleted file mode 100644 index 3ef9264ee70..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction013.sol +++ /dev/null @@ -1,56 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address dAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.testNN(dAddr,2);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount) public payable{ - // D d1=(new D)(); - dAddress.call.value(amount)(abi.encodeWithSignature("getOne()"));//2.1 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - E e = (new E).value(5)(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction014.sol deleted file mode 100644 index 5647048bab3..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction014.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract callerContract { - constructor() payable public{} - fallback() payable external{} - function sendToB(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - - contract calledContract { - fallback() payable external {} - constructor() payable public{} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call.value(5)(abi.encodeWithSignature("setI()")); - } - - } - - contract c{ - uint256 public i=0; - constructor() public payable{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } - function setI() payable public{ - i=5; - } - fallback() payable external{} - } diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction015.sol deleted file mode 100644 index 229f79f3c96..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction015.sol +++ /dev/null @@ -1,60 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address dAddr,address eAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.testNN(dAddr,2,eAddr);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount,address eAddress) public payable{ - // D d1=(new D)(); - dAddress.call.value(amount)(abi.encodeWithSignature("getOne(address)",address(this)));//2.1 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } - function suicide(address payable toAddress) public payable{ - selfdestruct(toAddress); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address payable eAddress) payable public{ - E e = (new E).value(5)(); - e.suicide(eAddress); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction016.sol deleted file mode 100644 index f5cbdc2f1fa..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction016.sol +++ /dev/null @@ -1,174 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - fallback() payable external{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - B b1=(new B).value(1)();//1 - address payable aaa=address(this); - b1.suicide1(aaa); - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - B b1=(new B).value(1)();//1 - address payable aaa=address(this); - b1.suicide1(aaa); - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - } - diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction017.sol deleted file mode 100644 index 6847eebc546..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction017.sol +++ /dev/null @@ -1,199 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer(address payable Address) payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - B b=(new B).value(1)();//1 - selfdestruct(Address); - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction018.sol deleted file mode 100644 index 80705ffd5e9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractInternalTransaction003testInternalTransaction018.sol +++ /dev/null @@ -1,97 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address payable bAddr,address eAddr) public payable{ - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call.value(1)(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - - } - -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable { - D d1=(new D).value(100)(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call.value(1)(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractLinkage001.sol deleted file mode 100644 index 8d441fba2da..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage001.sol +++ /dev/null @@ -1,9 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -constructor() payable public{} -fallback() payable external{} -function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage002.sol b/framework/src/test/resources/soliditycode_0.6.12/contractLinkage002.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage002.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage003.sol b/framework/src/test/resources/soliditycode_0.6.12/contractLinkage003.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage003.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage004.sol b/framework/src/test/resources/soliditycode_0.6.12/contractLinkage004.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage004.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage005.sol b/framework/src/test/resources/soliditycode_0.6.12/contractLinkage005.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage005.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage006.sol b/framework/src/test/resources/soliditycode_0.6.12/contractLinkage006.sol deleted file mode 100644 index 53449f61ce2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractLinkage006.sol +++ /dev/null @@ -1,18 +0,0 @@ - -contract AA{ - uint256 public count=0; - constructor () payable public{} - function init(address payable addr, uint256 max) payable public { - count =0; - this.hack(addr,max); - } - function hack(address payable addr, uint256 max) payable public { - while (count < max) { - count = count +1; - this.hack(addr,max); - } - if (count == max) { - addr.send(20); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractOriginEnergyLimit001.sol deleted file mode 100644 index 6feb7fff3b8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractOriginEnergyLimit001.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode_0.6.12/contractOriginEnergyLimit004.sol deleted file mode 100644 index 6feb7fff3b8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractOriginEnergyLimit004.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode_0.6.12/contractOtherToTrcToken.sol deleted file mode 100644 index 933358e128b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractOtherToTrcToken.sol +++ /dev/null @@ -1,41 +0,0 @@ - - -contract ConvertType { - -constructor() payable public{} - -fallback() payable external{} - -//function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { -// trcToken t = trcToken(tokenStr); // ERROR -// toAddress.transferToken(tokenValue, tokenStr); // ERROR -//} - -function uint256ToTrctoken(address payable toAddress, uint256 tokenValue, uint256 tokenInt) public { - trcToken t = trcToken(tokenInt); // OK - toAddress.transferToken(tokenValue, t); // OK - toAddress.transferToken(tokenValue, tokenInt); // OK -} - -function addressToTrctoken(address payable toAddress, uint256 tokenValue, address adr) public { - trcToken t = trcToken(adr); // OK - toAddress.transferToken(tokenValue, t); // OK -//toAddress.transferToken(tokenValue, adr); // ERROR -} - -//function bytesToTrctoken(address payable toAddress, bytes memory b, uint256 tokenValue) public { - // trcToken t = trcToken(b); // ERROR - // toAddress.transferToken(tokenValue, b); // ERROR -//} - -function bytes32ToTrctoken(address payable toAddress, uint256 tokenValue, bytes32 b32) public { - trcToken t = trcToken(b32); // OK - toAddress.transferToken(tokenValue, t); // OK -// toAddress.transferToken(tokenValue, b32); // ERROR -} - -//function arrayToTrctoken(address payable toAddress, uint256[] memory arr, uint256 tokenValue) public { -//trcToken t = trcToken(arr); // ERROR -// toAddress.transferToken(tokenValue, arr); // ERROR -//} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario001.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario001.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario002.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario002.sol deleted file mode 100644 index 5b990fe36e8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario002.sol +++ /dev/null @@ -1,53 +0,0 @@ - -contract TronNative{ - - address public voteContractAddress= address(0x10001); - address public freezeBalanceAddress = address(0x10002); - address public unFreezeBalanceAddress = address(0x10003); - address public withdrawBalanceAddress = address(0x10004); - address public approveProposalAddress = address(0x10005); - address public createProposalAddress = address(0x10006); - address public deleteProposalAddress = address(0x10007); - constructor () payable public {} - - function voteForSingleWitness (address payable witnessAddr, uint256 voteValue) public{ - // method 1: - voteContractAddress.delegatecall(abi.encode(witnessAddr,voteValue)); - } - - function voteUsingAssembly (address witnessAddr, uint256 voteValue) public{ - // method 2: - assembly{ - mstore(0x80,witnessAddr) - mstore(0xa0,voteValue) - // gas, address, in, size, out, size - if iszero(delegatecall(0, 0x10001, 0x80, 0x40, 0x80, 0x0)) { - revert(0, 0) - } - } - } - - function freezeBalance(uint256 frozen_Balance,uint256 frozen_Duration) public { - freezeBalanceAddress.delegatecall(abi.encode(frozen_Balance,frozen_Duration)); - } - - function unFreezeBalance() public { - unFreezeBalanceAddress.delegatecall(""); - } - - function withdrawBalance() public { - withdrawBalanceAddress.delegatecall(""); - } - - function approveProposal(uint256 id, bool isApprove) public { - approveProposalAddress.delegatecall(abi.encode(id,isApprove)); - } - - function createProposal(bytes32 [] memory data) public { - createProposalAddress.delegatecall(abi.encode(data)); - } - - function deleteProposal(uint256 id) public{ - deleteProposalAddress.delegatecall(abi.encode(id)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario003.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario003.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario003.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario004.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario004.sol deleted file mode 100644 index f6919502914..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario004.sol +++ /dev/null @@ -1,88 +0,0 @@ - - -contract TronToken { - - string public name = "Tronix"; // token name - string public symbol = "TRX"; // token symbol - uint256 public decimals = 6; // token digit - - mapping (address => uint256) public balanceOf; - mapping (address => mapping (address => uint256)) public allowance; - - uint256 public totalSupply = 0; - bool public stopped = false; - - uint256 constant valueFounder = 100000000000000000; - address owner = address(0x0); - - modifier isOwner { - assert(owner == msg.sender); - _; - } - - modifier isRunning { - assert (!stopped); - _; - } - - modifier validAddress { - assert(address(0x0) != msg.sender); - _; - } - - constructor(address _addressFounder) public { - owner = msg.sender; - totalSupply = valueFounder; - balanceOf[_addressFounder] = valueFounder; - emit Transfer(address(0x0), _addressFounder, valueFounder); - } - - function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[msg.sender] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - balanceOf[msg.sender] -= _value; - balanceOf[_to] += _value; - emit Transfer(msg.sender, _to, _value); - return true; - } - - function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[_from] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - require(allowance[_from][msg.sender] >= _value); - balanceOf[_to] += _value; - balanceOf[_from] -= _value; - allowance[_from][msg.sender] -= _value; - emit Transfer(_from, _to, _value); - return true; - } - - function approve(address _spender, uint256 _value) isRunning validAddress public returns (bool success) { - require(_value == 0 || allowance[msg.sender][_spender] == 0); - allowance[msg.sender][_spender] = _value; - emit Approval(msg.sender, _spender, _value); - return true; - } - - function stop() isOwner public { - stopped = true; - } - - function start() isOwner public { - stopped = false; - } - - function setName(string memory _name) isOwner public { - name = _name; - } - - function burn(uint256 _value) public { - require(balanceOf[msg.sender] >= _value); - balanceOf[msg.sender] -= _value; - balanceOf[address(0x0)] += _value; - emit Transfer(msg.sender, address(0x0), _value); - } - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario005.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario005.sol deleted file mode 100644 index c377af7da97..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario005.sol +++ /dev/null @@ -1,103 +0,0 @@ - - -interface token { - function transfer(address receiver, uint amount) external; -} - -contract Crowdsale { - address payable public beneficiary = 0x1b228F5D9f934c7bb18Aaa86F90418932888E7b4; // 募资成功后的收款方 - uint public fundingGoal = 10000000; // 募资额度 - uint public amountRaised = 1000000; // 参与数量 - uint public deadline; // 募资截止期 - - uint public price; // token 与以太坊的汇率 , token卖多少钱 - token public tokenReward; // 要卖的token - - mapping(address => uint256) public balanceOf; - - bool fundingGoalReached = false; // 众筹是否达到目标 - bool crowdsaleClosed = false; // 众筹是否结束 - - /** - * 事件可以用来跟踪信息 - **/ - event GoalReached(address recipient, uint totalAmountRaised); - event FundTransfer(address backer, uint amount, bool isContribution); - - /** - * 构造函数, 设置相关属性 - */ - constructor( - address payable ifSuccessfulSendTo, - uint fundingGoalInEthers, - uint durationInMinutes, - uint finneyCostOfEachToken, - address addressOfTokenUsedAsReward) public{ - beneficiary = ifSuccessfulSendTo; - fundingGoal = fundingGoalInEthers * 1 sun; - deadline = now + durationInMinutes * 1 minutes; - price = finneyCostOfEachToken * 1 trx; - tokenReward = token(addressOfTokenUsedAsReward); // 传入已发布的 token 合约的地址来创建实例 - } - - /** - * 无函数名的Fallback函数, - * 在向合约转账时,这个函数会被调用 - */ - fallback() payable external{ - require(!crowdsaleClosed); - uint amount = msg.value; - balanceOf[msg.sender] += amount; - amountRaised += amount; - tokenReward.transfer(msg.sender, amount / price); - emit FundTransfer(msg.sender, amount, true); - } - - /** - * 定义函数修改器modifier(作用和Python的装饰器很相似) - * 用于在函数执行前检查某种前置条件(判断通过之后才会继续执行该方法) - * _ 表示继续执行之后的代码 - **/ - modifier afterDeadline() { if (now >= deadline) _; } - - /** - * 判断众筹是否完成融资目标, 这个方法使用了afterDeadline函数修改器 - * - */ - function checkGoalReached() afterDeadline public{ - if (amountRaised >= fundingGoal) { - fundingGoalReached = true; - emit GoalReached(beneficiary, amountRaised); - } - crowdsaleClosed = true; - } - - - /** - * 完成融资目标时,融资款发送到收款方 - * 未完成融资目标时,执行退款 - * - */ - function safeWithdrawal() afterDeadline public{ - if (!fundingGoalReached) { - uint amount = balanceOf[msg.sender]; - balanceOf[msg.sender] = 0; - if (amount > 0) { - if (msg.sender.send(amount)) { - emit FundTransfer(msg.sender, amount, false); - } else { - balanceOf[msg.sender] = amount; - } - } - } - - if (fundingGoalReached && beneficiary == msg.sender) { - if (payable(beneficiary).send(amountRaised)) { - emit FundTransfer(beneficiary, amountRaised, false); - } else { - //If we fail to send the funds to beneficiary, unlock funders balance - fundingGoalReached = false; - } - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario006.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario006.sol deleted file mode 100644 index 6d6feeb8188..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario006.sol +++ /dev/null @@ -1,1963 +0,0 @@ - - -interface PlayerBookInterface { - function getPlayerID(address _addr) external returns (uint256); - function getPlayerName(uint256 _pID) external view returns (bytes32); - function getPlayerLAff(uint256 _pID) external view returns (uint256); - function getPlayerAddr(uint256 _pID) external view returns (address); - function getNameFee() external view returns (uint256); - function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); - function isDev(address _who) external view returns(bool); -} - - -/** -* @title -Name Filter- v0.1.9 -* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ -* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ -* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ -* _____ _____ -* (, / /) /) /) (, / /) /) -* ┌─┐ / _ (/_ // // / _ // _ __ _(/ -* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ -* ┴ ┴ / / .-/ _____ (__ / -* (__ / (_/ (, / /)™ -* / __ __ __ __ _ __ __ _ _/_ _ _(/ -* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ -* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 -* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ -* _ __ _ ____ ____ _ _ _____ ____ ___ -*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* -*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* -* -* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ -* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ -* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ -*/ - -library NameFilter { - /** - * @dev filters name strings - * -converts uppercase to lower case. - * -makes sure it does not start/end with a space - * -makes sure it does not contain multiple spaces in a row - * -cannot be only numbers - * -cannot start with 0x - * -restricts characters to A-Z, a-z, 0-9, and space. - * @return reprocessed string in bytes32 format - */ - function nameFilter(string memory _input) - internal - pure - returns(bytes32) - { - bytes memory _temp = bytes(_input); - uint256 _length = _temp.length; - - //sorry limited to 32 characters - require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); - // make sure it doesnt start with or end with space - require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); - // make sure first two characters are not 0x - if (_temp[0] == 0x30) - { - require(_temp[1] != 0x78, "string cannot start with 0x"); - require(_temp[1] != 0x58, "string cannot start with 0X"); - } - - // create a bool to track if we have a non number character - bool _hasNonNumber; - - // convert & check - for (uint256 i = 0; i < _length; i++) - { - // if its uppercase A-Z - if (_temp[i] > 0x40 && _temp[i] < 0x5b) - { - // convert to lower case a-z - _temp[i] = byte(uint8(_temp[i]) + 32); - - // we have a non number - if (_hasNonNumber == false) - _hasNonNumber = true; - } else { - require - ( - // require character is a space - _temp[i] == 0x20 || - // OR lowercase a-z - (_temp[i] > 0x60 && _temp[i] < 0x7b) || - // or 0-9 - (_temp[i] > 0x2f && _temp[i] < 0x3a), - "string contains invalid characters" - ); - // make sure theres not 2x spaces in a row - if (_temp[i] == 0x20) - require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); - - // see if we have a character other than a number - if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) - _hasNonNumber = true; - } - } - - require(_hasNonNumber == true, "string cannot be only numbers"); - - bytes32 _ret; - assembly { - _ret := mload(add(_temp, 32)) - } - return (_ret); - } -} - - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - if (a == 0) { - return 0; - } - c = a * b; - require(c / a == b, "SafeMath mul failed"); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return c; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { - require(b <= a, "SafeMath sub failed"); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - c = a + b; - require(c >= a, "SafeMath add failed"); - return c; - } - - /** - * @dev gives square root of given x. - */ - function sqrt(uint256 x) - internal - pure - returns (uint256 y) - { - uint256 z = ((add(x,1)) / 2); - y = x; - while (z < y) - { - y = z; - z = ((add((x / z),z)) / 2); - } - } - - /** - * @dev gives square. multiplies x by x - */ - function sq(uint256 x) - internal - pure - returns (uint256) - { - return (mul(x,x)); - } - - /** - * @dev x to the power of y - */ - function pwr(uint256 x, uint256 y) - internal - pure - returns (uint256) - { - if (x==0) - return (0); - else if (y==0) - return (1); - else - { - uint256 z = x; - for (uint256 i=1; i < y; i++) - z = mul(z,x); - return (z); - } - } -} - -//============================================================================== -// | _ _ _ | _ . -// |<(/_\/ (_(_||(_ . -//=======/====================================================================== -library F3DKeysCalcLong { - using SafeMath for *; - /** - * @dev calculates number of keys received given X eth - * @param _curEth current amount of eth in contract - * @param _newEth eth being spent - * @return amount of ticket purchased - */ - function keysRec(uint256 _curEth, uint256 _newEth) - internal - pure - returns (uint256) - { - return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); - } - - /** - * @dev calculates amount of eth received if you sold X keys - * @param _curKeys current amount of keys that exist - * @param _sellKeys amount of keys you wish to sell - * @return amount of eth received - */ - function ethRec(uint256 _curKeys, uint256 _sellKeys) - internal - pure - returns (uint256) - { - return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); - } - - /** - * @dev calculates how many keys would exist with given an amount of eth - * @param _eth eth "in contract" - * @return number of keys that would exist - */ - function keys(uint256 _eth) - internal - pure - returns(uint256) - { - return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); - } - - /** - * @dev calculates how much eth would be in contract given a number of keys - * @param _keys number of keys "in contract" - * @return eth that would exists - */ - function eth(uint256 _keys) - internal - pure - returns(uint256) - { - return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); - } -} - -library F3Ddatasets { - //compressedData key - // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] - // 0 - new player (bool) - // 1 - joined round (bool) - // 2 - new leader (bool) - // 3-5 - air drop tracker (uint 0-999) - // 6-16 - round end time - // 17 - winnerTeam - // 18 - 28 timestamp - // 29 - team - // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) - // 31 - airdrop happened bool - // 32 - airdrop tier - // 33 - airdrop amount won - //compressedIDs key - // [77-52][51-26][25-0] - // 0-25 - pID - // 26-51 - winPID - // 52-77 - rID - struct EventReturns { - uint256 compressedData; - uint256 compressedIDs; - address winnerAddr; // winner address - bytes32 winnerName; // winner name - uint256 amountWon; // amount won - uint256 newPot; // amount in new pot - uint256 P3DAmount; // amount distributed to p3d - uint256 genAmount; // amount distributed to gen - uint256 potAmount; // amount added to pot - } - struct Player { - address payable addr; // player address - bytes32 name; // player name - uint256 win; // winnings vault - uint256 gen; // general vault - uint256 aff; // affiliate vault - uint256 lrnd; // last round played - uint256 laff; // last affiliate id used - } - struct PlayerRounds { - uint256 eth; // eth player has added to round (used for eth limiter) - uint256 keys; // keys - uint256 mask; // player mask - uint256 ico; // ICO phase investment - } - struct Round { - uint256 plyr; // pID of player in lead - uint256 team; // tID of team in lead - uint256 end; // time ends/ended - bool ended; // has round end function been ran - uint256 strt; // time round started - uint256 keys; // keys - uint256 eth; // total eth in - uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) - uint256 mask; // global mask - uint256 ico; // total eth sent in during ICO phase - uint256 icoGen; // total eth for gen during ICO phase - uint256 icoAvg; // average key price for ICO phase - } - struct TeamFee { - uint256 gen; // % of buy in thats paid to key holders of current round - uint256 p3d; // % of buy in thats paid to p3d holders - } - struct PotSplit { - uint256 gen; // % of pot thats paid to key holders of current round - uint256 p3d; // % of pot thats paid to p3d holders - } -} - -contract F3Devents { - // fired whenever a player registers a name - event onNewName - ( - uint256 indexed playerID, - address indexed playerAddress, - bytes32 indexed playerName, - bool isNewPlayer, - uint256 affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 amountPaid, - uint256 timeStamp - ); - - // fired at end of buy or reload - event onEndTx - ( - uint256 compressedData, - uint256 compressedIDs, - bytes32 playerName, - address playerAddress, - uint256 ethIn, - uint256 keysBought, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount, - uint256 potAmount, - uint256 airDropPot - ); - - // fired whenever theres a withdraw - event onWithdraw - ( - uint256 indexed playerID, - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 timeStamp - ); - - // fired whenever a withdraw forces end round to be ran - event onWithdrawAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a buy after round timer - // hit zero, and causes end round to be ran. - event onBuyAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethIn, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a reload after round timer - // hit zero, and causes end round to be ran. - event onReLoadAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // fired whenever an affiliate is paid - event onAffiliatePayout - ( - uint256 indexed affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 indexed roundID, - uint256 indexed buyerID, - uint256 amount, - uint256 timeStamp - ); - - // received pot swap deposit - event onPotSwapDeposit - ( - uint256 roundID, - uint256 amountAddedToPot - ); -} - - - -contract FoMo3Dlong is F3Devents { - using SafeMath for *; - using NameFilter for string; - using F3DKeysCalcLong for uint256; - - address public otherF3D_; - address public Divies; - address public Jekyll_Island_Inc; - PlayerBookInterface public playerBook;// =PlayerBookInterface(0x0dcd2f752394c41875e259e00bb44fd505297caf);//new PlayerBook();// - // TeamJustInterface constant private teamJust = TeamJustInterface(0x3a5f8140b9213a0f733a6a639857c9df43ee3f5a);// new TeamJust();// - - //============================================================================== - // _ _ _ |`. _ _ _ |_ | _ _ . - // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) - //=================_|=========================================================== - string constant public name = "FoMo3D Long Official"; - string constant public symbol = "F3D"; - uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO - uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. - uint256 constant private rndInit_ = 1 hours; // round timer starts at this - uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer - uint256 constant private rndMax_ = 24 hours; // max length a round timer can be - //============================================================================== - // _| _ _|_ _ _ _ _|_ _ . - // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) - //=============================|================================================ - uint256 public airDropPot_; // person who gets the airdrop wins part of this pot - uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop - uint256 public rID_; // round id number / total rounds that have happened - //**************** - // PLAYER DATA - //**************** - mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address - mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name - mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data - mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id - mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) - //**************** - // ROUND DATA - //**************** - mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data - mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id - //**************** - // TEAM FEE DATA - //**************** - mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team - mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team - - function setPlayerBook(address _playerBook) external { - require(msg.sender == owner, 'only dev!'); - require(address(playerBook) == address(0), 'already set!'); - playerBook = PlayerBookInterface(_playerBook); - } - - address public owner; - - //============================================================================== - // _ _ _ __|_ _ __|_ _ _ . - // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) - //============================================================================== - constructor() - public - { - owner = msg.sender; - // Team allocation structures - // 0 = whales - // 1 = bears - // 2 = sneks - // 3 = bulls - - // Team allocation percentages - // (F3D, P3D) + (Pot , Referrals, Community) - // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. - fees_[0] = F3Ddatasets.TeamFee(30, 6); - //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[1] = F3Ddatasets.TeamFee(43, 0); - //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[2] = F3Ddatasets.TeamFee(56, 10); - //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[3] = F3Ddatasets.TeamFee(43, 8); - //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - - // how to split up the final pot based on which team was picked - // (F3D, P3D) - potSplit_[0] = F3Ddatasets.PotSplit(15, 10); - //48% to winner, 25% to next round, 2% to com - potSplit_[1] = F3Ddatasets.PotSplit(25, 0); - //48% to winner, 25% to next round, 2% to com - potSplit_[2] = F3Ddatasets.PotSplit(20, 20); - //48% to winner, 10% to next round, 2% to com - potSplit_[3] = F3Ddatasets.PotSplit(30, 10); - //48% to winner, 10% to next round, 2% to com - } - //============================================================================== - // _ _ _ _|. |`. _ _ _ . - // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) - //============================================================================== - /** - * @dev used to make sure no one can interact with contract until it has - * been activated. - */ - modifier isActivated() { - require(activated_ == true, "its not ready yet. check ?eta in discord"); - _; - } - - /** - * @dev prevents contracts from interacting with fomo3d - */ - modifier isHuman() { - address _addr = msg.sender; - uint256 _codeLength; - - assembly {_codeLength := extcodesize(_addr)} - require(_codeLength == 0, "sorry humans only"); - _; - } - - modifier onlyDevs() - { - require(playerBook.isDev(msg.sender) == true, "msg sender is not a dev"); - _; - } - - /** - * @dev sets boundaries for incoming tx - */ - modifier isWithinLimits(uint256 _eth) { - require(_eth >= 1000000000, "pocket lint: not a valid currency"); - require(_eth <= 100000000000000000000000, "no vitalik, no"); - _; - } - - //============================================================================== - // _ |_ |. _ |` _ __|_. _ _ _ . - // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) - //====|========================================================================= - /** - * @dev emergency buy uses last stored affiliate ID and team snek - */ - fallback() - isActivated() - isHuman() - isWithinLimits(msg.value) - external - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // buy core - buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); - } - - /** - * @dev converts all incoming ethereum to keys. - * -functionhash- 0x8f38f309 (using ID for affiliate) - * -functionhash- 0x98a0871d (using address for affiliate) - * -functionhash- 0xa65b37a1 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - */ - function buyXid(uint256 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affCode, _team, _eventData_); - } - - function buyXaddr(address _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - function buyXname(bytes32 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - /** - * @dev essentially the same as buy, but instead of you sending ether - * from your wallet, it uses your unwithdrawn earnings. - * -functionhash- 0x349cdcac (using ID for affiliate) - * -functionhash- 0x82bfc739 (using address for affiliate) - * -functionhash- 0x079ce327 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - * @param _eth amount of earnings to use (remainder returned to gen vault) - */ - function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affCode, _team, _eth, _eventData_); - } - - function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - /** - * @dev withdraws all of your earnings. - * -functionhash- 0x3ccfd60b - */ - function withdraw() - isActivated() - isHuman() - public - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // setup temp var for player eth - uint256 _eth; - - // check to see if round has ended and no one has run round end yet - if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // end the round (distributes pot) - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire withdraw and distribute event - emit F3Devents.onWithdrawAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eth, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - - // in any other situation - } else { - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // fire withdraw event - emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); - } - } - - /** - * @dev use these to register names. they are just wrappers that will send the - * registration requests to the PlayerBook contract. So registering here is the - * same as registering there. UI will always display the last name you registered. - * but you will still own all previously registered names to use as affiliate - * links. - * - must pay a registration fee. - * - name must be unique - * - names will be converted to lowercase - * - name cannot start or end with a space - * - cannot have more than 1 space in a row - * - cannot be only numbers - * - cannot start with 0x - * - name must be at least 1 char - * - max length of 32 characters long - * - allowed characters: a-z, 0-9, and space - * -functionhash- 0x921dec21 (using ID for affiliate) - * -functionhash- 0x3ddd4698 (using address for affiliate) - * -functionhash- 0x685ffd83 (using name for affiliate) - * @param _nameString players desired name - * @param _affCode affiliate ID, address, or name of who referred you - * @param _all set to true if you want this to push your info to all games - * (this might cost a lot of gas) - */ - function registerNameXID(string memory _nameString, uint256 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - - function registerNameXaddr(string memory _nameString, address _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - - function registerNameXname(string memory _nameString, bytes32 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - //============================================================================== - // _ _ _|__|_ _ _ _ . - // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) - //=====_|======================================================================= - /** - * @dev return the price buyer will pay for next 1 individual key. - * -functionhash- 0x018a25e8 - * @return price for next key bought (in wei format) - */ - function getBuyPrice() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); - else // rounds over. need price for new round - return (75000000000000); - // init - } - - /** - * @dev returns time left. dont spam this, you'll ddos yourself from your node - * provider - * -functionhash- 0xc7e284b8 - * @return time left in seconds - */ - function getTimeLeft() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - if (_now < round_[_rID].end) - if (_now > round_[_rID].strt + rndGap_) - return ((round_[_rID].end).sub(_now)); - else - return ((round_[_rID].strt + rndGap_).sub(_now)); - else - return (0); - } - - /** - * @dev returns player earnings per vaults - * -functionhash- 0x63066434 - * @return winnings vault - * @return general vault - * @return affiliate vault - */ - function getPlayerVaults(uint256 _pID) - public - view - returns (uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - // if round has ended. but round end has not been run (so contract has not distributed winnings) - if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // if player is winner - if (round_[_rID].plyr == _pID) - { - return - ( - (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - // if player is not the winner - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - } - - // if round is still going on, or round has ended and round end has been ran - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), - plyr_[_pID].aff - ); - } - } - - /** - * solidity hates stack limits. this lets us avoid that hate - */ - function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) - private - view - returns (uint256) - { - return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); - } - - /** - * @dev returns all current round info needed for front end - * -functionhash- 0x747dff42 - * @return eth invested during ICO phase - * @return round id - * @return total keys for round - * @return time round ends - * @return time round started - * @return current pot - * @return current team ID & player ID in lead - * @return current player in leads address - * @return current player in leads name - * @return whales eth in for round - * @return bears eth in for round - * @return sneks eth in for round - * @return bulls eth in for round - * @return airdrop tracker # & airdrop pot - */ - function getCurrentRoundInfo() - public - view - returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - return - ( - round_[_rID].ico, //0 - _rID, //1 - round_[_rID].keys, //2 - round_[_rID].end, //3 - round_[_rID].strt, //4 - round_[_rID].pot, //5 - (round_[_rID].team + (round_[_rID].plyr * 10)), //6 - plyr_[round_[_rID].plyr].addr, //7 - plyr_[round_[_rID].plyr].name, //8 - rndTmEth_[_rID][0], //9 - rndTmEth_[_rID][1], //10 - rndTmEth_[_rID][2], //11 - rndTmEth_[_rID][3], //12 - airDropTracker_ + (airDropPot_ * 1000) //13 - ); - } - - /** - * @dev returns player info based on address. if no address is given, it will - * use msg.sender - * -functionhash- 0xee0b5d8b - * @param _addr address of the player you want to lookup - * @return player ID - * @return player name - * @return keys owned (current round) - * @return winnings vault - * @return general vault - * @return affiliate vault - * @return player round eth - */ - function getPlayerInfoByAddress(address _addr) - public - view - returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - if (_addr == address(0)) - { - _addr == msg.sender; - } - uint256 _pID = pIDxAddr_[_addr]; - - return - ( - _pID, //0 - plyr_[_pID].name, //1 - plyrRnds_[_pID][_rID].keys, //2 - plyr_[_pID].win, //3 - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 - plyr_[_pID].aff, //5 - plyrRnds_[_pID][_rID].eth //6 - ); - } - - //============================================================================== - // _ _ _ _ | _ _ . _ . - // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) - //=====================_|======================================================= - /** - * @dev logic runs whenever a buy order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // call core - core(_rID, _pID, msg.value, _affID, _team, _eventData_); - - // if round is not active - } else { - // check to see if end round needs to be ran - if (_now > round_[_rID].end && round_[_rID].ended == false) - { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onBuyAndDistribute - ( - msg.sender, - plyr_[_pID].name, - msg.value, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - - // put eth in players vault - plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); - } - } - - /** - * @dev logic runs whenever a reload order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // get earnings from all vaults and return unused to gen vault - // because we use a custom safemath library. this will throw if player - // tried to spend more eth than they have. - plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); - - // call core - core(_rID, _pID, _eth, _affID, _team, _eventData_); - - // if round is not active and end round needs to be ran - } else if (_now > round_[_rID].end && round_[_rID].ended == false) { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onReLoadAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - } - - /** - * @dev this is the core logic for any buy/reload that happens while a round - * is live. - */ - function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // if player is new to round - if (plyrRnds_[_pID][_rID].keys == 0) - _eventData_ = managePlayer(_pID, _eventData_); - - // early round eth limiter - if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) - { - uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); - uint256 _refund = _eth.sub(_availableLimit); - plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); - _eth = _availableLimit; - } - - // if eth left is greater than min eth allowed (sorry no pocket lint) - if (_eth > 1000000000) - { - - // mint the new keys - uint256 _keys = (round_[_rID].eth).keysRec(_eth); - - // if they bought at least 1 whole key - if (_keys >= 1000000000000000000) - { - updateTimer(_keys, _rID); - - // set new leaders - if (round_[_rID].plyr != _pID) - round_[_rID].plyr = _pID; - if (round_[_rID].team != _team) - round_[_rID].team = _team; - - // set the new leader bool to true - _eventData_.compressedData = _eventData_.compressedData + 100; - } - - // manage airdrops - if (_eth >= 100000000000000000) - { - airDropTracker_++; - if (airdrop() == true) - { - // gib muni - uint256 _prize; - if (_eth >= 10000000000000000000) - { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(75)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(50)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 2 prize was won - _eventData_.compressedData += 200000000000000000000000000000000; - } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(25)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } - // set airdrop happened bool to true - _eventData_.compressedData += 10000000000000000000000000000000; - // let event know how much was won - _eventData_.compressedData += _prize * 1000000000000000000000000000000000; - - // reset air drop tracker - airDropTracker_ = 0; - } - } - - // store the air drop tracker number (number of buys since last airdrop) - _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); - - // update player - plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); - plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); - - // update round - round_[_rID].keys = _keys.add(round_[_rID].keys); - round_[_rID].eth = _eth.add(round_[_rID].eth); - rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); - - // distribute eth - _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); - _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); - - // call end tx function to fire end tx event. - endTx(_pID, _team, _eth, _keys, _eventData_); - } - } - //============================================================================== - // _ _ | _ | _ _|_ _ _ _ . - // (_(_||(_|_||(_| | (_)| _\ . - //============================================================================== - /** - * @dev calculates unmasked earnings (just calculates, does not update mask) - * @return earnings in wei format - */ - function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) - private - view - returns (uint256) - { - return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); - } - - /** - * @dev returns the amount of keys you would get given an amount of eth. - * -functionhash- 0xce89c80c - * @param _rID round ID you want price for - * @param _eth amount of eth sent in - * @return keys received - */ - function calcKeysReceived(uint256 _rID, uint256 _eth) - public - view - returns (uint256) - { - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].eth).keysRec(_eth)); - else // rounds over. need keys for new round - return ((_eth).keys()); - } - - /** - * @dev returns current eth price for X keys. - * -functionhash- 0xcf808000 - * @param _keys number of keys desired (in 18 decimal format) - * @return amount of eth needed to send - */ - function iWantXKeys(uint256 _keys) - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); - else // rounds over. need price for new round - return ((_keys).eth()); - } - //============================================================================== - // _|_ _ _ | _ . - // | (_)(_)|_\ . - //============================================================================== - /** - * @dev receives name/player info from names contract - */ - function receivePlayerInfo(uint256 _pID, address payable _addr, bytes32 _name, uint256 _laff) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (pIDxAddr_[_addr] != _pID) - pIDxAddr_[_addr] = _pID; - if (pIDxName_[_name] != _pID) - pIDxName_[_name] = _pID; - if (plyr_[_pID].addr != _addr) - plyr_[_pID].addr = _addr; - if (plyr_[_pID].name != _name) - plyr_[_pID].name = _name; - if (plyr_[_pID].laff != _laff) - plyr_[_pID].laff = _laff; - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev receives entire player name list - */ - function receivePlayerNameList(uint256 _pID, bytes32 _name) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev gets existing or registers new pID. use this when a player may be new - * @return pID - */ - function determinePID(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - uint256 _pID = pIDxAddr_[msg.sender]; - // if player is new to this version of fomo3d - if (_pID == 0) - { - // grab their player ID, name and last aff ID, from player names contract - _pID = playerBook.getPlayerID(msg.sender); - bytes32 _name = playerBook.getPlayerName(_pID); - uint256 _laff = playerBook.getPlayerLAff(_pID); - - // set up player account - pIDxAddr_[msg.sender] = _pID; - plyr_[_pID].addr = msg.sender; - - if (_name != "") - { - pIDxName_[_name] = _pID; - plyr_[_pID].name = _name; - plyrNames_[_pID][_name] = true; - } - - if (_laff != 0 && _laff != _pID) - plyr_[_pID].laff = _laff; - - // set the new player bool to true - _eventData_.compressedData = _eventData_.compressedData + 1; - } - return (_eventData_); - } - - /** - * @dev checks to make sure user picked a valid team. if not sets team - * to default (sneks) - */ - function verifyTeam(uint256 _team) - private - pure - returns (uint256) - { - if (_team < 0 || _team > 3) - return (2); - else - return (_team); - } - - /** - * @dev decides if round end needs to be run & new round started. and if - * player unmasked earnings from previously played rounds need to be moved. - */ - function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // if player has played a previous round, move their unmasked earnings - // from that round to gen vault. - if (plyr_[_pID].lrnd != 0) - updateGenVault(_pID, plyr_[_pID].lrnd); - - // update player's last round played - plyr_[_pID].lrnd = rID_; - - // set the joined round bool to true - _eventData_.compressedData = _eventData_.compressedData + 10; - - return (_eventData_); - } - - /** - * @dev ends the round. manages paying out winner/splitting up pot - */ - function endRound(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // setup local rID - uint256 _rID = rID_; - - // grab our winning player and team id's - uint256 _winPID = round_[_rID].plyr; - uint256 _winTID = round_[_rID].team; - - // grab our pot amount - uint256 _pot = round_[_rID].pot; - - // calculate our winner share, community rewards, gen share, - // p3d share, and amount reserved for next pot - uint256 _win = (_pot.mul(48)) / 100; - uint256 _com = (_pot / 50); - uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; - uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; - uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); - - // calculate ppt for round mask - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); - if (_dust > 0) - { - _gen = _gen.sub(_dust); - _res = _res.add(_dust); - } - - // pay our winner - plyr_[_winPID].win = _win.add(plyr_[_winPID].win); - - // community rewards - address payable add = address(uint160(Jekyll_Island_Inc)); - if (!add.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _p3d.add(_com); - _com = 0; - } - - // distribute gen portion to key holders - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // send share for p3d to divies - if (_p3d > 0){ - address payable addr = address(uint160(Divies)); - addr.transfer(_p3d); - } - // prepare event data - _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); - _eventData_.winnerAddr = plyr_[_winPID].addr; - _eventData_.winnerName = plyr_[_winPID].name; - _eventData_.amountWon = _win; - _eventData_.genAmount = _gen; - _eventData_.P3DAmount = _p3d; - _eventData_.newPot = _res; - - // start next round - rID_++; - _rID++; - round_[_rID].strt = now; - round_[_rID].end = now.add(rndInit_).add(rndGap_); - round_[_rID].pot = _res; - - return (_eventData_); - } - - /** - * @dev moves any unmasked earnings to gen vault. updates earnings mask - */ - function updateGenVault(uint256 _pID, uint256 _rIDlast) - private - { - uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); - if (_earnings > 0) - { - // put in gen vault - plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); - // zero out their earnings by updating mask - plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); - } - } - - /** - * @dev updates round timer based on number of whole keys bought. - */ - function updateTimer(uint256 _keys, uint256 _rID) - private - { - // grab time - uint256 _now = now; - - // calculate time based on number of keys bought - uint256 _newTime; - if (_now > round_[_rID].end && round_[_rID].plyr == 0) - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); - else - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); - - // compare to max and set new end time - if (_newTime < (rndMax_).add(_now)) - round_[_rID].end = _newTime; - else - round_[_rID].end = rndMax_.add(_now); - } - - /** - * @dev generates a random number between 0-99 and checks to see if thats - * resulted in an airdrop win - * @return do we have a winner? - */ - function airdrop() - private - view - returns (bool) - { - uint256 seed = uint256(keccak256(abi.encodePacked( - - (block.timestamp).add - (block.difficulty).add - ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add - (block.gaslimit).add - ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add - (block.number) - - ))); - if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) - return (true); - else - return (false); - } - - /** - * @dev distributes eth based on fees to com, aff, and p3d - */ - function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // pay 2% out to community rewards - uint256 _com = _eth / 50; - uint256 _p3d; - address payable addr = address(uint160(Jekyll_Island_Inc)); - if (!addr.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _com; - _com = 0; - } - - // pay 1% out to FoMo3D short - _com = _eth / 100; - address payable add = address(uint160(otherF3D_)); - add.transfer(_com); - - // distribute share to affiliate - _com = _eth / 10; - - // decide what to do with affiliate share of fees - // affiliate must not be self, and must have a name registered - if (_affID != _pID && plyr_[_affID].name != '') { - plyr_[_affID].aff = _com.add(plyr_[_affID].aff); - emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _com, now); - } else { - _p3d = _com; - } - - // pay out p3d - _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); - if (_p3d > 0) - { - // deposit to divies contract - address payable add = address(uint160(Divies)); - add.transfer(_p3d); - - // set up event data - _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); - } - - return (_eventData_); - } - - function potSwap() - external - payable - { - // setup local rID - uint256 _rID = rID_ + 1; - - round_[_rID].pot = round_[_rID].pot.add(msg.value); - emit F3Devents.onPotSwapDeposit(_rID, msg.value); - } - - /** - * @dev distributes eth based on fees to gen and pot - */ - function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // calculate gen share - uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; - - // toss 1% into airdrop pot - uint256 _air = (_eth / 100); - airDropPot_ = airDropPot_.add(_air); - - // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); - - // calculate pot - uint256 _pot = _eth.sub(_gen); - - // distribute gen share (thats what updateMasks() does) and adjust - // balances for dust. - uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); - if (_dust > 0) - _gen = _gen.sub(_dust); - - // add eth to pot - round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); - - // set up event data - _eventData_.genAmount = _gen.add(_eventData_.genAmount); - _eventData_.potAmount = _pot; - - return (_eventData_); - } - - /** - * @dev updates masks for round and player when keys are bought - * @return dust left over - */ - function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) - private - returns (uint256) - { - /* MASKING NOTES - earnings masks are a tricky thing for people to wrap their minds around. - the basic thing to understand here. is were going to have a global - tracker based on profit per share for each round, that increases in - relevant proportion to the increase in share supply. - - the player will have an additional mask that basically says "based - on the rounds mask, my shares, and how much i've already withdrawn, - how much is still owed to me?" - */ - - // calc profit per key & round mask based on this buy: (dust goes to pot) - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // calculate player earning from their own buy (only based on the keys - // they just bought). & update player earnings mask - uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); - plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); - - // calculate & return dust - return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); - } - - /** - * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 - * @return earnings in wei format - */ - function withdrawEarnings(uint256 _pID) - private - returns (uint256) - { - // update gen vault - updateGenVault(_pID, plyr_[_pID].lrnd); - - // from vaults - uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); - if (_earnings > 0) - { - plyr_[_pID].win = 0; - plyr_[_pID].gen = 0; - plyr_[_pID].aff = 0; - } - - return (_earnings); - } - - /** - * @dev prepares compression data and fires event for buy or reload tx's - */ - function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - { - _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); - - emit F3Devents.onEndTx - ( - _eventData_.compressedData, - _eventData_.compressedIDs, - plyr_[_pID].name, - msg.sender, - _eth, - _keys, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount, - _eventData_.potAmount, - airDropPot_ - ); - } - //============================================================================== - // (~ _ _ _._|_ . - // _)(/_(_|_|| | | \/ . - //====================/========================================================= - /** upon contract deploy, it will be deactivated. this is a one time - * use function that will activate the contract. we do this so devs - * have time to set things up on the web end **/ - bool public activated_ = false; - - function activate() - public - onlyDevs - { - - // can only be ran once - require(activated_ == false, "fomo3d already activated"); - - // activate the contract - activated_ = true; - - otherF3D_ = msg.sender; - Divies = msg.sender; - Jekyll_Island_Inc = msg.sender; - - // lets start first round - rID_ = 1; - round_[1].strt = now + rndExtra_ - rndGap_; - round_[1].end = now + rndInit_ + rndExtra_; - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario007.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario007.sol deleted file mode 100644 index a6fa095860f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario007.sol +++ /dev/null @@ -1,1432 +0,0 @@ - -/** - * @title ERC165 - * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md - */ -interface ERC165 { - - /** - * @notice Query if a contract implements an interface - * @param _interfaceId The interface identifier, as specified in ERC-165 - * @dev Interface identification is specified in ERC-165. This function - * uses less than 30,000 gas. - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool); - -} - -contract ERC721Basic is ERC165 { - - event Transfer( - address indexed _from, - address indexed _to, - uint256 indexed _tokenId - ); - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); - - function balanceOf(address _owner) public view returns (uint256 _balance); - function ownerOf(uint256 _tokenId) public view returns (address _owner); - function exists(uint256 _tokenId) public view returns (bool _exists); - - function approve(address _to, uint256 _tokenId) public; - function getApproved(uint256 _tokenId) - public view returns (address _operator); - - function setApprovalForAll(address _operator, bool _approved) public; - function isApprovedForAll(address _owner, address _operator) - public view returns (bool); - - function transferFrom(address _from, address _to, uint256 _tokenId) public; - function safeTransferFrom(address _from, address _to, uint256 _tokenId) - public; - - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public; -} - - -/** - * @title SupportsInterfaceWithLookup - * @author Matt Condon (@shrugs) - * @dev Implements ERC165 using a lookup table. - */ -contract SupportsInterfaceWithLookup is ERC165 { - bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; - /** - * 0x01ffc9a7 === - * bytes4(keccak256('supportsInterface(bytes4)')) - */ - - /** - * @dev a mapping of interface id to whether or not it's supported - */ - mapping(bytes4 => bool) internal supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself - */ - constructor() public { - _registerInterface(InterfaceId_ERC165); - } - - /** - * @dev implement supportsInterface(bytes4) using a lookup table - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool) { - return supportedInterfaces[_interfaceId]; - } - - /** - * @dev private method for registering an interface - */ - function _registerInterface(bytes4 _interfaceId) internal { - require(_interfaceId != 0xffffffff); - supportedInterfaces[_interfaceId] = true; - } -} - -contract Governable { - - event Pause(); - event Unpause(); - - address public governor; - bool public paused = false; - - constructor() public { - governor = msg.sender; - } - - function setGovernor(address _gov) public onlyGovernor { - governor = _gov; - } - - modifier onlyGovernor { - require(msg.sender == governor); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - */ - modifier whenPaused() { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyGovernor whenNotPaused public { - paused = true; - emit Pause(); - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyGovernor whenPaused public { - paused = false; - emit Unpause(); - } - -} - -contract CardBase is Governable { - - struct Card { - uint16 proto; - uint16 purity; - } - - function getCard(uint id) public view returns (uint16 proto, uint16 purity) { - Card memory card = cards[id]; - return (card.proto, card.purity); - } - - function getShine(uint16 purity) public pure returns (uint8) { - return uint8(purity / 1000); - } - - Card[] public cards; - -} - -contract CardProto is CardBase { - - event NewProtoCard( - uint16 id, uint8 season, uint8 god, - Rarity rarity, uint8 mana, uint8 attack, - uint8 health, uint8 cardType, uint8 tribe, bool packable - ); - - struct Limit { - uint64 limit; - bool exists; - } - - // limits for mythic cards - mapping(uint16 => Limit) public limits; - - // can only set limits once - function setLimit(uint16 id, uint64 limit) public onlyGovernor { - Limit memory l = limits[id]; - require(!l.exists); - limits[id] = Limit({ - limit: limit, - exists: true - }); - } - - function getLimit(uint16 id) public view returns (uint64 limit, bool set) { - Limit memory l = limits[id]; - return (l.limit, l.exists); - } - - // could make these arrays to save gas - // not really necessary - will be update a very limited no of times - mapping(uint8 => bool) public seasonTradable; - mapping(uint8 => bool) public seasonTradabilityLocked; - uint8 public currentSeason; - - function makeTradable(uint8 season) public onlyGovernor { - seasonTradable[season] = true; - } - - function makeUntradable(uint8 season) public onlyGovernor { - require(!seasonTradabilityLocked[season]); - seasonTradable[season] = false; - } - - function makePermanantlyTradable(uint8 season) public onlyGovernor { - require(seasonTradable[season]); - seasonTradabilityLocked[season] = true; - } - - function isTradable(uint16 proto) public view returns (bool) { - return seasonTradable[protos[proto].season]; - } - - function nextSeason() public onlyGovernor { - //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M - require(currentSeason <= 255); - - currentSeason++; - mythic.length = 0; - legendary.length = 0; - epic.length = 0; - rare.length = 0; - common.length = 0; - } - - enum Rarity { - Common, - Rare, - Epic, - Legendary, - Mythic - } - - uint8 constant SPELL = 1; - uint8 constant MINION = 2; - uint8 constant WEAPON = 3; - uint8 constant HERO = 4; - - struct ProtoCard { - bool exists; - uint8 god; - uint8 season; - uint8 cardType; - Rarity rarity; - uint8 mana; - uint8 attack; - uint8 health; - uint8 tribe; - } - - // there is a particular design decision driving this: - // need to be able to iterate over mythics only for card generation - // don't store 5 different arrays: have to use 2 ids - // better to bear this cost (2 bytes per proto card) - // rather than 1 byte per instance - - uint16 public protoCount; - - mapping(uint16 => ProtoCard) protos; - - uint16[] public mythic; - uint16[] public legendary; - uint16[] public epic; - uint16[] public rare; - uint16[] public common; - - function addProtos( - uint16[] memory externalIDs, uint8[] memory gods, Rarity[] memory rarities, uint8[] memory manas, uint8[] memory attacks, - uint8[] memory healths, uint8[] memory cardTypes, uint8[] memory tribes, bool[] memory packable - ) public onlyGovernor returns(uint16) { - - for (uint i = 0; i < externalIDs.length; i++) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: gods[i], - season: currentSeason, - cardType: cardTypes[i], - rarity: rarities[i], - mana: manas[i], - attack: attacks[i], - health: healths[i], - tribe: tribes[i] - }); - - _addProto(externalIDs[i], card, packable[i]); - } - - } - - function addProto( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: cardType, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function addWeapon( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: WEAPON, - rarity: rarity, - mana: mana, - attack: attack, - health: durability, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: SPELL, - rarity: rarity, - mana: mana, - attack: 0, - health: 0, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addMinion( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: MINION, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { - - require(!protos[externalID].exists); - - card.exists = true; - - protos[externalID] = card; - - protoCount++; - - emit NewProtoCard( - externalID, currentSeason, card.god, - card.rarity, card.mana, card.attack, - card.health, card.cardType, card.tribe, packable - ); - - if (packable) { - Rarity rarity = card.rarity; - if (rarity == Rarity.Common) { - common.push(externalID); - } else if (rarity == Rarity.Rare) { - rare.push(externalID); - } else if (rarity == Rarity.Epic) { - epic.push(externalID); - } else if (rarity == Rarity.Legendary) { - legendary.push(externalID); - } else if (rarity == Rarity.Mythic) { - mythic.push(externalID); - } else { - require(false); - } - } - } - - function getProto(uint16 id) public view returns( - bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) { - ProtoCard memory proto = protos[id]; - return ( - proto.exists, - proto.god, - proto.season, - proto.cardType, - proto.rarity, - proto.mana, - proto.attack, - proto.health, - proto.tribe - ); - } - - function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { - // modulo bias is fine - creates rarity tiers etc - // will obviously revert is there are no cards of that type: this is expected - should never happen - if (rarity == Rarity.Common) { - return common[random % common.length]; - } else if (rarity == Rarity.Rare) { - return rare[random % rare.length]; - } else if (rarity == Rarity.Epic) { - return epic[random % epic.length]; - } else if (rarity == Rarity.Legendary) { - return legendary[random % legendary.length]; - } else if (rarity == Rarity.Mythic) { - // make sure a mythic is available - uint16 id; - uint64 limit; - bool set; - for (uint i = 0; i < mythic.length; i++) { - id = mythic[(random + i) % mythic.length]; - (limit, set) = getLimit(id); - if (set && limit > 0){ - return id; - } - } - // if not, they get a legendary :( - return legendary[random % legendary.length]; - } - require(false); - return 0; - } - - // can never adjust tradable cards - // each season gets a 'balancing beta' - // totally immutable: season, rarity - function replaceProto( - uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) public onlyGovernor { - ProtoCard memory pc = protos[index]; - require(!seasonTradable[pc.season]); - protos[index] = ProtoCard({ - exists: true, - god: god, - season: pc.season, - cardType: cardType, - rarity: pc.rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - } - -} - -contract ERC721Receiver { - /** - * @dev Magic value to be returned upon successful reception of an NFT - * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, - * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - */ - bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; - - /** - * @notice Handle the receipt of an NFT - * @dev The ERC721 smart contract calls this function on the recipient - * after a `safetransfer`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the contract address is always the message sender. - * @param _operator The address which called `safeTransferFrom` function - * @param _from The address which previously owned the token - * @param _tokenId The NFT identifier which is being transfered - * @param _data Additional data with no specified format - * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - */ - function onERC721Received( - address _operator, - address _from, - uint256 _tokenId, - bytes memory _data - ) - public - returns(bytes4); -} - -library AddressUtils { - - /** - * Returns whether the target address is a contract - * @dev This function will return false if invoked during the constructor of a contract, - * as the code is not actually created until after the constructor finishes. - * @param addr address to check - * @return whether the target address is a contract - */ - function isContract1(address addr) internal view returns (bool) { - uint256 size; - // XXX Currently there is no better way to check if there is a contract in an address - // than to check the size of the code at that address. - // See https://ethereum.stackexchange.com/a/14016/36603 - // for more details about how this works. - // TODO Check this again before the Serenity release, because all addresses will be - // contracts then. - // solium-disable-next-line security/no-inline-assembly - assembly { size := extcodesize(addr) } - return size > 0; - } - -} - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { - // Gas optimization: this is cheaper than asserting 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 - if (a == 0) { - return 0; - } - - c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - // uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return a / b; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256 c) { - c = a + b; - assert(c >= a); - return c; - } -} - -contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic { - - bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; - /* - * 0x80ac58cd === - * bytes4(keccak256('balanceOf(address)')) ^ - * bytes4(keccak256('ownerOf(uint256)')) ^ - * bytes4(keccak256('approve(address,uint256)')) ^ - * bytes4(keccak256('getApproved(uint256)')) ^ - * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ - * bytes4(keccak256('isApprovedForAll(address,address)')) ^ - * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) - */ - - bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; - /* - * 0x4f558e79 === - * bytes4(keccak256('exists(uint256)')) - */ - - using SafeMath for uint256; - using AddressUtils for address; - - // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - bytes4 private constant ERC721_RECEIVED = 0x150b7a02; - - // Mapping from token ID to owner - mapping (uint256 => address) internal tokenOwner; - - // Mapping from token ID to approved address - mapping (uint256 => address) internal tokenApprovals; - - // Mapping from owner to number of owned token - // mapping (address => uint256) internal ownedTokensCount; - - // Mapping from owner to operator approvals - mapping (address => mapping (address => bool)) internal operatorApprovals; - - /** - * @dev Guarantees msg.sender is owner of the given token - * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender - */ - modifier onlyOwnerOf(uint256 _tokenId) { - require(ownerOf(_tokenId) == msg.sender); - _; - } - - /** - * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator - * @param _tokenId uint256 ID of the token to validate - */ - modifier canTransfer(uint256 _tokenId) { - require(isApprovedOrOwner(msg.sender, _tokenId)); - _; - } - - constructor() - public - { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721); - _registerInterface(InterfaceId_ERC721Exists); - } - - /** - * @dev Gets the balance of the specified address - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256); - - /** - * @dev Gets the owner of the specified token ID - * @param _tokenId uint256 ID of the token to query the owner of - * @return owner address currently marked as the owner of the given token ID - */ - function ownerOf(uint256 _tokenId) public view returns (address) { - address owner = tokenOwner[_tokenId]; - require(owner != address(0)); - return owner; - } - - /** - * @dev Returns whether the specified token exists - * @param _tokenId uint256 ID of the token to query the existence of - * @return whether the token exists - */ - function exists(uint256 _tokenId) public view returns (bool) { - address owner = tokenOwner[_tokenId]; - return owner != address(0); - } - - /** - * @dev Approves another address to transfer the given token ID - * The zero address indicates there is no approved address. - * There can only be one approved address per token at a given time. - * Can only be called by the token owner or an approved operator. - * @param _to address to be approved for the given token ID - * @param _tokenId uint256 ID of the token to be approved - */ - function approve(address _to, uint256 _tokenId) public { - address owner = ownerOf(_tokenId); - require(_to != owner); - require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); - - tokenApprovals[_tokenId] = _to; - emit Approval(owner, _to, _tokenId); - } - - /** - * @dev Gets the approved address for a token ID, or zero if no address set - * @param _tokenId uint256 ID of the token to query the approval of - * @return address currently approved for the given token ID - */ - function getApproved(uint256 _tokenId) public view returns (address) { - return tokenApprovals[_tokenId]; - } - - /** - * @dev Sets or unsets the approval of a given operator - * An operator is allowed to transfer all tokens of the sender on their behalf - * @param _to operator address to set the approval - * @param _approved representing the status of the approval to be set - */ - function setApprovalForAll(address _to, bool _approved) public { - require(_to != msg.sender); - operatorApprovals[msg.sender][_to] = _approved; - emit ApprovalForAll(msg.sender, _to, _approved); - } - - /** - * @dev Tells whether an operator is approved by a given owner - * @param _owner owner address which you want to query the approval of - * @param _operator operator address which you want to query the approval of - * @return bool whether the given operator is approved by the given owner - */ - function isApprovedForAll( - address _owner, - address _operator - ) - public - view - returns (bool) - { - return operatorApprovals[_owner][_operator]; - } - - /** - * @dev Transfers the ownership of a given token ID to another address - * Usage of this method is discouraged, use `safeTransferFrom` whenever possible - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - require(_from != address(0)); - require(_to != address(0)); - - clearApproval(_from, _tokenId); - removeTokenFrom(_from, _tokenId); - addTokenTo(_to, _tokenId); - - emit Transfer(_from, _to, _tokenId); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - // solium-disable-next-line arg-overflow - safeTransferFrom(_from, _to, _tokenId, ""); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes data to send along with a safe transfer check - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public - canTransfer(_tokenId) - { - transferFrom(_from, _to, _tokenId); - // solium-disable-next-line arg-overflow - require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); - } - - /** - * @dev Returns whether the given spender can transfer a given token ID - * @param _spender address of the spender to query - * @param _tokenId uint256 ID of the token to be transferred - * @return bool whether the msg.sender is approved for the given token ID, - * is an operator of the owner, or is the owner of the token - */ - function isApprovedOrOwner( - address _spender, - uint256 _tokenId - ) - internal - view - returns (bool) - { - address owner = ownerOf(_tokenId); - // Disable solium check because of - // https://github.com/duaraghav8/Solium/issues/175 - // solium-disable-next-line operator-whitespace - return ( - _spender == owner || - getApproved(_tokenId) == _spender || - isApprovedForAll(owner, _spender) - ); - } - - /** - * @dev Internal function to clear current approval of a given token ID - * Reverts if the given address is not indeed the owner of the token - * @param _owner owner of the token - * @param _tokenId uint256 ID of the token to be transferred - */ - function clearApproval(address _owner, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _owner); - if (tokenApprovals[_tokenId] != address(0)) { - tokenApprovals[_tokenId] = address(0); - } - } - - /** - * @dev Internal function to mint a new token - * Reverts if the given token ID already exists - * @param _to The address that will own the minted token - * @param _tokenId uint256 ID of the token to be minted by the msg.sender - */ - function _mint(address _to, uint256 _tokenId) internal { - require(_to != address(0)); - addNewTokenTo(_to, _tokenId); - emit Transfer(address(0), _to, _tokenId); - } - - - /** - * @dev Internal function to burn a specific token - * Reverts if the token does not exist - * @param _tokenId uint256 ID of the token being burned by the msg.sender - */ - function _burn(address _owner, uint256 _tokenId) internal { - clearApproval(_owner, _tokenId); - removeTokenFrom(_owner, _tokenId); - emit Transfer(_owner, address(0), _tokenId); - } - - function addNewTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - // ownedTokensCount[_to] = ownedTokensCount[_to].add(1); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _from); - // ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); - tokenOwner[_tokenId] = address(0); - } - - /** - * @dev Internal function to invoke `onERC721Received` on a target address - * The call is not executed if the target address is not a contract - * @param _from address representing the previous owner of the given token ID - * @param _to target address that will receive the tokens - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes optional data to send along with the call - * @return whether the call correctly returned the expected magic value - */ - function checkAndCallSafeTransfer( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - internal - returns (bool) - { - if (!_to.isContract1()) { - return true; - } - bytes4 retval = ERC721Receiver(_to).onERC721Received( - msg.sender, _from, _tokenId, _data); - return (retval == ERC721_RECEIVED); - } - -} - - - -contract ERC721Enumerable is ERC721Basic { - function totalSupply() public view returns (uint256); - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256 _tokenId); - - function tokenByIndex(uint256 _index) public view returns (uint256); -} - -contract ERC721Metadata is ERC721Basic { - function name() external view returns (string memory _name); - function symbol() external view returns (string memory _symbol); - function tokenURI(uint256 _tokenId) public view returns (string memory); -} - -contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { - -} - - - - -library Strings { - - // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory ) { - bytes memory _ba = bytes(_a); - bytes memory _bb = bytes(_b); - bytes memory _bc = bytes(_c); - bytes memory _bd = bytes(_d); - bytes memory _be = bytes(_e); - string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); - bytes memory babcde = bytes(abcde); - uint k = 0; - for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; - for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; - for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; - for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; - for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; - return string(babcde); - } - - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, _d, ""); - } - - function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, "", ""); - } - - function strConcat(string memory _a, string memory _b) internal pure returns (string memory ) { - return strConcat(_a, _b, "", "", ""); - } - - function uint2str(uint i) internal pure returns (string memory ) { - if (i == 0) return "0"; - uint j = i; - uint len; - while (j != 0){ - len++; - j /= 10; - } - bytes memory bstr = new bytes(len); - uint k = len - 1; - while (i != 0){ - bstr[k--] = byte(uint8(48 + i % 10)); - i /= 10; - } - return string(bstr); - } -} - -contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { - - using Strings for string; - - bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; - /** - * 0x780e9d63 === - * bytes4(keccak256('totalSupply()')) ^ - * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ - * bytes4(keccak256('tokenByIndex(uint256)')) - */ - - bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; - /** - * 0x5b5e139f === - * bytes4(keccak256('name()')) ^ - * bytes4(keccak256('symbol()')) ^ - * bytes4(keccak256('tokenURI(uint256)')) - */ - - /*** Constants ***/ - // Configure these for your own deployment - string public constant NAME = "Gods Unchained"; - string public constant SYMBOL = "GODS"; - string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/"; - - // Mapping from owner to list of owned token IDs - // EDITED: limit to 2^40 (around 1T) - mapping(address => uint40[]) internal ownedTokens; - - uint32[] ownedTokensIndex; - - /** - * @dev Constructor function - */ - constructor() public { - - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721Enumerable); - _registerInterface(InterfaceId_ERC721Metadata); - } - - /** - * @dev Gets the token name - * @return string representing the token name - */ - function name() external view returns (string memory) { - return NAME; - } - - /** - * @dev Gets the token symbol - * @return string representing the token symbol - */ - function symbol() external view returns (string memory) { - return SYMBOL; - } - - /** - * @dev Returns an URI for a given token ID - * Throws if the token ID does not exist. May return an empty string. - * @param _tokenId uint256 ID of the token to query - */ - function tokenURI(uint256 _tokenId) public view returns (string memory) { - return Strings.strConcat( - tokenMetadataBaseURI, - Strings.uint2str(_tokenId) - ); - } - - /** - * @dev Gets the token ID at a given index of the tokens list of the requested owner - * @param _owner address owning the tokens list to be accessed - * @param _index uint256 representing the index to be accessed of the requested tokens list - * @return uint256 token ID at the given index of the tokens list owned by the requested address - */ - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256) - { - require(_index < balanceOf(_owner)); - return ownedTokens[_owner][_index]; - } - - /** - * @dev Gets the total amount of tokens stored by the contract - * @return uint256 representing the total amount of tokens - */ - function totalSupply() public view returns (uint256) { - return cards.length; - } - - /** - * @dev Gets the token ID at a given index of all the tokens in this contract - * Reverts if the index is greater or equal to the total number of tokens - * @param _index uint256 representing the index to be accessed of the tokens list - * @return uint256 token ID at the given index of the tokens list - */ - function tokenByIndex(uint256 _index) public view returns (uint256) { - require(_index < totalSupply()); - return _index; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - super.addTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - - ownedTokensIndex[_tokenId] = uint32(length); - } - - // EDITED - // have to have in order to use array rather than mapping - function addNewTokenTo(address _to, uint256 _tokenId) internal { - super.addNewTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - ownedTokensIndex.push(uint32(length)); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - super.removeTokenFrom(_from, _tokenId); - - uint32 tokenIndex = ownedTokensIndex[_tokenId]; - uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); - uint40 lastToken = ownedTokens[_from][lastTokenIndex]; - - ownedTokens[_from][tokenIndex] = lastToken; - ownedTokens[_from][lastTokenIndex] = 0; - // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to - // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping - // the lastToken to the first position, and then dropping the element placed in the last position of the list - - ownedTokens[_from].length--; - ownedTokensIndex[_tokenId] = 0; - ownedTokensIndex[lastToken] = tokenIndex; - } - - /** - * @dev Gets the balance of the specified address - overrriden from previous to save gas - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256) { - return ownedTokens[_owner].length; - } - -} - -contract CardOwnershipTwo is ERC721Token { - - uint public burnCount; - - function getActiveCards() public view returns (uint) { - return totalSupply() - burnCount; - } - - /** - * @param to : the address to which the card will be transferred - * @param id : the id of the card to be transferred - */ - function transfer(address to, uint id) public payable onlyOwnerOf(id) { - require(isTradable(cards[id].proto)); - require(to != address(0)); - - _transfer(msg.sender, to, id); - } - - function _transfer(address from, address to, uint id) internal { - - clearApproval(from, id); - - removeTokenFrom(from, id); - - addTokenTo(to, id); - - emit Transfer(from, to, id); - } - - /** - * @param to : the address to which the cards will be transferred - * @param ids : the ids of the cards to be transferred - */ - function transferAll(address to, uint[] memory ids) public payable { - for (uint i = 0; i < ids.length; i++) { - transfer(to, ids[i]); - } - } - - /** - * @param proposed : the claimed owner of the cards - * @param ids : the ids of the cards to check - * @return whether proposed owns all of the cards - */ - function ownsAll(address proposed, uint[] memory ids) public view returns (bool) { - require(ids.length > 0); - for (uint i = 0; i < ids.length; i++) { - if (!owns(proposed, ids[i])) { - return false; - } - } - return true; - } - - /** - * @param proposed : the claimed owner of the card - * @param id : the id of the card to check - * @return whether proposed owns the card - */ - function owns(address proposed, uint id) public view returns (bool) { - return ownerOf(id) == proposed; - } - - function burn(uint id) public onlyOwnerOf(id) { - burnCount++; - _burn(msg.sender, id); - } - - /** - * @param ids : the indices of the tokens to burn - */ - function burnAll(uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++){ - burn(ids[i]); - } - } - - /** - * @param to : the address to approve for transfer - * @param id : the index of the card to be approved - */ - function approve(address to, uint id) public { - require(isTradable(cards[id].proto)); - super.approve(to, id); - } - - /** - * @param to : the address to approve for transfer - * @param ids : the indices of the cards to be approved - */ - function approveAll(address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - approve(to, ids[i]); - } - } - - /** - * @param to : the address to which the token should be transferred - * @param id : the index of the token to transfer - */ - function transferFrom(address from, address to, uint id) public { - require(isTradable(cards[id].proto)); - super.transferFrom(from, to, id); - } - - /** - * @param to : the address to which the tokens should be transferred - * @param ids : the indices of the tokens to transfer - */ - function transferAllFrom(address from, address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - transferFrom(from, to, ids[i]); - } - } - - /** - * @return the number of cards which have been burned - */ - function getBurnCount() public view returns (uint) { - return burnCount; - } - -} - -contract CardIntegrationTwo is CardOwnershipTwo { - - address[] public packs; - - event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); - - function addPack(address approved) public onlyGovernor { - packs.push(approved); - } - - modifier onlyApprovedPacks { - require(_isApprovedPack()); - _; - } - - function _isApprovedPack() private view returns (bool) { - for (uint i = 0; i < packs.length; i++) { - if (msg.sender == address(packs[i])) { - return true; - } - } - return false; - } - - function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { - ProtoCard memory card = protos[proto]; - require(card.season == currentSeason); - if (card.rarity == Rarity.Mythic) { - uint64 limit; - bool exists; - (limit, exists) = getLimit(proto); - require(!exists || limit > 0); - limits[proto].limit--; - } - return _createCard(owner, proto, purity); - } - - function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { - Card memory card = Card({ - proto: proto, - purity: purity - }); - - uint id = cards.push(card) - 1; - - _mint(owner, id); - - emit CardCreated(id, proto, purity, owner); - - return id; - } - - /*function combineCards(uint[] ids) public whenNotPaused { - require(ids.length == 5); - require(ownsAll(msg.sender, ids)); - Card memory first = cards[ids[0]]; - uint16 proto = first.proto; - uint8 shine = _getShine(first.purity); - require(shine < shineLimit); - uint16 puritySum = first.purity - (shine * 1000); - burn(ids[0]); - for (uint i = 1; i < ids.length; i++) { - Card memory next = cards[ids[i]]; - require(next.proto == proto); - require(_getShine(next.purity) == shine); - puritySum += (next.purity - (shine * 1000)); - burn(ids[i]); - } - uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); - _createCard(msg.sender, proto, newPurity); - }*/ - - - // PURITY NOTES - // currently, we only - // however, to protect rarity, you'll never be abl - // this is enforced by the restriction in the create-card function - // no cards above this point can be found in packs - - - -} - -contract PreviousInterface { - - function ownerOf(uint id) public view returns (address); - - function getCard(uint id) public view returns (uint16, uint16); - - function totalSupply() public view returns (uint); - - function burnCount() public view returns (uint); - -} - -contract CardMigration is CardIntegrationTwo { - - constructor(PreviousInterface previous) public { - old = previous; - } - - // use interface to lower deployment cost - PreviousInterface old; - - mapping(uint => bool) public migrated; - - function migrate(uint id) public { - - require(!migrated[id]); - - migrated[id] = true; - - address owner = old.ownerOf(id); - - uint16 proto; - uint16 purity; - - (proto, purity) = old.getCard(id); - - _createCard(owner, proto, purity); - } - - function migrateAll(uint[] memory ids) public { - - for (uint i = 0; i < ids.length; i++){ - migrate(ids[i]); - } - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario008.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario008.sol deleted file mode 100644 index d039f7393d2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario008.sol +++ /dev/null @@ -1,2061 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() virtual public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - kitties.push(_kitty); - uint256 newKittenId = kitties.length - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -abstract contract ERC721 { - // Required methods - function totalSupply() virtual public view returns (uint256 total); - function balanceOf(address _owner) virtual public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) virtual external view returns (address owner); - function approve(address _to, uint256 _tokenId) virtual external; - function transfer(address _to, uint256 _tokenId) virtual external; - function transferFrom(address _from, address _to, uint256 _tokenId) virtual external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) virtual external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external override view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public override view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() override public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - override - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - -/// @notice No tipping! -/// @dev Reject all Ether from being sent here, unless it's from one of the -/// two auction contracts. (Hopefully, we can prevent user accidents.) -fallback() external payable { -require( -msg.sender == address(saleAuction) || -msg.sender == address(siringAuction) -); -} - -/// @notice Returns all the relevant information about a specific kitty. -/// @param _id The ID of the kitty of interest. -function getKitty(uint256 _id) -external -view -returns ( -bool isGestating, -bool isReady, -uint256 cooldownIndex, -uint256 nextActionAt, -uint256 siringWithId, -uint256 birthTime, -uint256 matronId, -uint256 sireId, -uint256 generation, -uint256 genes -) { -Kitty storage kit = kitties[_id]; - -// if this variable is 0 then it's not gestating -isGestating = (kit.siringWithId != 0); -isReady = (kit.cooldownEndBlock <= block.number); -cooldownIndex = uint256(kit.cooldownIndex); -nextActionAt = uint256(kit.cooldownEndBlock); -siringWithId = uint256(kit.siringWithId); -birthTime = uint256(kit.birthTime); -matronId = uint256(kit.matronId); -sireId = uint256(kit.sireId); -generation = uint256(kit.generation); -genes = kit.genes; -} - -/// @dev Override unpause so it requires all external contract addresses -/// to be set before contract can be unpaused. Also, we can't have -/// newContractAddress set either, because then the contract was upgraded. -/// @notice This is public rather than external so we can call super.unpause -/// without using an expensive CALL. - -function unpause() override public onlyCEO whenPaused { -require(address(saleAuction) != address(0)); -require(address(siringAuction) != address(0)); -require(address(geneScience) != address(0)); -require(newContractAddress == address(0)); - -// Actually unpause the contract. -super.unpause(); -} - -// @dev Allows the CFO to capture the balance available to the contract. -function withdrawBalance() external onlyCFO { -uint256 balance = address(this).balance; -// Subtract all the currently pregnant kittens we have, plus 1 of margin. -uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - -if (balance > subtractFees) { -cfoAddress.transfer(balance - subtractFees); -} -} -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - -function isGeneScience() public pure returns (bool){ -return true; -} - -/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor -/// @param genes1 genes of mom -/// @param genes2 genes of sire -/// @return the genes that are supposed to be passed down the child -function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - -return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { -/// @dev Given a token Id, returns a byte array that is supposed to be converted into string. -function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { -if (_tokenId == 1) { -buffer[0] = "Hello World! :D"; -count = 15; -} else if (_tokenId == 2) { -buffer[0] = "I would definitely choose a medi"; -buffer[1] = "um length string."; -count = 49; -} else if (_tokenId == 3) { -buffer[0] = "Lorem ipsum dolor sit amet, mi e"; -buffer[1] = "st accumsan dapibus augue lorem,"; -buffer[2] = " tristique vestibulum id, libero"; -buffer[3] = " suscipit varius sapien aliquam."; -count = 128; -} -} -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - -// Represents an auction on an NFT -struct Auction { -// Current owner of NFT -address payable seller; -// Price (in wei) at beginning of auction -uint128 startingPrice; -// Price (in wei) at end of auction -uint128 endingPrice; -// Duration (in seconds) of auction -uint64 duration; -// Time when auction started -// NOTE: 0 if this auction has been concluded -uint64 startedAt; -} - -// Reference to contract tracking NFT ownership -ERC721 public nonFungibleContract; - -// Cut owner takes on each auction, measured in basis points (1/100 of a percent). -// Values 0-10,000 map to 0%-100% -uint256 public ownerCut; - -// Map from token ID to their corresponding auction. -mapping (uint256 => Auction) tokenIdToAuction; - -event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); -event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); -event AuctionCancelled(uint256 tokenId); - -/// @dev Returns true if the claimant owns the token. -/// @param _claimant - Address claiming to own the token. -/// @param _tokenId - ID of token whose ownership to verify. -function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { -return (nonFungibleContract.ownerOf(_tokenId) == _claimant); -} - -/// @dev Escrows the NFT, assigning ownership to this contract. -/// Throws if the escrow fails. -/// @param _owner - Current owner address of token to escrow. -/// @param _tokenId - ID of token whose approval to verify. -function _escrow(address _owner, uint256 _tokenId) internal { -// it will throw if transfer fails -nonFungibleContract.transferFrom(_owner, address(this), _tokenId); -} - -/// @dev Transfers an NFT owned by this contract to another address. -/// Returns true if the transfer succeeds. -/// @param _receiver - Address to transfer NFT to. -/// @param _tokenId - ID of token to transfer. -function _transfer(address _receiver, uint256 _tokenId) internal { -// it will throw if transfer fails -nonFungibleContract.transfer(_receiver, _tokenId); -} - -/// @dev Adds an auction to the list of open auctions. Also fires the -/// AuctionCreated event. -/// @param _tokenId The ID of the token to be put on auction. -/// @param _auction Auction to add. -function _addAuction(uint256 _tokenId, Auction memory _auction) internal { -// Require that all auctions have a duration of -// at least one minute. (Keeps our math from getting hairy!) -require(_auction.duration >= 1 minutes); - -tokenIdToAuction[_tokenId] = _auction; - -emit AuctionCreated( -uint256(_tokenId), -uint256(_auction.startingPrice), -uint256(_auction.endingPrice), -uint256(_auction.duration) -); -} - -/// @dev Cancels an auction unconditionally. -function _cancelAuction(uint256 _tokenId, address _seller) internal { -_removeAuction(_tokenId); -_transfer(_seller, _tokenId); -emit AuctionCancelled(_tokenId); -} - -/// @dev Computes the price and transfers winnings. -/// Does NOT transfer ownership of token. -function _bid(uint256 _tokenId, uint256 _bidAmount) -internal -returns (uint256) -{ -// Get a reference to the auction struct -Auction storage auction = tokenIdToAuction[_tokenId]; - -// Explicitly check that this auction is currently live. -// (Because of how Ethereum mappings work, we can't just count -// on the lookup above failing. An invalid _tokenId will just -// return an auction object that is all zeros.) -require(_isOnAuction(auction)); - -// Check that the bid is greater than or equal to the current price -uint256 price = _currentPrice(auction); -require(_bidAmount >= price); - -// Grab a reference to the seller before the auction struct -// gets deleted. -address payable seller = auction.seller; - -// The bid is good! Remove the auction before sending the fees -// to the sender so we can't have a reentrancy attack. -_removeAuction(_tokenId); - -// Transfer proceeds to seller (if there are any!) -if (price > 0) { -// Calculate the auctioneer's cut. -// (NOTE: _computeCut() is guaranteed to return a -// value <= price, so this subtraction can't go negative.) -uint256 auctioneerCut = _computeCut(price); -uint256 sellerProceeds = price - auctioneerCut; - -// NOTE: Doing a transfer() in the middle of a complex -// method like this is generally discouraged because of -// reentrancy attacks and DoS attacks if the seller is -// a contract with an invalid fallback function. We explicitly -// guard against reentrancy attacks by removing the auction -// before calling transfer(), and the only thing the seller -// can DoS is the sale of their own asset! (And if it's an -// accident, they can call cancelAuction(). ) -seller.transfer(sellerProceeds); -} - -// Calculate any excess funds included with the bid. If the excess -// is anything worth worrying about, transfer it back to bidder. -// NOTE: We checked above that the bid amount is greater than or -// equal to the price so this cannot underflow. -uint256 bidExcess = _bidAmount - price; - -// Return the funds. Similar to the previous transfer, this is -// not susceptible to a re-entry attack because the auction is -// removed before any transfers occur. -msg.sender.transfer(bidExcess); - -// Tell the world! -emit AuctionSuccessful(_tokenId, price, msg.sender); - -return price; -} - -/// @dev Removes an auction from the list of open auctions. -/// @param _tokenId - ID of NFT on auction. -function _removeAuction(uint256 _tokenId) internal { -delete tokenIdToAuction[_tokenId]; -} - -/// @dev Returns true if the NFT is on auction. -/// @param _auction - Auction to check. -function _isOnAuction(Auction storage _auction) internal view returns (bool) { -return (_auction.startedAt > 0); -} - -/// @dev Returns current price of an NFT on auction. Broken into two -/// functions (this one, that computes the duration from the auction -/// structure, and the other that does the price computation) so we -/// can easily test that the price computation works correctly. -function _currentPrice(Auction storage _auction) -internal -view -returns (uint256) -{ -uint256 secondsPassed = 0; - -// A bit of insurance against negative values (or wraparound). -// Probably not necessary (since Ethereum guarnatees that the -// now variable doesn't ever go backwards). -if (now > _auction.startedAt) { -secondsPassed = now - _auction.startedAt; -} - -return _computeCurrentPrice( -_auction.startingPrice, -_auction.endingPrice, -_auction.duration, -secondsPassed -); -} - -/// @dev Computes the current price of an auction. Factored out -/// from _currentPrice so we can run extensive unit tests. -/// When testing, make this function public and turn on -/// `Current price computation` test suite. -function _computeCurrentPrice( -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -uint256 _secondsPassed -) -internal -pure -returns (uint256) -{ -// NOTE: We don't use SafeMath (or similar) in this function because -// all of our public functions carefully cap the maximum values for -// time (at 64-bits) and currency (at 128-bits). _duration is -// also known to be non-zero (see the require() statement in -// _addAuction()) -if (_secondsPassed >= _duration) { -// We've reached the end of the dynamic pricing portion -// of the auction, just return the end price. -return _endingPrice; -} else { -// Starting price can be higher than ending price (and often is!), so -// this delta can be negative. -int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - -// This multiplication can't overflow, _secondsPassed will easily fit within -// 64-bits, and totalPriceChange will easily fit within 128-bits, their product -// will always fit within 256-bits. -int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - -// currentPriceChange can be negative, but if so, will have a magnitude -// less that _startingPrice. Thus, this result will always end up positive. -int256 currentPrice = int256(_startingPrice) + currentPriceChange; - -return uint256(currentPrice); -} -} - -/// @dev Computes owner's cut of a sale. -/// @param _price - Sale price of NFT. -function _computeCut(uint256 _price) internal view returns (uint256) { -// NOTE: We don't use SafeMath (or similar) in this function because -// all of our entry functions carefully cap the maximum values for -// currency (at 128-bits), and ownerCut <= 10000 (see the require() -// statement in the ClockAuction constructor). The result of this -// function is always guaranteed to be <= _price. -return _price * ownerCut / 10000; -} - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { -event Pause(); -event Unpause(); - -bool public paused = false; - - -/** - * @dev modifier to allow actions only when the contract IS paused - */ -modifier whenNotPaused() { -require(!paused); -_; -} - -/** - * @dev modifier to allow actions only when the contract IS NOT paused - */ -modifier whenPaused { -require(paused); -_; -} - -/** - * @dev called by the owner to pause, triggers stopped state - */ -function pause() onlyOwner whenNotPaused public returns (bool) { -paused = true; -emit Pause(); -return true; -} - -/** - * @dev called by the owner to unpause, returns to normal state - */ -function unpause() onlyOwner whenPaused public returns (bool) { -paused = false; -emit Unpause(); -return true; -} -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - -/// @dev The ERC-165 interface signature for ERC-721. -/// Ref: https://github.com/ethereum/EIPs/issues/165 -/// Ref: https://github.com/ethereum/EIPs/issues/721 -bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - -/// @dev Constructor creates a reference to the NFT ownership contract -/// and verifies the owner cut is in the valid range. -/// @param _nftAddress - address of a deployed contract implementing -/// the Nonfungible Interface. -/// @param _cut - percent cut the owner takes on each auction, must be -/// between 0-10,000. -constructor(address _nftAddress, uint256 _cut) public { -require(_cut <= 10000); -ownerCut = _cut; - -ERC721 candidateContract = ERC721(_nftAddress); -require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); -nonFungibleContract = candidateContract; -} - -/// @dev Remove all Ether from the contract, which is the owner's cuts -/// as well as any Ether sent directly to the contract address. -/// Always transfers to the NFT contract, but can be called either by -/// the owner or the NFT contract. -function withdrawBalance() external { -address payable nftAddress = address(uint160(address(nonFungibleContract))); - -require( -msg.sender == owner || -msg.sender == nftAddress -); -// We are using this boolean method to make sure that even if one fails it will still work -bool res = nftAddress.send(address(this).balance); -} - -/// @dev Creates and begins a new auction. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of time to move between starting -/// price and ending price (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -virtual -external -whenNotPaused -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(_owns(msg.sender, _tokenId)); -_escrow(msg.sender, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(now) -); -_addAuction(_tokenId, auction); -} - -/// @dev Bids on an open auction, completing the auction and transferring -/// ownership of the NFT if enough Ether is supplied. -/// @param _tokenId - ID of token to bid on. -function bid(uint256 _tokenId) -external -payable -whenNotPaused -virtual -{ -// _bid will throw if the bid or funds transfer fails -_bid(_tokenId, msg.value); -_transfer(msg.sender, _tokenId); -} - -/// @dev Cancels an auction that hasn't been won yet. -/// Returns the NFT to original owner. -/// @notice This is a state-modifying function that can -/// be called while the contract is paused. -/// @param _tokenId - ID of token on auction -function cancelAuction(uint256 _tokenId) -external -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -address seller = auction.seller; -require(msg.sender == seller); -_cancelAuction(_tokenId, seller); -} - -/// @dev Cancels an auction when the contract is paused. -/// Only the owner may do this, and NFTs are returned to -/// the seller. This should only be used in emergencies. -/// @param _tokenId - ID of the NFT on auction to cancel. -function cancelAuctionWhenPaused(uint256 _tokenId) -whenPaused -onlyOwner -external -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -_cancelAuction(_tokenId, auction.seller); -} - -/// @dev Returns auction info for an NFT on auction. -/// @param _tokenId - ID of NFT on auction. -function getAuction(uint256 _tokenId) -external -view -returns -( -address seller, -uint256 startingPrice, -uint256 endingPrice, -uint256 duration, -uint256 startedAt -) { -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -return ( -auction.seller, -auction.startingPrice, -auction.endingPrice, -auction.duration, -auction.startedAt -); -} - -/// @dev Returns the current price of an auction. -/// @param _tokenId - ID of the token price we are checking. -function getCurrentPrice(uint256 _tokenId) -external -view -returns (uint256) -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -return _currentPrice(auction); -} - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - -// @dev Sanity check that allows us to ensure that we are pointing to the -// right auction in our setSiringAuctionAddress() call. -bool public isSiringClockAuction = true; - -// Delegate constructor -constructor(address _nftAddr, uint256 _cut) public -ClockAuction(_nftAddr, _cut) {} - -/// @dev Creates and begins a new auction. Since this function is wrapped, -/// require sender to be KittyCore contract. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of auction (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -override -external -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(msg.sender == address(nonFungibleContract)); -_escrow(_seller, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(now) -); -_addAuction(_tokenId, auction); -} - -/// @dev Places a bid for siring. Requires the sender -/// is the KittyCore contract because all bid methods -/// should be wrapped. Also returns the kitty to the -/// seller rather than the winner. -function bid(uint256 _tokenId) -external -payable -override -{ -require(msg.sender == address(nonFungibleContract)); -address seller = tokenIdToAuction[_tokenId].seller; -// _bid checks that token ID is valid and will throw if bid fails -_bid(_tokenId, msg.value); -// We transfer the kitty back to the seller, the winner will get -// the offspring -_transfer(seller, _tokenId); -} - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - -// @dev Sanity check that allows us to ensure that we are pointing to the -// right auction in our setSaleAuctionAddress() call. -bool public isSaleClockAuction = true; - -// Tracks last 5 sale price of gen0 kitty sales -uint256 public gen0SaleCount; -uint256[5] public lastGen0SalePrices; - -// Delegate constructor -constructor(address _nftAddr, uint256 _cut) public -ClockAuction(_nftAddr, _cut) {} - -/// @dev Creates and begins a new auction. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of auction (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -override -external -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(msg.sender == address(nonFungibleContract)); -_escrow(_seller, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(now) -); -_addAuction(_tokenId, auction); -} - -/// @dev Updates lastSalePrice if seller is the nft contract -/// Otherwise, works the same as default bid method. -function bid(uint256 _tokenId) -external -override -payable -{ -// _bid verifies token ID size -address seller = tokenIdToAuction[_tokenId].seller; -uint256 price = _bid(_tokenId, msg.value); -_transfer(msg.sender, _tokenId); - -// If not a gen0 auction, exit -if (seller == address(nonFungibleContract)) { -// Track gen0 sale prices -lastGen0SalePrices[gen0SaleCount % 5] = price; -gen0SaleCount++; -} -} - -function averageGen0SalePrice() external view returns (uint256) { -uint256 sum = 0; -for (uint256 i = 0; i < 5; i++) { -sum += lastGen0SalePrices[i]; -} -return sum / 5; -} - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario009.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario009.sol deleted file mode 100644 index 52fa63e90ac..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario009.sol +++ /dev/null @@ -1,51 +0,0 @@ - - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert (Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register(uint value) public { - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario010.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario010.sol deleted file mode 100644 index 4e299efecad..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario010.sol +++ /dev/null @@ -1,107 +0,0 @@ - - -contract TRON_ERC721 { - //name - function name() view public returns (string memory name){ - return "Tron ERC721 Token"; - } - //symbol - function symbol() view public returns (string memory symbol){ - return "T721T"; - } - - //totalSupply - - function totalSupply() view public returns (uint256 supply){ - uint256 totalSupply = 1000000000000; - return totalSupply; - } - - mapping(address => uint) private balances; - function balanceOf(address _owner) view public returns (uint balance) - { - return balances[_owner]; - } - - - mapping(uint256 => address) private tokenOwners; - mapping(uint256 => bool) private tokenExists; - function ownerOf(uint256 _tokenId) view public returns (address owner) { - require(tokenExists[_tokenId]); - return tokenOwners[_tokenId]; - } - - - mapping(address => mapping (address => uint256)) allowed; - function approve(address _to, uint256 _tokenId) public{ - require(msg.sender == ownerOf(_tokenId)); - require(msg.sender != _to); - allowed[msg.sender][_to] = _tokenId; - emit Approval(msg.sender, _to, _tokenId); - } - - - function takeOwnership(uint256 _tokenId) public { - require(tokenExists[_tokenId]); - address oldOwner = ownerOf(_tokenId); - address newOwner = msg.sender; - require(newOwner != oldOwner); - require(allowed[oldOwner][newOwner] == _tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - mapping(address => mapping(uint256 => uint256)) private ownerTokens; - function removeFromTokenList(address owner, uint256 _tokenId) private { - for(uint256 i = 0;ownerTokens[owner][i] != _tokenId;i++){ - ownerTokens[owner][i] = 0; - } - } - - function transfer(address _to, uint256 _tokenId) public{ - address currentOwner = msg.sender; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - function transferFrom(address _from,address _to, uint256 _tokenId) public{ - address currentOwner = _from; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - function tokenOfOwnerByIndex(address _owner, uint256 _index) view public returns (uint tokenId){ - return ownerTokens[_owner][_index]; - } - - - mapping(uint256 => string) tokenLinks; - function tokenMetadata(uint256 _tokenId) view public returns (string memory infoUrl) { - return tokenLinks[_tokenId]; - } - // Events - event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); - event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario011.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario011.sol deleted file mode 100644 index 041d298cf32..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario011.sol +++ /dev/null @@ -1,2060 +0,0 @@ - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public virtual onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - kitties.push(_kitty); - uint256 newKittenId = kitties.length - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -abstract contract ERC721 { - // Required methods - function totalSupply() public virtual view returns (uint256 total); - function balanceOf(address _owner) public virtual view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external virtual view returns (address owner); - function approve(address _to, uint256 _tokenId) external virtual; - function transfer(address _to, uint256 _tokenId) external virtual; - function transferFrom(address _from, address _to, uint256 _tokenId) external virtual; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external virtual view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external override view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view override returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - override - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - override - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public override view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - override - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 ; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 ; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause() public override onlyCEO whenPaused { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - - } -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - virtual - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - virtual - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - override - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - override - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - override - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - override - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario012.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario012.sol deleted file mode 100644 index 7fea2b1ccf1..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario012.sol +++ /dev/null @@ -1,57 +0,0 @@ - -contract PayTest { - -uint256 public n; -constructor() payable public{ -n = 0; -} - -function nPlusOne() public{ -n = n+1; -} - -//get current contract balance -function getBalance() payable public returns (uint) { -return address(this).balance; -} - -function getSenderBalance() public view returns(address, uint) { -return (msg.sender, msg.sender.balance); -} - -address public user; - -//deposit 1 coin to msg.sender -function depositOneCoin() payable public returns(bool success){ -return msg.sender.send(1); -} - -// function transferOneCoin() payable public returns(){ -// address(msg.sender).transfer(1); -// } - -// function depositOneCoin() payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(1)); -// } - -//deposit coin to msg.sender -function deposit(uint256 money) payable public returns(bool success){ -return msg.sender.send(money); -} -// function deposit(uint money) payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(money)); -// } - -// fallback() payable { -// msg.sender.send(1); -// } - -function sendToAddress(address payable _receiver) payable public{ -_receiver.transfer(msg.value); -} - -function sendToAddress2(address payable _receiver) payable public{ -_receiver.transfer(5); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario013.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario013.sol deleted file mode 100644 index 93b7905679b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario013.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract timetest { - -function time() public{ -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractScenario014.sol b/framework/src/test/resources/soliditycode_0.6.12/contractScenario014.sol deleted file mode 100644 index 9f423d1b1ab..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractScenario014.sol +++ /dev/null @@ -1,34 +0,0 @@ - -contract Contract1 { - constructor() public payable{} - function send5SunToReceiver(address payable _receiver) payable public{ - _receiver.transfer(5); - } -} -contract contract2 { - address public payContract; - - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract1(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - } - - function triggerContract1ButRevert(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - require(1 == 2); - } - -} -contract contract3 { - address public payContract; - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract2(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("triggerContract1(address)",_receiver)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTest.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTest.sol deleted file mode 100644 index 9a72b4a53b4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTest.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract Test{ - -function a() public returns (uint){ - -uint256 count = 0; - -for (uint256 i = 1; i > 0; i++) { - -count++; - -} - -return count; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode_0.6.12/contractToMathedFeed.sol deleted file mode 100644 index d9df9d9c10d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractToMathedFeed.sol +++ /dev/null @@ -1,21 +0,0 @@ - - -contract ToMathedFeed { - uint public i=1; - function ToMathed (uint value) public { - i=value; - } -} - -contract ToMathedUseINContract { - function ToMathedIUseNR(address a,uint256 n) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathedNot(uint256)",n)); - return success; - } - function ToMathedIUseNRE(address a,uint256 value) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathed(uint256)",value)); - return success; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTransferToken001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTransferToken001.sol deleted file mode 100644 index 0edbbfbb44a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTransferToken001.sol +++ /dev/null @@ -1,22 +0,0 @@ -contract A { - address public a; - constructor() public payable{} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - function newB() public payable returns(address){ - B bAddress=new B(); - a= address(bAddress); - return a; - - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken001.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken001.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken001.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken002.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken002.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken002.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken003.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken003.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken003.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken005.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken005.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken005.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken011.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken011.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken011.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken012.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken012.sol deleted file mode 100644 index ab0c19767e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken012.sol +++ /dev/null @@ -1,26 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken014.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken014.sol deleted file mode 100644 index 589406c47c6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken014.sol +++ /dev/null @@ -1,34 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken018.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken018.sol deleted file mode 100644 index ab0c19767e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken018.sol +++ /dev/null @@ -1,26 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken023.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken023.sol deleted file mode 100644 index 070acb201ff..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken023.sol +++ /dev/null @@ -1,26 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external { - flag = 1; -} - -} - -contract C{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable { - //flag = 1; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken026.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken026.sol deleted file mode 100644 index 5464265d81f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken026.sol +++ /dev/null @@ -1,31 +0,0 @@ - - -contract token{ - constructor() payable public{} - fallback() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - //callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - fallback() external payable{} - function transC(address payable callCAddress,address payable toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - fallback() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken027.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken027.sol deleted file mode 100644 index e7d6ee768f3..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken027.sol +++ /dev/null @@ -1,30 +0,0 @@ - - -contract token{ - constructor() payable public{} - fallback() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - fallback() external payable{} - function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - fallback() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken028.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken028.sol deleted file mode 100644 index 0f27d89c819..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken028.sol +++ /dev/null @@ -1,25 +0,0 @@ - - -contract token{ - uint256 public a=1; - constructor() public payable{} - function tokenBalanceWithSameName(trcToken id) public payable{ - B b= new B(); - a= b.tokenBalance(id); - } - function getA() public returns(uint256){ - return a; - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - fallback() external payable{} - function tokenBalance(trcToken id) payable public returns(uint256){ - flag =9; - return flag; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken029.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken029.sol deleted file mode 100644 index 8480cf6f19d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken029.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract token{ - address public a; - constructor() public payable{} - function transferTokenWithSameName(trcToken id,uint256 amount) public payable{ - B b= new B(); - b.transferToken(amount,id); - a= address(b); - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - fallback() external payable{} - function transferToken(uint256 amount, trcToken id) payable public returns(bool){ - flag =9; - } - function getFlag() public view returns (uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken030.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken030.sol deleted file mode 100644 index 06b8201979c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken030.sol +++ /dev/null @@ -1,17 +0,0 @@ - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken031.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken031.sol deleted file mode 100644 index 65ec394e8da..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken031.sol +++ /dev/null @@ -1,18 +0,0 @@ - - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken034.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken034.sol deleted file mode 100644 index 32c55f8c84b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken034.sol +++ /dev/null @@ -1,25 +0,0 @@ - - - contract token{ - - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken035.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken035.sol deleted file mode 100644 index ca45dde790d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken035.sol +++ /dev/null @@ -1,24 +0,0 @@ - - - contract token{ - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036.sol deleted file mode 100644 index c1da2f7555e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036.sol +++ /dev/null @@ -1,52 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate1 { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -fallback() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_1.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_1.sol deleted file mode 100644 index 327ab5a756e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_1.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_2.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_2.sol deleted file mode 100644 index 817a96e3c80..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_2.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_3.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_3.sol deleted file mode 100644 index 67400c2e8ad..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_3.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_4.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_4.sol deleted file mode 100644 index cbaca0d4b38..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_4.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -event log(uint256); -constructor() payable public{} -fallback() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_old.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_old.sol deleted file mode 100644 index 1f03afb7636..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken036_old.sol +++ /dev/null @@ -1,41 +0,0 @@ - - - -contract IllegalDecorate1 { -constructor() payable public{} -fallback() payable public{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -fallback() payable public{} -event log(uint256); -function transferTokenWithView(address toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -fallback() payable public{} -function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken037.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken037.sol deleted file mode 100644 index 7cdd91702e8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken037.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - require(0==address(this).tokenBalance(msg.tokenid)); - require(bamount+aamount==rec.tokenBalance(msg.tokenid)); - (bool success, bytes memory data) =rec.call(abi.encodeWithSignature("checkTrc10(uint256,trcToken,uint256)",bamount+aamount,msg.tokenid,0)); - require(success); - - } -} - -contract receiveTrc10 { - fallback() external payable {} - function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ - require(amount==address(this).tokenBalance(tid)); - require(meamount==msg.sender.tokenBalance(tid)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken038.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken038.sol deleted file mode 100644 index eeb5ae744cf..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken038.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - //require(rec.call(abi.encode(bytes4(keccak256("AssertError()"))))); - (bool suc, bytes memory data) = rec.call(abi.encodeWithSignature("AssertError()")); - require(suc); - require(aamount==address(this).tokenBalance(msg.tokenid)); - require(bamount==rec.tokenBalance(msg.tokenid)); - } -} - -contract receiveTrc10 { - fallback() external payable { - } - function AssertError() public{ - assert(1==2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken039.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken039.sol deleted file mode 100644 index ebf6fb932ed..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken039.sol +++ /dev/null @@ -1,44 +0,0 @@ - -/* - * 1. caller账户issue一个token - * 2. caller部署proxy, 传入1000 token,1000 trx - * 3. caller部署A - * 4. caller部署B - * 5. caller调用proxy中upgradetTo函数,传入A的地址 - * 6. caller调用proxy中不存在的trans(uint256,address,trcToken)函数,注意这时trcToken是无意义的,但也带上tokenid。address是任意另外某账户的地址 - * 7. 可以看到目标地址trx增长5,caller账户trx减少5 - * 8. caller调用proxy中upgradeTo函数,传入B的地址 - * 9. caller调用proxy中不存在的trans(uint256,address,trcToken)函数。 - * 10. 可以看到目标地址token增长5,caller账户token减少5 -*/ -contract Proxy { - constructor() payable public{} - address public implementation; - function upgradeTo(address _address) public { - implementation = _address; - } - fallback() payable external{ - address addr = implementation; - require(addr != address(0)); - assembly { - let freememstart := mload(0x40) - calldatacopy(freememstart, 0, calldatasize()) - let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 0) - returndatacopy(freememstart, 0, returndatasize()) - switch success - case 0 { revert(freememstart, returndatasize()) } - default { return(freememstart, returndatasize()) } - } - } -} - -contract A { - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transfer(amount); - } -} -contract B{ - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transferToken(amount,id); - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken041.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken041.sol deleted file mode 100644 index 6284253d1d5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken041.sol +++ /dev/null @@ -1,20 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} - - function setFlag() public payable{ - flag = 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken043.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken043.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken043.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken048.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken048.sol deleted file mode 100644 index e705f696c1d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken048.sol +++ /dev/null @@ -1,14 +0,0 @@ - - - contract Test { - event log(uint256); - function testMsgTokenValue() payable public returns(uint256 value) { - emit log(msg.tokenvalue); - return msg.tokenvalue; - } - - function testMsgValue() payable public returns(uint256 value) { - emit log(msg.value); - return msg.value; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken049.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken049.sol deleted file mode 100644 index d40480720df..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken049.sol +++ /dev/null @@ -1,9 +0,0 @@ - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken050.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken050.sol deleted file mode 100644 index 6bc6d956898..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken050.sol +++ /dev/null @@ -1,10 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken051.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken051.sol deleted file mode 100644 index 493016b777f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken051.sol +++ /dev/null @@ -1,11 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - fallback() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken052.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken052.sol deleted file mode 100644 index 6bc6d956898..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken052.sol +++ /dev/null @@ -1,10 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken054.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken054.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken054.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken055.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken055.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken055.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken060.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken060.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken060.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken061.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken061.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken061.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken064.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken064.sol deleted file mode 100644 index 43e0da8a510..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken064.sol +++ /dev/null @@ -1,49 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } - function transferTokenTestValueMaxBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0); - } - function transferTokenTestValueOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775808, 1000001); - } - function transferTokenTestValueMaxLong(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775807, 1000001); - } - function transferTokenTestValue0IdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0, 9223372036854775809); - } -} - - - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken066.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken066.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken066.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken067.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken067.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken067.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken073.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken073.sol deleted file mode 100644 index a9ee8ea412b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken073.sol +++ /dev/null @@ -1,16 +0,0 @@ - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - fallback() payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken075.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken075.sol deleted file mode 100644 index 9f201900295..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken075.sol +++ /dev/null @@ -1,26 +0,0 @@ - - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMin() payable public{ - // long.min - 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(-9223372036855775828)), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMax() payable public{ - // long.max + 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); - } - - fallback() payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken076.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken076.sol deleted file mode 100644 index a9decbee320..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken076.sol +++ /dev/null @@ -1,19 +0,0 @@ - -contract Test { - address public origin; - address public sender; - bool public result1; - bool public result2; - function test() external { - origin = tx.origin; - sender = msg.sender; - result1 = msg.sender == tx.origin; // true - result2 = origin == sender; // true - } -function getResult1() public returns(bool){ - return result1; -} -function getResult2() public returns(bool){ - return result2; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken077.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken077.sol deleted file mode 100644 index aeecf9cb9a5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken077.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract trcToken077 { -function addressTest() public returns(bytes32 addressValue) { - assembly{ - let x := mload(0x40) //Find empty storage location using "free memory pointer" - mstore(x,address) //Place current contract address - addressValue := mload(x) - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken078.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken078.sol deleted file mode 100644 index 02ba4a79699..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken078.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract callerContract { - constructor() public payable{} - fallback() external payable{} - function sendToB(address called_address, address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - contract calledContract { - fallback() external payable{} - constructor() public payable {} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call.value(5)(abi.encode(bytes4(keccak256("setI()")))); - } - - } - contract c{ - address public origin; - address public sender; - constructor() public payable{} - event log(address,address); - fallback() payable external{ - emit log(tx.origin,msg.sender); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken079.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken079.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken079.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken080.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken080.sol deleted file mode 100644 index 2d2688b74a4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcToken080.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - fallback() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode_0.6.12/contractTrcTokenToOther.sol deleted file mode 100644 index 8e926d3ba17..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractTrcTokenToOther.sol +++ /dev/null @@ -1,44 +0,0 @@ - - -contract ConvertType { - -constructor() payable public{} - -fallback() payable external{} - -//function trcTokenOnStorage(trcToken storage token) internal { // ERROR: Data location can only be specified for array, struct or mapping types, but "storage" was given. -//} - -function trcTokenToString(trcToken token) public pure returns(string memory s){ -// s = token; // ERROR -// s = string(token); // ERROR -} - -function trcTokenToUint256(trcToken token) public pure returns(uint256 r){ -uint256 u = token; // OK -uint256 u2 = uint256(token); // OK -r = u2; -} - -function trcTokenToAddress(trcToken token) public pure returns(address r){ -//r = token; // ERROR -token = 0x1234567812345678123456781234567812345678123456781234567812345678; -address a2 = address(token); // OK -r = a2; -} - -function trcTokenToBytes(trcToken token) public pure returns(bytes memory r){ -//r = token; // ERROR -// r = bytes(token); // ERROR -} - -function trcTokenToBytes32(trcToken token) public pure returns(bytes32 r){ -// r = token; // ERROR -bytes32 b2 = bytes32(token); // OK -r = b2; -} - -function trcTokenToArray(trcToken token) public pure returns(uint[] memory r){ -//r = token; // ERROR -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/contractUnknownException.sol b/framework/src/test/resources/soliditycode_0.6.12/contractUnknownException.sol deleted file mode 100644 index 4fd9c64be72..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/contractUnknownException.sol +++ /dev/null @@ -1,64 +0,0 @@ - -contract testA { - constructor() public payable { - A a = (new A).value(10)(); - a.fun(); - } -} - -contract testB { - constructor() public payable { - B b = (new B).value(10)(); - b.fun(); - } -} - - -contract testC { - constructor() public payable{ - C c = (new C).value(10)(); - c.fun(); - } -} - -contract testD { - constructor() public payable{ - D d = (new D).value(10)(); - d.fun(); - } -} - - -contract A { - constructor() public payable{ - selfdestruct(msg.sender); - } - function fun() public { - } - -} - -contract B { - constructor() public payable { - revert(); - } - function fun() public { - } -} - - -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} - -contract D { - constructor() public payable { - require(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/create2CallContract.sol b/framework/src/test/resources/soliditycode_0.6.12/create2CallContract.sol deleted file mode 100644 index 046706ebd9e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/create2CallContract.sol +++ /dev/null @@ -1,37 +0,0 @@ -contract callerContract { - constructor() payable public{} - fallback() payable external{} - function delegateCallCreate2(address called_address, bytes memory code, uint256 salt) public { - called_address.delegatecall(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } - function callCreate2(address called_address,bytes memory code, uint256 salt) public returns(bool,bytes memory){ - return called_address.call(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } -} - - -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/create2Istanbul.sol b/framework/src/test/resources/soliditycode_0.6.12/create2Istanbul.sol deleted file mode 100644 index c2ef8f3236b..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/create2Istanbul.sol +++ /dev/null @@ -1,28 +0,0 @@ - - -contract create2Istanbul { - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - - } - return addr; - } - - // prefix in main net is 0x41, testnet config is 0xa0 - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } - -} - -contract B { - constructor() public payable{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/create2contract.sol b/framework/src/test/resources/soliditycode_0.6.12/create2contract.sol deleted file mode 100644 index 0171f4d5486..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/create2contract.sol +++ /dev/null @@ -1,52 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract FactoryBytes { - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/create2contract22.sol b/framework/src/test/resources/soliditycode_0.6.12/create2contract22.sol deleted file mode 100644 index c33cb08edc3..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/create2contract22.sol +++ /dev/null @@ -1,109 +0,0 @@ -contract Factory { - event Deployed(address addr, trcToken salt, address sender); - event Deployed1(address addr, uint8 salt, address sender); - event Deployed2(address addr, address salt, address sender); - event Deployed3(address addr, string salt, address sender); - - - function deploy(bytes memory code, trcToken salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function deploy1(bytes memory code, uint8 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed1(addr, salt, msg.sender); - return addr; - } - - function deploy2(bytes memory code, address salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed2(addr, salt, msg.sender); - return addr; - } - - function deploy3(bytes memory code, string memory salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed3(addr, salt, msg.sender); - return addr; - } - -} - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract1 { - uint public i=2; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract2 { - uint public i=3; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract3 { - uint public i=4; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/create2contractn.sol b/framework/src/test/resources/soliditycode_0.6.12/create2contractn.sol deleted file mode 100644 index e0e3ae64c16..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/create2contractn.sol +++ /dev/null @@ -1,29 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/create2contractn2.sol b/framework/src/test/resources/soliditycode_0.6.12/create2contractn2.sol deleted file mode 100644 index 626988c4e04..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/create2contractn2.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function set() payable public { - i=5; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/demo.sol b/framework/src/test/resources/soliditycode_0.6.12/demo.sol deleted file mode 100644 index 06bf15387fc..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/demo.sol +++ /dev/null @@ -1,73 +0,0 @@ - - - contract tokenTest{ - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - } - codesize = m; - } - - // positive case - function pulsone() public payable{ - uint256 j = 0; - uint i = 100; - for (; i < i; i++) { - j++; - } - } - - - function getCodeSize() public returns (uint256){ - return codesize; - } - - } - - contract confirmTest{ - - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - - } - codesize = m; - } - - function getCodeSize() public returns (uint256){ - return codesize; - } - - function confirm(address addr) public returns (uint256){ - uint256 j; - assembly { - j := extcodesize(addr) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return j; - } - - function at(address _addr) public returns (bytes memory o_code) { - assembly { - // retrieve the size of the code, this needs assembly - let size := extcodesize(_addr) - // allocate output byte array - this could also be done without assembly - // by using o_code = new bytes(size) - o_code := mload(0x40) - // new "memory end" including padding - mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) - // store length in memory - mstore(o_code, size) - // actually retrieve the code, this needs assembly - extcodecopy(_addr, add(o_code, 0x20), 0, size) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/enumAndStruct.sol b/framework/src/test/resources/soliditycode_0.6.12/enumAndStruct.sol deleted file mode 100644 index 836a4ac850e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/enumAndStruct.sol +++ /dev/null @@ -1,43 +0,0 @@ - - -struct S_out { -uint x; -} - -enum ErrorType { -Revert_Error, //0 -RevertWithMsg_Error, //1 -Require_Error, //2 -RequirewithMsg_Error, //3 -Assert_Error, //4 -Tansfer_Error, //5 -Send_Error, //6 -Math_Error, //7 -ArrayOverFlow_Error //8 -} - -contract enumAndStructTest { - -struct S_inner { -int x; -} - -enum ErrorType_inner { -Revert_Error, //0 -RevertWithMsg_Error, //1 -Require_Error, //2 -RequirewithMsg_Error, //3 -Assert_Error, //4 -Tansfer_Error, //5 -Send_Error, //6 -Math_Error, //7 -ArrayOverFlow_Error //8 -} - -function getvalue() public returns(uint) { - require(ErrorType.Require_Error == ErrorType(2)); - S_out memory s = S_out(1); - return s.x; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/event001.sol b/framework/src/test/resources/soliditycode_0.6.12/event001.sol deleted file mode 100644 index 7662df3a5c6..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/event001.sol +++ /dev/null @@ -1,10 +0,0 @@ -contract Event { - event xixi(uint256 id) ; - event log2(uint256,uint256,uint256); - constructor() public payable{} - function messageI() payable public returns (uint ret) { - //emit log2(1,2,3); - emit xixi(1); - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/event002.sol b/framework/src/test/resources/soliditycode_0.6.12/event002.sol deleted file mode 100644 index a61f834e1b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/event002.sol +++ /dev/null @@ -1,52 +0,0 @@ - - -contract Event { - - event _0(); - event a_0() anonymous; - event a_4i(uint256 indexed x1, uint256 indexed x2 , uint256 indexed x3, uint256 indexed x4, uint256 x5)anonymous ; - event _3i(uint256 x1, uint256 indexed x2 , uint256 indexed x3, uint256 x4, uint256 x5) ; - event _1i(uint256 indexed x1, uint256, uint256 indexed, uint256 x4) ; - event a_1i(uint256) anonymous; - event _ai(uint8[2], uint8) ; - event a_ai(uint8[2], uint8) anonymous; - event _a1i(uint8[2] indexed, uint8) ; - event a_a1i(uint8[2] indexed, uint8) anonymous; - - constructor () public { - // emit a_0(); - // emit a_1i(123); - // emit a_4i(1,2,3,5,16); - // emit _0(); - emit _3i(1,2,3,5,16); - // emit _1i(1,2,3,5); - // emit _ai([1,2], 3); - // emit a_ai([3,4], 5); - // emit _a1i([1,2], 3); - // emit a_a1i([3,4], 5); - } - - function e() public { - emit _1i(1,2,3,4); - } - - function l() public { - emit a_1i(1); - } - - function k() public{ - emit a_4i(2,3,4,5,17); - emit _3i(2,3,4,5,16); - emit _1i(2,3,4,5); - emit a_1i(128); - emit _0(); - emit a_0(); - //selfdestruct(msg.sender); - //emit a_4i(1,2,3,5,16); - //emit _3i(1,2,3,5,16); - //emit _1i(1,2,3,5); - //emit a_1i(123); - //emit _0(); - //emit a_0(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/extCodeHash.sol b/framework/src/test/resources/soliditycode_0.6.12/extCodeHash.sol deleted file mode 100644 index d6209770682..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/extCodeHash.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract TestExtCodeHash { - - function getCodeHashByAddr(address _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } - function getCodeHashByUint(uint256 _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/extCodeHash11.sol b/framework/src/test/resources/soliditycode_0.6.12/extCodeHash11.sol deleted file mode 100644 index ad59f6cce1c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/extCodeHash11.sol +++ /dev/null @@ -1,103 +0,0 @@ -contract Counter { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} -revert(); -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract Counter1 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter2 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} - addr.call(abi.encodeWithSignature("testSuicideNonexistentTarget(address)",c)); - - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter3 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract TestConstract { - uint public i=1; - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/extCodeHashConstruct.sol b/framework/src/test/resources/soliditycode_0.6.12/extCodeHashConstruct.sol deleted file mode 100644 index 6bb91b3d3b1..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/extCodeHashConstruct.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract CounterConstruct { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore); - constructor() public{ - owner = msg.sender; - address addr = address(this); - bytes32 _hashBefore; - assembly { - _hashBefore := extcodehash(addr) - } - emit LogResult(_hashBefore); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/extCodeHashStress.sol b/framework/src/test/resources/soliditycode_0.6.12/extCodeHashStress.sol deleted file mode 100644 index cf41f3c8106..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/extCodeHashStress.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract Trigger { - function test(address addr) public returns(uint i) { - bytes32 hash; - while (gasleft() > 1000) { - assembly { - hash := extcodehash(addr) - } - i++; - } - } - - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - assembly { - hash := extcodehash(addr) - } - } - return i; - } - } - - - - contract TriggerNormal { - function test(address addr) public returns(uint i) { - i = 0; - while (gasleft() > 100000) { - i++; - } - } - } - - contract TriggerNormal1 { - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - addr.balance; - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/extCodeHashTestNoPayable.sol b/framework/src/test/resources/soliditycode_0.6.12/extCodeHashTestNoPayable.sol deleted file mode 100644 index c3a2ad8c6ae..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/extCodeHashTestNoPayable.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testConstantContract{ -uint256 public i; -function testNoPayable() public returns (uint256 z) { -i=1; -z=i; -return z; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/fallbackUpgrade.sol b/framework/src/test/resources/soliditycode_0.6.12/fallbackUpgrade.sol deleted file mode 100644 index f73140ad245..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/fallbackUpgrade.sol +++ /dev/null @@ -1,83 +0,0 @@ -contract Test0{ - event FuncCalled(bytes data,uint a); -} - -contract Test1 { - - event FuncCalled(string a); - fallback() external { - x = "fallback"; - emit FuncCalled(x); - } - string x; -} -//含有payable的fallback,无receice -contract Test2 { - - event FuncCalled(string data); - fallback() external payable{ - x = "fallback"; - emit FuncCalled(x); - } - string x; -} - -contract TestPayable { - event FuncCalled(string a); - - fallback() external payable { - x = "fallback"; - emit FuncCalled(x); - } - - receive() external payable { - x = "receive"; - emit FuncCalled(x); - } - string x; -} - -contract Caller { - function callTest0(Test0 test) public{ - (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - } - function callTest1(address test) public returns (bool) { - (bool success,) = test.call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - (success,) = address(test).call(""); - require(success); - return true; - } - function callTest2(address test) public payable returns (bool) { - (bool success,) = test.call.value(1000)(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - return true; - } - function callTestPayable1(TestPayable test) public payable returns (bool) { - (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - (success,) = address(test).call(""); - require(success); - return true; - } -} - - -//contract Test0 { -// event FallbackCall(string data,bytes msg); -// //event FuncCalled(string a,bytes data); -// function() external payable{ -// x = "fallback"; -// emit FallbackCall(x,msg.data); -// } -// string x; -//} -//contract Caller{ -// function call(Test0 test) public payable returns(bool){ -// (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); -// require(success); -// return true; -// } -//} - diff --git a/framework/src/test/resources/soliditycode_0.6.12/freezeContract001.sol b/framework/src/test/resources/soliditycode_0.6.12/freezeContract001.sol deleted file mode 100644 index 0ad8ed9f460..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/freezeContract001.sol +++ /dev/null @@ -1,63 +0,0 @@ - -contract TestFreeze { - constructor() public payable {} - - function freeze(address payable receiver, uint amount, uint res) external payable{ - receiver.freeze(amount, res); - } - - function unfreeze(address payable receiver, uint res) external { - receiver.unfreeze(res); - } - - function destroy(address payable inheritor) external { - selfdestruct(inheritor); - } - - function send(address payable A) external { - A.transfer(10); - } - - function send(address payable A, uint256 value) external { - A.transfer(value); - } - - function getExpireTime(address payable target, uint res) external view returns(uint) { - return target.freezeExpireTime(res); - } - - function deploy(uint256 salt) public returns(address){ - address addr; - bytes memory code = type(C).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - - function freezeAndSend(address payable receiver, uint amount, uint res) external { - receiver.transfer(amount); - receiver.freeze(amount, res); - } - - -} - - -contract C { - constructor() public payable {} - - function destroy(address payable inheritor) external { - selfdestruct(inheritor); - } -} - -contract D { - constructor() public payable { - msg.sender.freeze(msg.value, 1); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/getAddressChange.sol b/framework/src/test/resources/soliditycode_0.6.12/getAddressChange.sol deleted file mode 100644 index 2796da68770..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/getAddressChange.sol +++ /dev/null @@ -1,12 +0,0 @@ -contract getAddressChange { - constructor() public payable {} - // testaddress1函数新增了一个address属性。0.6.0之前 external函数可以通过address(x)来转化为地址,6.0将其禁止,可以通过函数address属性直接获取 - function testaddress1() public view returns(address) { - //return address(this.getamount); //0.6.0之前可以使用 - return this.getamount.address; //0.6.0 - - } - function getamount(address) external view returns(uint256) { - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/isSRCandidate.sol b/framework/src/test/resources/soliditycode_0.6.12/isSRCandidate.sol deleted file mode 100644 index e8e9b692dec..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/isSRCandidate.sol +++ /dev/null @@ -1,35 +0,0 @@ - - - -contract ContractB{ - address others; -} - -contract TestIsSRCandidate{ - - ContractB contractB = new ContractB(); - - function isSRCandidateTest(address addr) public view returns (bool) { - return address(addr).isSRCandidate; - } - - function zeroAddressTest() public view returns (bool) { - return address(0x0).isSRCandidate; - } - - function localContractAddrTest() public view returns (bool) { - return address(this).isSRCandidate; - } - - function otherContractAddrTest() public view returns (bool) { - return address(contractB).isSRCandidate; - } - - function nonpayableAddrTest(address addr) public view returns (bool) { - return addr.isSRCandidate; - } - - function payableAddrTest(address payable addr) public returns (bool) { - return addr.isSRCandidate; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/mappingGetter.sol b/framework/src/test/resources/soliditycode_0.6.12/mappingGetter.sol deleted file mode 100644 index dbd473717cb..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/mappingGetter.sol +++ /dev/null @@ -1,4 +0,0 @@ -contract mappingGetter { - mapping(bytes => uint256) public balances1; - mapping(string => uint256) public balances2; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/multiValiSignPerformance01.sol b/framework/src/test/resources/soliditycode_0.6.12/multiValiSignPerformance01.sol deleted file mode 100644 index 74baa963366..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/multiValiSignPerformance01.sol +++ /dev/null @@ -1,37 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract ecrecoverValidateSign { - - using ECVerify for bytes32; - - function validateSign(bytes32 hash,bytes[] memory sig,address[] memory signer) public returns (bool) { - for(uint256 i=0;i=0.5.0 <0.7.0; - -contract A { - uint public x; - function setValue(uint _x) public { - x = _x; - } -} -contract B is A {} -contract C is A {} -// No explicit override required -contract D is B, C {} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/override003.sol b/framework/src/test/resources/soliditycode_0.6.12/override003.sol deleted file mode 100644 index 103133fc53c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/override003.sol +++ /dev/null @@ -1,20 +0,0 @@ -pragma solidity ^0.6.0; -contract A { - uint public x; - function setValue(uint _x) public virtual { - x = _x; - } -} - -contract B { - uint public y; - function setValue(uint _y) public virtual { - y = _y; - } -} - -contract C is A, B { - function setValue(uint _x) public override(B,A) { - A.setValue(_x); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/override004.sol b/framework/src/test/resources/soliditycode_0.6.12/override004.sol deleted file mode 100644 index 1549d49b53f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/override004.sol +++ /dev/null @@ -1,25 +0,0 @@ -pragma solidity >=0.5.0 <0.7.0; - -contract A { - uint public x = 4; - function setValue(uint _x) public notZero { - x = _x; - } - modifier notZero() virtual { - require(x >= 5,"x must >= 5"); - _; - } -} - -contract B is A { - function setValue2(uint _x) public { - x = _x; - } -} - -contract C is A,B { - modifier notZero override { - require(x >= 6,"x must >= 6"); - _; - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/override005.sol b/framework/src/test/resources/soliditycode_0.6.12/override005.sol deleted file mode 100644 index a8e44399ece..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/override005.sol +++ /dev/null @@ -1,39 +0,0 @@ -pragma solidity >= 0.6.0; - -contract Base { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices public choice2 = ActionChoices.GoRight; - - function stopped() virtual external pure returns (bool) { - return true; - } - function i() virtual external pure returns (int) { - return 32482980; - } - function i2() virtual external pure returns (int) { - return -32482980; - } - function ui() virtual external pure returns (uint) { - return 23487820; - } - function origin() virtual external pure returns (address) { - return 0x3b0E4a6EdEE231CE0c3433F00F1bbc5FeD409c0B; - } - function b32() virtual external pure returns (bytes32) { - return 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd231050; - } - function choice() virtual external returns (ActionChoices) { - return choice2; - } -} - -contract Test is Base { - - bool override public stopped = false; - int override public i = 32482989; - int override public i2 = -32482989; - uint override public ui = 23487823; - address override public origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 override public b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - ActionChoices override public choice = ActionChoices.SitStill; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/overridePrivateFunction.sol b/framework/src/test/resources/soliditycode_0.6.12/overridePrivateFunction.sol deleted file mode 100644 index b0b4d679620..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/overridePrivateFunction.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.5.17; - -contract A { - - function test() private pure returns(uint) { - return 1; - } - -} - -contract B is A { - - function basic() private pure returns(uint) { - return 2; - } - function testOverridePrivate() external payable returns(uint) { - return basic(); - } - - constructor() public payable {} -} - diff --git a/framework/src/test/resources/soliditycode_0.6.12/payable001.sol b/framework/src/test/resources/soliditycode_0.6.12/payable001.sol deleted file mode 100644 index 4fe7b20921f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/payable001.sol +++ /dev/null @@ -1,31 +0,0 @@ - - - -contract A { - constructor() public payable{ - } - - fallback() external payable { - } -} - -contract PayableTest { - -address payable a1; -function receiveMoneyTransfer(address a, uint256 _x) public { -a1 = payable(a); -a1.transfer(_x); -} - -function receiveMoneySend(address a, uint256 x) public { -address payable a2 = payable(a); -a2.send(x); -} - -function receiveMoneyTransferWithContract(A PayableTest, uint256 x) public { -payable(address(PayableTest)).transfer(x); -} - -constructor() public payable{ -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/pedersenHash001.sol b/framework/src/test/resources/soliditycode_0.6.12/pedersenHash001.sol deleted file mode 100644 index 6cad7cb9855..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/pedersenHash001.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract pedersenHashTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000004).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000004).delegatecall(data); - } - - function test3(uint32 hash, bytes32 left, bytes32 right) public returns (bytes32){ - return pedersenHash(hash, left, right); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/pedersenHash002.sol b/framework/src/test/resources/soliditycode_0.6.12/pedersenHash002.sol deleted file mode 100644 index b0a78973ef2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/pedersenHash002.sol +++ /dev/null @@ -1,320 +0,0 @@ -pragma experimental ABIEncoderV2; - -import "./SafeMath.sol"; - -abstract contract TokenTRC20 { - function transfer(address _to, uint256 _value) public virtual returns (bool success); - - function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success); -} - -contract ShieldedTRC20 { - using SafeMath for uint256; - - uint256 public scalingFactor; // used when decimals of TRC20 token is too large. - uint256 public leafCount; - uint256 constant INT64_MAX = 2 ** 63 - 1; - bytes32 public latestRoot; - mapping(bytes32 => bytes32) public nullifiers; // store nullifiers of spent commitments - mapping(bytes32 => bytes32) public roots; // store history root - mapping(uint256 => bytes32) public tree; - mapping(bytes32 => bytes32) public noteCommitment; - bytes32[33] frontier; - bytes32[32] zeroes = [bytes32(0x0100000000000000000000000000000000000000000000000000000000000000), bytes32(0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155), bytes32(0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34), bytes32(0xd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c), bytes32(0xe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49), bytes32(0x912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a), bytes32(0x8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613), bytes32(0xd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813), bytes32(0x7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444), bytes32(0x43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b), bytes32(0xba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce72), bytes32(0x4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c), bytes32(0xec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048), bytes32(0x1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651), bytes32(0xbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c), bytes32(0xd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f), bytes32(0x1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451), bytes32(0x6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c), bytes32(0xcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf00), bytes32(0x6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b159216), bytes32(0x8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673), bytes32(0x08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023), bytes32(0x0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49), bytes32(0x4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850), bytes32(0xfee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712), bytes32(0x16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a), bytes32(0xd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb58), bytes32(0xa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a), bytes32(0x28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a), bytes32(0xe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72), bytes32(0x12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d), bytes32(0xb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c53814)]; - address owner; - TokenTRC20 trc20Token; - - event MintNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TransferNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event BurnNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TokenMint(address from, uint256 value); - event TokenBurn(address to, uint256 value, bytes32[3] ciphertext); - event NoteSpent(bytes32 nf); - - constructor (address trc20ContractAddress, uint256 scalingFactorExponent) public { - require(scalingFactorExponent < 77, "The scalingFactorExponent is out of range!"); - scalingFactor = 10 ** scalingFactorExponent; - owner = msg.sender; - trc20Token = TokenTRC20(trc20ContractAddress); - } - // output: cm, cv, epk, proof - function mint(uint256 rawValue, bytes32[9] calldata output, bytes32[2] calldata bindingSignature, bytes32[21] calldata c) external { - address sender = msg.sender; - // transfer the trc20Token from the sender to this contract - bool transferResult = trc20Token.transferFrom(sender, address(this), rawValue); - require(transferResult, "TransferFrom failed!"); - - require(noteCommitment[output[0]] == 0, "Duplicate noteCommitments!"); - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), value, output, c)); - (bytes32[] memory ret) = verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[0]; - if (slot == 0) { - frontier[0] = output[0]; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[output[0]] = output[0]; - leafCount ++; - - emit MintNewLeaf(leafCount - 1, output[0], output[1], output[2], c); - emit TokenMint(sender, rawValue); - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function transfer(bytes32[10][] calldata input, bytes32[2][] calldata spendAuthoritySignature, bytes32[9][] calldata output, bytes32[2] calldata bindingSignature, bytes32[21][] calldata c) external { - require(input.length >= 1 && input.length <= 2, "Input number must be 1 or 2!"); - require(input.length == spendAuthoritySignature.length, "Input number must be equal to spendAuthoritySignature number!"); - require(output.length >= 1 && output.length <= 2, "Output number must be 1 or 2!"); - require(output.length == c.length, "Output number must be equal to c number!"); - - for (uint256 i = 0; i < input.length; i++) { - require(nullifiers[input[i][0]] == 0, "The note has already been spent!"); - require(roots[input[i][1]] != 0, "The anchor must exist!"); - } - for (uint256 i = 0; i < output.length; i++) { - require(noteCommitment[output[i][0]] == 0, "Duplicate noteCommitment!"); - } - - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c)); - (bytes32[] memory ret) = verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, 0, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 offset = 1; - //ret offset - for (uint256 i = 0; i < output.length; i++) { - uint256 slot = uint256(ret[offset++]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[i][0]; - if (slot == 0) { - frontier[0] = output[i][0]; - } - for (uint256 k = 1; k < slot + 1; k++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[offset++]; - if (k == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - leafCount++; - } - latestRoot = ret[offset]; - roots[latestRoot] = latestRoot; - for (uint256 i = 0; i < input.length; i++) { - bytes32 nf = input[i][0]; - nullifiers[nf] = nf; - emit NoteSpent(nf); - } - for (uint256 i = 0; i < output.length; i++) { - noteCommitment[output[i][0]] = output[i][0]; - emit TransferNewLeaf(leafCount - (output.length - i), output[i][0], output[i][1], output[i][2], c[i]); - } - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function burn(bytes32[10] calldata input, bytes32[2] calldata spendAuthoritySignature, uint256 rawValue, bytes32[2] calldata bindingSignature, address payTo, bytes32[3] calldata burnCipher, bytes32[9][] calldata output, bytes32[21][] calldata c) external { - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c, payTo, value)); - - bytes32 nf = input[0]; - bytes32 anchor = input[1]; - require(nullifiers[nf] == 0, "The note has already been spent!"); - require(roots[anchor] != 0, "The anchor must exist!"); - - require(output.length <= 1, "Output number cannot exceed 1!"); - require(output.length == c.length, "Output number must be equal to length of c!"); - - // bytes32 signHash = sha256(abi.encodePacked(address(this), input, payTo, value, output, c)); - if (output.length == 0) { - (bool result) = verifyBurnProof(input, spendAuthoritySignature, value, bindingSignature, signHash); - require(result, "The proof and signature have not been verified by the contract!"); - } else { - transferInBurn(input, spendAuthoritySignature, value, bindingSignature, signHash, output, c); - } - - nullifiers[nf] = nf; - emit NoteSpent(nf); - //Finally, transfer trc20Token from this contract to the nominated address - bool transferResult = trc20Token.transfer(payTo, rawValue); - require(transferResult, "Transfer failed!"); - - emit TokenBurn(payTo, rawValue, burnCipher); - } - - function transferInBurn(bytes32[10] memory input, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature, bytes32 signHash, bytes32[9][] memory output, bytes32[21][] memory c) private { - bytes32 cm = output[0][0]; - require(noteCommitment[cm] == 0, "Duplicate noteCommitment!"); - bytes32[10][] memory inputs = new bytes32[10][](1); - inputs[0] = input; - bytes32[2][] memory spendAuthoritySignatures = new bytes32[2][](1); - spendAuthoritySignatures[0] = spendAuthoritySignature; - (bytes32[] memory ret) = verifyTransferProof(inputs, spendAuthoritySignatures, output, bindingSignature, signHash, value, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = cm; - if (slot == 0) { - frontier[0] = cm; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[cm] = cm; - leafCount ++; - - emit BurnNewLeaf(leafCount - 1, cm, output[0][1], output[0][2], c[0]); - } - - //position: index of leafnode, start from 0 - function getPath(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValue(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - //position: index of leafnode, start from 0 - function getPathByValueIsZero(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValueByValueIsZero(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - function ancestorLevel(uint256 leafIndex) private view returns (uint32) { - uint256 nodeIndex1 = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex2 = leafCount + 2 ** 32 - 2; - uint32 level = 0; - while (((nodeIndex1 - 1) / 2) != ((nodeIndex2 - 1) / 2)) { - nodeIndex1 = (nodeIndex1 - 1) / 2; - nodeIndex2 = (nodeIndex2 - 1) / 2; - level = level + 1; - } - return level; - } - - function getTargetNodeValue(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function getTargetNodeValueByValueIsZero(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - left = bytes32(0x0); - right = bytes32(0x0); - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function rawValueToValue(uint256 rawValue) private view returns (uint64) { - require(rawValue > 0, "Value must be positive!"); - require(rawValue.mod(scalingFactor) == 0, "Value must be integer multiples of scalingFactor!"); - uint256 value = rawValue.div(scalingFactor); - require(value < INT64_MAX); - return uint64(value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest1TestRequireContract.sol deleted file mode 100644 index 16d01911d35..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest1TestRequireContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - //function testThrow(){ - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest2TestThrowsContract.sol deleted file mode 100644 index 1ff73ad6460..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest2TestThrowsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow() public { - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest3TestRevertContract.sol deleted file mode 100644 index b42a8c3fb23..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest3TestRevertContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow(){ - // throw; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest4noPayableContract.sol deleted file mode 100644 index 35f89631e7d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest4noPayableContract.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract noPayableContract { - -function noPayable() public payable returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest4noPayableContract_1.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest4noPayableContract_1.sol deleted file mode 100644 index 5b6dd509f6f..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest4noPayableContract_1.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract noPayableContract { - -function noPayable() public returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest5noPayableConstructor.sol deleted file mode 100644 index 097594ab7c9..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest5noPayableConstructor.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public payable{ - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest5noPayableConstructor_1.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest5noPayableConstructor_1.sol deleted file mode 100644 index 5008ec5c9bf..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest5noPayableConstructor_1.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public { - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest6transferTestContract.sol deleted file mode 100644 index 4f171aebb9a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest6transferTestContract.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract transferTestContract { - function tranferTest(address payable addr) public payable{ - addr.transfer(10); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest7payableFallbakContract.sol deleted file mode 100644 index 534726cb1b4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest7payableFallbakContract.sol +++ /dev/null @@ -1,14 +0,0 @@ - - -contract Test { - fallback() external { x = 1; } - uint x; -} - - -contract Caller { - function callTest(Test test) public { - //test.call(0xabcdef01); // hash does not exist - address(test).call(abi.encode(0xabcdef01)); // hash does not exist - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest8newContractGasNoenough.sol deleted file mode 100644 index b8743e8231a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest8newContractGasNoenough.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract Account{ - uint256 public accId; - - // function Account(uint accountId) payable{ - constructor(uint accountId) payable public { - accId = accountId; - } -} - -contract Initialize{ - // Account public account = new Account(10); - - function newAccount() public { - Account account = new Account(1); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest9MessageUsedErrorFeed.sol deleted file mode 100644 index 18142d20ee8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontest9MessageUsedErrorFeed.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -contract MathedFeed { - - function divideMathed() public returns (uint ret) { - uint x=1; - uint y=0; - return x/y; - } -} - - -contract MathedUseContract { - - function MathedUse(address addr) public returns (uint) { - return MathedFeed(addr).divideMathed(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontestFunctionUsedErrorFeed.sol deleted file mode 100644 index ad90faa6dab..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/requireExceptiontestFunctionUsedErrorFeed.sol +++ /dev/null @@ -1,17 +0,0 @@ - - -contract MessageFeed { - - function mValue() payable public returns (uint ret) { - return msg.value; - } -} - -contract MessageUseContract { - function inputValue() payable public returns (uint){ - return msg.value; - } - function messageUse(address addr) payable public returns (uint) { - return MessageFeed(addr).mValue.value(1)(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/selector.sol b/framework/src/test/resources/soliditycode_0.6.12/selector.sol deleted file mode 100644 index 5805a6e8d22..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/selector.sol +++ /dev/null @@ -1,21 +0,0 @@ - - -library A { - function getBalance(address) public view returns (uint256) { - return address(this).balance; - } - - function getamount(address) external view returns (uint256) { - return address(this).balance; - } -} - -contract testSelector { - using A for address; - - - function getselector2() public view returns (bytes4, bytes4) { - return (A.getBalance.selector, A.getamount.selector); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/stackContract001.sol b/framework/src/test/resources/soliditycode_0.6.12/stackContract001.sol deleted file mode 100644 index c2e8f2f7611..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/stackContract001.sol +++ /dev/null @@ -1,61 +0,0 @@ - - -contract A{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function test() public{ - emit log(123); - } -} - -contract B{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function rewardBalance(address addr) public view returns (uint256){ - return addr.rewardbalance; - } - - function nullAddressTest() public view returns (uint256) { - return address(0x0).rewardbalance; - } - - function localContractAddrTest() public view returns (uint256) { - address payable localContract = address(uint160(address(this))); - return localContract.rewardbalance; - } - - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function contractBWithdrawRewardTest(address contractB) public returns (uint) { - return B(contractB).withdrawRewardTest(); - } - - function createA() public returns (address){ - return address(new A()); - } - - function callA(address Addr) public{ - A(Addr).test(); - } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/stackSuicide001.sol b/framework/src/test/resources/soliditycode_0.6.12/stackSuicide001.sol deleted file mode 100644 index d1fc520ddb2..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/stackSuicide001.sol +++ /dev/null @@ -1,84 +0,0 @@ - -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public payable returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function transfer(address payable add,uint256 num) public { - return add.transfer(num); - } -} - -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/stateVariableShadowing.sol b/framework/src/test/resources/soliditycode_0.6.12/stateVariableShadowing.sol deleted file mode 100644 index a9109ee296c..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/stateVariableShadowing.sol +++ /dev/null @@ -1,21 +0,0 @@ -contract test { -// uint public x; -// function setValue1(uint _x) public returns (uint){ -// x = _x; -// return x; -// } - uint public y; - function setValue3(uint _x) public returns (uint){ - y = _x; - return y; - } -} - -contract stateVariableShadowing is test { - uint public x; - function setValue2(uint _x) public returns (uint){ - x = _x; - return x; - } -} - diff --git a/framework/src/test/resources/soliditycode_0.6.12/stringSplit.sol b/framework/src/test/resources/soliditycode_0.6.12/stringSplit.sol deleted file mode 100644 index 84231f2d1fe..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/stringSplit.sol +++ /dev/null @@ -1,45 +0,0 @@ - - -contract testStringSplit { -string s1 = "s""1""2"",./"; -string s2 = "s123?\\'."; -string s3 = hex"41"hex"42"; -string s4 = hex"4142"; - -function getS1() public view returns (string memory) { -return s1; -} - -function getS1N1() public pure returns (string memory) { -string memory n1 = "s""1""2"",./"; -return n1; -} - -function getS2() public view returns (string memory) { -return s2; -} - -function getS2N2() public pure returns (string memory) { -string memory n2 = "s123?\'."; -return n2; -} - -function getS3() public view returns (string memory) { -return s3; -} - -function getS3N3() public pure returns (string memory) { -string memory n3 = hex"41"hex"42"; -return n3; -} - -function getS4() public view returns (string memory) { -return s4; -} - -function getS4N4() public pure returns (string memory) { -string memory n4 = hex"4142"; -return n4; -} - -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/suicide001.sol b/framework/src/test/resources/soliditycode_0.6.12/suicide001.sol deleted file mode 100644 index 3544f8bf84a..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/suicide001.sol +++ /dev/null @@ -1,32 +0,0 @@ -contract factory { - constructor() payable public { - } - - function create1() payable public returns (address){ - Caller add = (new Caller).value(0)(); - return address(add); - } - - function kill() payable public{ - selfdestruct(msg.sender); - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - Caller addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/suicide002.sol b/framework/src/test/resources/soliditycode_0.6.12/suicide002.sol deleted file mode 100644 index 160ab64f320..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/suicide002.sol +++ /dev/null @@ -1,43 +0,0 @@ -contract Factory { - uint256 public num; - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(msg.sender); - addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/testOutOfMem.sol b/framework/src/test/resources/soliditycode_0.6.12/testOutOfMem.sol deleted file mode 100644 index 8d285b28b7d..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/testOutOfMem.sol +++ /dev/null @@ -1,7 +0,0 @@ -contract Test { - function testOutOfMem(uint256 x) public returns(bytes32 r) { - uint[] memory memVar; - memVar = new uint[](x); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/testStakeSuicide.sol b/framework/src/test/resources/soliditycode_0.6.12/testStakeSuicide.sol deleted file mode 100644 index 3342a5607f7..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/testStakeSuicide.sol +++ /dev/null @@ -1,71 +0,0 @@ - -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function BSelfdestructTest(address payable target) public{ - b.SelfdestructTest(target); - } -} -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/tryCatch001.sol b/framework/src/test/resources/soliditycode_0.6.12/tryCatch001.sol deleted file mode 100644 index 283db92e159..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/tryCatch001.sol +++ /dev/null @@ -1,105 +0,0 @@ - - -enum ErrorType { - Revert_Error, //0 - RevertWithMsg_Error, //1 - Require_Error, //2 - RequirewithMsg_Error, //3 - Assert_Error, //4 - Tansfer_Error, //5 - Send_Error, //6 - Math_Error, //7 - ArrayOverFlow_Error //8 -} -contract errorContract { - uint256[] arraryUint ; - - function errorSwitch(uint256 errorType) public returns(string memory) { - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - return "success"; - - } - - function callFun(string memory functionStr, string memory argsStr) public{ - address(this).call(abi.encodeWithSignature(functionStr, argsStr)); - } - -} - -contract NewContract { - uint256[] arraryUint ; - - constructor(uint256 errorType) public payable{ - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - } -} - -contract tryTest { - function getData(errorContract inter, string memory functionStr, string memory argsStr) public payable returns(string memory) { - try inter.callFun(functionStr,argsStr) { - return "123"; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "3"; - } - } - - function getErrorSwitch(errorContract add, uint256 errorType ) public payable returns(string memory) { - try add.errorSwitch(errorType) returns (string memory Msg) { - return Msg; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "NoErrorMsg"; - } - } - - function catchNewErrorSwitch(uint256 errorType) public returns (address nc){ - try new NewContract(errorType) returns (NewContract nc){ - return address(nc); - }catch { - return address(0x00); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue001.sol b/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue001.sol deleted file mode 100644 index 5388ed68473..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue001.sol +++ /dev/null @@ -1,25 +0,0 @@ - -contract tvmAssetIssue001 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateOtherAccountAsset(string memory url, string memory desc) public returns (bool) { - trcToken tokenId = trcToken(1000004); - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue002.sol b/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue002.sol deleted file mode 100644 index 87c1206b778..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue002.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract tvmAssetIssue002 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - assetissue(name, abbr, totalSupply, precision); - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url1, string memory desc1, string memory url2, string memory desc2) public returns (bool) { - updateasset(tokenId, bytes(url1), bytes(desc1)); - return updateasset(tokenId, bytes(url2), bytes(desc2)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue003.sol b/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue003.sol deleted file mode 100644 index f5ce5e0dc3e..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue003.sol +++ /dev/null @@ -1,23 +0,0 @@ - - -contract tvmAssetIssue003 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function tokenIssueAndTransfer(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - assetissue(name, abbr, totalSupply, precision); - newaddress.transfer(100000000); - } - - function updateAssetAndTransfer(trcToken tokenId, string memory url, string memory desc, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - updateasset(tokenId, bytes(url), bytes(desc)); - newaddress.transfer(100000000); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue004.sol b/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue004.sol deleted file mode 100644 index c8332de8f45..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue004.sol +++ /dev/null @@ -1,39 +0,0 @@ - - -contract A { - - constructor() payable public{} - fallback() payable external {} - - function tokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint){ - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAssetA(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} - -contract tvmAssetIssue004 { - - A a; - - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return a.tokenIssueA(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return a.updateAssetA(tokenId, url, desc); - } - - function getContractAddress() public payable returns (address) { - a = (new A).value(1024000000)(); - return address(a); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue005.sol b/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue005.sol deleted file mode 100644 index 8c36d050ff8..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/tvmAssetIssue005.sol +++ /dev/null @@ -1,45 +0,0 @@ - - -contract tvmAssetIssue005 { - constructor() payable public{} - - fallback() external payable { - } - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} - -contract B { - event Deployed(address addr, uint256 salt); - - function deploy(uint256 salt) public returns (address) { - address addr; - bytes memory code = type(tvmAssetIssue005).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt); - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/typeName.sol b/framework/src/test/resources/soliditycode_0.6.12/typeName.sol deleted file mode 100644 index 5b44abd1bbb..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/typeName.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract TypeName { - function testTypeName() public returns (string memory){ - return type(TypeName).name; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/unStake001.sol b/framework/src/test/resources/soliditycode_0.6.12/unStake001.sol deleted file mode 100644 index 03734fecfa5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/unStake001.sol +++ /dev/null @@ -1,90 +0,0 @@ - - -contract unStakeTest { - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - - function selfdestructTest(address payable target) public { - selfdestruct(target); - } - - function selfdestructTest2(address sr, uint256 amount, address payable target) public { - stake(sr, amount); - selfdestruct(target); - } - - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - - function unStake() public returns (bool result){ - return unstake(); - } - - function unStake2() public returns (bool result){ - unstake(); - return unstake(); - } - - function withdrawReward() public returns (uint256 amount) { - return withdrawreward(); - } - - function rewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - - function revertTest1(address sr, uint256 amount, address payable transferAddr) public { - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000); - //stake more than balance to fail - transferAddr.transfer(4000000); - } - - function revertTest2(address payable transferAddr) public { - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake(); - //unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - - function BSelfdestructTest(address payable target) public { - b.SelfdestructTest(target); - } -} - -contract B { - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function UnStake() public returns (bool result){ - return unstake(); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/validatemultisign001.sol b/framework/src/test/resources/soliditycode_0.6.12/validatemultisign001.sol deleted file mode 100644 index cc0a742d0c5..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/validatemultisign001.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract validatemultisignTest { - function testmulti(address a, uint256 perid, bytes32 hash, bytes[] memory signatures) public returns (bool){ - return validatemultisign(a, perid, hash, signatures); - } - - function testbatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns (bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testMultiPrecompileContract(bytes memory data) public returns(bool, bytes memory){ - return address(0xa).delegatecall(data); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/verifyTransferProof001.sol b/framework/src/test/resources/soliditycode_0.6.12/verifyTransferProof001.sol deleted file mode 100644 index 587b4defd10..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/verifyTransferProof001.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract verifyTransferProofTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000002).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000002).delegatecall(data); - } - - function test3(bytes32[10][] memory input, bytes32[2][] memory spendAuthoritySignature, bytes32[9][] memory output, bytes32[2] memory bindingSignature, bytes32 signHash, uint64 valueBalance, bytes32[33] memory frontier, uint256 leafCount) public returns (bytes32[] memory){ - return verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, valueBalance, frontier, leafCount); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.6.12/virtual001.sol b/framework/src/test/resources/soliditycode_0.6.12/virtual001.sol deleted file mode 100644 index 6dddac07ef4..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/virtual001.sol +++ /dev/null @@ -1,19 +0,0 @@ -pragma solidity ^0.6.0; -interface X { - function setValue(uint _x) external; -} -abstract contract Y { - function setBool(bool _y) external virtual ; -} -contract Y2 { - string public z; - function setString(string calldata _z) external virtual { z = "123"; } -} - -contract Z is X,Y,Y2 { - uint public x; - bool public y; - function setValue(uint _x) external override { x = _x; } - function setBool(bool _y) external override { y = _y; } - function setString(string calldata _z) external override { z = _z; } -} diff --git a/framework/src/test/resources/soliditycode_0.6.12/walletTestMutiSign004.sol b/framework/src/test/resources/soliditycode_0.6.12/walletTestMutiSign004.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_0.6.12/walletTestMutiSign004.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/AssertException002.sol b/framework/src/test/resources/soliditycode_0.7.6/AssertException002.sol deleted file mode 100644 index 15cc07ff984..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/AssertException002.sol +++ /dev/null @@ -1,17 +0,0 @@ - - -contract AssertException{ - function divideIHaveArgsReturn(int x,int y) public returns (int z) { - return x / y; - } - function testAssert() public { - require(2==1); - } -} -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/AssignToExternal.sol b/framework/src/test/resources/soliditycode_0.7.6/AssignToExternal.sol deleted file mode 100644 index d4f09590a36..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/AssignToExternal.sol +++ /dev/null @@ -1,30 +0,0 @@ -contract AssignToExternal { - // Not allow: - // function f(uint256[] calldata x, uint256[] calldata y) external pure { - // x = y; - // } - - // allow: - - function f(uint256 a) external returns (uint){ - a = a + 1; - return a; - } - - function StringSet(string calldata a) external returns (string memory){ - return a; - } - - function ByteSet(bytes32 a) external returns (bytes32){ - return a; - } - - function UintArraySet(uint256[2] calldata a) external returns (uint256[2] memory){ - return a; - } - - function AddSet(address a) external returns (address){ - return a; - } - -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/BlockHash.sol b/framework/src/test/resources/soliditycode_0.7.6/BlockHash.sol deleted file mode 100644 index 6603da65e44..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/BlockHash.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract TestBlockHash { - - function testOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) | bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) | blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) & bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testAND2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) & blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR1(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = blockhash(block.number - 1) ^ bytes32(value); - return (b1, c, blockhash(block.number - 1)); - } - - function testXOR2(bytes32 value) public returns(bytes32, bytes32, bytes32) { - bytes32 b1 = blockhash(block.number - 1); - bytes32 c = bytes32(value) ^ blockhash(block.number - 1); - return (b1, c, blockhash(block.number - 1)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/ClearAbi001.sol b/framework/src/test/resources/soliditycode_0.7.6/ClearAbi001.sol deleted file mode 100644 index 39a8e8cf005..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ClearAbi001.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract testConstantContract{ -function testPayable() public view returns (int z) { -return 1; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/ClearAbi005.sol b/framework/src/test/resources/soliditycode_0.7.6/ClearAbi005.sol deleted file mode 100644 index a3115398386..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ClearAbi005.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=0; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/ConstructorDefaults.sol b/framework/src/test/resources/soliditycode_0.7.6/ConstructorDefaults.sol deleted file mode 100644 index 4b6186ccb95..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ConstructorDefaults.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract testIsContract{ - bool result; - constructor (bool a) public { - result = a; - } -function test( address a) public returns (bool) { -return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/Create2Test023.sol b/framework/src/test/resources/soliditycode_0.7.6/Create2Test023.sol deleted file mode 100644 index ba48645ae3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/Create2Test023.sol +++ /dev/null @@ -1,31 +0,0 @@ -contract factory { - constructor() payable public { - } - - function deploy(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } - - function testCreate() payable public returns (address){ - Caller add = (new Caller){value:0}(); - return address(add); - } - - function kill( ) payable public{ - selfdestruct(msg.sender); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/Create2Test024.sol b/framework/src/test/resources/soliditycode_0.7.6/Create2Test024.sol deleted file mode 100644 index f5a9d032cff..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/Create2Test024.sol +++ /dev/null @@ -1,56 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(msg.sender); - addr.set(); - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } - - function deploy2(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - //addr.testSuicideNonexistentTarget(msg.sender); - //addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/Create2Test025.sol b/framework/src/test/resources/soliditycode_0.7.6/Create2Test025.sol deleted file mode 100644 index 895dc43e56f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/Create2Test025.sol +++ /dev/null @@ -1,34 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } -} - -contract TestContract{ - uint256 public num; - constructor(uint256 j) public{ - num = j; - } - function getNum() public returns (uint256){ - return num; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/ExtCodeHashTest010.sol b/framework/src/test/resources/soliditycode_0.7.6/ExtCodeHashTest010.sol deleted file mode 100644 index 6feaa923f4b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ExtCodeHashTest010.sol +++ /dev/null @@ -1,46 +0,0 @@ -contract Counter { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); - constructor() public{ - owner = msg.sender; - } - function getCodeHashSuicide(address addr) public returns (bytes32 _hashBefore){ - assembly{ - _hashBefore := extcodehash(addr) - } - selfdestruct(owner); - return _hashBefore; - } - - function getCodeHashRevert() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - address addr = address(this); - assembly { - _hashBefore := extcodehash(addr) - } - if (owner == msg.sender) { - selfdestruct(owner); - } - assembly { - _hashAfter := extcodehash(addr) - } - revert(); - emit LogResult(_hashBefore, _hashAfter); - } - - function getCodeHashCreate() public returns (bytes32 _hashBefore){ - TestContract A = (new TestContract){value:0}(); - address addr = address(A); - assembly{ - _hashBefore := extcodehash(addr) - } - revert(); - return _hashBefore; - } -} - -contract TestContract{ - uint256 count = 1; - constructor() public payable{ - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/ExternalSelector.sol b/framework/src/test/resources/soliditycode_0.7.6/ExternalSelector.sol deleted file mode 100644 index 01fddac9e2e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ExternalSelector.sol +++ /dev/null @@ -1,92 +0,0 @@ -//pragma solidity ^0.6.0; - -contract selectorContract { - function testSelectorNoParam() external pure returns(uint) { - return 11; - } - - function testSelectorWithParam(uint x) external pure returns(uint) { - return 22; - } -} - -interface interfaceSelector { - function getSelector() external pure returns(uint); -} - -interface B is interfaceSelector { - // interface现在可以继承自其他interface - function testImplemention() external pure returns(uint); -} - -contract implementContract is B{ - function getSelector() external override pure returns(uint) { - return 66; - } - - function testImplemention() external override pure returns(uint) { - return 77; - } - - constructor() public payable {} -} - -contract basicContract{ - function testNewUse() external payable returns(uint) { - return 345; - } - - constructor() public payable {} -} - -contract TestGasValue{ - constructor() public payable {} - - function testNewUse() external payable returns(uint) { - return 123; - } - basicContract bc = new basicContract(); - // external方法在调用时可以采用c.f{gas: 10000, value: 4 trx}()的形式 - function callWithGasAndValue(uint x,uint y) external returns(uint) { - return bc.testNewUse{gas:x, value:y}(); - } - - function callThisNoGasAnd1Value() external returns(uint) { - return this.testNewUse{gas:0, value:1}(); - } - - // inline assembly中允许true和false字面量 - function testAssemblyTrue() public pure returns(uint x) { - assembly { - x := true - } - } - - // inline assembly中允许true和false字面量 - function testAssemblyFalse() public pure returns(uint x) { - assembly { - x := false - } - } - - // create2的high-level用法new C{salt: 0x1234, value: 1 ether}(arg1, arg2) - function testCreate2() public returns(address) { - basicContract c = new basicContract{salt: bytes32(bytes1(0x01)), value: 1 trx}(); - return address(c); - } - - - function getContractSelectorNoParam() public pure returns(bytes4) { - return selectorContract.testSelectorNoParam.selector; - } - - function getContractSelectorWithParam() public pure returns(bytes4) { - return selectorContract.testSelectorWithParam.selector; - } - - function getInterfaceSelectorNoParam() public pure returns(bytes4) { - return interfaceSelector.getSelector.selector; - } - -} - diff --git a/framework/src/test/resources/soliditycode_0.7.6/NewFeature068.sol b/framework/src/test/resources/soliditycode_0.7.6/NewFeature068.sol deleted file mode 100644 index be4ee209e15..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/NewFeature068.sol +++ /dev/null @@ -1,126 +0,0 @@ -// SPDX-License-Identifier: GPL-3.0 -//pragma solidity ^0.6.8; - -abstract contract testModifier { - modifier isOwner() virtual; -} - -abstract contract testInterfaceId { - function getValue() external view virtual returns(uint); - function getOwner() external view virtual returns(uint); - -} - -interface a { - function getValue() external view returns(uint); - function getOwner() external view returns(uint); -} - -contract testMapKey is testModifier{ - - enum size{ - SMALL, - LARGE - } - - mapping(size => uint) public enums; - - mapping(testMapKey => uint) public contracts; - - function setEnumValue(uint value) public { - enums[size.SMALL] = value; - } - - function getEnumValue() public view returns(uint) { - return enums[size.SMALL]; - } - - function setContractValue() public { - contracts[this] = 2; - } - - function getContractValue() public view returns(uint) { - return contracts[this]; - } - - bytes4 constant functionSelector = this.getEnumValue.selector; - - function getfunctionSelector() public pure returns(bytes4) { - return functionSelector; - } - - uint immutable x; - address immutable owner = msg.sender; - - constructor() public { - x = 5; - } - - string b = "test"; - - function testStorage() public view returns(string memory) { - string storage aa; - aa = b; - return aa; - - } - - function getImmutableVal() public view returns(uint) { - return x; - } - - function getOwner() public view returns(address) { - return owner; - } - - function getInterfaceId() public pure returns(bytes4,bytes4) { - return (type(a).interfaceId, type(testInterfaceId).interfaceId); - } - - modifier isOwner() override { - require(msg.sender == owner); - _; - } - - function requireOwner() public view isOwner returns(uint) { - return 6; - } - - - function getUint256MinAndMax() public pure returns(uint, uint) { - return (type(uint).min, type(uint).max); - } - - - function getUint8MinAndMax() public pure returns(uint8, uint8) { - return (type(uint8).min, type(uint8).max); - } - -} - - -abstract contract base { - function abstractfun() virtual public returns(uint); -} - -abstract contract callEmptyFunction is base { - function callfun() public returns(uint) { - return abstractfun(); - } -} - - - - - - - - - - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.7.6/NewFeature076.sol b/framework/src/test/resources/soliditycode_0.7.6/NewFeature076.sol deleted file mode 100644 index 3191acb8f1d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/NewFeature076.sol +++ /dev/null @@ -1,21 +0,0 @@ -function a() returns (uint) { - return 1; -} -abstract contract abvd { - -} -interface qwer { - function getValue() external view returns(uint); - function getOwner() external view returns(uint); -} -contract C { - function getOutsideMethod() external returns (uint) { - return a(); - } - function getAbstractName() public returns(string memory) { - return type(abvd).name; - } - function getInterfaceName() public returns(string memory) { - return type(qwer).name; - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/ParentTypeBug.sol b/framework/src/test/resources/soliditycode_0.7.6/ParentTypeBug.sol deleted file mode 100644 index 897c843ae24..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ParentTypeBug.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract Parent { - uint256 public m_aMember; - address public m_bMember; -} -contract Child is Parent { - function foo() public view returns (uint256) { return Parent.m_aMember; } - function bar() public view returns (address) { return Parent.m_bMember; } - - // complie failed - // function foo() public pure returns (uint256) { return Parent.m_aMember; } - // function bar() public pure returns (address) { return Parent.m_bMember; } - -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/SafeMath.sol b/framework/src/test/resources/soliditycode_0.7.6/SafeMath.sol deleted file mode 100644 index 1a7f1be2b8e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/SafeMath.sol +++ /dev/null @@ -1,149 +0,0 @@ - - -/** - * @dev Wrappers over Solidity's arithmetic operations with added overflow - * checks. - * - * Arithmetic operations in Solidity wrap on overflow. This can easily result - * in bugs, because programmers usually assume that an overflow raises an - * error, which is the standard behavior in high level programming languages. - * `SafeMath` restores this intuition by reverting the transaction when an - * operation overflows. - * - * Using this library instead of the unchecked operations eliminates an entire - * class of bugs, so it's recommended to use it always. - */ -library SafeMath { - /** - * @dev Returns the addition of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `+` operator. - * - * Requirements: - * - Addition cannot overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256) { - uint256 c = a + b; - require(c >= a, "SafeMath: addition overflow"); - - return c; - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - return sub(a, b, "SafeMath: subtraction overflow"); - } - - /** - * @dev Returns the subtraction of two unsigned integers, reverting with custom message on - * overflow (when the result is negative). - * - * Counterpart to Solidity's `-` operator. - * - * Requirements: - * - Subtraction cannot overflow. - */ - function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b <= a, errorMessage); - uint256 c = a - b; - - return c; - } - - /** - * @dev Returns the multiplication of two unsigned integers, reverting on - * overflow. - * - * Counterpart to Solidity's `*` operator. - * - * Requirements: - * - Multiplication cannot overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256) { - // Gas optimization: this is cheaper than requiring 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 - if (a == 0) { - return 0; - } - - uint256 c = a * b; - require(c / a == b, "SafeMath: multiplication overflow"); - - return c; - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - return div(a, b, "SafeMath: division by zero"); - } - - /** - * @dev Returns the integer division of two unsigned integers. Reverts with custom message on - * division by zero. The result is rounded towards zero. - * - * Counterpart to Solidity's `/` operator. Note: this function uses a - * `revert` opcode (which leaves remaining gas untouched) while Solidity - * uses an invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b > 0, errorMessage); - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - - return c; - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b) internal pure returns (uint256) { - return mod(a, b, "SafeMath: modulo by zero"); - } - - /** - * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), - * Reverts with custom message when dividing by zero. - * - * Counterpart to Solidity's `%` operator. This function uses a `revert` - * opcode (which leaves remaining gas untouched) while Solidity uses an - * invalid opcode to revert (consuming all remaining gas). - * - * Requirements: - * - The divisor cannot be zero. - */ - function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { - require(b != 0, errorMessage); - return a % b; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/ShiftCommand001.sol b/framework/src/test/resources/soliditycode_0.7.6/ShiftCommand001.sol deleted file mode 100644 index 574ee2b571b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/ShiftCommand001.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(uint256 num, uint256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/SolidityMappingFix.sol b/framework/src/test/resources/soliditycode_0.7.6/SolidityMappingFix.sol deleted file mode 100644 index 67692d3b4ae..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/SolidityMappingFix.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Tests { - mapping(address => uint) public balances; - function update(uint256 amount) public returns (address addr) - { - balances[msg.sender] = amount; - return msg.sender; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TestMappings_array_pop.sol b/framework/src/test/resources/soliditycode_0.7.6/TestMappings_array_pop.sol deleted file mode 100644 index 0d5c4bb7013..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TestMappings_array_pop.sol +++ /dev/null @@ -1,19 +0,0 @@ -contract C { - mapping (uint256 => uint256)[] a; - - function n1(uint256 key, uint256 value) public { - a.push(); - a[a.length - 1][key] = value; - } - - - - function map(uint256 key) public view returns (uint) { - return a[a.length - 1][key]; - } - - function p() public { - a.pop(); - } -} - diff --git a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed001.sol b/framework/src/test/resources/soliditycode_0.7.6/TransferFailed001.sol deleted file mode 100644 index e35cd04f590..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed001.sol +++ /dev/null @@ -1,147 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - - function testTransferTokenCompiledLongMax() payable public{ - address(0x1).transferToken(1,9223372036855775827); - } - - function testTransferTokenCompiled() payable public{ - address(0x1).transferToken(1,1); - } - - function testTransferTokenCompiledLongMin() payable public{ - //address(0x1).transferToken(1,-9223372036855775828); - } - - function testTransferTokenCompiledLongMin1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(-9223372036855775828)); - } - - function testTransferTokenCompiled1() payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(1)); - } - - function testTransferTokenCompiledLongMax1() payable public returns(uint256){ - return address(0x2).tokenBalance(trcToken(9223372036855775827)); - } - - function testTransferTokenCompiledTokenId(uint256 tokenid) payable public returns(uint256){ - return address(0x1).tokenBalance(trcToken(tokenid)); - } - - function testTransferTokenTest(address addr ,uint256 tokenid) payable public returns(uint256){ - return addr.tokenBalance(trcToken(tokenid)); - } - - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public { - caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - } - - function testSendTrxRevert(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.send(i); - revert(); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.transfer(i); - } - - function testTransferTrxrevert(uint256 i,address payable nonexistentTarget) payable public{ - nonexistentTarget.transfer(i); - revert(); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - } - - function testTransferTokenRevert(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - nonexistentTarget.transferToken(i, tokenId); - revert(); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - function testSuicideRevert(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - revert(); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - function deploy2(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(300, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed005.sol b/framework/src/test/resources/soliditycode_0.7.6/TransferFailed005.sol deleted file mode 100644 index 0a1a9d1849e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed005.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed006.sol b/framework/src/test/resources/soliditycode_0.7.6/TransferFailed006.sol deleted file mode 100644 index 0a1a9d1849e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed006.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed007.sol b/framework/src/test/resources/soliditycode_0.7.6/TransferFailed007.sol deleted file mode 100644 index 0a1a9d1849e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TransferFailed007.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address payable caller) public returns (bool,bytes memory){ - return caller.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller){value:i}(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address payable nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address payable nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call{value:i}(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address payable self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant001.sol b/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant001.sol deleted file mode 100644 index b385850577d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant001.sol +++ /dev/null @@ -1,28 +0,0 @@ - - -contract testConstantContract{ - uint256 public i; - function testPayable() public payable returns (uint256 z) { - i=1; - z=i; - return z; - } - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - function testView2() public view returns (uint256 z) { - uint256 i=1; - revert(); - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant002.sol b/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant002.sol deleted file mode 100644 index 7708d81792a..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant002.sol +++ /dev/null @@ -1,10 +0,0 @@ - - -contract testConstantContract{ - uint256 public i; - function testNoPayable() public returns (uint256 z) { - i=1; - z=i; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant003.sol b/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant003.sol deleted file mode 100644 index 947b3f610e6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant003.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -contract testConstantContract{ - function testView() public view returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPure() public pure returns (uint256 z) { - uint256 i=1; - return i; - } - - function testPayable() public payable returns (uint256 z) { - uint256 i=1; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant004.sol b/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant004.sol deleted file mode 100644 index 7fcb44950e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant004.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testPure() public pure returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant015.sol b/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant015.sol deleted file mode 100644 index d926c43c824..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant015.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - constructor () public { - } - function plusOne() public returns(uint){ - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant024.sol b/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant024.sol deleted file mode 100644 index 69ad3a2d5b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TriggerConstant024.sol +++ /dev/null @@ -1,9 +0,0 @@ - - -contract testConstantContract{ -function testView() public view returns (uint256 z) { -uint256 i=1; -revert(); -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract.sol deleted file mode 100644 index 4266b9e92ca..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract001.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract001.sol deleted file mode 100644 index 77aae930b59..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract001.sol +++ /dev/null @@ -1,24 +0,0 @@ -contract testIsContract{ -bool public isContrct; -constructor () public { - isContrct = address(this).isContract; -} -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} - -function testIsContractView(address a) view public returns (bool) { -return (a.isContract); -} - -function selfdestructContract(address payable a) public { - selfdestruct(a); -} -function testConstructor() public returns(bool){ - return isContrct; -} - -function testConstructorView() public view returns(bool){ - return isContrct; -} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract002.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract002.sol deleted file mode 100644 index 2fe474fd98c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmIsContract002.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract testIsContract{ -function testIsContractCommand(address a) public returns (bool) { -return (a.isContract); -} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand043.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand043.sol deleted file mode 100644 index 04d9f7dde28..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand043.sol +++ /dev/null @@ -1,18 +0,0 @@ -contract TestBitwiseShift { - - function shlTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shl(num, input) - } - } - function shrTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := shr(num, input) - } - } - function sarTest(int256 num, int256 input) public returns (bytes32 out) { - assembly { - out := sar(num, input) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand103.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand103.sol deleted file mode 100644 index dbc7fd0f0f4..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand103.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testView() public constant returns (uint256 z) { -uint256 i=1; -return i; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand107.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand107.sol deleted file mode 100644 index 5b51cd1842c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand107.sol +++ /dev/null @@ -1,9 +0,0 @@ - - - contract testConstantContract{ - int256 public i; - function testPayable() public returns (int z) { - z=1+1; - return z; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand108.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand108.sol deleted file mode 100644 index 0088054faf9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand108.sol +++ /dev/null @@ -1,7 +0,0 @@ - - - contract testConstantContract{ - function test() pure public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand109.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand109.sol deleted file mode 100644 index dc8dd1e8399..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmNewCommand109.sol +++ /dev/null @@ -1,7 +0,0 @@ - - - contract testConstantContract{ - function test() view public returns (int z) { - return 1; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/TvmOldCommand001.sol b/framework/src/test/resources/soliditycode_0.7.6/TvmOldCommand001.sol deleted file mode 100644 index f2927bd8e45..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/TvmOldCommand001.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract binaryRightContract{ - function binaryMoveR(uint i)public returns (uint z) { - return z = 5 >> i; - } - function binaryLiftR(uint i)public returns (uint z) { - return z = 5 << i; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/VerifyBurnProof001.sol b/framework/src/test/resources/soliditycode_0.7.6/VerifyBurnProof001.sol deleted file mode 100644 index 4173e84de23..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/VerifyBurnProof001.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract VerifyBurnProof001Test { - // verifyBurnProof(bytes32[10],bytes32[2],uint64,bytes32[2],bytes32) - // size = 512 - // - - function VerifyBurnProofSize001(bytes32[10] memory output, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature,bytes32 signHash) public returns (bool){ - return verifyBurnProof(output, spendAuthoritySignature, value, bindingSignature, signHash); - } - - function VerifyBurnProofSize002(bytes memory data) public returns (bool, bytes memory){ - // bytes memory empty = ""; - return address(0x1000003).delegatecall(data); - } - - function VerifyBurnProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000003).delegatecall(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/VerifyMintProof001.sol b/framework/src/test/resources/soliditycode_0.7.6/VerifyMintProof001.sol deleted file mode 100644 index cb0812c2ef5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/VerifyMintProof001.sol +++ /dev/null @@ -1,33 +0,0 @@ - -contract VerifyMintProof001Test { - // verifyMintProof(bytes32[9],bytes32[2],uint64,bytes32,bytes32[33],uint256) - - function VerifyMintProofSize001(bytes32[9] memory output, bytes32[2] memory bindingSignature, uint64 value, bytes32 signHash, bytes32[33] memory frontier,uint256 leafCount) public returns (bytes32[] memory){ - return verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - } - - function VerifyMintProofSize002(bytes memory data) public returns (bool, bytes memory){ -// address verifyMint = address (0x1000001); -// -// assembly { -// let succeeded := delegatecall(sub(gas, 5000), verifyMint, add(data, 0x20), mload(data), 0, 0) -// let size := returndatasize -// let response := mload(0x40) -// mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) -// mstore(response, size) -// returndatacopy(add(response, 0x20), 0, size) -// switch iszero(succeeded) -// case 1 { -// // throw if delegatecall failed -// revert(add(response, 0x20), size) -// } -// } - - return address(0x1000001).delegatecall(data); - } - - function VerifyMintProofSize003() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000001).call(empty); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/abiencode.sol b/framework/src/test/resources/soliditycode_0.7.6/abiencode.sol deleted file mode 100644 index 38fad3454d6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/abiencode.sol +++ /dev/null @@ -1,16 +0,0 @@ -pragma experimental ABIEncoderV2; - -// tests encoding from storage arrays - -contract AbiEncode { - int256[2][] tmp_h; - function h(int256[2][] calldata s) external returns (bytes memory) { - tmp_h = s; - return abi.encode(tmp_h); - } - int256[2][2] tmp_i; - function i(int256[2][2] calldata s) external returns (bytes memory) { - tmp_i = s; - return abi.encode(tmp_i); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/abstract001.sol b/framework/src/test/resources/soliditycode_0.7.6/abstract001.sol deleted file mode 100644 index 741f236925d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/abstract001.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.6.0; - -interface X { - function setValue(uint _x) external; - function setBalance(uint _x) external; -} - -abstract contract abstract001 is X { - uint x; - function setX(uint _x) public { x = _x; } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/abstract002.sol b/framework/src/test/resources/soliditycode_0.7.6/abstract002.sol deleted file mode 100644 index 7358fc8e163..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/abstract002.sol +++ /dev/null @@ -1,13 +0,0 @@ -//pragma solidity ^0.6.0; - -interface X { - function setValue(uint _x) external; - function setBalance(uint _x) external; -} - -abstract contract abstract002 is X { - uint x; - function setX(uint _x) public { x = _x; } - function setValue(uint _x) external override{ x = _x; } - function setBalance(uint _x) external override{ x = _x; } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/accountAssert.sol b/framework/src/test/resources/soliditycode_0.7.6/accountAssert.sol deleted file mode 100644 index 9ddeea64d91..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/accountAssert.sol +++ /dev/null @@ -1,94 +0,0 @@ -//pragma solidity ^0.6.0; - -contract transferTokenTestA { - - // transfer trc10 to a new address or exist address in constructor - constructor(address payable toAddress, uint256 tokenValue, trcToken id) payable public{ - toAddress.transferToken(tokenValue, id); - require(toAddress.tokenBalance(id) > 0, "tokenBalance should not be 0"); - } - - fallback() payable external{} - - function transferTest(address payable toAddress, uint256 tokenValue) payable public { - toAddress.transfer(tokenValue); - } - - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - // suicide to a new address - function selfdestructTest(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - // transfer to a new contract - function createContractTest(uint256 tokenValue, trcToken id) payable public returns(address){ - Simple s = new Simple(); - require(address(s).tokenBalance(id)==0, "tokenBalance should be 0"); - address(s).transferToken(tokenValue, id); - require(address(s).tokenBalance(id)==tokenValue, "tokenBalance should not be 0"); - return address(s); - } - - // revert transfer to a new contract - function revertCreateContractTest(uint256 tokenValue, trcToken id) payable public { - Simple s = new Simple(); - address(s).transferToken(tokenValue, id); - revert(); - } -} - -contract transferTokenTestB { - - constructor() payable public{ - } - - fallback() payable external{} - - function transferTest(address payable toAddress, uint256 tokenValue) payable public { - toAddress.transfer(tokenValue); - } - - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - // suicide to a new address - function selfdestructTest(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - // transfer to a new contract - function createContractTest(uint256 tokenValue, trcToken id) payable public returns(address){ - Simple s = new Simple(); - require(address(s).tokenBalance(id)==0, "tokenBalance should be 0"); - address(s).transferToken(tokenValue, id); - require(address(s).tokenBalance(id)==tokenValue, "tokenBalance should not be 0"); - return address(s); - } - - // revert transfer to a new contract - function revertCreateContractTest(uint256 tokenValue, trcToken id) payable public { - Simple s = new Simple(); - address(s).transferToken(tokenValue, id); - revert(); - } -} - -contract transferTokenTestC { - Simple public s; - - // transfer to a new address in constructor - constructor(trcToken id) payable public{ - s = new Simple(); - require(address(s).tokenBalance(id)==0, "new contract tokenBalance should be 0"); - require(address(this).tokenBalance(id)==0, "this.tokenBalance should be 0"); - } -} - -contract Simple { - constructor() payable public{} - fallback() payable external{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.7.6/addMsg001Nonpayable.sol deleted file mode 100644 index fcd40cdb521..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addMsg001Nonpayable.sol +++ /dev/null @@ -1,20 +0,0 @@ - - -contract IllegalDecorate { - -event log(uint256); -constructor() payable public{} - -fallback() payable external{} - -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue)public { -// function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addMsg002View.sol b/framework/src/test/resources/soliditycode_0.7.6/addMsg002View.sol deleted file mode 100644 index 0c04b5c0b8a..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addMsg002View.sol +++ /dev/null @@ -1,20 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} - diff --git a/framework/src/test/resources/soliditycode_0.7.6/addMsg003Constant.sol b/framework/src/test/resources/soliditycode_0.7.6/addMsg003Constant.sol deleted file mode 100644 index 2065802bed1..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addMsg003Constant.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addMsg004Pure.sol b/framework/src/test/resources/soliditycode_0.7.6/addMsg004Pure.sol deleted file mode 100644 index 25f1a36d8b7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addMsg004Pure.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode_0.7.6/addTransferToken001Nonpayable.sol deleted file mode 100644 index 039b341b6ac..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken001Nonpayable.sol +++ /dev/null @@ -1,13 +0,0 @@ - - - contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue)public { - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken001payable.sol b/framework/src/test/resources/soliditycode_0.7.6/addTransferToken001payable.sol deleted file mode 100644 index 17078e30189..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken001payable.sol +++ /dev/null @@ -1,13 +0,0 @@ - - - contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithOutPayable(address payable toAddress,trcToken id, uint256 tokenValue) public payable{ - - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken002View.sol b/framework/src/test/resources/soliditycode_0.7.6/addTransferToken002View.sol deleted file mode 100644 index c50a16390f5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken002View.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithView(address payable toAddress,trcToken id, uint256 tokenValue) public view{ - - toAddress.transferToken(tokenValue, id); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode_0.7.6/addTransferToken003Constant.sol deleted file mode 100644 index 18721d9b94c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken003Constant.sol +++ /dev/null @@ -1,14 +0,0 @@ - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public constant{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode_0.7.6/addTransferToken004Pure.sol deleted file mode 100644 index f7716ee3874..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTransferToken004Pure.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract IllegalDecorate { - - constructor() payable public{} - - fallback() payable external{} - - function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure{ - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode_0.7.6/addTrcToken001Assemble.sol deleted file mode 100644 index fe7a7f4cef8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTrcToken001Assemble.sol +++ /dev/null @@ -1,62 +0,0 @@ - - -contract InAssemble { - -mapping(trcToken => uint256) tokenCnt; -mapping(uint256 => mapping(trcToken => trcToken)) cntTokenToken; -constructor () payable public {} -function getBalance (address addr) view public returns(uint256 r) { -assembly{ -r := balance(addr) -} -} - -function getTokenBalanceConstant (address addr, trcToken tokenId) view public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function getTokenBalance (address addr, trcToken tokenId) public returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function transferTokenInAssembly(address addr, trcToken tokenId, uint256 tokenValue) public payable { -bytes4 sig = bytes4(keccak256("()")); // function signature - -assembly { -let x := mload(0x40) // get empty storage location -mstore(x,sig) // 4 bytes - place signature in empty storage - -let ret := calltoken(gas, addr, tokenValue, tokenId, -x, // input -0x04, // input size = 4 bytes -x, // output stored at input location, save space -0x0 // output size = 0 bytes -) - -// let ret := calltoken(gas, addr, tokenValue, -// x, // input -// 0x04, // input size = 4 bytes -// x, // output stored at input location, save space -// 0x0 // output size = 0 bytes -// ) // ERROR - - -mstore(0x40, add(x,0x20)) // update free memory pointer -} - -} - -function trcTokenInMap(trcToken tokenId, uint256 tokenValue) public returns(uint256 r) { -tokenCnt[tokenId] += tokenValue; -r = tokenCnt[tokenId]; -} - -function cntTokenTokenInMap(trcToken tokenId1, trcToken tokenId2, uint256 tokenValue) public returns(trcToken r) { -cntTokenToken[tokenValue][tokenId1] = tokenId2; -r = cntTokenToken[tokenValue][tokenId1]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode_0.7.6/addTrcToken002Cat.sol deleted file mode 100644 index 0cd407079ba..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTrcToken002Cat.sol +++ /dev/null @@ -1,2051 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.7.6/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode_0.7.6/addTrcToken002Cat_withFinny.sol deleted file mode 100644 index 24117bc5e6b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addTrcToken002Cat_withFinny.sol +++ /dev/null @@ -1,2051 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 finney; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 finney; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause(address payable toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(address(newContractAddress) == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.7.6/addressCheckNew.sol b/framework/src/test/resources/soliditycode_0.7.6/addressCheckNew.sol deleted file mode 100644 index 3c10b8c680d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addressCheckNew.sol +++ /dev/null @@ -1,9 +0,0 @@ -pragma experimental ABIEncoderV2; -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns(address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/addressCheckOld.sol b/framework/src/test/resources/soliditycode_0.7.6/addressCheckOld.sol deleted file mode 100644 index 6c6b15d1736..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/addressCheckOld.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testIsContract{ - function checkAddress(address addr) public returns (address){ - return addr; - } - function checkAddress2(address addr) pure public returns (address){ - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/altbn.sol b/framework/src/test/resources/soliditycode_0.7.6/altbn.sol deleted file mode 100644 index c3cfcdbe2b9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/altbn.sol +++ /dev/null @@ -1,61 +0,0 @@ -contract AltBn128 { - constructor() public payable {} - function callBn256Add(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas(), 0x06, 0, input, 0x80, result, 0x40) - } - - } - - function callBn256AddNoValue(bytes32 ax, bytes32 ay, bytes32 bx, bytes32 by) public returns - (bytes32[2] memory result) { - bytes32[4] memory input; - input[0] = ax; - input[1] = ay; - input[2] = bx; - input[3] = by; - assembly { - let success := call(gas(), 0xac, 0, input, 0x80, result, 0x40) - } - } - - function callBn256ScalarMul(bytes32 x, bytes32 y, bytes32 scalar) public returns (bytes32[2] memory result) { - bytes32[3] memory input; - input[0] = x; - input[1] = y; - input[2] = scalar; - assembly { - let success := call(gas(), 0x07, 0, input, 0x60, result, 0x40) - switch success - case 0 { - revert(0,0) - } - } - } - - function callBn256Pairing(bytes memory input) public returns (bytes32 result) { - // input is a serialized bytes stream of (a1, b1, a2, b2, ..., ak, bk) from (G_1 x G_2)^k - uint256 len = input.length; - require(len % 192 == 0); - assembly { - let memPtr := mload(0x40) - let success := call(gas(), 0x08, 0, add(input, 0x20), len, memPtr, 0x20) - switch success - case 0 { - revert(0,0) - } default { - result := mload(memPtr) - } - } - } - - function convert(uint256 num) public view returns(bytes32) { - return bytes32(num); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/arrayLength001.sol b/framework/src/test/resources/soliditycode_0.7.6/arrayLength001.sol deleted file mode 100644 index 46b2405a97e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/arrayLength001.sol +++ /dev/null @@ -1,64 +0,0 @@ - - -contract arrayLength { - byte[] a; - uint256[] IntergerArray; - bytes bs; - - // arrary length - function arrayPushValue() public returns (byte[] memory){ - a = new byte[](1); - a.push(0x01); - return a; - } - - function arrayPush() public returns(byte[] memory){ - a = new byte[](1); - a.push(); - return a; - } - - function arrayPop() public returns(byte[] memory){ - a = new byte[](1); - a.pop(); - return a; - } - - // arrary push/pop return Value - function arrayPushValueReturn() public { - a = new byte[](1); - return a.push(0x01); - } - - function arrayPushReturn() public returns (bytes1){ - a = new byte[](1); - return a.push(); - } - - function arrayPopReturn() public{ - a = new byte[](1); - return a.pop(); - } - - function uint256ArrayPushValue() public returns (byte[] memory){ - IntergerArray = [1,2,3]; - IntergerArray.push(); - return a; - } - - - // bytes - function bytesPushValue() public { - - return bs.push(0x01); - } - - function bytesPush() public returns (bytes1){ - return bs.push(); - } - - function bytesPop() public { - return bs.pop(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assemblyTest.sol b/framework/src/test/resources/soliditycode_0.7.6/assemblyTest.sol deleted file mode 100644 index 519a5a85fa3..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assemblyTest.sol +++ /dev/null @@ -1,61 +0,0 @@ - -contract assemblyTest { - - uint constant x = 1; - uint constant y = x; - function getZuint() public view returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - function getZuint2() public returns (uint) { - uint z = y + 1; - assembly { - z := y - } - return z; - } - - bool constant bool1 = true; - bool constant bool2 = bool1; - function getZbool() public view returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - function getZbool2() public returns (bool) { - bool z; - assembly { - z := bool2 - } - return z; - } - - -// string constant string1 = "abc"; -// string constant string2 = string1; -// function getZstring() public view returns (string memory) { -// string memory z; -// assembly { -// z := string2 -// } -// return z; -// } - - -// address origin1 = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; -// address origin2 = origin1; -// function getZaddress() public view returns (address) { -// address z; -// assembly { -// z := origin2 -// } -// return z; -// } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest1DivideInt.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest1DivideInt.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest2FindArgsContractMinTest.sol deleted file mode 100644 index 75436287805..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest2FindArgsContractMinTest.sol +++ /dev/null @@ -1,10 +0,0 @@ - -contract findArgsIContract{ -function findArgsByIndex1(uint i) public returns (uint z) { -uint[] memory a = new uint[](3); -a[0]=1; -a[1]=2; -a[2]=3; -return a[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest3ByteMinContract.sol deleted file mode 100644 index c8a2e5e363b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest3ByteMinContract.sol +++ /dev/null @@ -1,11 +0,0 @@ - -contract byteContract{ -bytes b; -function testBytesGet(uint i) public returns (bytes1){ -b = new bytes(3); -b[0]=0x0b; -b[1]=0x0c; -b[2]=0x0d; -return b[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest4Enum.sol deleted file mode 100644 index 6bd2ade2eea..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest4Enum.sol +++ /dev/null @@ -1,13 +0,0 @@ - - -contract enumContract { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices _choice; - function setGoStraight(ActionChoices choice) public { - _choice = choice; - } - - function getChoice() public returns (ActionChoices) { - return _choice; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest5MoveRight.sol deleted file mode 100644 index ad8f6f0f173..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest5MoveRight.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract binaryRightContract{ - function binaryMoveR(uint i)public returns (uint z) { - return z = 5 >> i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest6UninitializedContract.sol deleted file mode 100644 index c82e0f5806c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest6UninitializedContract.sol +++ /dev/null @@ -1,27 +0,0 @@ - -contract uni { -function b(int x, int y) internal returns (int) -{ - return x * y; -} - -function test1() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - funcPtr = b; - - // This call to funcPtr will succeed - return funcPtr(4, 5); -} - -function test2() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - // This call will fail because funcPtr is still a zero-initialized function pointer - return funcPtr(4, 5); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest7TestAssertContract.sol deleted file mode 100644 index 05b592e0682..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/assertExceptiontest7TestAssertContract.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract TestThrowsContract{ - function testAssert() public{ - assert(1==2); - } - function testRequire() public{ - require(2==1); - } - function testRevert() public{ - revert(); - } - function testThrow() public{ - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign.sol deleted file mode 100644 index 9e1c1b289b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - //function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - //} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign001.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign001.sol deleted file mode 100644 index 57e051ce415..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign001.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testPure(bytes32 hash, bytes[] memory signatures, address[] memory addresses) pure public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign002.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign002.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign002.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign003.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign003.sol deleted file mode 100644 index c43536af499..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign003.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { -bytes32 public result; -constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); -} -function testConstructor() public returns(bytes32){ - return result; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign005.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign005.sol deleted file mode 100644 index 3a6ca362973..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign005.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - - function testArray2(bytes memory data) public returns(bool, bytes memory){ - return address(0x9).delegatecall(data); - } - - function testArray4(bytes memory data) public { - //address(0x1).delegatecall(data); - } - function testArray3(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - //address(0x9).delegatecall(hash,signatures,addresses); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign007.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign007.sol deleted file mode 100644 index 974ffb34efe..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign007.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract Demo { - bytes32 public result; - - constructor (bytes32 hash, bytes[] memory signatures, address[] memory addresses) public { - result = batchvalidatesign(hash, signatures, addresses); - } - - function testConstructor() public returns(bytes32){ - return result; - } - - function testConstructorPure() public view returns(bytes32){ - return result; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign02.sol b/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign02.sol deleted file mode 100644 index 375cec3a2a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/batchvalidatesign02.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma experimental ABIEncoderV2; -contract Demo { - function testArray(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns(bytes32){ - - return batchvalidatesign(hash, signatures, addresses); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/callValueGasPure.sol b/framework/src/test/resources/soliditycode_0.7.6/callValueGasPure.sol deleted file mode 100644 index 6aab49bab84..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/callValueGasPure.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract C { -function check(address a) external pure returns (bool success) { - a.call{value:42,gas:42}; - a.call{gas:42}; - //a.call.value(1).gas(42)("fwefewf"); -} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/calldata.sol b/framework/src/test/resources/soliditycode_0.7.6/calldata.sol deleted file mode 100644 index 6e877ac1b2f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/calldata.sol +++ /dev/null @@ -1,33 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract C { - struct S { uint256 a; } - - function f(S calldata s) external returns (bytes memory) { - return abi.encode(s); - } - - function g(S calldata s) external returns (bytes memory) { - return this.f(s); - } - - function m(uint256[] calldata) external pure returns (bytes memory) { - return msg.data; - } - function h(uint8[] calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function i(uint8[][2] calldata s, uint256 which) external view returns (bytes memory) { - return this.h(s[which]); - } - function j(bytes calldata s) external pure returns (bytes memory) { - return abi.encode(s); - } - function k(bytes[2] calldata s, uint256 which) external view returns (bytes memory) { - return this.j(s[which]); - } - function l(function() external returns (uint)[] calldata s) external returns (uint, uint, uint) { - assert(s.length == 3); - return (s[0](), s[1](), s[2]()); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/callvalue.sol b/framework/src/test/resources/soliditycode_0.7.6/callvalue.sol deleted file mode 100644 index f01dcf2b52f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/callvalue.sol +++ /dev/null @@ -1,9 +0,0 @@ -contract Callvalue { -function check() public payable returns(uint) { - uint256 wad; - assembly { - wad := callvalue() - } - return wad; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/chainid001.sol b/framework/src/test/resources/soliditycode_0.7.6/chainid001.sol deleted file mode 100644 index 9cf24077dfb..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/chainid001.sol +++ /dev/null @@ -1,19 +0,0 @@ - -contract IstanbulTest { - constructor() public payable {} - function getId() public view returns(uint256){ - uint256 id; - assembly { - id := chainid() - } - return id; - } - - function getBalance(address src) public view returns(uint256){ - return address(src).balance; - } - - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/codeSaftySupport.sol b/framework/src/test/resources/soliditycode_0.7.6/codeSaftySupport.sol deleted file mode 100644 index 1cee8e4646c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/codeSaftySupport.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract IllegalDecorate { - -constructor() payable public{} - -fallback() payable external{} - -event log(uint256); - -function transferToken(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode_0.7.6/codeSaftyUnsupport.sol deleted file mode 100644 index fa65a134001..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/codeSaftyUnsupport.sol +++ /dev/null @@ -1,56 +0,0 @@ - - -contract SubC { - -event log(string); - -fallback() payable external{} - -function receiveToken() payable public{} - -function getBalance() view public returns (uint256 r) { -r = address(this).balance; -} -} - -contract UseDot { -constructor() payable public{} -fallback() payable external{} -mapping(address => mapping(trcToken => uint256)) sender_tokens; - -function trigger1(address payable addr, trcToken tokenInputId) payable public { - //address(SubC(addr)).call.value(1000).tokenId(tokenInputId)(abi.encodeWithSignature("receiveToken()")); // ERROR -} - -function trigger2(address payable addr) payable public { -// addr.transferToken.value(10)(10, 0x6e6d62); // ERROR -} - -function trigger3(address payable addr) payable public { - // address(SubC(addr)).receiveToken.tokenvalue(10)(); // ERROR -} - -function trigger4(address payable addr) payable public { - //SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR -} - -function trigger5(address payable addr) payable public { - SubC(addr).receiveToken{value:10}(); -} - -function trigger6(address payable addr, trcToken tokenId) payable public { -address(SubC(addr)).call{value:1000}(abi.encodeWithSignature("transferToken(uint256, trcToken)", 10, tokenId)); -} - -function trigger7(address addr) payable public { - //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger -} - -function trigger8(address addr) public payable returns(bytes memory r){ -// r = msg.data; // compile success, no necessary to trigger -} - -function getBalance() public returns (uint256 r){ -r = address(this).balance; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage001.sol b/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage001.sol deleted file mode 100644 index 1f584923a55..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage001.sol +++ /dev/null @@ -1,159 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} -contract viewCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = bytes32(uint256(0xdCad3a6d3569DF655070DEd0)); - bytes bs = new bytes(3); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.GoRight; - int64[] b = [-1, 2, -3]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - constructor() payable public{ - mapa[address(0x00)] = 34; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - function changeBool(bool param) public returns (bool){ - stopped = param; - emit log(stopped); - return stopped; - } - function getBool() public returns (bool){ - emit log(stopped); - return stopped; - } - function changeInt(int param) public returns (int){ - i = param; - emit log(i); - return i; - } - function getInt() public returns (int){ - emit log(i); - return i; - } - function changeNegativeInt(int param) public returns (int){ - i2 = param; - emit log(i2); - return i2; - } - function getNegativeInt() public returns (int){ - emit log(i2); - return i2; - } - function changeUint(uint param) public returns (uint){ - ui = param; - emit log(ui); - return ui; - } - function getUint() public returns (uint){ - emit log(ui); - return ui; - } - function changeAddress(address param) public returns (address){ - origin = param; - emit log(origin); - return origin; - } - function getAddress() public returns (address){ - emit log(origin); - return origin; - } - function changeBytes32(bytes32 param) public returns (bytes32){ - b32 = param; - emit log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - emit log(b32); - return b32; - } - function changeBytes(bytes memory param) public returns (bytes memory){ - bs = param; - emit log(bs); - return bs; - } - function getBytes() public returns (bytes memory){ - emit log(bs); - return bs; - } - function changeString(string memory param) public returns (string memory){ - s = param; - emit log(s); - return s; - } - function getString() public returns (string memory){ - emit log(s); - return s; - } - function changeActionChoices(ActionChoices param) public returns (ActionChoices){ - choice = param; - emit log(choice); - return choice; - } - function getActionChoices() public returns (ActionChoices){ - emit log(choice); - return choice; - } - function changeInt64NegativeArray(int64[] memory param) public returns (int64[] memory){ - b = param; - emit log(b); - return b; - } - function getInt64NegativeArray() public returns (int64[] memory){ - emit log(b); - return b; - } - function changeInt32Array(int32[2][] memory param) public returns (int32[2][] memory){ - tmp_h = param; - emit log(tmp_h); - return tmp_h; - } - function getInt32Array() public returns (int32[2][] memory){ - emit log(tmp_h); - return tmp_h; - } - function changeInt256Array(int256[2][2] memory param) public returns (int256[2][2] memory){ - tmp_i = param; - emit log(tmp_i); - return tmp_i; - } - function getInt256Array() public returns (int256[2][2] memory){ - emit log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage002.sol b/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage002.sol deleted file mode 100644 index 1ceba5e87d2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage002.sol +++ /dev/null @@ -1,16 +0,0 @@ -contract NotView { - uint256 public num = 123; - function setnum() public returns(uint256){ - num = num + 15; - return num; - } -} -contract NotViewInterface{ - function setnum() public view returns(uint256); -} -contract UseNotView { - function setnumuseproxy(address contractAddress) public view returns(uint256){ - NotViewInterface inter = NotViewInterface(contractAddress); - return inter.setnum(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage0425.sol b/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage0425.sol deleted file mode 100644 index 8ecf771626d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/constantCallStorage0425.sol +++ /dev/null @@ -1,156 +0,0 @@ -contract constantCall { - bool stopped = false; - int i = 32482989; - int i2 = -32482989; - uint ui = 23487823; - address origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - bytes bs = new bytes(9); - string s = "123qwe"; - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices choice = ActionChoices.SitStill; - int64[] b = [91, 2, 333]; - int32[2][] tmp_h = [[1,2],[3,4],[5,6]]; - int256[2][2] tmp_i = [[11,22],[33,44]]; - mapping (address => uint256) public mapa; - - constructor() payable public{ - mapa[address(0x00)] = 88; - } - event log(int); - event log(uint); - event log(bool); - event log(address); - event log(bytes32); - event log(bytes); - event log(string); - event log(ActionChoices); - event log(int64[]); - event log(int32[2][]); - event log(int256[2][2]); - - function changeBool(bool param) public constant returns (bool){ - stopped = param; - log(stopped); - return stopped; - } - function getBool() public constant returns (bool){ - log(stopped); - return stopped; - } - - function changeInt(int param) public returns (int){ - i = param; - log(i); - return i; - } - function getInt() public returns (int){ - log(i); - return i; - } - - function changeNegativeInt(int param) public constant returns (int){ - i2 = param; - log(i2); - return i2; - } - function getNegativeInt() public constant returns (int){ - log(i2); - return i2; - } - - function changeUint(uint param) public returns (uint){ - ui = param; - log(ui); - return ui; - } - function getUint() public returns (uint){ - log(ui); - return ui; - } - - function changeAddress(address param) public constant returns (address){ - origin = param; - log(origin); - return origin; - } - function getAddress() public constant returns (address){ - log(origin); - return origin; - } - - function changeBytes32(bytes32 param) public constant returns (bytes32){ - b32 = param; - log(b32); - return b32; - } - function getBytes32() public returns (bytes32){ - log(b32); - return b32; - } - - function changeBytes(bytes param) public constant returns (bytes){ - bs = param; - log(bs); - return bs; - } - function getBytes() public constant returns (bytes){ - log(bs); - return bs; - } - - function changeString(string param) public constant returns (string){ - s = param; - log(s); - return s; - } - function getString() public returns (string){ - log(s); - return s; - } - - function changeActionChoices(ActionChoices param) public constant returns (ActionChoices){ - choice = param; - log(choice); - return choice; - } - function getActionChoices() public constant returns (ActionChoices){ - log(choice); - return choice; - } - - function changeInt64NegativeArray(int64[] param) public constant returns (int64[]){ - b = param; - log(b); - return b; - } - function getInt64NegativeArray() public constant returns (int64[]){ - log(b); - return b; - } - - function changeInt32Array(int32[2][] param) public returns (int32[2][]){ - tmp_h = param; - log(tmp_h); - return tmp_h; - } - function getInt32Array() public constant returns (int32[2][]){ - log(tmp_h); - return tmp_h; - } - - function changeInt256Array(int256[2][2] param) public returns (int256[2][2]){ - tmp_i = param; - log(tmp_i); - return tmp_i; - } - function getInt256Array() public constant returns (int256[2][2]){ - log(tmp_i); - return tmp_i; - } - function setMapping(uint256 param) public returns (uint256){ - mapa[msg.sender] = param; - return mapa[msg.sender]; - - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/constantContract001.sol b/framework/src/test/resources/soliditycode_0.7.6/constantContract001.sol deleted file mode 100644 index 7d574c5a008..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/constantContract001.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract testConstantContract{ -function testPure(uint256 x,uint256 y) public pure returns (uint256 z) { -uint256 i=1; -return i + x + y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGetterContract.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGetterContract.sol deleted file mode 100644 index 365b53ebf1a..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGetterContract.sol +++ /dev/null @@ -1,17 +0,0 @@ - - - -contract getterContract { - -constructor() public payable{} -fallback() external payable{} - -uint public c = msg.value; - -function getDataUsingAccessor() public payable returns (uint){ - -return c; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test1Grammar001.sol deleted file mode 100644 index 659e56c9150..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test1Grammar001.sol +++ /dev/null @@ -1,18 +0,0 @@ - -contract FunctionSelector { - function select(bool useB, uint x) public returns (uint z) { - //var f = a; - //if (useB) f = b; - //return f(x); - if (useB) - return b(x); - else - return a(x); - } -function a(uint x) public returns (uint z) { - return x * x; - } -function b(uint x) public returns (uint z) { - return 2 * x; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test2Grammar002.sol deleted file mode 100644 index 744b17e9585..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test2Grammar002.sol +++ /dev/null @@ -1,44 +0,0 @@ - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert(Data storage self, uint value) public returns (bool) { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public returns (bool) { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public returns (bool) { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register (uint value) public{ - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test3Grammar003.sol deleted file mode 100644 index 140ba2a8f56..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test3Grammar003.sol +++ /dev/null @@ -1,44 +0,0 @@ - - -library Set { - struct Data { mapping(uint => bool) flags; } - - function insert(Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - using Set for Set.Data; // this is the crucial change - Set.Data knownValues; - - function register(uint value) public{ - // Here, all variables of type Set.Data have - // corresponding member functions. - // The following function call is identical to - // Set.insert(knownValues, value) - if (!knownValues.insert(value)) - revert(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test4Grammar004.sol deleted file mode 100644 index 772691cebc5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test4Grammar004.sol +++ /dev/null @@ -1,31 +0,0 @@ - - -library Search { - function indexOf(uint[] storage self, uint value) public returns (uint) { - for (uint i = 0; i < self.length; i++) - if (self[i] == value) return i; - return uint(-1); - } -} - - -contract C { - using Search for uint[]; - uint[] public data; - - function append(uint value) public{ - data.push(value); - } - - function replace(uint _old, uint _new) public{ - // This performs the library function call - uint index = data.indexOf(_old); - if (index == uint(-1)) - data.push(_new); - else - data[index] = _new; - } - function getData(uint256 index) public returns(uint256){ - return data[index]; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test5Grammar006.sol deleted file mode 100644 index 275d42d1e71..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar001test5Grammar006.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract InfoFeed { -function d1(uint x1) public{ - - assembly{ - function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } } - } - } - function d2(uint x1) public{ - assembly { - let x:=1 - x := mul(1, add(2, 3))} - } - function f(uint x) public{ - assembly { x := sub(x, 1) } - - } - // 0.6.0 Variable declarations cannot shadow declarations outside the assembly block. - function d(uint x1) public returns(uint256){ - uint256 x; - assembly{ - x := add(2, 3) - let y := mload(0x40) - x := add(x, y) - } - return x; - } - function d4(uint x) public{ - // Error: The labels 'repeat' is disallowed. Please use "if", "switch", "for" or function calls instead - //assembly{let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0)) - x = x; - //} - } - function d5(uint x1) public{ - assembly{ - function f(x) -> y { switch x case 0 { y := mul(x, 2) } default { y := 0 } } - - } - } - - function d6(uint x1) public{ - assembly{ - function f(x) -> y { for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) } } - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test1Grammar007_1.sol deleted file mode 100644 index 020c2a38ca4..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test1Grammar007_1.sol +++ /dev/null @@ -1,60 +0,0 @@ -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -// -abstract contract DogInterface { - function getDougAge(uint _age) public virtual returns (uint); - function contracts(bytes32 name) public virtual returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test1Grammar007_2.sol deleted file mode 100644 index 8945b566543..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test1Grammar007_2.sol +++ /dev/null @@ -1,60 +0,0 @@ - -contract Doug{ - mapping (bytes32 => uint) public contracts; - constructor() public{ - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string memory _name) public view returns(string memory) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -abstract contract DogInterface { - function getDougAge(uint _age) public virtual returns (uint); - function contracts(bytes32 name) public virtual returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) public { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) public returns (uint) { - - dogContract.contracts(_name); - emit FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test2Grammar008.sol deleted file mode 100644 index 956623c3103..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test2Grammar008.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -// version 0.6.0 change -// add abstract and override -abstract contract Feline { - - function utterance() public virtual returns (bytes32); - - function getContractName() public returns (string memory){ - return "Feline"; - } -} - - -contract Cat is Feline { - function utterance() public override returns (bytes32) { return "miaow"; } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test3Grammar010.sol deleted file mode 100644 index 617f96cb4e5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test3Grammar010.sol +++ /dev/null @@ -1,10 +0,0 @@ - -contract InfoFeed { -function info() public payable returns (uint ret) { return 42; } -} -contract Consumer { -constructor() payable public{} -InfoFeed feed; -function setFeed(address addr) public { feed = InfoFeed(addr); } -function callFeed() public payable { feed.info{value:10,gas:800}(); } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test4Grammar011.sol deleted file mode 100644 index fcd18f438ef..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test4Grammar011.sol +++ /dev/null @@ -1,11 +0,0 @@ - -contract C { -function f(uint key, uint value) public returns(uint) { -return key; -// do something -} -function g() public { -// named arguments -f({value: 2, key: 3}); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test4Grammar012.sol deleted file mode 100644 index 293b5e2ba9d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test4Grammar012.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract rTest { -function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { -//function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { -//var a = block.coinbase ; -//var b = block.difficulty; -//var c = block.gaslimit; -//var d = block.number; -//var e = block.blockhash(0); -//var e = d; -//var f = block.timestamp; -//bytes memory g = msg.data; -uint256 h = gasleft(); -address payable i = msg.sender; -bytes4 j = msg.sig; -uint256 k = msg.value; -uint256 l = block.timestamp; -uint256 m = tx.gasprice; -address payable n = tx.origin; -uint256 o = address(this).balance; -return (h,i,j,k,l,m,n,o); -//return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test6Grammar013.sol deleted file mode 100644 index 53de5def6bc..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar002test6Grammar013.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract Counter { -uint count = 0; -address payable owner; -//function Counter() public{ -constructor() public{ -owner = msg.sender; -} -function increment() public { -uint step = 10; -if (owner == msg.sender) { -count = count + step; -} -} -function getCount() public returns (uint){ -return count; -} -function kill() public{ -if (owner == msg.sender) { -selfdestruct(owner); -//selfdestruct(address(owner)); -} -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test1Grammar014.sol deleted file mode 100644 index b2d70b3741c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test1Grammar014.sol +++ /dev/null @@ -1,67 +0,0 @@ -contract A { -uint256 public numberForB; -address public senderForB; -function callTest(address bAddress, uint256 _number) public{ - -//bAddress.call(bytes4(sha3("setValue(uint256)")), _number); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("setValue(uint256)",_number)); // B's storage is set, A is not modified -} -function callcodeTest(address bAddress, uint256 _number) public{ -//bAddress.callcode(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} -function delegatecallTest(address bAddress, uint256 _number) public{ -//bAddress.delegatecall(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -bAddress.delegatecall(abi.encodeWithSignature("setValue(uint256)", _number)); // A's storage is set, B is not modified -} - -function callAddTest(address bAddress) public{ -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -//bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(abi.encodeWithSignature("add()")); // B's storage is set, A is not modified -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract B { -uint256 public numberForB; -address public senderForB; -address public addr11; -mapping(uint256=>address) public addr1; -mapping(uint256=>address) public addr2; -event ssss(uint256); -function setValue(uint256 _number) public{ - -emit ssss(_number); -numberForB = _number; -senderForB = msg.sender; -// senderForB is A if invoked by A's callTest. B's storage will be updated -// senderForB is A if invoked by A's callcodeTest. None of B's storage is updated -// senderForB is OWNER if invoked by A's delegatecallTest. None of B's storage is updated -} - -function add() public{ -numberForB=numberForB+1; -C c1 = new C(); -addr1[numberForB]=c1.getAddress(); -addr11 = c1.getAddress(); -C c2 = new C(); -addr2[numberForB] = c2.getAddress(); -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract C { -function getAddress() public view returns(address){ -return address(this); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test2Grammar015.sol deleted file mode 100644 index 0aa93e5e94f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test2Grammar015.sol +++ /dev/null @@ -1,40 +0,0 @@ - - -contract ExecuteFallback{ - - //回退事件,会把调用的数据打印出来 - event FallbackCalled(bytes data); - //fallback函数,注意是没有名字的,没有参数,没有返回值的 - // 0.6.0 Split unnamed fallback functions into two cases defined using fallback() and receive() - fallback() external{ - emit FallbackCalled(msg.data); - } - - //调用已存在函数的事件,会把调用的原始数据,请求参数打印出来 - event ExistFuncCalled(bytes data, uint256 para); - //一个存在的函数 - function existFunc(uint256 para) public{ - emit ExistFuncCalled(msg.data, para); - } - - // 模拟从外部对一个存在的函数发起一个调用,将直接调用函数 - function callExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("existFunc(uint256)")); - //this.call(funcIdentifier, uint256(1)); - address(this).call(abi.encode(funcIdentifier, uint256(1))); - } - - //模拟从外部对一个不存在的函数发起一个调用,由于匹配不到函数,将调用回退函数 - function callNonExistFunc() public{ - bytes4 funcIdentifier = bytes4(keccak256("functionNotExist()")); - //this.call(funcIdentifier); - address(this).call(abi.encode(funcIdentifier)); - } - - function ExistFuncCalledTopic() view public returns(bytes32){ - return keccak256("ExistFuncCalled(bytes,uint256)"); - } - function FallbackCalledTopic() view public returns(bytes32){ - return keccak256("FallbackCalled(bytes)"); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test3Grammar016.sol deleted file mode 100644 index 6a73d7a8d7e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test3Grammar016.sol +++ /dev/null @@ -1,23 +0,0 @@ - -contract C { -uint private data; -function f(uint a) private returns(uint b) { return a + 1; } -function setData(uint a) public { data = a; } -function getData() public returns(uint) { return data; } -function compute(uint a, uint b) internal returns (uint) { return a+b; } -} -contract D { -function readData() public{ -C c = new C(); -//uint local = c.f(7); // error: member "f" is not visible -c.setData(3); -uint local = c.getData(); -// local = c.compute(3, 5); // error: member "compute" is not visible -} -} -contract E is C { -function g() public { -C c = new C(); -uint val = compute(3, 5); // access to internal member (from derived to parent contract) -} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test4Grammar017.sol deleted file mode 100644 index 38746d90734..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test4Grammar017.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract CrowdFunding{ - struct Funder{ - address addr; - uint amount; - } - - struct Campaign{ - address payable beneficiary; - uint goal; - uint amount; - uint funderNum; - mapping(uint => Funder) funders; - } - - uint compaingnID; - mapping (uint => Campaign) campaigns; - - function candidate(address payable beneficiary, uint goal) public payable returns (uint compaingnID){ - // initialize - Campaign storage c = campaigns[compaingnID++]; - c.beneficiary = beneficiary; - c.goal = goal; - } - - function vote(uint compaingnID) payable public { - Campaign storage c = campaigns[compaingnID]; - - //another way to initialize - c.funders[c.funderNum++] = Funder({addr: msg.sender, amount: msg.value}); - c.amount += msg.value; - } - - function check(uint comapingnId) public payable returns (bool){ - Campaign storage c = campaigns[comapingnId]; - - if(c.amount < c.goal){ - return false; - } - - uint amount = c.amount; - // incase send much more - c.amount = 0; - // address payable addr = address(uint160(c.beneficiary)); - //if(! addr.send(amount)){ - - if (! c.beneficiary.send(amount)){ - revert(); - } - return true; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test5Grammar018.sol deleted file mode 100644 index ec241f3eae9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test5Grammar018.sol +++ /dev/null @@ -1,37 +0,0 @@ - - - -contract Grammar18{ - function testAddmod() public returns (uint z) { - //计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕 - z=addmod(2, 2, 3); - return z; - } - function testMulmod() public returns (uint z) { -//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。 - z=mulmod(2, 3, 4); - return z; - } - - function testKeccak256() public returns(bytes32){ - //计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 - return keccak256("11"); - } - - function testSha256() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - return sha256("11"); - } - function testSha3() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - //return sha3("11"); - return keccak256("11"); - } - - function testRipemd160() public returns(bytes32){ - //计算(紧密包装)参数的RIPEMD-160哈希值 - return ripemd160("11"); - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test6Grammar019.sol deleted file mode 100644 index 727ef7091e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test6Grammar019.sol +++ /dev/null @@ -1,12 +0,0 @@ - -contract timetest { - -constructor() public { -require( 1 == 1 seconds); -require(1 minutes == 60 seconds); -require(1 hours == 60 minutes); -require(1 days == 24 hours); -require(1 weeks == 7 days); -//require(1 years == 365 days); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test7Grammar020.sol deleted file mode 100644 index 39a7fddcb7e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractGrammar003test7Grammar020.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract trxtest { - -function test() public { -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInnerContract.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInnerContract.sol deleted file mode 100644 index 5e6addef105..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInnerContract.sol +++ /dev/null @@ -1,32 +0,0 @@ - - - - -contract InnerContract { - - constructor() public payable{} - fallback() external payable{} - - function messageI() payable public returns (uint ret) { - - - - } - -} - - - -contract OuterContract { - - - constructor() public payable{} - fallback() external payable{} - - function callInner(address payable addr) payable public returns (uint) { - - return InnerContract(addr).messageI{value:1}(); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction001.sol deleted file mode 100644 index 52dcfb16fc3..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction001.sol +++ /dev/null @@ -1,41 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address payable cAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - B b2 = new B();//1.2 - payable(address(b2)).transfer(5);//1.3 - b2.callCGetZero(cAddr, 1);//1.4 - b2.callCGetZero(cAddr,2);//1.6 - } - function test2(address payable cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - cAddress.call{value:amount + 1}(abi.encodeWithSignature("newBAndTransfer()"));//2.6 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(address payable cAddress,uint256 amount) public{ - cAddress.call{value:amount}(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - B b1 = (new B){value:7}();//2.2,2.7 - b1.getOne();//2.3,2.8 - B b2 = (new B){value:3}();//2.4,2.9 - b2.getOne();//2.5,2.10 - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction002.sol deleted file mode 100644 index 502e42d0c7b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction002.sol +++ /dev/null @@ -1,20 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - - function test2(address cAddress,uint256 amount) public payable{ - //cAddress.call.value(amount)();//2.1 - cAddress.call{value:amount}("");//2.1 - } -} - - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction003.sol deleted file mode 100644 index 9d3e38affbd..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction003.sol +++ /dev/null @@ -1,30 +0,0 @@ - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - B b = (new B){value:10}();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction004.sol deleted file mode 100644 index e8f32d7bfd9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction004.sol +++ /dev/null @@ -1,24 +0,0 @@ - -contract A{ - constructor () payable public{} - function test(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - fallback() payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} -contract B{ - fallback() external payable{} - function kill(address contractAddres, address toAddress) payable public { - contractAddres.call(abi.encodeWithSignature("test(address)",address(this))); - } - function kill2() public{ - A a = new A(); - a.test(payable(address(this))); - } - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction005.sol deleted file mode 100644 index f6bdf294a99..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction005.sol +++ /dev/null @@ -1,53 +0,0 @@ - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1() public payable{ - B b1 = (new B){value:10}();//1.1 - b1.callCGetZero(false); - b1.callCGetZero(true);//1.4 - } - function test2() public payable{ - C c1 = (new C){value:10}();//1.1 - c1.newBAndTransfer(false); - c1.newBAndTransfer(true);//1.4 - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction006.sol deleted file mode 100644 index ec574998b29..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction001testInternalTransaction006.sol +++ /dev/null @@ -1,54 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1() public payable{ - B b1 = (new B){value:10}();//1.1 - b1.callCGetZero(true);//1.4 - b1.callCGetZero(false); - } - function test2() public payable{ - C c1 = (new C){value:10}();//1.1 - c1.newBAndTransfer(true);//1.4 - c1.newBAndTransfer(false); - - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) public payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test1InternalTransaction007.sol deleted file mode 100644 index d14c3d8aa16..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test1InternalTransaction007.sol +++ /dev/null @@ -1,38 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address cAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - B b2 = new B();//1.2 - payable(address(b2)).transfer(5);//1.3 - b2.callCGetZero();//1.4 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero() public{ - assert(1==2); - - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test2InternalTransaction008.sol deleted file mode 100644 index 2e57a0e635c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test2InternalTransaction008.sol +++ /dev/null @@ -1,60 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - - function testAssert(address bAddress,uint256 amount) public payable{ - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",true)); - } - function testRequire(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - } - function testAssert1(address bAddress,uint256 amount) public payable{ - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",true)); - bAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("callCGetZero(bool)",false));//2.1 - } - function testtRequire2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",true)); - cAddress.call{value:amount,gas:1000000}(abi.encodeWithSignature("newBAndTransfer(bool)",false));//2.1 - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable public{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return address(this).balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test3InternalTransaction009.sol deleted file mode 100644 index d750df65ea4..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test3InternalTransaction009.sol +++ /dev/null @@ -1,47 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address cAddr,address dcontract,address baddress) public payable{ - B b1 = (new B){value:10}();//1.1 - payable(address(b1)).transfer(5);//1.3 - b1.callCGetZero(cAddr, 1);//1.4 - b1.getOne(dcontract,baddress); - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne(address contractAddres, address toAddress) payable public{ - contractAddres.call(abi.encodeWithSignature("suicide1(address)",address(this))); - - } - function callCGetZero(address cAddress,uint256 amount) public{ - cAddress.call{value:amount}(abi.encodeWithSignature("getZero()"));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public{ - B b1 = (new B){value:7}();//2.2,2.7 - B b2 = (new B){value:3}();//2.4,2.9 - } -} - -contract D{ - constructor () payable public{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - fallback() payable external{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test4InternalTransaction010.sol deleted file mode 100644 index ff5817ea173..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test4InternalTransaction010.sol +++ /dev/null @@ -1,186 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - } - function transfer2() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - } - function getBalance() public returns(uint256) { - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test4InternalTransaction010_1.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test4InternalTransaction010_1.sol deleted file mode 100644 index d0c80d14ffb..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test4InternalTransaction010_1.sol +++ /dev/null @@ -1,210 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - fallback() payable{} - } - - \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test5InternalTransaction012.sol deleted file mode 100644 index 59ffe9f0fe9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction002test5InternalTransaction012.sol +++ /dev/null @@ -1,51 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address bAddr,address eAddr) public payable{ - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - } - -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable{ - D d1=(new D){value:1000}(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call{value:1}(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction013.sol deleted file mode 100644 index 1dae0beb03c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction013.sol +++ /dev/null @@ -1,56 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address dAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - b1.testNN(dAddr,2);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount) public payable{ - // D d1=(new D)(); - dAddress.call{value:amount}(abi.encodeWithSignature("getOne()"));//2.1 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - E e = (new E){value:5}(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction014.sol deleted file mode 100644 index 0346cec669b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction014.sol +++ /dev/null @@ -1,38 +0,0 @@ -contract callerContract { - constructor() payable public{} - fallback() payable external{} - function sendToB(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - - contract calledContract { - fallback() payable external {} - constructor() payable public{} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call{value:5}(abi.encodeWithSignature("setI()")); - } - - } - - contract c{ - uint256 public i=0; - constructor() public payable{} - function getBalance() public view returns(uint256){ - return address(this).balance; - } - function setI() payable public{ - i=5; - } - fallback() payable external{} - } diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction015.sol deleted file mode 100644 index edeb9488454..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction015.sol +++ /dev/null @@ -1,60 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address dAddr,address eAddr) public payable{ - B b1 = (new B){value:10}();//1.1 - b1.testNN(dAddr,2,eAddr);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call{value:amount}(abi.encodeWithSignature("newBAndTransfer()"));//2.1 - } -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount,address eAddress) public payable{ - // D d1=(new D)(); - dAddress.call{value:amount}(abi.encodeWithSignature("getOne(address)",address(this)));//2.1 - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } - function suicide(address payable toAddress) public payable{ - selfdestruct(toAddress); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address payable eAddress) payable public{ - E e = (new E){value:5}(); - e.suicide(eAddress); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction016.sol deleted file mode 100644 index 418d4d09ac0..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction016.sol +++ /dev/null @@ -1,174 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - fallback() payable external{} - function transfer() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - B b1=(new B){value:1}();//1 - address payable aaa=address(this); - b1.suicide1(aaa); - } - function transfer2() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - B b1=(new B){value:1}();//1 - address payable aaa=address(this); - b1.suicide1(aaa); - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - function suicide1(address payable toAddress) public payable{ - selfdestruct(toAddress); - } - } - diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction017.sol deleted file mode 100644 index 32cf9f2a04d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction017.sol +++ /dev/null @@ -1,199 +0,0 @@ - - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer(address payable Address) payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - B b=(new B){value:1}();//1 - selfdestruct(Address); - } - function transfer2() payable public{ - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - (new B){value:1}();//1 - - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable public returns(bool) { - return true; - } - constructor() public payable {} - function payC(address payable c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return address(this).balance; - } - fallback() payable external{} - } - diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction018.sol deleted file mode 100644 index fadb5f84b51..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractInternalTransaction003testInternalTransaction018.sol +++ /dev/null @@ -1,97 +0,0 @@ - - -contract A{ - constructor() payable public{} - fallback() payable external{} - function test1(address payable bAddr,address eAddr) public payable{ - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - bAddr.call{value:1}(abi.encodeWithSignature("testNN(address)",eAddr));//2.1 - - } - -} - -contract B{ - constructor() payable public{} - fallback() payable external{} - function getOne() payable public returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable { - D d1=(new D){value:100}(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - fallback() payable external{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - fallback() payable external{} - function getOne(address eAddress) payable public returns(uint256){ - eAddress.call{value:1}(abi.encodeWithSignature("getZero()"));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractLinkage001.sol deleted file mode 100644 index 8d441fba2da..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage001.sol +++ /dev/null @@ -1,9 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -constructor() payable public{} -fallback() payable external{} -function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage002.sol b/framework/src/test/resources/soliditycode_0.7.6/contractLinkage002.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage002.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage003.sol b/framework/src/test/resources/soliditycode_0.7.6/contractLinkage003.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage003.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage004.sol b/framework/src/test/resources/soliditycode_0.7.6/contractLinkage004.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage004.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage005.sol b/framework/src/test/resources/soliditycode_0.7.6/contractLinkage005.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage005.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage006.sol b/framework/src/test/resources/soliditycode_0.7.6/contractLinkage006.sol deleted file mode 100644 index 53449f61ce2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractLinkage006.sol +++ /dev/null @@ -1,18 +0,0 @@ - -contract AA{ - uint256 public count=0; - constructor () payable public{} - function init(address payable addr, uint256 max) payable public { - count =0; - this.hack(addr,max); - } - function hack(address payable addr, uint256 max) payable public { - while (count < max) { - count = count +1; - this.hack(addr,max); - } - if (count == max) { - addr.send(20); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractOriginEnergyLimit001.sol deleted file mode 100644 index 6feb7fff3b8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractOriginEnergyLimit001.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode_0.7.6/contractOriginEnergyLimit004.sol deleted file mode 100644 index 6feb7fff3b8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractOriginEnergyLimit004.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode_0.7.6/contractOtherToTrcToken.sol deleted file mode 100644 index 933358e128b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractOtherToTrcToken.sol +++ /dev/null @@ -1,41 +0,0 @@ - - -contract ConvertType { - -constructor() payable public{} - -fallback() payable external{} - -//function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { -// trcToken t = trcToken(tokenStr); // ERROR -// toAddress.transferToken(tokenValue, tokenStr); // ERROR -//} - -function uint256ToTrctoken(address payable toAddress, uint256 tokenValue, uint256 tokenInt) public { - trcToken t = trcToken(tokenInt); // OK - toAddress.transferToken(tokenValue, t); // OK - toAddress.transferToken(tokenValue, tokenInt); // OK -} - -function addressToTrctoken(address payable toAddress, uint256 tokenValue, address adr) public { - trcToken t = trcToken(adr); // OK - toAddress.transferToken(tokenValue, t); // OK -//toAddress.transferToken(tokenValue, adr); // ERROR -} - -//function bytesToTrctoken(address payable toAddress, bytes memory b, uint256 tokenValue) public { - // trcToken t = trcToken(b); // ERROR - // toAddress.transferToken(tokenValue, b); // ERROR -//} - -function bytes32ToTrctoken(address payable toAddress, uint256 tokenValue, bytes32 b32) public { - trcToken t = trcToken(b32); // OK - toAddress.transferToken(tokenValue, t); // OK -// toAddress.transferToken(tokenValue, b32); // ERROR -} - -//function arrayToTrctoken(address payable toAddress, uint256[] memory arr, uint256 tokenValue) public { -//trcToken t = trcToken(arr); // ERROR -// toAddress.transferToken(tokenValue, arr); // ERROR -//} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario001.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario001.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario002.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario002.sol deleted file mode 100644 index 5b990fe36e8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario002.sol +++ /dev/null @@ -1,53 +0,0 @@ - -contract TronNative{ - - address public voteContractAddress= address(0x10001); - address public freezeBalanceAddress = address(0x10002); - address public unFreezeBalanceAddress = address(0x10003); - address public withdrawBalanceAddress = address(0x10004); - address public approveProposalAddress = address(0x10005); - address public createProposalAddress = address(0x10006); - address public deleteProposalAddress = address(0x10007); - constructor () payable public {} - - function voteForSingleWitness (address payable witnessAddr, uint256 voteValue) public{ - // method 1: - voteContractAddress.delegatecall(abi.encode(witnessAddr,voteValue)); - } - - function voteUsingAssembly (address witnessAddr, uint256 voteValue) public{ - // method 2: - assembly{ - mstore(0x80,witnessAddr) - mstore(0xa0,voteValue) - // gas, address, in, size, out, size - if iszero(delegatecall(0, 0x10001, 0x80, 0x40, 0x80, 0x0)) { - revert(0, 0) - } - } - } - - function freezeBalance(uint256 frozen_Balance,uint256 frozen_Duration) public { - freezeBalanceAddress.delegatecall(abi.encode(frozen_Balance,frozen_Duration)); - } - - function unFreezeBalance() public { - unFreezeBalanceAddress.delegatecall(""); - } - - function withdrawBalance() public { - withdrawBalanceAddress.delegatecall(""); - } - - function approveProposal(uint256 id, bool isApprove) public { - approveProposalAddress.delegatecall(abi.encode(id,isApprove)); - } - - function createProposal(bytes32 [] memory data) public { - createProposalAddress.delegatecall(abi.encode(data)); - } - - function deleteProposal(uint256 id) public{ - deleteProposalAddress.delegatecall(abi.encode(id)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario003.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario003.sol deleted file mode 100644 index 92778e42bc9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario003.sol +++ /dev/null @@ -1,7 +0,0 @@ - - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario004.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario004.sol deleted file mode 100644 index f6919502914..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario004.sol +++ /dev/null @@ -1,88 +0,0 @@ - - -contract TronToken { - - string public name = "Tronix"; // token name - string public symbol = "TRX"; // token symbol - uint256 public decimals = 6; // token digit - - mapping (address => uint256) public balanceOf; - mapping (address => mapping (address => uint256)) public allowance; - - uint256 public totalSupply = 0; - bool public stopped = false; - - uint256 constant valueFounder = 100000000000000000; - address owner = address(0x0); - - modifier isOwner { - assert(owner == msg.sender); - _; - } - - modifier isRunning { - assert (!stopped); - _; - } - - modifier validAddress { - assert(address(0x0) != msg.sender); - _; - } - - constructor(address _addressFounder) public { - owner = msg.sender; - totalSupply = valueFounder; - balanceOf[_addressFounder] = valueFounder; - emit Transfer(address(0x0), _addressFounder, valueFounder); - } - - function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[msg.sender] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - balanceOf[msg.sender] -= _value; - balanceOf[_to] += _value; - emit Transfer(msg.sender, _to, _value); - return true; - } - - function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[_from] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - require(allowance[_from][msg.sender] >= _value); - balanceOf[_to] += _value; - balanceOf[_from] -= _value; - allowance[_from][msg.sender] -= _value; - emit Transfer(_from, _to, _value); - return true; - } - - function approve(address _spender, uint256 _value) isRunning validAddress public returns (bool success) { - require(_value == 0 || allowance[msg.sender][_spender] == 0); - allowance[msg.sender][_spender] = _value; - emit Approval(msg.sender, _spender, _value); - return true; - } - - function stop() isOwner public { - stopped = true; - } - - function start() isOwner public { - stopped = false; - } - - function setName(string memory _name) isOwner public { - name = _name; - } - - function burn(uint256 _value) public { - require(balanceOf[msg.sender] >= _value); - balanceOf[msg.sender] -= _value; - balanceOf[address(0x0)] += _value; - emit Transfer(msg.sender, address(0x0), _value); - } - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario005.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario005.sol deleted file mode 100644 index 39fe4665559..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario005.sol +++ /dev/null @@ -1,103 +0,0 @@ - - -interface token { - function transfer(address receiver, uint amount) external; -} - -contract Crowdsale { - address payable public beneficiary = 0x1b228F5D9f934c7bb18Aaa86F90418932888E7b4; // 募资成功后的收款方 - uint public fundingGoal = 10000000; // 募资额度 - uint public amountRaised = 1000000; // 参与数量 - uint public deadline; // 募资截止期 - - uint public price; // token 与以太坊的汇率 , token卖多少钱 - token public tokenReward; // 要卖的token - - mapping(address => uint256) public balanceOf; - - bool fundingGoalReached = false; // 众筹是否达到目标 - bool crowdsaleClosed = false; // 众筹是否结束 - - /** - * 事件可以用来跟踪信息 - **/ - event GoalReached(address recipient, uint totalAmountRaised); - event FundTransfer(address backer, uint amount, bool isContribution); - - /** - * 构造函数, 设置相关属性 - */ - constructor( - address payable ifSuccessfulSendTo, - uint fundingGoalInEthers, - uint durationInMinutes, - uint finneyCostOfEachToken, - address addressOfTokenUsedAsReward) public{ - beneficiary = ifSuccessfulSendTo; - fundingGoal = fundingGoalInEthers * 1 sun; - deadline = block.timestamp + durationInMinutes * 1 minutes; - price = finneyCostOfEachToken * 1 trx; - tokenReward = token(addressOfTokenUsedAsReward); // 传入已发布的 token 合约的地址来创建实例 - } - - /** - * 无函数名的Fallback函数, - * 在向合约转账时,这个函数会被调用 - */ - fallback() payable external{ - require(!crowdsaleClosed); - uint amount = msg.value; - balanceOf[msg.sender] += amount; - amountRaised += amount; - tokenReward.transfer(msg.sender, amount / price); - emit FundTransfer(msg.sender, amount, true); - } - - /** - * 定义函数修改器modifier(作用和Python的装饰器很相似) - * 用于在函数执行前检查某种前置条件(判断通过之后才会继续执行该方法) - * _ 表示继续执行之后的代码 - **/ - modifier afterDeadline() { if (block.timestamp >= deadline) _; } - - /** - * 判断众筹是否完成融资目标, 这个方法使用了afterDeadline函数修改器 - * - */ - function checkGoalReached() afterDeadline public{ - if (amountRaised >= fundingGoal) { - fundingGoalReached = true; - emit GoalReached(beneficiary, amountRaised); - } - crowdsaleClosed = true; - } - - - /** - * 完成融资目标时,融资款发送到收款方 - * 未完成融资目标时,执行退款 - * - */ - function safeWithdrawal() afterDeadline public{ - if (!fundingGoalReached) { - uint amount = balanceOf[msg.sender]; - balanceOf[msg.sender] = 0; - if (amount > 0) { - if (msg.sender.send(amount)) { - emit FundTransfer(msg.sender, amount, false); - } else { - balanceOf[msg.sender] = amount; - } - } - } - - if (fundingGoalReached && beneficiary == msg.sender) { - if (payable(beneficiary).send(amountRaised)) { - emit FundTransfer(beneficiary, amountRaised, false); - } else { - //If we fail to send the funds to beneficiary, unlock funders balance - fundingGoalReached = false; - } - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario006.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario006.sol deleted file mode 100644 index 7b8e2270e23..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario006.sol +++ /dev/null @@ -1,1963 +0,0 @@ - - -interface PlayerBookInterface { - function getPlayerID(address _addr) external returns (uint256); - function getPlayerName(uint256 _pID) external view returns (bytes32); - function getPlayerLAff(uint256 _pID) external view returns (uint256); - function getPlayerAddr(uint256 _pID) external view returns (address); - function getNameFee() external view returns (uint256); - function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); - function isDev(address _who) external view returns(bool); -} - - -/** -* @title -Name Filter- v0.1.9 -* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ -* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ -* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ -* _____ _____ -* (, / /) /) /) (, / /) /) -* ┌─┐ / _ (/_ // // / _ // _ __ _(/ -* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ -* ┴ ┴ / / .-/ _____ (__ / -* (__ / (_/ (, / /)™ -* / __ __ __ __ _ __ __ _ _/_ _ _(/ -* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ -* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 -* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ -* _ __ _ ____ ____ _ _ _____ ____ ___ -*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* -*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* -* -* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ -* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ -* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ -*/ - -library NameFilter { - /** - * @dev filters name strings - * -converts uppercase to lower case. - * -makes sure it does not start/end with a space - * -makes sure it does not contain multiple spaces in a row - * -cannot be only numbers - * -cannot start with 0x - * -restricts characters to A-Z, a-z, 0-9, and space. - * @return reprocessed string in bytes32 format - */ - function nameFilter(string memory _input) - internal - pure - returns(bytes32) - { - bytes memory _temp = bytes(_input); - uint256 _length = _temp.length; - - //sorry limited to 32 characters - require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); - // make sure it doesnt start with or end with space - require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); - // make sure first two characters are not 0x - if (_temp[0] == 0x30) - { - require(_temp[1] != 0x78, "string cannot start with 0x"); - require(_temp[1] != 0x58, "string cannot start with 0X"); - } - - // create a bool to track if we have a non number character - bool _hasNonNumber; - - // convert & check - for (uint256 i = 0; i < _length; i++) - { - // if its uppercase A-Z - if (_temp[i] > 0x40 && _temp[i] < 0x5b) - { - // convert to lower case a-z - _temp[i] = byte(uint8(_temp[i]) + 32); - - // we have a non number - if (_hasNonNumber == false) - _hasNonNumber = true; - } else { - require - ( - // require character is a space - _temp[i] == 0x20 || - // OR lowercase a-z - (_temp[i] > 0x60 && _temp[i] < 0x7b) || - // or 0-9 - (_temp[i] > 0x2f && _temp[i] < 0x3a), - "string contains invalid characters" - ); - // make sure theres not 2x spaces in a row - if (_temp[i] == 0x20) - require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); - - // see if we have a character other than a number - if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) - _hasNonNumber = true; - } - } - - require(_hasNonNumber == true, "string cannot be only numbers"); - - bytes32 _ret; - assembly { - _ret := mload(add(_temp, 32)) - } - return (_ret); - } -} - - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - if (a == 0) { - return 0; - } - c = a * b; - require(c / a == b, "SafeMath mul failed"); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return c; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { - require(b <= a, "SafeMath sub failed"); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - c = a + b; - require(c >= a, "SafeMath add failed"); - return c; - } - - /** - * @dev gives square root of given x. - */ - function sqrt(uint256 x) - internal - pure - returns (uint256 y) - { - uint256 z = ((add(x,1)) / 2); - y = x; - while (z < y) - { - y = z; - z = ((add((x / z),z)) / 2); - } - } - - /** - * @dev gives square. multiplies x by x - */ - function sq(uint256 x) - internal - pure - returns (uint256) - { - return (mul(x,x)); - } - - /** - * @dev x to the power of y - */ - function pwr(uint256 x, uint256 y) - internal - pure - returns (uint256) - { - if (x==0) - return (0); - else if (y==0) - return (1); - else - { - uint256 z = x; - for (uint256 i=1; i < y; i++) - z = mul(z,x); - return (z); - } - } -} - -//============================================================================== -// | _ _ _ | _ . -// |<(/_\/ (_(_||(_ . -//=======/====================================================================== -library F3DKeysCalcLong { - using SafeMath for *; - /** - * @dev calculates number of keys received given X eth - * @param _curEth current amount of eth in contract - * @param _newEth eth being spent - * @return amount of ticket purchased - */ - function keysRec(uint256 _curEth, uint256 _newEth) - internal - pure - returns (uint256) - { - return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); - } - - /** - * @dev calculates amount of eth received if you sold X keys - * @param _curKeys current amount of keys that exist - * @param _sellKeys amount of keys you wish to sell - * @return amount of eth received - */ - function ethRec(uint256 _curKeys, uint256 _sellKeys) - internal - pure - returns (uint256) - { - return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); - } - - /** - * @dev calculates how many keys would exist with given an amount of eth - * @param _eth eth "in contract" - * @return number of keys that would exist - */ - function keys(uint256 _eth) - internal - pure - returns(uint256) - { - return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); - } - - /** - * @dev calculates how much eth would be in contract given a number of keys - * @param _keys number of keys "in contract" - * @return eth that would exists - */ - function eth(uint256 _keys) - internal - pure - returns(uint256) - { - return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); - } -} - -library F3Ddatasets { - //compressedData key - // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] - // 0 - new player (bool) - // 1 - joined round (bool) - // 2 - new leader (bool) - // 3-5 - air drop tracker (uint 0-999) - // 6-16 - round end time - // 17 - winnerTeam - // 18 - 28 timestamp - // 29 - team - // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) - // 31 - airdrop happened bool - // 32 - airdrop tier - // 33 - airdrop amount won - //compressedIDs key - // [77-52][51-26][25-0] - // 0-25 - pID - // 26-51 - winPID - // 52-77 - rID - struct EventReturns { - uint256 compressedData; - uint256 compressedIDs; - address winnerAddr; // winner address - bytes32 winnerName; // winner name - uint256 amountWon; // amount won - uint256 newPot; // amount in new pot - uint256 P3DAmount; // amount distributed to p3d - uint256 genAmount; // amount distributed to gen - uint256 potAmount; // amount added to pot - } - struct Player { - address payable addr; // player address - bytes32 name; // player name - uint256 win; // winnings vault - uint256 gen; // general vault - uint256 aff; // affiliate vault - uint256 lrnd; // last round played - uint256 laff; // last affiliate id used - } - struct PlayerRounds { - uint256 eth; // eth player has added to round (used for eth limiter) - uint256 keys; // keys - uint256 mask; // player mask - uint256 ico; // ICO phase investment - } - struct Round { - uint256 plyr; // pID of player in lead - uint256 team; // tID of team in lead - uint256 end; // time ends/ended - bool ended; // has round end function been ran - uint256 strt; // time round started - uint256 keys; // keys - uint256 eth; // total eth in - uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) - uint256 mask; // global mask - uint256 ico; // total eth sent in during ICO phase - uint256 icoGen; // total eth for gen during ICO phase - uint256 icoAvg; // average key price for ICO phase - } - struct TeamFee { - uint256 gen; // % of buy in thats paid to key holders of current round - uint256 p3d; // % of buy in thats paid to p3d holders - } - struct PotSplit { - uint256 gen; // % of pot thats paid to key holders of current round - uint256 p3d; // % of pot thats paid to p3d holders - } -} - -contract F3Devents { - // fired whenever a player registers a name - event onNewName - ( - uint256 indexed playerID, - address indexed playerAddress, - bytes32 indexed playerName, - bool isNewPlayer, - uint256 affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 amountPaid, - uint256 timeStamp - ); - - // fired at end of buy or reload - event onEndTx - ( - uint256 compressedData, - uint256 compressedIDs, - bytes32 playerName, - address playerAddress, - uint256 ethIn, - uint256 keysBought, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount, - uint256 potAmount, - uint256 airDropPot - ); - - // fired whenever theres a withdraw - event onWithdraw - ( - uint256 indexed playerID, - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 timeStamp - ); - - // fired whenever a withdraw forces end round to be ran - event onWithdrawAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a buy after round timer - // hit zero, and causes end round to be ran. - event onBuyAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethIn, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a reload after round timer - // hit zero, and causes end round to be ran. - event onReLoadAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // fired whenever an affiliate is paid - event onAffiliatePayout - ( - uint256 indexed affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 indexed roundID, - uint256 indexed buyerID, - uint256 amount, - uint256 timeStamp - ); - - // received pot swap deposit - event onPotSwapDeposit - ( - uint256 roundID, - uint256 amountAddedToPot - ); -} - - - -contract FoMo3Dlong is F3Devents { - using SafeMath for *; - using NameFilter for string; - using F3DKeysCalcLong for uint256; - - address public otherF3D_; - address public Divies; - address public Jekyll_Island_Inc; - PlayerBookInterface public playerBook;// =PlayerBookInterface(0x0dcd2f752394c41875e259e00bb44fd505297caf);//new PlayerBook();// - // TeamJustInterface constant private teamJust = TeamJustInterface(0x3a5f8140b9213a0f733a6a639857c9df43ee3f5a);// new TeamJust();// - - //============================================================================== - // _ _ _ |`. _ _ _ |_ | _ _ . - // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) - //=================_|=========================================================== - string constant public name = "FoMo3D Long Official"; - string constant public symbol = "F3D"; - uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO - uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. - uint256 constant private rndInit_ = 1 hours; // round timer starts at this - uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer - uint256 constant private rndMax_ = 24 hours; // max length a round timer can be - //============================================================================== - // _| _ _|_ _ _ _ _|_ _ . - // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) - //=============================|================================================ - uint256 public airDropPot_; // person who gets the airdrop wins part of this pot - uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop - uint256 public rID_; // round id number / total rounds that have happened - //**************** - // PLAYER DATA - //**************** - mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address - mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name - mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data - mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id - mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) - //**************** - // ROUND DATA - //**************** - mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data - mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id - //**************** - // TEAM FEE DATA - //**************** - mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team - mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team - - function setPlayerBook(address _playerBook) external { - require(msg.sender == owner, 'only dev!'); - require(address(playerBook) == address(0), 'already set!'); - playerBook = PlayerBookInterface(_playerBook); - } - - address public owner; - - //============================================================================== - // _ _ _ __|_ _ __|_ _ _ . - // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) - //============================================================================== - constructor() - public - { - owner = msg.sender; - // Team allocation structures - // 0 = whales - // 1 = bears - // 2 = sneks - // 3 = bulls - - // Team allocation percentages - // (F3D, P3D) + (Pot , Referrals, Community) - // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. - fees_[0] = F3Ddatasets.TeamFee(30, 6); - //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[1] = F3Ddatasets.TeamFee(43, 0); - //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[2] = F3Ddatasets.TeamFee(56, 10); - //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[3] = F3Ddatasets.TeamFee(43, 8); - //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - - // how to split up the final pot based on which team was picked - // (F3D, P3D) - potSplit_[0] = F3Ddatasets.PotSplit(15, 10); - //48% to winner, 25% to next round, 2% to com - potSplit_[1] = F3Ddatasets.PotSplit(25, 0); - //48% to winner, 25% to next round, 2% to com - potSplit_[2] = F3Ddatasets.PotSplit(20, 20); - //48% to winner, 10% to next round, 2% to com - potSplit_[3] = F3Ddatasets.PotSplit(30, 10); - //48% to winner, 10% to next round, 2% to com - } - //============================================================================== - // _ _ _ _|. |`. _ _ _ . - // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) - //============================================================================== - /** - * @dev used to make sure no one can interact with contract until it has - * been activated. - */ - modifier isActivated() { - require(activated_ == true, "its not ready yet. check ?eta in discord"); - _; - } - - /** - * @dev prevents contracts from interacting with fomo3d - */ - modifier isHuman() { - address _addr = msg.sender; - uint256 _codeLength; - - assembly {_codeLength := extcodesize(_addr)} - require(_codeLength == 0, "sorry humans only"); - _; - } - - modifier onlyDevs() - { - require(playerBook.isDev(msg.sender) == true, "msg sender is not a dev"); - _; - } - - /** - * @dev sets boundaries for incoming tx - */ - modifier isWithinLimits(uint256 _eth) { - require(_eth >= 1000000000, "pocket lint: not a valid currency"); - require(_eth <= 100000000000000000000000, "no vitalik, no"); - _; - } - - //============================================================================== - // _ |_ |. _ |` _ __|_. _ _ _ . - // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) - //====|========================================================================= - /** - * @dev emergency buy uses last stored affiliate ID and team snek - */ - fallback() - isActivated() - isHuman() - isWithinLimits(msg.value) - external - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // buy core - buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); - } - - /** - * @dev converts all incoming ethereum to keys. - * -functionhash- 0x8f38f309 (using ID for affiliate) - * -functionhash- 0x98a0871d (using address for affiliate) - * -functionhash- 0xa65b37a1 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - */ - function buyXid(uint256 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affCode, _team, _eventData_); - } - - function buyXaddr(address _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - function buyXname(bytes32 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ ; - _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - /** - * @dev essentially the same as buy, but instead of you sending ether - * from your wallet, it uses your unwithdrawn earnings. - * -functionhash- 0x349cdcac (using ID for affiliate) - * -functionhash- 0x82bfc739 (using address for affiliate) - * -functionhash- 0x079ce327 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - * @param _eth amount of earnings to use (remainder returned to gen vault) - */ - function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affCode, _team, _eth, _eventData_); - } - - function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - /** - * @dev withdraws all of your earnings. - * -functionhash- 0x3ccfd60b - */ - function withdraw() - isActivated() - isHuman() - public - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // setup temp var for player eth - uint256 _eth; - - // check to see if round has ended and no one has run round end yet - if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // end the round (distributes pot) - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire withdraw and distribute event - emit F3Devents.onWithdrawAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eth, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - - // in any other situation - } else { - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // fire withdraw event - emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); - } - } - - /** - * @dev use these to register names. they are just wrappers that will send the - * registration requests to the PlayerBook contract. So registering here is the - * same as registering there. UI will always display the last name you registered. - * but you will still own all previously registered names to use as affiliate - * links. - * - must pay a registration fee. - * - name must be unique - * - names will be converted to lowercase - * - name cannot start or end with a space - * - cannot have more than 1 space in a row - * - cannot be only numbers - * - cannot start with 0x - * - name must be at least 1 char - * - max length of 32 characters long - * - allowed characters: a-z, 0-9, and space - * -functionhash- 0x921dec21 (using ID for affiliate) - * -functionhash- 0x3ddd4698 (using address for affiliate) - * -functionhash- 0x685ffd83 (using name for affiliate) - * @param _nameString players desired name - * @param _affCode affiliate ID, address, or name of who referred you - * @param _all set to true if you want this to push your info to all games - * (this might cost a lot of gas) - */ - function registerNameXID(string memory _nameString, uint256 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXIDFromDapp{value:_paid}(_addr, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, block.timestamp); - } - - function registerNameXaddr(string memory _nameString, address _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXaddrFromDapp{value:msg.value}(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, block.timestamp); - } - - function registerNameXname(string memory _nameString, bytes32 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXnameFromDapp{value:msg.value}(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, block.timestamp); - } - //============================================================================== - // _ _ _|__|_ _ _ _ . - // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) - //=====_|======================================================================= - /** - * @dev return the price buyer will pay for next 1 individual key. - * -functionhash- 0x018a25e8 - * @return price for next key bought (in wei format) - */ - function getBuyPrice() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); - else // rounds over. need price for new round - return (75000000000000); - // init - } - - /** - * @dev returns time left. dont spam this, you'll ddos yourself from your node - * provider - * -functionhash- 0xc7e284b8 - * @return time left in seconds - */ - function getTimeLeft() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - if (_now < round_[_rID].end) - if (_now > round_[_rID].strt + rndGap_) - return ((round_[_rID].end).sub(_now)); - else - return ((round_[_rID].strt + rndGap_).sub(_now)); - else - return (0); - } - - /** - * @dev returns player earnings per vaults - * -functionhash- 0x63066434 - * @return winnings vault - * @return general vault - * @return affiliate vault - */ - function getPlayerVaults(uint256 _pID) - public - view - returns (uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - // if round has ended. but round end has not been run (so contract has not distributed winnings) - if (block.timestamp > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // if player is winner - if (round_[_rID].plyr == _pID) - { - return - ( - (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - // if player is not the winner - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - } - - // if round is still going on, or round has ended and round end has been ran - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), - plyr_[_pID].aff - ); - } - } - - /** - * solidity hates stack limits. this lets us avoid that hate - */ - function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) - private - view - returns (uint256) - { - return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); - } - - /** - * @dev returns all current round info needed for front end - * -functionhash- 0x747dff42 - * @return eth invested during ICO phase - * @return round id - * @return total keys for round - * @return time round ends - * @return time round started - * @return current pot - * @return current team ID & player ID in lead - * @return current player in leads address - * @return current player in leads name - * @return whales eth in for round - * @return bears eth in for round - * @return sneks eth in for round - * @return bulls eth in for round - * @return airdrop tracker # & airdrop pot - */ - function getCurrentRoundInfo() - public - view - returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - return - ( - round_[_rID].ico, //0 - _rID, //1 - round_[_rID].keys, //2 - round_[_rID].end, //3 - round_[_rID].strt, //4 - round_[_rID].pot, //5 - (round_[_rID].team + (round_[_rID].plyr * 10)), //6 - plyr_[round_[_rID].plyr].addr, //7 - plyr_[round_[_rID].plyr].name, //8 - rndTmEth_[_rID][0], //9 - rndTmEth_[_rID][1], //10 - rndTmEth_[_rID][2], //11 - rndTmEth_[_rID][3], //12 - airDropTracker_ + (airDropPot_ * 1000) //13 - ); - } - - /** - * @dev returns player info based on address. if no address is given, it will - * use msg.sender - * -functionhash- 0xee0b5d8b - * @param _addr address of the player you want to lookup - * @return player ID - * @return player name - * @return keys owned (current round) - * @return winnings vault - * @return general vault - * @return affiliate vault - * @return player round eth - */ - function getPlayerInfoByAddress(address _addr) - public - view - returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - if (_addr == address(0)) - { - _addr == msg.sender; - } - uint256 _pID = pIDxAddr_[_addr]; - - return - ( - _pID, //0 - plyr_[_pID].name, //1 - plyrRnds_[_pID][_rID].keys, //2 - plyr_[_pID].win, //3 - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 - plyr_[_pID].aff, //5 - plyrRnds_[_pID][_rID].eth //6 - ); - } - - //============================================================================== - // _ _ _ _ | _ _ . _ . - // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) - //=====================_|======================================================= - /** - * @dev logic runs whenever a buy order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // call core - core(_rID, _pID, msg.value, _affID, _team, _eventData_); - - // if round is not active - } else { - // check to see if end round needs to be ran - if (_now > round_[_rID].end && round_[_rID].ended == false) - { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onBuyAndDistribute - ( - msg.sender, - plyr_[_pID].name, - msg.value, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - - // put eth in players vault - plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); - } - } - - /** - * @dev logic runs whenever a reload order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // get earnings from all vaults and return unused to gen vault - // because we use a custom safemath library. this will throw if player - // tried to spend more eth than they have. - plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); - - // call core - core(_rID, _pID, _eth, _affID, _team, _eventData_); - - // if round is not active and end round needs to be ran - } else if (_now > round_[_rID].end && round_[_rID].ended == false) { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onReLoadAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - } - - /** - * @dev this is the core logic for any buy/reload that happens while a round - * is live. - */ - function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // if player is new to round - if (plyrRnds_[_pID][_rID].keys == 0) - _eventData_ = managePlayer(_pID, _eventData_); - - // early round eth limiter - if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) - { - uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); - uint256 _refund = _eth.sub(_availableLimit); - plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); - _eth = _availableLimit; - } - - // if eth left is greater than min eth allowed (sorry no pocket lint) - if (_eth > 1000000000) - { - - // mint the new keys - uint256 _keys = (round_[_rID].eth).keysRec(_eth); - - // if they bought at least 1 whole key - if (_keys >= 1000000000000000000) - { - updateTimer(_keys, _rID); - - // set new leaders - if (round_[_rID].plyr != _pID) - round_[_rID].plyr = _pID; - if (round_[_rID].team != _team) - round_[_rID].team = _team; - - // set the new leader bool to true - _eventData_.compressedData = _eventData_.compressedData + 100; - } - - // manage airdrops - if (_eth >= 100000000000000000) - { - airDropTracker_++; - if (airdrop() == true) - { - // gib muni - uint256 _prize; - if (_eth >= 10000000000000000000) - { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(75)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(50)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 2 prize was won - _eventData_.compressedData += 200000000000000000000000000000000; - } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(25)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } - // set airdrop happened bool to true - _eventData_.compressedData += 10000000000000000000000000000000; - // let event know how much was won - _eventData_.compressedData += _prize * 1000000000000000000000000000000000; - - // reset air drop tracker - airDropTracker_ = 0; - } - } - - // store the air drop tracker number (number of buys since last airdrop) - _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); - - // update player - plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); - plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); - - // update round - round_[_rID].keys = _keys.add(round_[_rID].keys); - round_[_rID].eth = _eth.add(round_[_rID].eth); - rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); - - // distribute eth - _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); - _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); - - // call end tx function to fire end tx event. - endTx(_pID, _team, _eth, _keys, _eventData_); - } - } - //============================================================================== - // _ _ | _ | _ _|_ _ _ _ . - // (_(_||(_|_||(_| | (_)| _\ . - //============================================================================== - /** - * @dev calculates unmasked earnings (just calculates, does not update mask) - * @return earnings in wei format - */ - function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) - private - view - returns (uint256) - { - return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); - } - - /** - * @dev returns the amount of keys you would get given an amount of eth. - * -functionhash- 0xce89c80c - * @param _rID round ID you want price for - * @param _eth amount of eth sent in - * @return keys received - */ - function calcKeysReceived(uint256 _rID, uint256 _eth) - public - view - returns (uint256) - { - // grab time - uint256 _now = block.timestamp; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].eth).keysRec(_eth)); - else // rounds over. need keys for new round - return ((_eth).keys()); - } - - /** - * @dev returns current eth price for X keys. - * -functionhash- 0xcf808000 - * @param _keys number of keys desired (in 18 decimal format) - * @return amount of eth needed to send - */ - function iWantXKeys(uint256 _keys) - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = block.timestamp; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); - else // rounds over. need price for new round - return ((_keys).eth()); - } - //============================================================================== - // _|_ _ _ | _ . - // | (_)(_)|_\ . - //============================================================================== - /** - * @dev receives name/player info from names contract - */ - function receivePlayerInfo(uint256 _pID, address payable _addr, bytes32 _name, uint256 _laff) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (pIDxAddr_[_addr] != _pID) - pIDxAddr_[_addr] = _pID; - if (pIDxName_[_name] != _pID) - pIDxName_[_name] = _pID; - if (plyr_[_pID].addr != _addr) - plyr_[_pID].addr = _addr; - if (plyr_[_pID].name != _name) - plyr_[_pID].name = _name; - if (plyr_[_pID].laff != _laff) - plyr_[_pID].laff = _laff; - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev receives entire player name list - */ - function receivePlayerNameList(uint256 _pID, bytes32 _name) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev gets existing or registers new pID. use this when a player may be new - * @return pID - */ - function determinePID(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - uint256 _pID = pIDxAddr_[msg.sender]; - // if player is new to this version of fomo3d - if (_pID == 0) - { - // grab their player ID, name and last aff ID, from player names contract - _pID = playerBook.getPlayerID(msg.sender); - bytes32 _name = playerBook.getPlayerName(_pID); - uint256 _laff = playerBook.getPlayerLAff(_pID); - - // set up player account - pIDxAddr_[msg.sender] = _pID; - plyr_[_pID].addr = msg.sender; - - if (_name != "") - { - pIDxName_[_name] = _pID; - plyr_[_pID].name = _name; - plyrNames_[_pID][_name] = true; - } - - if (_laff != 0 && _laff != _pID) - plyr_[_pID].laff = _laff; - - // set the new player bool to true - _eventData_.compressedData = _eventData_.compressedData + 1; - } - return (_eventData_); - } - - /** - * @dev checks to make sure user picked a valid team. if not sets team - * to default (sneks) - */ - function verifyTeam(uint256 _team) - private - pure - returns (uint256) - { - if (_team < 0 || _team > 3) - return (2); - else - return (_team); - } - - /** - * @dev decides if round end needs to be run & new round started. and if - * player unmasked earnings from previously played rounds need to be moved. - */ - function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // if player has played a previous round, move their unmasked earnings - // from that round to gen vault. - if (plyr_[_pID].lrnd != 0) - updateGenVault(_pID, plyr_[_pID].lrnd); - - // update player's last round played - plyr_[_pID].lrnd = rID_; - - // set the joined round bool to true - _eventData_.compressedData = _eventData_.compressedData + 10; - - return (_eventData_); - } - - /** - * @dev ends the round. manages paying out winner/splitting up pot - */ - function endRound(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // setup local rID - uint256 _rID = rID_; - - // grab our winning player and team id's - uint256 _winPID = round_[_rID].plyr; - uint256 _winTID = round_[_rID].team; - - // grab our pot amount - uint256 _pot = round_[_rID].pot; - - // calculate our winner share, community rewards, gen share, - // p3d share, and amount reserved for next pot - uint256 _win = (_pot.mul(48)) / 100; - uint256 _com = (_pot / 50); - uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; - uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; - uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); - - // calculate ppt for round mask - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); - if (_dust > 0) - { - _gen = _gen.sub(_dust); - _res = _res.add(_dust); - } - - // pay our winner - plyr_[_winPID].win = _win.add(plyr_[_winPID].win); - - // community rewards - address payable add = address(uint160(Jekyll_Island_Inc)); - if (!add.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _p3d.add(_com); - _com = 0; - } - - // distribute gen portion to key holders - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // send share for p3d to divies - if (_p3d > 0){ - address payable addr = address(uint160(Divies)); - addr.transfer(_p3d); - } - // prepare event data - _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); - _eventData_.winnerAddr = plyr_[_winPID].addr; - _eventData_.winnerName = plyr_[_winPID].name; - _eventData_.amountWon = _win; - _eventData_.genAmount = _gen; - _eventData_.P3DAmount = _p3d; - _eventData_.newPot = _res; - - // start next round - rID_++; - _rID++; - round_[_rID].strt = block.timestamp; - round_[_rID].end = block.timestamp.add(rndInit_).add(rndGap_); - round_[_rID].pot = _res; - - return (_eventData_); - } - - /** - * @dev moves any unmasked earnings to gen vault. updates earnings mask - */ - function updateGenVault(uint256 _pID, uint256 _rIDlast) - private - { - uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); - if (_earnings > 0) - { - // put in gen vault - plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); - // zero out their earnings by updating mask - plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); - } - } - - /** - * @dev updates round timer based on number of whole keys bought. - */ - function updateTimer(uint256 _keys, uint256 _rID) - private - { - // grab time - uint256 _now = block.timestamp; - - // calculate time based on number of keys bought - uint256 _newTime; - if (_now > round_[_rID].end && round_[_rID].plyr == 0) - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); - else - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); - - // compare to max and set new end time - if (_newTime < (rndMax_).add(_now)) - round_[_rID].end = _newTime; - else - round_[_rID].end = rndMax_.add(_now); - } - - /** - * @dev generates a random number between 0-99 and checks to see if thats - * resulted in an airdrop win - * @return do we have a winner? - */ - function airdrop() - private - view - returns (bool) - { - uint256 seed = uint256(keccak256(abi.encodePacked( - - (block.timestamp).add - (block.difficulty).add - ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (block.timestamp)).add - (block.gaslimit).add - ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (block.timestamp)).add - (block.number) - - ))); - if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) - return (true); - else - return (false); - } - - /** - * @dev distributes eth based on fees to com, aff, and p3d - */ - function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // pay 2% out to community rewards - uint256 _com = _eth / 50; - uint256 _p3d; - address payable addr = address(uint160(Jekyll_Island_Inc)); - if (!addr.send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _com; - _com = 0; - } - - // pay 1% out to FoMo3D short - _com = _eth / 100; - address payable add = address(uint160(otherF3D_)); - add.transfer(_com); - - // distribute share to affiliate - _com = _eth / 10; - - // decide what to do with affiliate share of fees - // affiliate must not be self, and must have a name registered - if (_affID != _pID && plyr_[_affID].name != '') { - plyr_[_affID].aff = _com.add(plyr_[_affID].aff); - emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _com, block.timestamp); - } else { - _p3d = _com; - } - - // pay out p3d - _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); - if (_p3d > 0) - { - // deposit to divies contract - address payable add = address(uint160(Divies)); - add.transfer(_p3d); - - // set up event data - _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); - } - - return (_eventData_); - } - - function potSwap() - external - payable - { - // setup local rID - uint256 _rID = rID_ + 1; - - round_[_rID].pot = round_[_rID].pot.add(msg.value); - emit F3Devents.onPotSwapDeposit(_rID, msg.value); - } - - /** - * @dev distributes eth based on fees to gen and pot - */ - function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns memory) - { - // calculate gen share - uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; - - // toss 1% into airdrop pot - uint256 _air = (_eth / 100); - airDropPot_ = airDropPot_.add(_air); - - // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); - - // calculate pot - uint256 _pot = _eth.sub(_gen); - - // distribute gen share (thats what updateMasks() does) and adjust - // balances for dust. - uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); - if (_dust > 0) - _gen = _gen.sub(_dust); - - // add eth to pot - round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); - - // set up event data - _eventData_.genAmount = _gen.add(_eventData_.genAmount); - _eventData_.potAmount = _pot; - - return (_eventData_); - } - - /** - * @dev updates masks for round and player when keys are bought - * @return dust left over - */ - function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) - private - returns (uint256) - { - /* MASKING NOTES - earnings masks are a tricky thing for people to wrap their minds around. - the basic thing to understand here. is were going to have a global - tracker based on profit per share for each round, that increases in - relevant proportion to the increase in share supply. - - the player will have an additional mask that basically says "based - on the rounds mask, my shares, and how much i've already withdrawn, - how much is still owed to me?" - */ - - // calc profit per key & round mask based on this buy: (dust goes to pot) - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // calculate player earning from their own buy (only based on the keys - // they just bought). & update player earnings mask - uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); - plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); - - // calculate & return dust - return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); - } - - /** - * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 - * @return earnings in wei format - */ - function withdrawEarnings(uint256 _pID) - private - returns (uint256) - { - // update gen vault - updateGenVault(_pID, plyr_[_pID].lrnd); - - // from vaults - uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); - if (_earnings > 0) - { - plyr_[_pID].win = 0; - plyr_[_pID].gen = 0; - plyr_[_pID].aff = 0; - } - - return (_earnings); - } - - /** - * @dev prepares compression data and fires event for buy or reload tx's - */ - function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - { - _eventData_.compressedData = _eventData_.compressedData + (block.timestamp * 1000000000000000000) + (_team * 100000000000000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); - - emit F3Devents.onEndTx - ( - _eventData_.compressedData, - _eventData_.compressedIDs, - plyr_[_pID].name, - msg.sender, - _eth, - _keys, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount, - _eventData_.potAmount, - airDropPot_ - ); - } - //============================================================================== - // (~ _ _ _._|_ . - // _)(/_(_|_|| | | \/ . - //====================/========================================================= - /** upon contract deploy, it will be deactivated. this is a one time - * use function that will activate the contract. we do this so devs - * have time to set things up on the web end **/ - bool public activated_ = false; - - function activate() - public - onlyDevs - { - - // can only be ran once - require(activated_ == false, "fomo3d already activated"); - - // activate the contract - activated_ = true; - - otherF3D_ = msg.sender; - Divies = msg.sender; - Jekyll_Island_Inc = msg.sender; - - // lets start first round - rID_ = 1; - round_[1].strt = block.timestamp + rndExtra_ - rndGap_; - round_[1].end = block.timestamp + rndInit_ + rndExtra_; - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario007.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario007.sol deleted file mode 100644 index a6fa095860f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario007.sol +++ /dev/null @@ -1,1432 +0,0 @@ - -/** - * @title ERC165 - * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md - */ -interface ERC165 { - - /** - * @notice Query if a contract implements an interface - * @param _interfaceId The interface identifier, as specified in ERC-165 - * @dev Interface identification is specified in ERC-165. This function - * uses less than 30,000 gas. - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool); - -} - -contract ERC721Basic is ERC165 { - - event Transfer( - address indexed _from, - address indexed _to, - uint256 indexed _tokenId - ); - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); - - function balanceOf(address _owner) public view returns (uint256 _balance); - function ownerOf(uint256 _tokenId) public view returns (address _owner); - function exists(uint256 _tokenId) public view returns (bool _exists); - - function approve(address _to, uint256 _tokenId) public; - function getApproved(uint256 _tokenId) - public view returns (address _operator); - - function setApprovalForAll(address _operator, bool _approved) public; - function isApprovedForAll(address _owner, address _operator) - public view returns (bool); - - function transferFrom(address _from, address _to, uint256 _tokenId) public; - function safeTransferFrom(address _from, address _to, uint256 _tokenId) - public; - - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public; -} - - -/** - * @title SupportsInterfaceWithLookup - * @author Matt Condon (@shrugs) - * @dev Implements ERC165 using a lookup table. - */ -contract SupportsInterfaceWithLookup is ERC165 { - bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; - /** - * 0x01ffc9a7 === - * bytes4(keccak256('supportsInterface(bytes4)')) - */ - - /** - * @dev a mapping of interface id to whether or not it's supported - */ - mapping(bytes4 => bool) internal supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself - */ - constructor() public { - _registerInterface(InterfaceId_ERC165); - } - - /** - * @dev implement supportsInterface(bytes4) using a lookup table - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool) { - return supportedInterfaces[_interfaceId]; - } - - /** - * @dev private method for registering an interface - */ - function _registerInterface(bytes4 _interfaceId) internal { - require(_interfaceId != 0xffffffff); - supportedInterfaces[_interfaceId] = true; - } -} - -contract Governable { - - event Pause(); - event Unpause(); - - address public governor; - bool public paused = false; - - constructor() public { - governor = msg.sender; - } - - function setGovernor(address _gov) public onlyGovernor { - governor = _gov; - } - - modifier onlyGovernor { - require(msg.sender == governor); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - */ - modifier whenPaused() { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyGovernor whenNotPaused public { - paused = true; - emit Pause(); - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyGovernor whenPaused public { - paused = false; - emit Unpause(); - } - -} - -contract CardBase is Governable { - - struct Card { - uint16 proto; - uint16 purity; - } - - function getCard(uint id) public view returns (uint16 proto, uint16 purity) { - Card memory card = cards[id]; - return (card.proto, card.purity); - } - - function getShine(uint16 purity) public pure returns (uint8) { - return uint8(purity / 1000); - } - - Card[] public cards; - -} - -contract CardProto is CardBase { - - event NewProtoCard( - uint16 id, uint8 season, uint8 god, - Rarity rarity, uint8 mana, uint8 attack, - uint8 health, uint8 cardType, uint8 tribe, bool packable - ); - - struct Limit { - uint64 limit; - bool exists; - } - - // limits for mythic cards - mapping(uint16 => Limit) public limits; - - // can only set limits once - function setLimit(uint16 id, uint64 limit) public onlyGovernor { - Limit memory l = limits[id]; - require(!l.exists); - limits[id] = Limit({ - limit: limit, - exists: true - }); - } - - function getLimit(uint16 id) public view returns (uint64 limit, bool set) { - Limit memory l = limits[id]; - return (l.limit, l.exists); - } - - // could make these arrays to save gas - // not really necessary - will be update a very limited no of times - mapping(uint8 => bool) public seasonTradable; - mapping(uint8 => bool) public seasonTradabilityLocked; - uint8 public currentSeason; - - function makeTradable(uint8 season) public onlyGovernor { - seasonTradable[season] = true; - } - - function makeUntradable(uint8 season) public onlyGovernor { - require(!seasonTradabilityLocked[season]); - seasonTradable[season] = false; - } - - function makePermanantlyTradable(uint8 season) public onlyGovernor { - require(seasonTradable[season]); - seasonTradabilityLocked[season] = true; - } - - function isTradable(uint16 proto) public view returns (bool) { - return seasonTradable[protos[proto].season]; - } - - function nextSeason() public onlyGovernor { - //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M - require(currentSeason <= 255); - - currentSeason++; - mythic.length = 0; - legendary.length = 0; - epic.length = 0; - rare.length = 0; - common.length = 0; - } - - enum Rarity { - Common, - Rare, - Epic, - Legendary, - Mythic - } - - uint8 constant SPELL = 1; - uint8 constant MINION = 2; - uint8 constant WEAPON = 3; - uint8 constant HERO = 4; - - struct ProtoCard { - bool exists; - uint8 god; - uint8 season; - uint8 cardType; - Rarity rarity; - uint8 mana; - uint8 attack; - uint8 health; - uint8 tribe; - } - - // there is a particular design decision driving this: - // need to be able to iterate over mythics only for card generation - // don't store 5 different arrays: have to use 2 ids - // better to bear this cost (2 bytes per proto card) - // rather than 1 byte per instance - - uint16 public protoCount; - - mapping(uint16 => ProtoCard) protos; - - uint16[] public mythic; - uint16[] public legendary; - uint16[] public epic; - uint16[] public rare; - uint16[] public common; - - function addProtos( - uint16[] memory externalIDs, uint8[] memory gods, Rarity[] memory rarities, uint8[] memory manas, uint8[] memory attacks, - uint8[] memory healths, uint8[] memory cardTypes, uint8[] memory tribes, bool[] memory packable - ) public onlyGovernor returns(uint16) { - - for (uint i = 0; i < externalIDs.length; i++) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: gods[i], - season: currentSeason, - cardType: cardTypes[i], - rarity: rarities[i], - mana: manas[i], - attack: attacks[i], - health: healths[i], - tribe: tribes[i] - }); - - _addProto(externalIDs[i], card, packable[i]); - } - - } - - function addProto( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: cardType, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function addWeapon( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: WEAPON, - rarity: rarity, - mana: mana, - attack: attack, - health: durability, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: SPELL, - rarity: rarity, - mana: mana, - attack: 0, - health: 0, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addMinion( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: MINION, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { - - require(!protos[externalID].exists); - - card.exists = true; - - protos[externalID] = card; - - protoCount++; - - emit NewProtoCard( - externalID, currentSeason, card.god, - card.rarity, card.mana, card.attack, - card.health, card.cardType, card.tribe, packable - ); - - if (packable) { - Rarity rarity = card.rarity; - if (rarity == Rarity.Common) { - common.push(externalID); - } else if (rarity == Rarity.Rare) { - rare.push(externalID); - } else if (rarity == Rarity.Epic) { - epic.push(externalID); - } else if (rarity == Rarity.Legendary) { - legendary.push(externalID); - } else if (rarity == Rarity.Mythic) { - mythic.push(externalID); - } else { - require(false); - } - } - } - - function getProto(uint16 id) public view returns( - bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) { - ProtoCard memory proto = protos[id]; - return ( - proto.exists, - proto.god, - proto.season, - proto.cardType, - proto.rarity, - proto.mana, - proto.attack, - proto.health, - proto.tribe - ); - } - - function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { - // modulo bias is fine - creates rarity tiers etc - // will obviously revert is there are no cards of that type: this is expected - should never happen - if (rarity == Rarity.Common) { - return common[random % common.length]; - } else if (rarity == Rarity.Rare) { - return rare[random % rare.length]; - } else if (rarity == Rarity.Epic) { - return epic[random % epic.length]; - } else if (rarity == Rarity.Legendary) { - return legendary[random % legendary.length]; - } else if (rarity == Rarity.Mythic) { - // make sure a mythic is available - uint16 id; - uint64 limit; - bool set; - for (uint i = 0; i < mythic.length; i++) { - id = mythic[(random + i) % mythic.length]; - (limit, set) = getLimit(id); - if (set && limit > 0){ - return id; - } - } - // if not, they get a legendary :( - return legendary[random % legendary.length]; - } - require(false); - return 0; - } - - // can never adjust tradable cards - // each season gets a 'balancing beta' - // totally immutable: season, rarity - function replaceProto( - uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) public onlyGovernor { - ProtoCard memory pc = protos[index]; - require(!seasonTradable[pc.season]); - protos[index] = ProtoCard({ - exists: true, - god: god, - season: pc.season, - cardType: cardType, - rarity: pc.rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - } - -} - -contract ERC721Receiver { - /** - * @dev Magic value to be returned upon successful reception of an NFT - * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, - * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - */ - bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; - - /** - * @notice Handle the receipt of an NFT - * @dev The ERC721 smart contract calls this function on the recipient - * after a `safetransfer`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the contract address is always the message sender. - * @param _operator The address which called `safeTransferFrom` function - * @param _from The address which previously owned the token - * @param _tokenId The NFT identifier which is being transfered - * @param _data Additional data with no specified format - * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - */ - function onERC721Received( - address _operator, - address _from, - uint256 _tokenId, - bytes memory _data - ) - public - returns(bytes4); -} - -library AddressUtils { - - /** - * Returns whether the target address is a contract - * @dev This function will return false if invoked during the constructor of a contract, - * as the code is not actually created until after the constructor finishes. - * @param addr address to check - * @return whether the target address is a contract - */ - function isContract1(address addr) internal view returns (bool) { - uint256 size; - // XXX Currently there is no better way to check if there is a contract in an address - // than to check the size of the code at that address. - // See https://ethereum.stackexchange.com/a/14016/36603 - // for more details about how this works. - // TODO Check this again before the Serenity release, because all addresses will be - // contracts then. - // solium-disable-next-line security/no-inline-assembly - assembly { size := extcodesize(addr) } - return size > 0; - } - -} - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { - // Gas optimization: this is cheaper than asserting 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 - if (a == 0) { - return 0; - } - - c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - // uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return a / b; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256 c) { - c = a + b; - assert(c >= a); - return c; - } -} - -contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic { - - bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; - /* - * 0x80ac58cd === - * bytes4(keccak256('balanceOf(address)')) ^ - * bytes4(keccak256('ownerOf(uint256)')) ^ - * bytes4(keccak256('approve(address,uint256)')) ^ - * bytes4(keccak256('getApproved(uint256)')) ^ - * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ - * bytes4(keccak256('isApprovedForAll(address,address)')) ^ - * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) - */ - - bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; - /* - * 0x4f558e79 === - * bytes4(keccak256('exists(uint256)')) - */ - - using SafeMath for uint256; - using AddressUtils for address; - - // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - bytes4 private constant ERC721_RECEIVED = 0x150b7a02; - - // Mapping from token ID to owner - mapping (uint256 => address) internal tokenOwner; - - // Mapping from token ID to approved address - mapping (uint256 => address) internal tokenApprovals; - - // Mapping from owner to number of owned token - // mapping (address => uint256) internal ownedTokensCount; - - // Mapping from owner to operator approvals - mapping (address => mapping (address => bool)) internal operatorApprovals; - - /** - * @dev Guarantees msg.sender is owner of the given token - * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender - */ - modifier onlyOwnerOf(uint256 _tokenId) { - require(ownerOf(_tokenId) == msg.sender); - _; - } - - /** - * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator - * @param _tokenId uint256 ID of the token to validate - */ - modifier canTransfer(uint256 _tokenId) { - require(isApprovedOrOwner(msg.sender, _tokenId)); - _; - } - - constructor() - public - { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721); - _registerInterface(InterfaceId_ERC721Exists); - } - - /** - * @dev Gets the balance of the specified address - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256); - - /** - * @dev Gets the owner of the specified token ID - * @param _tokenId uint256 ID of the token to query the owner of - * @return owner address currently marked as the owner of the given token ID - */ - function ownerOf(uint256 _tokenId) public view returns (address) { - address owner = tokenOwner[_tokenId]; - require(owner != address(0)); - return owner; - } - - /** - * @dev Returns whether the specified token exists - * @param _tokenId uint256 ID of the token to query the existence of - * @return whether the token exists - */ - function exists(uint256 _tokenId) public view returns (bool) { - address owner = tokenOwner[_tokenId]; - return owner != address(0); - } - - /** - * @dev Approves another address to transfer the given token ID - * The zero address indicates there is no approved address. - * There can only be one approved address per token at a given time. - * Can only be called by the token owner or an approved operator. - * @param _to address to be approved for the given token ID - * @param _tokenId uint256 ID of the token to be approved - */ - function approve(address _to, uint256 _tokenId) public { - address owner = ownerOf(_tokenId); - require(_to != owner); - require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); - - tokenApprovals[_tokenId] = _to; - emit Approval(owner, _to, _tokenId); - } - - /** - * @dev Gets the approved address for a token ID, or zero if no address set - * @param _tokenId uint256 ID of the token to query the approval of - * @return address currently approved for the given token ID - */ - function getApproved(uint256 _tokenId) public view returns (address) { - return tokenApprovals[_tokenId]; - } - - /** - * @dev Sets or unsets the approval of a given operator - * An operator is allowed to transfer all tokens of the sender on their behalf - * @param _to operator address to set the approval - * @param _approved representing the status of the approval to be set - */ - function setApprovalForAll(address _to, bool _approved) public { - require(_to != msg.sender); - operatorApprovals[msg.sender][_to] = _approved; - emit ApprovalForAll(msg.sender, _to, _approved); - } - - /** - * @dev Tells whether an operator is approved by a given owner - * @param _owner owner address which you want to query the approval of - * @param _operator operator address which you want to query the approval of - * @return bool whether the given operator is approved by the given owner - */ - function isApprovedForAll( - address _owner, - address _operator - ) - public - view - returns (bool) - { - return operatorApprovals[_owner][_operator]; - } - - /** - * @dev Transfers the ownership of a given token ID to another address - * Usage of this method is discouraged, use `safeTransferFrom` whenever possible - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - require(_from != address(0)); - require(_to != address(0)); - - clearApproval(_from, _tokenId); - removeTokenFrom(_from, _tokenId); - addTokenTo(_to, _tokenId); - - emit Transfer(_from, _to, _tokenId); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - // solium-disable-next-line arg-overflow - safeTransferFrom(_from, _to, _tokenId, ""); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes data to send along with a safe transfer check - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public - canTransfer(_tokenId) - { - transferFrom(_from, _to, _tokenId); - // solium-disable-next-line arg-overflow - require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); - } - - /** - * @dev Returns whether the given spender can transfer a given token ID - * @param _spender address of the spender to query - * @param _tokenId uint256 ID of the token to be transferred - * @return bool whether the msg.sender is approved for the given token ID, - * is an operator of the owner, or is the owner of the token - */ - function isApprovedOrOwner( - address _spender, - uint256 _tokenId - ) - internal - view - returns (bool) - { - address owner = ownerOf(_tokenId); - // Disable solium check because of - // https://github.com/duaraghav8/Solium/issues/175 - // solium-disable-next-line operator-whitespace - return ( - _spender == owner || - getApproved(_tokenId) == _spender || - isApprovedForAll(owner, _spender) - ); - } - - /** - * @dev Internal function to clear current approval of a given token ID - * Reverts if the given address is not indeed the owner of the token - * @param _owner owner of the token - * @param _tokenId uint256 ID of the token to be transferred - */ - function clearApproval(address _owner, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _owner); - if (tokenApprovals[_tokenId] != address(0)) { - tokenApprovals[_tokenId] = address(0); - } - } - - /** - * @dev Internal function to mint a new token - * Reverts if the given token ID already exists - * @param _to The address that will own the minted token - * @param _tokenId uint256 ID of the token to be minted by the msg.sender - */ - function _mint(address _to, uint256 _tokenId) internal { - require(_to != address(0)); - addNewTokenTo(_to, _tokenId); - emit Transfer(address(0), _to, _tokenId); - } - - - /** - * @dev Internal function to burn a specific token - * Reverts if the token does not exist - * @param _tokenId uint256 ID of the token being burned by the msg.sender - */ - function _burn(address _owner, uint256 _tokenId) internal { - clearApproval(_owner, _tokenId); - removeTokenFrom(_owner, _tokenId); - emit Transfer(_owner, address(0), _tokenId); - } - - function addNewTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - // ownedTokensCount[_to] = ownedTokensCount[_to].add(1); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _from); - // ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); - tokenOwner[_tokenId] = address(0); - } - - /** - * @dev Internal function to invoke `onERC721Received` on a target address - * The call is not executed if the target address is not a contract - * @param _from address representing the previous owner of the given token ID - * @param _to target address that will receive the tokens - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes optional data to send along with the call - * @return whether the call correctly returned the expected magic value - */ - function checkAndCallSafeTransfer( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - internal - returns (bool) - { - if (!_to.isContract1()) { - return true; - } - bytes4 retval = ERC721Receiver(_to).onERC721Received( - msg.sender, _from, _tokenId, _data); - return (retval == ERC721_RECEIVED); - } - -} - - - -contract ERC721Enumerable is ERC721Basic { - function totalSupply() public view returns (uint256); - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256 _tokenId); - - function tokenByIndex(uint256 _index) public view returns (uint256); -} - -contract ERC721Metadata is ERC721Basic { - function name() external view returns (string memory _name); - function symbol() external view returns (string memory _symbol); - function tokenURI(uint256 _tokenId) public view returns (string memory); -} - -contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { - -} - - - - -library Strings { - - // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory ) { - bytes memory _ba = bytes(_a); - bytes memory _bb = bytes(_b); - bytes memory _bc = bytes(_c); - bytes memory _bd = bytes(_d); - bytes memory _be = bytes(_e); - string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); - bytes memory babcde = bytes(abcde); - uint k = 0; - for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; - for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; - for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; - for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; - for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; - return string(babcde); - } - - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, _d, ""); - } - - function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, "", ""); - } - - function strConcat(string memory _a, string memory _b) internal pure returns (string memory ) { - return strConcat(_a, _b, "", "", ""); - } - - function uint2str(uint i) internal pure returns (string memory ) { - if (i == 0) return "0"; - uint j = i; - uint len; - while (j != 0){ - len++; - j /= 10; - } - bytes memory bstr = new bytes(len); - uint k = len - 1; - while (i != 0){ - bstr[k--] = byte(uint8(48 + i % 10)); - i /= 10; - } - return string(bstr); - } -} - -contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { - - using Strings for string; - - bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; - /** - * 0x780e9d63 === - * bytes4(keccak256('totalSupply()')) ^ - * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ - * bytes4(keccak256('tokenByIndex(uint256)')) - */ - - bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; - /** - * 0x5b5e139f === - * bytes4(keccak256('name()')) ^ - * bytes4(keccak256('symbol()')) ^ - * bytes4(keccak256('tokenURI(uint256)')) - */ - - /*** Constants ***/ - // Configure these for your own deployment - string public constant NAME = "Gods Unchained"; - string public constant SYMBOL = "GODS"; - string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/"; - - // Mapping from owner to list of owned token IDs - // EDITED: limit to 2^40 (around 1T) - mapping(address => uint40[]) internal ownedTokens; - - uint32[] ownedTokensIndex; - - /** - * @dev Constructor function - */ - constructor() public { - - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721Enumerable); - _registerInterface(InterfaceId_ERC721Metadata); - } - - /** - * @dev Gets the token name - * @return string representing the token name - */ - function name() external view returns (string memory) { - return NAME; - } - - /** - * @dev Gets the token symbol - * @return string representing the token symbol - */ - function symbol() external view returns (string memory) { - return SYMBOL; - } - - /** - * @dev Returns an URI for a given token ID - * Throws if the token ID does not exist. May return an empty string. - * @param _tokenId uint256 ID of the token to query - */ - function tokenURI(uint256 _tokenId) public view returns (string memory) { - return Strings.strConcat( - tokenMetadataBaseURI, - Strings.uint2str(_tokenId) - ); - } - - /** - * @dev Gets the token ID at a given index of the tokens list of the requested owner - * @param _owner address owning the tokens list to be accessed - * @param _index uint256 representing the index to be accessed of the requested tokens list - * @return uint256 token ID at the given index of the tokens list owned by the requested address - */ - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256) - { - require(_index < balanceOf(_owner)); - return ownedTokens[_owner][_index]; - } - - /** - * @dev Gets the total amount of tokens stored by the contract - * @return uint256 representing the total amount of tokens - */ - function totalSupply() public view returns (uint256) { - return cards.length; - } - - /** - * @dev Gets the token ID at a given index of all the tokens in this contract - * Reverts if the index is greater or equal to the total number of tokens - * @param _index uint256 representing the index to be accessed of the tokens list - * @return uint256 token ID at the given index of the tokens list - */ - function tokenByIndex(uint256 _index) public view returns (uint256) { - require(_index < totalSupply()); - return _index; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - super.addTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - - ownedTokensIndex[_tokenId] = uint32(length); - } - - // EDITED - // have to have in order to use array rather than mapping - function addNewTokenTo(address _to, uint256 _tokenId) internal { - super.addNewTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - ownedTokensIndex.push(uint32(length)); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - super.removeTokenFrom(_from, _tokenId); - - uint32 tokenIndex = ownedTokensIndex[_tokenId]; - uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); - uint40 lastToken = ownedTokens[_from][lastTokenIndex]; - - ownedTokens[_from][tokenIndex] = lastToken; - ownedTokens[_from][lastTokenIndex] = 0; - // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to - // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping - // the lastToken to the first position, and then dropping the element placed in the last position of the list - - ownedTokens[_from].length--; - ownedTokensIndex[_tokenId] = 0; - ownedTokensIndex[lastToken] = tokenIndex; - } - - /** - * @dev Gets the balance of the specified address - overrriden from previous to save gas - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256) { - return ownedTokens[_owner].length; - } - -} - -contract CardOwnershipTwo is ERC721Token { - - uint public burnCount; - - function getActiveCards() public view returns (uint) { - return totalSupply() - burnCount; - } - - /** - * @param to : the address to which the card will be transferred - * @param id : the id of the card to be transferred - */ - function transfer(address to, uint id) public payable onlyOwnerOf(id) { - require(isTradable(cards[id].proto)); - require(to != address(0)); - - _transfer(msg.sender, to, id); - } - - function _transfer(address from, address to, uint id) internal { - - clearApproval(from, id); - - removeTokenFrom(from, id); - - addTokenTo(to, id); - - emit Transfer(from, to, id); - } - - /** - * @param to : the address to which the cards will be transferred - * @param ids : the ids of the cards to be transferred - */ - function transferAll(address to, uint[] memory ids) public payable { - for (uint i = 0; i < ids.length; i++) { - transfer(to, ids[i]); - } - } - - /** - * @param proposed : the claimed owner of the cards - * @param ids : the ids of the cards to check - * @return whether proposed owns all of the cards - */ - function ownsAll(address proposed, uint[] memory ids) public view returns (bool) { - require(ids.length > 0); - for (uint i = 0; i < ids.length; i++) { - if (!owns(proposed, ids[i])) { - return false; - } - } - return true; - } - - /** - * @param proposed : the claimed owner of the card - * @param id : the id of the card to check - * @return whether proposed owns the card - */ - function owns(address proposed, uint id) public view returns (bool) { - return ownerOf(id) == proposed; - } - - function burn(uint id) public onlyOwnerOf(id) { - burnCount++; - _burn(msg.sender, id); - } - - /** - * @param ids : the indices of the tokens to burn - */ - function burnAll(uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++){ - burn(ids[i]); - } - } - - /** - * @param to : the address to approve for transfer - * @param id : the index of the card to be approved - */ - function approve(address to, uint id) public { - require(isTradable(cards[id].proto)); - super.approve(to, id); - } - - /** - * @param to : the address to approve for transfer - * @param ids : the indices of the cards to be approved - */ - function approveAll(address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - approve(to, ids[i]); - } - } - - /** - * @param to : the address to which the token should be transferred - * @param id : the index of the token to transfer - */ - function transferFrom(address from, address to, uint id) public { - require(isTradable(cards[id].proto)); - super.transferFrom(from, to, id); - } - - /** - * @param to : the address to which the tokens should be transferred - * @param ids : the indices of the tokens to transfer - */ - function transferAllFrom(address from, address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - transferFrom(from, to, ids[i]); - } - } - - /** - * @return the number of cards which have been burned - */ - function getBurnCount() public view returns (uint) { - return burnCount; - } - -} - -contract CardIntegrationTwo is CardOwnershipTwo { - - address[] public packs; - - event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); - - function addPack(address approved) public onlyGovernor { - packs.push(approved); - } - - modifier onlyApprovedPacks { - require(_isApprovedPack()); - _; - } - - function _isApprovedPack() private view returns (bool) { - for (uint i = 0; i < packs.length; i++) { - if (msg.sender == address(packs[i])) { - return true; - } - } - return false; - } - - function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { - ProtoCard memory card = protos[proto]; - require(card.season == currentSeason); - if (card.rarity == Rarity.Mythic) { - uint64 limit; - bool exists; - (limit, exists) = getLimit(proto); - require(!exists || limit > 0); - limits[proto].limit--; - } - return _createCard(owner, proto, purity); - } - - function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { - Card memory card = Card({ - proto: proto, - purity: purity - }); - - uint id = cards.push(card) - 1; - - _mint(owner, id); - - emit CardCreated(id, proto, purity, owner); - - return id; - } - - /*function combineCards(uint[] ids) public whenNotPaused { - require(ids.length == 5); - require(ownsAll(msg.sender, ids)); - Card memory first = cards[ids[0]]; - uint16 proto = first.proto; - uint8 shine = _getShine(first.purity); - require(shine < shineLimit); - uint16 puritySum = first.purity - (shine * 1000); - burn(ids[0]); - for (uint i = 1; i < ids.length; i++) { - Card memory next = cards[ids[i]]; - require(next.proto == proto); - require(_getShine(next.purity) == shine); - puritySum += (next.purity - (shine * 1000)); - burn(ids[i]); - } - uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); - _createCard(msg.sender, proto, newPurity); - }*/ - - - // PURITY NOTES - // currently, we only - // however, to protect rarity, you'll never be abl - // this is enforced by the restriction in the create-card function - // no cards above this point can be found in packs - - - -} - -contract PreviousInterface { - - function ownerOf(uint id) public view returns (address); - - function getCard(uint id) public view returns (uint16, uint16); - - function totalSupply() public view returns (uint); - - function burnCount() public view returns (uint); - -} - -contract CardMigration is CardIntegrationTwo { - - constructor(PreviousInterface previous) public { - old = previous; - } - - // use interface to lower deployment cost - PreviousInterface old; - - mapping(uint => bool) public migrated; - - function migrate(uint id) public { - - require(!migrated[id]); - - migrated[id] = true; - - address owner = old.ownerOf(id); - - uint16 proto; - uint16 purity; - - (proto, purity) = old.getCard(id); - - _createCard(owner, proto, purity); - } - - function migrateAll(uint[] memory ids) public { - - for (uint i = 0; i < ids.length; i++){ - migrate(ids[i]); - } - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario008.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario008.sol deleted file mode 100644 index 9881507fab7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario008.sol +++ /dev/null @@ -1,2061 +0,0 @@ - - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() virtual public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer1(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer1(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(block.timestamp), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - kitties.push(_kitty); - uint256 newKittenId = kitties.length - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -abstract contract ERC721 { - // Required methods - function totalSupply() virtual public view returns (uint256 total); - function balanceOf(address _owner) virtual public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) virtual external view returns (address owner); - function approve(address _to, uint256 _tokenId) virtual external; - function transfer(address _to, uint256 _tokenId) virtual external; - function transferFrom(address _from, address _to, uint256 _tokenId) virtual external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) virtual external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external override view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public override view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() override public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - override - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid{value:(msg.value - autoBirthFee)}(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - -/// @notice No tipping! -/// @dev Reject all Ether from being sent here, unless it's from one of the -/// two auction contracts. (Hopefully, we can prevent user accidents.) -fallback() external payable { -require( -msg.sender == address(saleAuction) || -msg.sender == address(siringAuction) -); -} - -/// @notice Returns all the relevant information about a specific kitty. -/// @param _id The ID of the kitty of interest. -function getKitty(uint256 _id) -external -view -returns ( -bool isGestating, -bool isReady, -uint256 cooldownIndex, -uint256 nextActionAt, -uint256 siringWithId, -uint256 birthTime, -uint256 matronId, -uint256 sireId, -uint256 generation, -uint256 genes -) { -Kitty storage kit = kitties[_id]; - -// if this variable is 0 then it's not gestating -isGestating = (kit.siringWithId != 0); -isReady = (kit.cooldownEndBlock <= block.number); -cooldownIndex = uint256(kit.cooldownIndex); -nextActionAt = uint256(kit.cooldownEndBlock); -siringWithId = uint256(kit.siringWithId); -birthTime = uint256(kit.birthTime); -matronId = uint256(kit.matronId); -sireId = uint256(kit.sireId); -generation = uint256(kit.generation); -genes = kit.genes; -} - -/// @dev Override unpause so it requires all external contract addresses -/// to be set before contract can be unpaused. Also, we can't have -/// newContractAddress set either, because then the contract was upgraded. -/// @notice This is public rather than external so we can call super.unpause -/// without using an expensive CALL. - -function unpause() override public onlyCEO whenPaused { -require(address(saleAuction) != address(0)); -require(address(siringAuction) != address(0)); -require(address(geneScience) != address(0)); -require(newContractAddress == address(0)); - -// Actually unpause the contract. -super.unpause(); -} - -// @dev Allows the CFO to capture the balance available to the contract. -function withdrawBalance() external onlyCFO { -uint256 balance = address(this).balance; -// Subtract all the currently pregnant kittens we have, plus 1 of margin. -uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - -if (balance > subtractFees) { -cfoAddress.transfer(balance - subtractFees); -} -} -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - -function isGeneScience() public pure returns (bool){ -return true; -} - -/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor -/// @param genes1 genes of mom -/// @param genes2 genes of sire -/// @return the genes that are supposed to be passed down the child -function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - -return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { -/// @dev Given a token Id, returns a byte array that is supposed to be converted into string. -function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { -if (_tokenId == 1) { -buffer[0] = "Hello World! :D"; -count = 15; -} else if (_tokenId == 2) { -buffer[0] = "I would definitely choose a medi"; -buffer[1] = "um length string."; -count = 49; -} else if (_tokenId == 3) { -buffer[0] = "Lorem ipsum dolor sit amet, mi e"; -buffer[1] = "st accumsan dapibus augue lorem,"; -buffer[2] = " tristique vestibulum id, libero"; -buffer[3] = " suscipit varius sapien aliquam."; -count = 128; -} -} -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - -// Represents an auction on an NFT -struct Auction { -// Current owner of NFT -address payable seller; -// Price (in wei) at beginning of auction -uint128 startingPrice; -// Price (in wei) at end of auction -uint128 endingPrice; -// Duration (in seconds) of auction -uint64 duration; -// Time when auction started -// NOTE: 0 if this auction has been concluded -uint64 startedAt; -} - -// Reference to contract tracking NFT ownership -ERC721 public nonFungibleContract; - -// Cut owner takes on each auction, measured in basis points (1/100 of a percent). -// Values 0-10,000 map to 0%-100% -uint256 public ownerCut; - -// Map from token ID to their corresponding auction. -mapping (uint256 => Auction) tokenIdToAuction; - -event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); -event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); -event AuctionCancelled(uint256 tokenId); - -/// @dev Returns true if the claimant owns the token. -/// @param _claimant - Address claiming to own the token. -/// @param _tokenId - ID of token whose ownership to verify. -function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { -return (nonFungibleContract.ownerOf(_tokenId) == _claimant); -} - -/// @dev Escrows the NFT, assigning ownership to this contract. -/// Throws if the escrow fails. -/// @param _owner - Current owner address of token to escrow. -/// @param _tokenId - ID of token whose approval to verify. -function _escrow(address _owner, uint256 _tokenId) internal { -// it will throw if transfer fails -nonFungibleContract.transferFrom(_owner, address(this), _tokenId); -} - -/// @dev Transfers an NFT owned by this contract to another address. -/// Returns true if the transfer succeeds. -/// @param _receiver - Address to transfer NFT to. -/// @param _tokenId - ID of token to transfer. -function _transfer(address _receiver, uint256 _tokenId) internal { -// it will throw if transfer fails -nonFungibleContract.transfer(_receiver, _tokenId); -} - -/// @dev Adds an auction to the list of open auctions. Also fires the -/// AuctionCreated event. -/// @param _tokenId The ID of the token to be put on auction. -/// @param _auction Auction to add. -function _addAuction(uint256 _tokenId, Auction memory _auction) internal { -// Require that all auctions have a duration of -// at least one minute. (Keeps our math from getting hairy!) -require(_auction.duration >= 1 minutes); - -tokenIdToAuction[_tokenId] = _auction; - -emit AuctionCreated( -uint256(_tokenId), -uint256(_auction.startingPrice), -uint256(_auction.endingPrice), -uint256(_auction.duration) -); -} - -/// @dev Cancels an auction unconditionally. -function _cancelAuction(uint256 _tokenId, address _seller) internal { -_removeAuction(_tokenId); -_transfer(_seller, _tokenId); -emit AuctionCancelled(_tokenId); -} - -/// @dev Computes the price and transfers winnings. -/// Does NOT transfer ownership of token. -function _bid(uint256 _tokenId, uint256 _bidAmount) -internal -returns (uint256) -{ -// Get a reference to the auction struct -Auction storage auction = tokenIdToAuction[_tokenId]; - -// Explicitly check that this auction is currently live. -// (Because of how Ethereum mappings work, we can't just count -// on the lookup above failing. An invalid _tokenId will just -// return an auction object that is all zeros.) -require(_isOnAuction(auction)); - -// Check that the bid is greater than or equal to the current price -uint256 price = _currentPrice(auction); -require(_bidAmount >= price); - -// Grab a reference to the seller before the auction struct -// gets deleted. -address payable seller = auction.seller; - -// The bid is good! Remove the auction before sending the fees -// to the sender so we can't have a reentrancy attack. -_removeAuction(_tokenId); - -// Transfer proceeds to seller (if there are any!) -if (price > 0) { -// Calculate the auctioneer's cut. -// (NOTE: _computeCut() is guaranteed to return a -// value <= price, so this subtraction can't go negative.) -uint256 auctioneerCut = _computeCut(price); -uint256 sellerProceeds = price - auctioneerCut; - -// NOTE: Doing a transfer() in the middle of a complex -// method like this is generally discouraged because of -// reentrancy attacks and DoS attacks if the seller is -// a contract with an invalid fallback function. We explicitly -// guard against reentrancy attacks by removing the auction -// before calling transfer(), and the only thing the seller -// can DoS is the sale of their own asset! (And if it's an -// accident, they can call cancelAuction(). ) -seller.transfer(sellerProceeds); -} - -// Calculate any excess funds included with the bid. If the excess -// is anything worth worrying about, transfer it back to bidder. -// NOTE: We checked above that the bid amount is greater than or -// equal to the price so this cannot underflow. -uint256 bidExcess = _bidAmount - price; - -// Return the funds. Similar to the previous transfer, this is -// not susceptible to a re-entry attack because the auction is -// removed before any transfers occur. -msg.sender.transfer(bidExcess); - -// Tell the world! -emit AuctionSuccessful(_tokenId, price, msg.sender); - -return price; -} - -/// @dev Removes an auction from the list of open auctions. -/// @param _tokenId - ID of NFT on auction. -function _removeAuction(uint256 _tokenId) internal { -delete tokenIdToAuction[_tokenId]; -} - -/// @dev Returns true if the NFT is on auction. -/// @param _auction - Auction to check. -function _isOnAuction(Auction storage _auction) internal view returns (bool) { -return (_auction.startedAt > 0); -} - -/// @dev Returns current price of an NFT on auction. Broken into two -/// functions (this one, that computes the duration from the auction -/// structure, and the other that does the price computation) so we -/// can easily test that the price computation works correctly. -function _currentPrice(Auction storage _auction) -internal -view -returns (uint256) -{ -uint256 secondsPassed = 0; - -// A bit of insurance against negative values (or wraparound). -// Probably not necessary (since Ethereum guarnatees that the -// now variable doesn't ever go backwards). -if (block.timestamp > _auction.startedAt) { -secondsPassed = block.timestamp - _auction.startedAt; -} - -return _computeCurrentPrice( -_auction.startingPrice, -_auction.endingPrice, -_auction.duration, -secondsPassed -); -} - -/// @dev Computes the current price of an auction. Factored out -/// from _currentPrice so we can run extensive unit tests. -/// When testing, make this function public and turn on -/// `Current price computation` test suite. -function _computeCurrentPrice( -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -uint256 _secondsPassed -) -internal -pure -returns (uint256) -{ -// NOTE: We don't use SafeMath (or similar) in this function because -// all of our public functions carefully cap the maximum values for -// time (at 64-bits) and currency (at 128-bits). _duration is -// also known to be non-zero (see the require() statement in -// _addAuction()) -if (_secondsPassed >= _duration) { -// We've reached the end of the dynamic pricing portion -// of the auction, just return the end price. -return _endingPrice; -} else { -// Starting price can be higher than ending price (and often is!), so -// this delta can be negative. -int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - -// This multiplication can't overflow, _secondsPassed will easily fit within -// 64-bits, and totalPriceChange will easily fit within 128-bits, their product -// will always fit within 256-bits. -int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - -// currentPriceChange can be negative, but if so, will have a magnitude -// less that _startingPrice. Thus, this result will always end up positive. -int256 currentPrice = int256(_startingPrice) + currentPriceChange; - -return uint256(currentPrice); -} -} - -/// @dev Computes owner's cut of a sale. -/// @param _price - Sale price of NFT. -function _computeCut(uint256 _price) internal view returns (uint256) { -// NOTE: We don't use SafeMath (or similar) in this function because -// all of our entry functions carefully cap the maximum values for -// currency (at 128-bits), and ownerCut <= 10000 (see the require() -// statement in the ClockAuction constructor). The result of this -// function is always guaranteed to be <= _price. -return _price * ownerCut / 10000; -} - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { -event Pause(); -event Unpause(); - -bool public paused = false; - - -/** - * @dev modifier to allow actions only when the contract IS paused - */ -modifier whenNotPaused() { -require(!paused); -_; -} - -/** - * @dev modifier to allow actions only when the contract IS NOT paused - */ -modifier whenPaused { -require(paused); -_; -} - -/** - * @dev called by the owner to pause, triggers stopped state - */ -function pause() onlyOwner whenNotPaused public returns (bool) { -paused = true; -emit Pause(); -return true; -} - -/** - * @dev called by the owner to unpause, returns to normal state - */ -function unpause() onlyOwner whenPaused public returns (bool) { -paused = false; -emit Unpause(); -return true; -} -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - -/// @dev The ERC-165 interface signature for ERC-721. -/// Ref: https://github.com/ethereum/EIPs/issues/165 -/// Ref: https://github.com/ethereum/EIPs/issues/721 -bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - -/// @dev Constructor creates a reference to the NFT ownership contract -/// and verifies the owner cut is in the valid range. -/// @param _nftAddress - address of a deployed contract implementing -/// the Nonfungible Interface. -/// @param _cut - percent cut the owner takes on each auction, must be -/// between 0-10,000. -constructor(address _nftAddress, uint256 _cut) public { -require(_cut <= 10000); -ownerCut = _cut; - -ERC721 candidateContract = ERC721(_nftAddress); -require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); -nonFungibleContract = candidateContract; -} - -/// @dev Remove all Ether from the contract, which is the owner's cuts -/// as well as any Ether sent directly to the contract address. -/// Always transfers to the NFT contract, but can be called either by -/// the owner or the NFT contract. -function withdrawBalance() external { -address payable nftAddress = address(uint160(address(nonFungibleContract))); - -require( -msg.sender == owner || -msg.sender == nftAddress -); -// We are using this boolean method to make sure that even if one fails it will still work -bool res = nftAddress.send(address(this).balance); -} - -/// @dev Creates and begins a new auction. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of time to move between starting -/// price and ending price (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -virtual -external -whenNotPaused -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(_owns(msg.sender, _tokenId)); -_escrow(msg.sender, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(block.timestamp) -); -_addAuction(_tokenId, auction); -} - -/// @dev Bids on an open auction, completing the auction and transferring -/// ownership of the NFT if enough Ether is supplied. -/// @param _tokenId - ID of token to bid on. -function bid(uint256 _tokenId) -external -payable -whenNotPaused -virtual -{ -// _bid will throw if the bid or funds transfer fails -_bid(_tokenId, msg.value); -_transfer(msg.sender, _tokenId); -} - -/// @dev Cancels an auction that hasn't been won yet. -/// Returns the NFT to original owner. -/// @notice This is a state-modifying function that can -/// be called while the contract is paused. -/// @param _tokenId - ID of token on auction -function cancelAuction(uint256 _tokenId) -external -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -address seller = auction.seller; -require(msg.sender == seller); -_cancelAuction(_tokenId, seller); -} - -/// @dev Cancels an auction when the contract is paused. -/// Only the owner may do this, and NFTs are returned to -/// the seller. This should only be used in emergencies. -/// @param _tokenId - ID of the NFT on auction to cancel. -function cancelAuctionWhenPaused(uint256 _tokenId) -whenPaused -onlyOwner -external -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -_cancelAuction(_tokenId, auction.seller); -} - -/// @dev Returns auction info for an NFT on auction. -/// @param _tokenId - ID of NFT on auction. -function getAuction(uint256 _tokenId) -external -view -returns -( -address seller, -uint256 startingPrice, -uint256 endingPrice, -uint256 duration, -uint256 startedAt -) { -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -return ( -auction.seller, -auction.startingPrice, -auction.endingPrice, -auction.duration, -auction.startedAt -); -} - -/// @dev Returns the current price of an auction. -/// @param _tokenId - ID of the token price we are checking. -function getCurrentPrice(uint256 _tokenId) -external -view -returns (uint256) -{ -Auction storage auction = tokenIdToAuction[_tokenId]; -require(_isOnAuction(auction)); -return _currentPrice(auction); -} - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - -// @dev Sanity check that allows us to ensure that we are pointing to the -// right auction in our setSiringAuctionAddress() call. -bool public isSiringClockAuction = true; - -// Delegate constructor -constructor(address _nftAddr, uint256 _cut) public -ClockAuction(_nftAddr, _cut) {} - -/// @dev Creates and begins a new auction. Since this function is wrapped, -/// require sender to be KittyCore contract. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of auction (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -override -external -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(msg.sender == address(nonFungibleContract)); -_escrow(_seller, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(block.timestamp) -); -_addAuction(_tokenId, auction); -} - -/// @dev Places a bid for siring. Requires the sender -/// is the KittyCore contract because all bid methods -/// should be wrapped. Also returns the kitty to the -/// seller rather than the winner. -function bid(uint256 _tokenId) -external -payable -override -{ -require(msg.sender == address(nonFungibleContract)); -address seller = tokenIdToAuction[_tokenId].seller; -// _bid checks that token ID is valid and will throw if bid fails -_bid(_tokenId, msg.value); -// We transfer the kitty back to the seller, the winner will get -// the offspring -_transfer(seller, _tokenId); -} - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - -// @dev Sanity check that allows us to ensure that we are pointing to the -// right auction in our setSaleAuctionAddress() call. -bool public isSaleClockAuction = true; - -// Tracks last 5 sale price of gen0 kitty sales -uint256 public gen0SaleCount; -uint256[5] public lastGen0SalePrices; - -// Delegate constructor -constructor(address _nftAddr, uint256 _cut) public -ClockAuction(_nftAddr, _cut) {} - -/// @dev Creates and begins a new auction. -/// @param _tokenId - ID of token to auction, sender must be owner. -/// @param _startingPrice - Price of item (in wei) at beginning of auction. -/// @param _endingPrice - Price of item (in wei) at end of auction. -/// @param _duration - Length of auction (in seconds). -/// @param _seller - Seller, if not the message sender -function createAuction( -uint256 _tokenId, -uint256 _startingPrice, -uint256 _endingPrice, -uint256 _duration, -address payable _seller -) -override -external -{ -// Sanity check that no inputs overflow how many bits we've allocated -// to store them in the auction struct. -require(_startingPrice == uint256(uint128(_startingPrice))); -require(_endingPrice == uint256(uint128(_endingPrice))); -require(_duration == uint256(uint64(_duration))); - -require(msg.sender == address(nonFungibleContract)); -_escrow(_seller, _tokenId); -Auction memory auction = Auction( -_seller, -uint128(_startingPrice), -uint128(_endingPrice), -uint64(_duration), -uint64(block.timestamp) -); -_addAuction(_tokenId, auction); -} - -/// @dev Updates lastSalePrice if seller is the nft contract -/// Otherwise, works the same as default bid method. -function bid(uint256 _tokenId) -external -override -payable -{ -// _bid verifies token ID size -address seller = tokenIdToAuction[_tokenId].seller; -uint256 price = _bid(_tokenId, msg.value); -_transfer(msg.sender, _tokenId); - -// If not a gen0 auction, exit -if (seller == address(nonFungibleContract)) { -// Track gen0 sale prices -lastGen0SalePrices[gen0SaleCount % 5] = price; -gen0SaleCount++; -} -} - -function averageGen0SalePrice() external view returns (uint256) { -uint256 sum = 0; -for (uint256 i = 0; i < 5; i++) { -sum += lastGen0SalePrices[i]; -} -return sum / 5; -} - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario009.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario009.sol deleted file mode 100644 index 52fa63e90ac..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario009.sol +++ /dev/null @@ -1,51 +0,0 @@ - - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert (Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register(uint value) public { - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - revert(); - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario010.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario010.sol deleted file mode 100644 index 4e299efecad..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario010.sol +++ /dev/null @@ -1,107 +0,0 @@ - - -contract TRON_ERC721 { - //name - function name() view public returns (string memory name){ - return "Tron ERC721 Token"; - } - //symbol - function symbol() view public returns (string memory symbol){ - return "T721T"; - } - - //totalSupply - - function totalSupply() view public returns (uint256 supply){ - uint256 totalSupply = 1000000000000; - return totalSupply; - } - - mapping(address => uint) private balances; - function balanceOf(address _owner) view public returns (uint balance) - { - return balances[_owner]; - } - - - mapping(uint256 => address) private tokenOwners; - mapping(uint256 => bool) private tokenExists; - function ownerOf(uint256 _tokenId) view public returns (address owner) { - require(tokenExists[_tokenId]); - return tokenOwners[_tokenId]; - } - - - mapping(address => mapping (address => uint256)) allowed; - function approve(address _to, uint256 _tokenId) public{ - require(msg.sender == ownerOf(_tokenId)); - require(msg.sender != _to); - allowed[msg.sender][_to] = _tokenId; - emit Approval(msg.sender, _to, _tokenId); - } - - - function takeOwnership(uint256 _tokenId) public { - require(tokenExists[_tokenId]); - address oldOwner = ownerOf(_tokenId); - address newOwner = msg.sender; - require(newOwner != oldOwner); - require(allowed[oldOwner][newOwner] == _tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - mapping(address => mapping(uint256 => uint256)) private ownerTokens; - function removeFromTokenList(address owner, uint256 _tokenId) private { - for(uint256 i = 0;ownerTokens[owner][i] != _tokenId;i++){ - ownerTokens[owner][i] = 0; - } - } - - function transfer(address _to, uint256 _tokenId) public{ - address currentOwner = msg.sender; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - function transferFrom(address _from,address _to, uint256 _tokenId) public{ - address currentOwner = _from; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - function tokenOfOwnerByIndex(address _owner, uint256 _index) view public returns (uint tokenId){ - return ownerTokens[_owner][_index]; - } - - - mapping(uint256 => string) tokenLinks; - function tokenMetadata(uint256 _tokenId) view public returns (string memory infoUrl) { - return tokenLinks[_tokenId]; - } - // Events - event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); - event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario011.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario011.sol deleted file mode 100644 index 6b213fa0f28..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario011.sol +++ /dev/null @@ -1,2060 +0,0 @@ - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address payable public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address payable _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public virtual onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer1(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer1(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(block.timestamp), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - kitties.push(_kitty); - uint256 newKittenId = kitties.length - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -abstract contract ERC721 { - // Required methods - function totalSupply() public virtual view returns (uint256 total); - function balanceOf(address _owner) public virtual view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external virtual view returns (address owner); - function approve(address _to, uint256 _tokenId) external virtual; - function transfer(address _to, uint256 _tokenId) external virtual; - function transferFrom(address _from, address _to, uint256 _tokenId) external virtual; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external virtual view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external override view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view override returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - override - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - override - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - override - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public override view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - override - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string calldata _preferredTransport) external view returns (string memory infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 ; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid{value : (msg.value - autoBirthFee)}(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 ; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - fallback() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause() public override onlyCEO whenPaused { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - - } -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address payable seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address payable seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (block.timestamp > _auction.startedAt) { - secondsPassed = block.timestamp - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address payable nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - virtual - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(block.timestamp) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - virtual - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - override - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(block.timestamp) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - override - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address payable _seller - ) - external - override - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(block.timestamp) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - override - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario012.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario012.sol deleted file mode 100644 index 7fea2b1ccf1..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario012.sol +++ /dev/null @@ -1,57 +0,0 @@ - -contract PayTest { - -uint256 public n; -constructor() payable public{ -n = 0; -} - -function nPlusOne() public{ -n = n+1; -} - -//get current contract balance -function getBalance() payable public returns (uint) { -return address(this).balance; -} - -function getSenderBalance() public view returns(address, uint) { -return (msg.sender, msg.sender.balance); -} - -address public user; - -//deposit 1 coin to msg.sender -function depositOneCoin() payable public returns(bool success){ -return msg.sender.send(1); -} - -// function transferOneCoin() payable public returns(){ -// address(msg.sender).transfer(1); -// } - -// function depositOneCoin() payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(1)); -// } - -//deposit coin to msg.sender -function deposit(uint256 money) payable public returns(bool success){ -return msg.sender.send(money); -} -// function deposit(uint money) payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(money)); -// } - -// fallback() payable { -// msg.sender.send(1); -// } - -function sendToAddress(address payable _receiver) payable public{ -_receiver.transfer(msg.value); -} - -function sendToAddress2(address payable _receiver) payable public{ -_receiver.transfer(5); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario013.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario013.sol deleted file mode 100644 index 93b7905679b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario013.sol +++ /dev/null @@ -1,8 +0,0 @@ - -contract timetest { - -function time() public{ -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractScenario014.sol b/framework/src/test/resources/soliditycode_0.7.6/contractScenario014.sol deleted file mode 100644 index 9f423d1b1ab..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractScenario014.sol +++ /dev/null @@ -1,34 +0,0 @@ - -contract Contract1 { - constructor() public payable{} - function send5SunToReceiver(address payable _receiver) payable public{ - _receiver.transfer(5); - } -} -contract contract2 { - address public payContract; - - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract1(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - } - - function triggerContract1ButRevert(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - require(1 == 2); - } - -} -contract contract3 { - address public payContract; - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract2(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("triggerContract1(address)",_receiver)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTest.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTest.sol deleted file mode 100644 index 9a72b4a53b4..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTest.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract Test{ - -function a() public returns (uint){ - -uint256 count = 0; - -for (uint256 i = 1; i > 0; i++) { - -count++; - -} - -return count; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode_0.7.6/contractToMathedFeed.sol deleted file mode 100644 index d9df9d9c10d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractToMathedFeed.sol +++ /dev/null @@ -1,21 +0,0 @@ - - -contract ToMathedFeed { - uint public i=1; - function ToMathed (uint value) public { - i=value; - } -} - -contract ToMathedUseINContract { - function ToMathedIUseNR(address a,uint256 n) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathedNot(uint256)",n)); - return success; - } - function ToMathedIUseNRE(address a,uint256 value) public returns(bool){ - address payContract=a; - (bool success, bytes memory data) = payContract.call(abi.encodeWithSignature("ToMathed(uint256)",value)); - return success; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTransferToken001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTransferToken001.sol deleted file mode 100644 index 0edbbfbb44a..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTransferToken001.sol +++ /dev/null @@ -1,22 +0,0 @@ -contract A { - address public a; - constructor() public payable{} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - function newB() public payable returns(address){ - B bAddress=new B(); - a= address(bAddress); - return a; - - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken001.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken001.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken001.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken002.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken002.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken002.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken003.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken003.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken003.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken005.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken005.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken005.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken011.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken011.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken011.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken012.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken012.sol deleted file mode 100644 index ab0c19767e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken012.sol +++ /dev/null @@ -1,26 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken014.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken014.sol deleted file mode 100644 index 589406c47c6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken014.sol +++ /dev/null @@ -1,34 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken018.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken018.sol deleted file mode 100644 index ab0c19767e7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken018.sol +++ /dev/null @@ -1,26 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken023.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken023.sol deleted file mode 100644 index 070acb201ff..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken023.sol +++ /dev/null @@ -1,26 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external { - flag = 1; -} - -} - -contract C{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable { - //flag = 1; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken026.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken026.sol deleted file mode 100644 index 5464265d81f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken026.sol +++ /dev/null @@ -1,31 +0,0 @@ - - -contract token{ - constructor() payable public{} - fallback() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - //callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - fallback() external payable{} - function transC(address payable callCAddress,address payable toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - fallback() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken027.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken027.sol deleted file mode 100644 index e7d6ee768f3..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken027.sol +++ /dev/null @@ -1,30 +0,0 @@ - - -contract token{ - constructor() payable public{} - fallback() payable external{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - callBAddress.call(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callCAddress,toAddress,amount,id)); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(abi.encodeWithSignature("transC(address,address,uint256,trcToken)",callAddressC,toAddress,amount,id)); - } - } - - - -contract B{ - constructor() public payable{} - fallback() external payable{} - function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(abi.encodeWithSignature("trans(address,uint256,trcToken)",toAddress,amount,id)); - } -} -contract C{ - constructor() payable public{} - fallback() payable external{} - function trans(address payable toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken028.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken028.sol deleted file mode 100644 index 0f27d89c819..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken028.sol +++ /dev/null @@ -1,25 +0,0 @@ - - -contract token{ - uint256 public a=1; - constructor() public payable{} - function tokenBalanceWithSameName(trcToken id) public payable{ - B b= new B(); - a= b.tokenBalance(id); - } - function getA() public returns(uint256){ - return a; - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - fallback() external payable{} - function tokenBalance(trcToken id) payable public returns(uint256){ - flag =9; - return flag; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken029.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken029.sol deleted file mode 100644 index 8480cf6f19d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken029.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract token{ - address public a; - constructor() public payable{} - function transferTokenWithSameName(trcToken id,uint256 amount) public payable{ - B b= new B(); - b.transferToken(amount,id); - a= address(b); - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - fallback() external payable{} - function transferToken(uint256 amount, trcToken id) payable public returns(bool){ - flag =9; - } - function getFlag() public view returns (uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken030.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken030.sol deleted file mode 100644 index 06b8201979c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken030.sol +++ /dev/null @@ -1,17 +0,0 @@ - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken031.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken031.sol deleted file mode 100644 index 65ec394e8da..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken031.sol +++ /dev/null @@ -1,18 +0,0 @@ - - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address payable toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken034.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken034.sol deleted file mode 100644 index 32c55f8c84b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken034.sol +++ /dev/null @@ -1,25 +0,0 @@ - - - contract token{ - - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken035.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken035.sol deleted file mode 100644 index ca45dde790d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken035.sol +++ /dev/null @@ -1,24 +0,0 @@ - - - contract token{ - constructor() public payable {} - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address payable toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036.sol deleted file mode 100644 index c1da2f7555e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036.sol +++ /dev/null @@ -1,52 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate1 { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithConstant(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -fallback() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_1.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_1.sol deleted file mode 100644 index 327ab5a756e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_1.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithPure(address payable toAddress, uint256 tokenValue) public pure { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_2.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_2.sol deleted file mode 100644 index 817a96e3c80..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_2.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_3.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_3.sol deleted file mode 100644 index 67400c2e8ad..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_3.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -constructor() payable public{} -fallback() payable external{} -event log(uint256); -function transferTokenWithView(address payable toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_4.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_4.sol deleted file mode 100644 index cbaca0d4b38..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_4.sol +++ /dev/null @@ -1,13 +0,0 @@ - -contract IllegalDecorate { -event log(uint256); -constructor() payable public{} -fallback() payable external{} -function transferTokenWithOutPayable(address payable toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_old.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_old.sol deleted file mode 100644 index 1f03afb7636..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken036_old.sol +++ /dev/null @@ -1,41 +0,0 @@ - - - -contract IllegalDecorate1 { -constructor() payable public{} -fallback() payable public{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -fallback() payable public{} -event log(uint256); -function transferTokenWithView(address toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -fallback() payable public{} -function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken037.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken037.sol deleted file mode 100644 index 7cdd91702e8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken037.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - require(0==address(this).tokenBalance(msg.tokenid)); - require(bamount+aamount==rec.tokenBalance(msg.tokenid)); - (bool success, bytes memory data) =rec.call(abi.encodeWithSignature("checkTrc10(uint256,trcToken,uint256)",bamount+aamount,msg.tokenid,0)); - require(success); - - } -} - -contract receiveTrc10 { - fallback() external payable {} - function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ - require(amount==address(this).tokenBalance(tid)); - require(meamount==msg.sender.tokenBalance(tid)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken038.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken038.sol deleted file mode 100644 index eeb5ae744cf..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken038.sol +++ /dev/null @@ -1,24 +0,0 @@ - - -contract transferTrc10 { - function receive(address payable rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - //require(rec.call(abi.encode(bytes4(keccak256("AssertError()"))))); - (bool suc, bytes memory data) = rec.call(abi.encodeWithSignature("AssertError()")); - require(suc); - require(aamount==address(this).tokenBalance(msg.tokenid)); - require(bamount==rec.tokenBalance(msg.tokenid)); - } -} - -contract receiveTrc10 { - fallback() external payable { - } - function AssertError() public{ - assert(1==2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken039.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken039.sol deleted file mode 100644 index ebf6fb932ed..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken039.sol +++ /dev/null @@ -1,44 +0,0 @@ - -/* - * 1. caller账户issue一个token - * 2. caller部署proxy, 传入1000 token,1000 trx - * 3. caller部署A - * 4. caller部署B - * 5. caller调用proxy中upgradetTo函数,传入A的地址 - * 6. caller调用proxy中不存在的trans(uint256,address,trcToken)函数,注意这时trcToken是无意义的,但也带上tokenid。address是任意另外某账户的地址 - * 7. 可以看到目标地址trx增长5,caller账户trx减少5 - * 8. caller调用proxy中upgradeTo函数,传入B的地址 - * 9. caller调用proxy中不存在的trans(uint256,address,trcToken)函数。 - * 10. 可以看到目标地址token增长5,caller账户token减少5 -*/ -contract Proxy { - constructor() payable public{} - address public implementation; - function upgradeTo(address _address) public { - implementation = _address; - } - fallback() payable external{ - address addr = implementation; - require(addr != address(0)); - assembly { - let freememstart := mload(0x40) - calldatacopy(freememstart, 0, calldatasize()) - let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 0) - returndatacopy(freememstart, 0, returndatasize()) - switch success - case 0 { revert(freememstart, returndatasize()) } - default { return(freememstart, returndatasize()) } - } - } -} - -contract A { - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transfer(amount); - } -} -contract B{ - function trans(uint256 amount, address payable toAddress, trcToken id) payable public { - toAddress.transferToken(amount,id); - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken041.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken041.sol deleted file mode 100644 index 6284253d1d5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken041.sol +++ /dev/null @@ -1,20 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - fallback() external payable {} - - function setFlag() public payable{ - flag = 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken043.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken043.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken043.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken048.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken048.sol deleted file mode 100644 index e705f696c1d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken048.sol +++ /dev/null @@ -1,14 +0,0 @@ - - - contract Test { - event log(uint256); - function testMsgTokenValue() payable public returns(uint256 value) { - emit log(msg.tokenvalue); - return msg.tokenvalue; - } - - function testMsgValue() payable public returns(uint256 value) { - emit log(msg.value); - return msg.value; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken049.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken049.sol deleted file mode 100644 index d40480720df..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken049.sol +++ /dev/null @@ -1,9 +0,0 @@ - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken050.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken050.sol deleted file mode 100644 index 6bc6d956898..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken050.sol +++ /dev/null @@ -1,10 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken051.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken051.sol deleted file mode 100644 index 493016b777f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken051.sol +++ /dev/null @@ -1,11 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - fallback() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken052.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken052.sol deleted file mode 100644 index 6bc6d956898..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken052.sol +++ /dev/null @@ -1,10 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken054.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken054.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken054.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken055.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken055.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken055.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken060.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken060.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken060.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken061.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken061.sol deleted file mode 100644 index ea28f4a62b6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken061.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken064.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken064.sol deleted file mode 100644 index 43e0da8a510..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken064.sol +++ /dev/null @@ -1,49 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } - function transferTokenTestValueMaxBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0); - } - function transferTokenTestValueOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775808, 1000001); - } - function transferTokenTestValueMaxLong(address payable toAddress) payable public { - toAddress.transferToken(9223372036854775807, 1000001); - } - function transferTokenTestValue0IdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(0, 9223372036854775809); - } -} - - - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken066.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken066.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken066.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken067.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken067.sol deleted file mode 100644 index 43e4010ec3f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken067.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract transferTokenContract { - constructor() payable public{} - fallback() payable external{} - function transferTokenTest(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address payable toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - fallback() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken073.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken073.sol deleted file mode 100644 index a9ee8ea412b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken073.sol +++ /dev/null @@ -1,16 +0,0 @@ - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - fallback() payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken075.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken075.sol deleted file mode 100644 index 9f201900295..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken075.sol +++ /dev/null @@ -1,26 +0,0 @@ - - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - constructor() payable public {} - - function getToken(trcToken tokenId) payable public{ - emit logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMin() payable public{ - // long.min - 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(-9223372036855775828)), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMax() payable public{ - // long.max + 1000020 - emit logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); - } - - fallback() payable external{ - emit logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken076.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken076.sol deleted file mode 100644 index a9decbee320..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken076.sol +++ /dev/null @@ -1,19 +0,0 @@ - -contract Test { - address public origin; - address public sender; - bool public result1; - bool public result2; - function test() external { - origin = tx.origin; - sender = msg.sender; - result1 = msg.sender == tx.origin; // true - result2 = origin == sender; // true - } -function getResult1() public returns(bool){ - return result1; -} -function getResult2() public returns(bool){ - return result2; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken077.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken077.sol deleted file mode 100644 index aeecf9cb9a5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken077.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract trcToken077 { -function addressTest() public returns(bytes32 addressValue) { - assembly{ - let x := mload(0x40) //Find empty storage location using "free memory pointer" - mstore(x,address) //Place current contract address - addressValue := mload(x) - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken078.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken078.sol deleted file mode 100644 index 8d10d25312d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken078.sol +++ /dev/null @@ -1,35 +0,0 @@ - -contract callerContract { - constructor() public payable{} - fallback() external payable{} - function sendToB(address called_address, address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(abi.encodeWithSignature("transferTo(address)",c)); - } - function sendToB3(address called_address,address c) public payable{ - called_address.delegatecall(abi.encodeWithSignature("transferTo(address)",c)); - } -} - contract calledContract { - fallback() external payable{} - constructor() public payable {} - function transferTo(address payable toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call{value:5}(abi.encode(bytes4(keccak256("setI()")))); - } - - } - contract c{ - address public origin; - address public sender; - constructor() public payable{} - event log(address,address); - fallback() payable external{ - emit log(tx.origin,msg.sender); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken079.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken079.sol deleted file mode 100644 index 863429fc4f8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken079.sol +++ /dev/null @@ -1,16 +0,0 @@ - - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken080.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken080.sol deleted file mode 100644 index 2d2688b74a4..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcToken080.sol +++ /dev/null @@ -1,30 +0,0 @@ - - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - fallback() external payable{} - // positive case - function TransferTokenTo(address payable toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode_0.7.6/contractTrcTokenToOther.sol deleted file mode 100644 index 8e926d3ba17..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractTrcTokenToOther.sol +++ /dev/null @@ -1,44 +0,0 @@ - - -contract ConvertType { - -constructor() payable public{} - -fallback() payable external{} - -//function trcTokenOnStorage(trcToken storage token) internal { // ERROR: Data location can only be specified for array, struct or mapping types, but "storage" was given. -//} - -function trcTokenToString(trcToken token) public pure returns(string memory s){ -// s = token; // ERROR -// s = string(token); // ERROR -} - -function trcTokenToUint256(trcToken token) public pure returns(uint256 r){ -uint256 u = token; // OK -uint256 u2 = uint256(token); // OK -r = u2; -} - -function trcTokenToAddress(trcToken token) public pure returns(address r){ -//r = token; // ERROR -token = 0x1234567812345678123456781234567812345678123456781234567812345678; -address a2 = address(token); // OK -r = a2; -} - -function trcTokenToBytes(trcToken token) public pure returns(bytes memory r){ -//r = token; // ERROR -// r = bytes(token); // ERROR -} - -function trcTokenToBytes32(trcToken token) public pure returns(bytes32 r){ -// r = token; // ERROR -bytes32 b2 = bytes32(token); // OK -r = b2; -} - -function trcTokenToArray(trcToken token) public pure returns(uint[] memory r){ -//r = token; // ERROR -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/contractUnknownException.sol b/framework/src/test/resources/soliditycode_0.7.6/contractUnknownException.sol deleted file mode 100644 index 0aca7badde8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/contractUnknownException.sol +++ /dev/null @@ -1,64 +0,0 @@ - -contract testA { - constructor() public payable { - A a = (new A){value:10}(); - a.fun(); - } -} - -contract testB { - constructor() public payable { - B b = (new B){value:10}(); - b.fun(); - } -} - - -contract testC { - constructor() public payable{ - C c = (new C){value:10}(); - c.fun(); - } -} - -contract testD { - constructor() public payable{ - D d = (new D){value:10}(); - d.fun(); - } -} - - -contract A { - constructor() public payable{ - selfdestruct(msg.sender); - } - function fun() public { - } - -} - -contract B { - constructor() public payable { - revert(); - } - function fun() public { - } -} - - -contract C { - constructor() public payable { - assert(1==2); - } - function fun() public { - } -} - -contract D { - constructor() public payable { - require(1==2); - } - function fun() public { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/create2CallContract.sol b/framework/src/test/resources/soliditycode_0.7.6/create2CallContract.sol deleted file mode 100644 index 046706ebd9e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/create2CallContract.sol +++ /dev/null @@ -1,37 +0,0 @@ -contract callerContract { - constructor() payable public{} - fallback() payable external{} - function delegateCallCreate2(address called_address, bytes memory code, uint256 salt) public { - called_address.delegatecall(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } - function callCreate2(address called_address,bytes memory code, uint256 salt) public returns(bool,bytes memory){ - return called_address.call(abi.encodeWithSignature("deploy(bytes,uint256)",code,salt)); - } -} - - -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/create2Istanbul.sol b/framework/src/test/resources/soliditycode_0.7.6/create2Istanbul.sol deleted file mode 100644 index c2ef8f3236b..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/create2Istanbul.sol +++ /dev/null @@ -1,28 +0,0 @@ - - -contract create2Istanbul { - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - - } - return addr; - } - - // prefix in main net is 0x41, testnet config is 0xa0 - function get(bytes1 prefix, bytes calldata code, uint256 salt) external view returns(address) { - //bytes32 hash = keccak256(abi.encodePacked(bytes1(0x41),address(this), salt, keccak256(code))); - bytes32 hash = keccak256(abi.encodePacked(prefix,address(this), salt, keccak256(code))); - address addr = address(uint160(uint256(hash))); - return addr; - } - -} - -contract B { - constructor() public payable{} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/create2contract.sol b/framework/src/test/resources/soliditycode_0.7.6/create2contract.sol deleted file mode 100644 index 0171f4d5486..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/create2contract.sol +++ /dev/null @@ -1,52 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract FactoryBytes { - event Deployed(address addr, bytes32 salt, address sender); - function deploy(bytes memory code, bytes32 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - -contract TestConstract { - uint public i; - constructor () public { - } - function plusOne() public returns(uint){ - i++; - return i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/create2contract22.sol b/framework/src/test/resources/soliditycode_0.7.6/create2contract22.sol deleted file mode 100644 index c33cb08edc3..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/create2contract22.sol +++ /dev/null @@ -1,109 +0,0 @@ -contract Factory { - event Deployed(address addr, trcToken salt, address sender); - event Deployed1(address addr, uint8 salt, address sender); - event Deployed2(address addr, address salt, address sender); - event Deployed3(address addr, string salt, address sender); - - - function deploy(bytes memory code, trcToken salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } - - function deploy1(bytes memory code, uint8 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed1(addr, salt, msg.sender); - return addr; - } - - function deploy2(bytes memory code, address salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed2(addr, salt, msg.sender); - return addr; - } - - function deploy3(bytes memory code, string memory salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed3(addr, salt, msg.sender); - return addr; - } - -} - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract1 { - uint public i=2; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract2 { - uint public i=3; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} - -contract TestConstract3 { - uint public i=4; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/create2contractn.sol b/framework/src/test/resources/soliditycode_0.7.6/create2contractn.sol deleted file mode 100644 index e0e3ae64c16..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/create2contractn.sol +++ /dev/null @@ -1,29 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function testTransfer(uint256 i) payable public{ - msg.sender.transfer(i); - } - function testTransferToken(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/create2contractn2.sol b/framework/src/test/resources/soliditycode_0.7.6/create2contractn2.sol deleted file mode 100644 index 626988c4e04..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/create2contractn2.sol +++ /dev/null @@ -1,26 +0,0 @@ -contract Factory { - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract TestConstract { - uint public i=1; - function set() payable public { - i=5; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/demo.sol b/framework/src/test/resources/soliditycode_0.7.6/demo.sol deleted file mode 100644 index 06bf15387fc..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/demo.sol +++ /dev/null @@ -1,73 +0,0 @@ - - - contract tokenTest{ - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - } - codesize = m; - } - - // positive case - function pulsone() public payable{ - uint256 j = 0; - uint i = 100; - for (; i < i; i++) { - j++; - } - } - - - function getCodeSize() public returns (uint256){ - return codesize; - } - - } - - contract confirmTest{ - - uint256 codesize; - constructor() payable public{ - uint256 m; - address addr = address(this); - assembly { - m := extcodesize(addr) - - } - codesize = m; - } - - function getCodeSize() public returns (uint256){ - return codesize; - } - - function confirm(address addr) public returns (uint256){ - uint256 j; - assembly { - j := extcodesize(addr) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return j; - } - - function at(address _addr) public returns (bytes memory o_code) { - assembly { - // retrieve the size of the code, this needs assembly - let size := extcodesize(_addr) - // allocate output byte array - this could also be done without assembly - // by using o_code = new bytes(size) - o_code := mload(0x40) - // new "memory end" including padding - mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f)))) - // store length in memory - mstore(o_code, size) - // actually retrieve the code, this needs assembly - extcodecopy(_addr, add(o_code, 0x20), 0, size) - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/enumAndStruct.sol b/framework/src/test/resources/soliditycode_0.7.6/enumAndStruct.sol deleted file mode 100644 index 836a4ac850e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/enumAndStruct.sol +++ /dev/null @@ -1,43 +0,0 @@ - - -struct S_out { -uint x; -} - -enum ErrorType { -Revert_Error, //0 -RevertWithMsg_Error, //1 -Require_Error, //2 -RequirewithMsg_Error, //3 -Assert_Error, //4 -Tansfer_Error, //5 -Send_Error, //6 -Math_Error, //7 -ArrayOverFlow_Error //8 -} - -contract enumAndStructTest { - -struct S_inner { -int x; -} - -enum ErrorType_inner { -Revert_Error, //0 -RevertWithMsg_Error, //1 -Require_Error, //2 -RequirewithMsg_Error, //3 -Assert_Error, //4 -Tansfer_Error, //5 -Send_Error, //6 -Math_Error, //7 -ArrayOverFlow_Error //8 -} - -function getvalue() public returns(uint) { - require(ErrorType.Require_Error == ErrorType(2)); - S_out memory s = S_out(1); - return s.x; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/event001.sol b/framework/src/test/resources/soliditycode_0.7.6/event001.sol deleted file mode 100644 index 7662df3a5c6..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/event001.sol +++ /dev/null @@ -1,10 +0,0 @@ -contract Event { - event xixi(uint256 id) ; - event log2(uint256,uint256,uint256); - constructor() public payable{} - function messageI() payable public returns (uint ret) { - //emit log2(1,2,3); - emit xixi(1); - return 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/event002.sol b/framework/src/test/resources/soliditycode_0.7.6/event002.sol deleted file mode 100644 index a61f834e1b5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/event002.sol +++ /dev/null @@ -1,52 +0,0 @@ - - -contract Event { - - event _0(); - event a_0() anonymous; - event a_4i(uint256 indexed x1, uint256 indexed x2 , uint256 indexed x3, uint256 indexed x4, uint256 x5)anonymous ; - event _3i(uint256 x1, uint256 indexed x2 , uint256 indexed x3, uint256 x4, uint256 x5) ; - event _1i(uint256 indexed x1, uint256, uint256 indexed, uint256 x4) ; - event a_1i(uint256) anonymous; - event _ai(uint8[2], uint8) ; - event a_ai(uint8[2], uint8) anonymous; - event _a1i(uint8[2] indexed, uint8) ; - event a_a1i(uint8[2] indexed, uint8) anonymous; - - constructor () public { - // emit a_0(); - // emit a_1i(123); - // emit a_4i(1,2,3,5,16); - // emit _0(); - emit _3i(1,2,3,5,16); - // emit _1i(1,2,3,5); - // emit _ai([1,2], 3); - // emit a_ai([3,4], 5); - // emit _a1i([1,2], 3); - // emit a_a1i([3,4], 5); - } - - function e() public { - emit _1i(1,2,3,4); - } - - function l() public { - emit a_1i(1); - } - - function k() public{ - emit a_4i(2,3,4,5,17); - emit _3i(2,3,4,5,16); - emit _1i(2,3,4,5); - emit a_1i(128); - emit _0(); - emit a_0(); - //selfdestruct(msg.sender); - //emit a_4i(1,2,3,5,16); - //emit _3i(1,2,3,5,16); - //emit _1i(1,2,3,5); - //emit a_1i(123); - //emit _0(); - //emit a_0(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/extCodeHash.sol b/framework/src/test/resources/soliditycode_0.7.6/extCodeHash.sol deleted file mode 100644 index d6209770682..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/extCodeHash.sol +++ /dev/null @@ -1,13 +0,0 @@ -contract TestExtCodeHash { - - function getCodeHashByAddr(address _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } - function getCodeHashByUint(uint256 _addr) public returns (bytes32 _hash) { - assembly { - _hash := extcodehash(_addr) - } - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/extCodeHash11.sol b/framework/src/test/resources/soliditycode_0.7.6/extCodeHash11.sol deleted file mode 100644 index ad59f6cce1c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/extCodeHash11.sol +++ /dev/null @@ -1,103 +0,0 @@ -contract Counter { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} -revert(); -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract Counter1 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr() public returns (bytes32 _hashBefore, bytes32 _hashAfter) { -address addr = address(this); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter2 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} - addr.call(abi.encodeWithSignature("testSuicideNonexistentTarget(address)",c)); - - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - - -contract Counter3 { -uint count = 0; -address payable owner; -event LogResult(bytes32 _hashBefore, bytes32 _hashAfter); -constructor() public{ -owner = msg.sender; -} -function getCodeHashByAddr(address c) public returns (bytes32 _hashBefore, bytes32 _hashAfter) { - TestConstract t=new TestConstract(); -address addr = address(t); -assembly { -_hashBefore := extcodehash(addr) -} -if (owner == msg.sender) { -selfdestruct(owner); -} - -assembly { -_hashAfter := extcodehash(addr) -} - -emit LogResult(_hashBefore, _hashAfter); -} -} - -contract TestConstract { - uint public i=1; - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/extCodeHashConstruct.sol b/framework/src/test/resources/soliditycode_0.7.6/extCodeHashConstruct.sol deleted file mode 100644 index 6bb91b3d3b1..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/extCodeHashConstruct.sol +++ /dev/null @@ -1,14 +0,0 @@ -contract CounterConstruct { - uint count = 0; - address payable owner; - event LogResult(bytes32 _hashBefore); - constructor() public{ - owner = msg.sender; - address addr = address(this); - bytes32 _hashBefore; - assembly { - _hashBefore := extcodehash(addr) - } - emit LogResult(_hashBefore); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/extCodeHashStress.sol b/framework/src/test/resources/soliditycode_0.7.6/extCodeHashStress.sol deleted file mode 100644 index cf41f3c8106..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/extCodeHashStress.sol +++ /dev/null @@ -1,45 +0,0 @@ -contract Trigger { - function test(address addr) public returns(uint i) { - bytes32 hash; - while (gasleft() > 1000) { - assembly { - hash := extcodehash(addr) - } - i++; - } - } - - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - assembly { - hash := extcodehash(addr) - } - } - return i; - } - } - - - - contract TriggerNormal { - function test(address addr) public returns(uint i) { - i = 0; - while (gasleft() > 100000) { - i++; - } - } - } - - contract TriggerNormal1 { - function test(address[] memory addrs) public returns(uint i) { - bytes32 hash; - uint i = 0; - for (; i < addrs.length; i++) { - address addr = addrs[i]; - addr.balance; - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/extCodeHashTestNoPayable.sol b/framework/src/test/resources/soliditycode_0.7.6/extCodeHashTestNoPayable.sol deleted file mode 100644 index c3a2ad8c6ae..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/extCodeHashTestNoPayable.sol +++ /dev/null @@ -1,8 +0,0 @@ -contract testConstantContract{ -uint256 public i; -function testNoPayable() public returns (uint256 z) { -i=1; -z=i; -return z; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/fallbackUpgrade.sol b/framework/src/test/resources/soliditycode_0.7.6/fallbackUpgrade.sol deleted file mode 100644 index 6751858c65e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/fallbackUpgrade.sol +++ /dev/null @@ -1,83 +0,0 @@ -contract Test0{ - event FuncCalled(bytes data,uint a); -} - -contract Test1 { - - event FuncCalled(string a); - fallback() external { - x = "fallback"; - emit FuncCalled(x); - } - string x; -} -//含有payable的fallback,无receice -contract Test2 { - - event FuncCalled(string data); - fallback() external payable{ - x = "fallback"; - emit FuncCalled(x); - } - string x; -} - -contract TestPayable { - event FuncCalled(string a); - - fallback() external payable { - x = "fallback"; - emit FuncCalled(x); - } - - receive() external payable { - x = "receive"; - emit FuncCalled(x); - } - string x; -} - -contract Caller { - function callTest0(Test0 test) public{ - (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - } - function callTest1(address test) public returns (bool) { - (bool success,) = test.call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - (success,) = address(test).call(""); - require(success); - return true; - } - function callTest2(address test) public payable returns (bool) { - (bool success,) = test.call{value:1000}(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - return true; - } - function callTestPayable1(TestPayable test) public payable returns (bool) { - (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); - require(success); - (success,) = address(test).call(""); - require(success); - return true; - } -} - - -//contract Test0 { -// event FallbackCall(string data,bytes msg); -// //event FuncCalled(string a,bytes data); -// function() external payable{ -// x = "fallback"; -// emit FallbackCall(x,msg.data); -// } -// string x; -//} -//contract Caller{ -// function call(Test0 test) public payable returns(bool){ -// (bool success,) = address(test).call(abi.encodeWithSignature("nonExistingFunction()")); -// require(success); -// return true; -// } -//} - diff --git a/framework/src/test/resources/soliditycode_0.7.6/freezeContract001.sol b/framework/src/test/resources/soliditycode_0.7.6/freezeContract001.sol deleted file mode 100644 index 0ad8ed9f460..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/freezeContract001.sol +++ /dev/null @@ -1,63 +0,0 @@ - -contract TestFreeze { - constructor() public payable {} - - function freeze(address payable receiver, uint amount, uint res) external payable{ - receiver.freeze(amount, res); - } - - function unfreeze(address payable receiver, uint res) external { - receiver.unfreeze(res); - } - - function destroy(address payable inheritor) external { - selfdestruct(inheritor); - } - - function send(address payable A) external { - A.transfer(10); - } - - function send(address payable A, uint256 value) external { - A.transfer(value); - } - - function getExpireTime(address payable target, uint res) external view returns(uint) { - return target.freezeExpireTime(res); - } - - function deploy(uint256 salt) public returns(address){ - address addr; - bytes memory code = type(C).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } - - function freezeAndSend(address payable receiver, uint amount, uint res) external { - receiver.transfer(amount); - receiver.freeze(amount, res); - } - - -} - - -contract C { - constructor() public payable {} - - function destroy(address payable inheritor) external { - selfdestruct(inheritor); - } -} - -contract D { - constructor() public payable { - msg.sender.freeze(msg.value, 1); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/getAddressChange.sol b/framework/src/test/resources/soliditycode_0.7.6/getAddressChange.sol deleted file mode 100644 index 2796da68770..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/getAddressChange.sol +++ /dev/null @@ -1,12 +0,0 @@ -contract getAddressChange { - constructor() public payable {} - // testaddress1函数新增了一个address属性。0.6.0之前 external函数可以通过address(x)来转化为地址,6.0将其禁止,可以通过函数address属性直接获取 - function testaddress1() public view returns(address) { - //return address(this.getamount); //0.6.0之前可以使用 - return this.getamount.address; //0.6.0 - - } - function getamount(address) external view returns(uint256) { - return address(this).balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/isSRCandidate.sol b/framework/src/test/resources/soliditycode_0.7.6/isSRCandidate.sol deleted file mode 100644 index e8e9b692dec..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/isSRCandidate.sol +++ /dev/null @@ -1,35 +0,0 @@ - - - -contract ContractB{ - address others; -} - -contract TestIsSRCandidate{ - - ContractB contractB = new ContractB(); - - function isSRCandidateTest(address addr) public view returns (bool) { - return address(addr).isSRCandidate; - } - - function zeroAddressTest() public view returns (bool) { - return address(0x0).isSRCandidate; - } - - function localContractAddrTest() public view returns (bool) { - return address(this).isSRCandidate; - } - - function otherContractAddrTest() public view returns (bool) { - return address(contractB).isSRCandidate; - } - - function nonpayableAddrTest(address addr) public view returns (bool) { - return addr.isSRCandidate; - } - - function payableAddrTest(address payable addr) public returns (bool) { - return addr.isSRCandidate; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/mappingGetter.sol b/framework/src/test/resources/soliditycode_0.7.6/mappingGetter.sol deleted file mode 100644 index dbd473717cb..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/mappingGetter.sol +++ /dev/null @@ -1,4 +0,0 @@ -contract mappingGetter { - mapping(bytes => uint256) public balances1; - mapping(string => uint256) public balances2; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/multiValiSignPerformance01.sol b/framework/src/test/resources/soliditycode_0.7.6/multiValiSignPerformance01.sol deleted file mode 100644 index 74baa963366..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/multiValiSignPerformance01.sol +++ /dev/null @@ -1,37 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract ecrecoverValidateSign { - - using ECVerify for bytes32; - - function validateSign(bytes32 hash,bytes[] memory sig,address[] memory signer) public returns (bool) { - for(uint256 i=0;i=0.5.0 <0.7.0; - -contract A { - uint public x; - function setValue(uint _x) public { - x = _x; - } -} -contract B is A {} -contract C is A {} -// No explicit override required -contract D is B, C {} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/override003.sol b/framework/src/test/resources/soliditycode_0.7.6/override003.sol deleted file mode 100644 index 0ca6a2663d1..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/override003.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.6.0; -contract A { - uint public x; - function setValue(uint _x) public virtual { - x = _x; - } -} - -contract B { - uint public y; - function setValue(uint _y) public virtual { - y = _y; - } -} - -contract C is A, B { - function setValue(uint _x) public override(B,A) { - A.setValue(_x); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/override004.sol b/framework/src/test/resources/soliditycode_0.7.6/override004.sol deleted file mode 100644 index d0cf20525d5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/override004.sol +++ /dev/null @@ -1,25 +0,0 @@ -//pragma solidity >=0.5.0 <0.7.0; - -contract A { - uint public x = 4; - function setValue(uint _x) public notZero { - x = _x; - } - modifier notZero() virtual { - require(x >= 5,"x must >= 5"); - _; - } -} - -contract B is A { - function setValue2(uint _x) public { - x = _x; - } -} - -contract C is A,B { - modifier notZero override { - require(x >= 6,"x must >= 6"); - _; - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/override005.sol b/framework/src/test/resources/soliditycode_0.7.6/override005.sol deleted file mode 100644 index 0ea485ae0a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/override005.sol +++ /dev/null @@ -1,39 +0,0 @@ -pragma solidity >= 0.6.0; - -contract Base { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices public choice2 = ActionChoices.GoRight; - - function stopped() virtual external view returns (bool) { - return true; - } - function i() virtual external view returns (int) { - return 32482980; - } - function i2() virtual external view returns (int) { - return -32482980; - } - function ui() virtual external view returns (uint) { - return 23487820; - } - function origin() virtual external view returns (address) { - return 0x3b0E4a6EdEE231CE0c3433F00F1bbc5FeD409c0B; - } - function b32() virtual external view returns (bytes32) { - return 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd231050; - } - function choice() virtual external returns (ActionChoices) { - return choice2; - } -} - -contract Test is Base { - - bool override public stopped = false; - int override public i = 32482989; - int override public i2 = -32482989; - uint override public ui = 23487823; - address override public origin = 0xdCad3a6d3569DF655070DEd06cb7A1b2Ccd1D3AF; - bytes32 override public b32 = 0xb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c; - ActionChoices override public choice = ActionChoices.SitStill; -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/overridePrivateFunction.sol b/framework/src/test/resources/soliditycode_0.7.6/overridePrivateFunction.sol deleted file mode 100644 index b0b4d679620..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/overridePrivateFunction.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.5.17; - -contract A { - - function test() private pure returns(uint) { - return 1; - } - -} - -contract B is A { - - function basic() private pure returns(uint) { - return 2; - } - function testOverridePrivate() external payable returns(uint) { - return basic(); - } - - constructor() public payable {} -} - diff --git a/framework/src/test/resources/soliditycode_0.7.6/payable001.sol b/framework/src/test/resources/soliditycode_0.7.6/payable001.sol deleted file mode 100644 index 4fe7b20921f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/payable001.sol +++ /dev/null @@ -1,31 +0,0 @@ - - - -contract A { - constructor() public payable{ - } - - fallback() external payable { - } -} - -contract PayableTest { - -address payable a1; -function receiveMoneyTransfer(address a, uint256 _x) public { -a1 = payable(a); -a1.transfer(_x); -} - -function receiveMoneySend(address a, uint256 x) public { -address payable a2 = payable(a); -a2.send(x); -} - -function receiveMoneyTransferWithContract(A PayableTest, uint256 x) public { -payable(address(PayableTest)).transfer(x); -} - -constructor() public payable{ -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/pedersenHash001.sol b/framework/src/test/resources/soliditycode_0.7.6/pedersenHash001.sol deleted file mode 100644 index 6cad7cb9855..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/pedersenHash001.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract pedersenHashTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000004).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000004).delegatecall(data); - } - - function test3(uint32 hash, bytes32 left, bytes32 right) public returns (bytes32){ - return pedersenHash(hash, left, right); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/pedersenHash002.sol b/framework/src/test/resources/soliditycode_0.7.6/pedersenHash002.sol deleted file mode 100644 index b0a78973ef2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/pedersenHash002.sol +++ /dev/null @@ -1,320 +0,0 @@ -pragma experimental ABIEncoderV2; - -import "./SafeMath.sol"; - -abstract contract TokenTRC20 { - function transfer(address _to, uint256 _value) public virtual returns (bool success); - - function transferFrom(address _from, address _to, uint256 _value) public virtual returns (bool success); -} - -contract ShieldedTRC20 { - using SafeMath for uint256; - - uint256 public scalingFactor; // used when decimals of TRC20 token is too large. - uint256 public leafCount; - uint256 constant INT64_MAX = 2 ** 63 - 1; - bytes32 public latestRoot; - mapping(bytes32 => bytes32) public nullifiers; // store nullifiers of spent commitments - mapping(bytes32 => bytes32) public roots; // store history root - mapping(uint256 => bytes32) public tree; - mapping(bytes32 => bytes32) public noteCommitment; - bytes32[33] frontier; - bytes32[32] zeroes = [bytes32(0x0100000000000000000000000000000000000000000000000000000000000000), bytes32(0x817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca155), bytes32(0xffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e34), bytes32(0xd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c), bytes32(0xe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49), bytes32(0x912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a), bytes32(0x8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613), bytes32(0xd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813), bytes32(0x7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444), bytes32(0x43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b), bytes32(0xba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce72), bytes32(0x4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c), bytes32(0xec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048), bytes32(0x1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651), bytes32(0xbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c), bytes32(0xd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f), bytes32(0x1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451), bytes32(0x6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c), bytes32(0xcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf00), bytes32(0x6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b159216), bytes32(0x8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673), bytes32(0x08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023), bytes32(0x0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49), bytes32(0x4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850), bytes32(0xfee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712), bytes32(0x16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a), bytes32(0xd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb58), bytes32(0xa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a), bytes32(0x28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a), bytes32(0xe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72), bytes32(0x12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d), bytes32(0xb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c53814)]; - address owner; - TokenTRC20 trc20Token; - - event MintNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TransferNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event BurnNewLeaf(uint256 position, bytes32 cm, bytes32 cv, bytes32 epk, bytes32[21] c); - event TokenMint(address from, uint256 value); - event TokenBurn(address to, uint256 value, bytes32[3] ciphertext); - event NoteSpent(bytes32 nf); - - constructor (address trc20ContractAddress, uint256 scalingFactorExponent) public { - require(scalingFactorExponent < 77, "The scalingFactorExponent is out of range!"); - scalingFactor = 10 ** scalingFactorExponent; - owner = msg.sender; - trc20Token = TokenTRC20(trc20ContractAddress); - } - // output: cm, cv, epk, proof - function mint(uint256 rawValue, bytes32[9] calldata output, bytes32[2] calldata bindingSignature, bytes32[21] calldata c) external { - address sender = msg.sender; - // transfer the trc20Token from the sender to this contract - bool transferResult = trc20Token.transferFrom(sender, address(this), rawValue); - require(transferResult, "TransferFrom failed!"); - - require(noteCommitment[output[0]] == 0, "Duplicate noteCommitments!"); - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), value, output, c)); - (bytes32[] memory ret) = verifyMintProof(output, bindingSignature, value, signHash, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[0]; - if (slot == 0) { - frontier[0] = output[0]; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[output[0]] = output[0]; - leafCount ++; - - emit MintNewLeaf(leafCount - 1, output[0], output[1], output[2], c); - emit TokenMint(sender, rawValue); - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function transfer(bytes32[10][] calldata input, bytes32[2][] calldata spendAuthoritySignature, bytes32[9][] calldata output, bytes32[2] calldata bindingSignature, bytes32[21][] calldata c) external { - require(input.length >= 1 && input.length <= 2, "Input number must be 1 or 2!"); - require(input.length == spendAuthoritySignature.length, "Input number must be equal to spendAuthoritySignature number!"); - require(output.length >= 1 && output.length <= 2, "Output number must be 1 or 2!"); - require(output.length == c.length, "Output number must be equal to c number!"); - - for (uint256 i = 0; i < input.length; i++) { - require(nullifiers[input[i][0]] == 0, "The note has already been spent!"); - require(roots[input[i][1]] != 0, "The anchor must exist!"); - } - for (uint256 i = 0; i < output.length; i++) { - require(noteCommitment[output[i][0]] == 0, "Duplicate noteCommitment!"); - } - - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c)); - (bytes32[] memory ret) = verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, 0, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 offset = 1; - //ret offset - for (uint256 i = 0; i < output.length; i++) { - uint256 slot = uint256(ret[offset++]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = output[i][0]; - if (slot == 0) { - frontier[0] = output[i][0]; - } - for (uint256 k = 1; k < slot + 1; k++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[offset++]; - if (k == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - leafCount++; - } - latestRoot = ret[offset]; - roots[latestRoot] = latestRoot; - for (uint256 i = 0; i < input.length; i++) { - bytes32 nf = input[i][0]; - nullifiers[nf] = nf; - emit NoteSpent(nf); - } - for (uint256 i = 0; i < output.length; i++) { - noteCommitment[output[i][0]] = output[i][0]; - emit TransferNewLeaf(leafCount - (output.length - i), output[i][0], output[i][1], output[i][2], c[i]); - } - } - //input: nf, anchor, cv, rk, proof - //output: cm, cv, epk, proof - function burn(bytes32[10] calldata input, bytes32[2] calldata spendAuthoritySignature, uint256 rawValue, bytes32[2] calldata bindingSignature, address payTo, bytes32[3] calldata burnCipher, bytes32[9][] calldata output, bytes32[21][] calldata c) external { - uint64 value = rawValueToValue(rawValue); - bytes32 signHash = sha256(abi.encodePacked(address(this), input, output, c, payTo, value)); - - bytes32 nf = input[0]; - bytes32 anchor = input[1]; - require(nullifiers[nf] == 0, "The note has already been spent!"); - require(roots[anchor] != 0, "The anchor must exist!"); - - require(output.length <= 1, "Output number cannot exceed 1!"); - require(output.length == c.length, "Output number must be equal to length of c!"); - - // bytes32 signHash = sha256(abi.encodePacked(address(this), input, payTo, value, output, c)); - if (output.length == 0) { - (bool result) = verifyBurnProof(input, spendAuthoritySignature, value, bindingSignature, signHash); - require(result, "The proof and signature have not been verified by the contract!"); - } else { - transferInBurn(input, spendAuthoritySignature, value, bindingSignature, signHash, output, c); - } - - nullifiers[nf] = nf; - emit NoteSpent(nf); - //Finally, transfer trc20Token from this contract to the nominated address - bool transferResult = trc20Token.transfer(payTo, rawValue); - require(transferResult, "Transfer failed!"); - - emit TokenBurn(payTo, rawValue, burnCipher); - } - - function transferInBurn(bytes32[10] memory input, bytes32[2] memory spendAuthoritySignature, uint64 value, bytes32[2] memory bindingSignature, bytes32 signHash, bytes32[9][] memory output, bytes32[21][] memory c) private { - bytes32 cm = output[0][0]; - require(noteCommitment[cm] == 0, "Duplicate noteCommitment!"); - bytes32[10][] memory inputs = new bytes32[10][](1); - inputs[0] = input; - bytes32[2][] memory spendAuthoritySignatures = new bytes32[2][](1); - spendAuthoritySignatures[0] = spendAuthoritySignature; - (bytes32[] memory ret) = verifyTransferProof(inputs, spendAuthoritySignatures, output, bindingSignature, signHash, value, frontier, leafCount); - uint256 result = uint256(ret[0]); - require(result == 1, "The proof and signature have not been verified by the contract!"); - - uint256 slot = uint256(ret[1]); - uint256 nodeIndex = leafCount + 2 ** 32 - 1; - tree[nodeIndex] = cm; - if (slot == 0) { - frontier[0] = cm; - } - for (uint256 i = 1; i < slot + 1; i++) { - nodeIndex = (nodeIndex - 1) / 2; - tree[nodeIndex] = ret[i + 1]; - if (i == slot) { - frontier[slot] = tree[nodeIndex]; - } - } - latestRoot = ret[slot + 2]; - roots[latestRoot] = latestRoot; - noteCommitment[cm] = cm; - leafCount ++; - - emit BurnNewLeaf(leafCount - 1, cm, output[0][1], output[0][2], c[0]); - } - - //position: index of leafnode, start from 0 - function getPath(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValue(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - //position: index of leafnode, start from 0 - function getPathByValueIsZero(uint256 position) public view returns (bytes32, bytes32[32] memory) { - require(position >= 0, "Position should be non-negative!"); - require(position < leafCount, "Position should be smaller than leafCount!"); - uint256 index = position + 2 ** 32 - 1; - bytes32[32] memory path; - uint32 level = ancestorLevel(position); - bytes32 targetNodeValue = getTargetNodeValueByValueIsZero(position, level); - for (uint32 i = 0; i < 32; i++) { - if (i == level) { - path[31 - i] = targetNodeValue; - } else { - if (index % 2 == 0) { - path[31 - i] = tree[index - 1]; - } else { - path[31 - i] = tree[index + 1] == 0 ? zeroes[i] : tree[index + 1]; - } - } - index = (index - 1) / 2; - } - return (latestRoot, path); - } - - function ancestorLevel(uint256 leafIndex) private view returns (uint32) { - uint256 nodeIndex1 = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex2 = leafCount + 2 ** 32 - 2; - uint32 level = 0; - while (((nodeIndex1 - 1) / 2) != ((nodeIndex2 - 1) / 2)) { - nodeIndex1 = (nodeIndex1 - 1) / 2; - nodeIndex2 = (nodeIndex2 - 1) / 2; - level = level + 1; - } - return level; - } - - function getTargetNodeValue(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function getTargetNodeValueByValueIsZero(uint256 leafIndex, uint32 level) private view returns (bytes32) { - bytes32 left; - bytes32 right; - uint256 index = leafIndex + 2 ** 32 - 1; - uint256 nodeIndex = leafCount + 2 ** 32 - 2; - bytes32 nodeValue = tree[nodeIndex]; - if (level == 0) { - if (index < nodeIndex) { - return nodeValue; - } - if (index == nodeIndex) { - if (index % 2 == 0) { - return tree[index - 1]; - } else { - return zeroes[0]; - } - } - } - for (uint32 i = 0; i < level; i++) { - if (nodeIndex % 2 == 0) { - left = tree[nodeIndex - 1]; - right = nodeValue; - } else { - left = nodeValue; - right = zeroes[i]; - } - left = bytes32(0x0); - right = bytes32(0x0); - nodeValue = pedersenHash(i, left, right); - nodeIndex = (nodeIndex - 1) / 2; - } - return nodeValue; - } - - function rawValueToValue(uint256 rawValue) private view returns (uint64) { - require(rawValue > 0, "Value must be positive!"); - require(rawValue.mod(scalingFactor) == 0, "Value must be integer multiples of scalingFactor!"); - uint256 value = rawValue.div(scalingFactor); - require(value < INT64_MAX); - return uint64(value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest1TestRequireContract.sol deleted file mode 100644 index 16d01911d35..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest1TestRequireContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - //function testThrow(){ - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest2TestThrowsContract.sol deleted file mode 100644 index 1ff73ad6460..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest2TestThrowsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow() public { - // throw; - //} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest3TestRevertContract.sol deleted file mode 100644 index b42a8c3fb23..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest3TestRevertContract.sol +++ /dev/null @@ -1,15 +0,0 @@ - -contract TestThrowsContract{ - function testAssert() public { - assert(1==2); - } - function testRequire() public { - require(2==1); - } - function testRevert() public { - revert(); - } - // function testThrow(){ - // throw; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest4noPayableContract.sol deleted file mode 100644 index 35f89631e7d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest4noPayableContract.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract noPayableContract { - -function noPayable() public payable returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest4noPayableContract_1.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest4noPayableContract_1.sol deleted file mode 100644 index 5b6dd509f6f..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest4noPayableContract_1.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract noPayableContract { - -function noPayable() public returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest5noPayableConstructor.sol deleted file mode 100644 index 097594ab7c9..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest5noPayableConstructor.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public payable{ - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest5noPayableConstructor_1.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest5noPayableConstructor_1.sol deleted file mode 100644 index 5008ec5c9bf..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest5noPayableConstructor_1.sol +++ /dev/null @@ -1,11 +0,0 @@ - - -contract MyContract { - uint money; - - //function MyContract(uint _money) { - constructor(uint _money) public { - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest6transferTestContract.sol deleted file mode 100644 index 4f171aebb9a..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest6transferTestContract.sol +++ /dev/null @@ -1,8 +0,0 @@ - - -contract transferTestContract { - function tranferTest(address payable addr) public payable{ - addr.transfer(10); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest7payableFallbakContract.sol deleted file mode 100644 index 534726cb1b4..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest7payableFallbakContract.sol +++ /dev/null @@ -1,14 +0,0 @@ - - -contract Test { - fallback() external { x = 1; } - uint x; -} - - -contract Caller { - function callTest(Test test) public { - //test.call(0xabcdef01); // hash does not exist - address(test).call(abi.encode(0xabcdef01)); // hash does not exist - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest8newContractGasNoenough.sol deleted file mode 100644 index b8743e8231a..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest8newContractGasNoenough.sol +++ /dev/null @@ -1,19 +0,0 @@ - - -contract Account{ - uint256 public accId; - - // function Account(uint accountId) payable{ - constructor(uint accountId) payable public { - accId = accountId; - } -} - -contract Initialize{ - // Account public account = new Account(10); - - function newAccount() public { - Account account = new Account(1); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest9MessageUsedErrorFeed.sol deleted file mode 100644 index 18142d20ee8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontest9MessageUsedErrorFeed.sol +++ /dev/null @@ -1,18 +0,0 @@ - - -contract MathedFeed { - - function divideMathed() public returns (uint ret) { - uint x=1; - uint y=0; - return x/y; - } -} - - -contract MathedUseContract { - - function MathedUse(address addr) public returns (uint) { - return MathedFeed(addr).divideMathed(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontestFunctionUsedErrorFeed.sol deleted file mode 100644 index 64243dffd7c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/requireExceptiontestFunctionUsedErrorFeed.sol +++ /dev/null @@ -1,17 +0,0 @@ - - -contract MessageFeed { - - function mValue() payable public returns (uint ret) { - return msg.value; - } -} - -contract MessageUseContract { - function inputValue() payable public returns (uint){ - return msg.value; - } - function messageUse(address addr) payable public returns (uint) { - return MessageFeed(addr).mValue{value:1}(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/selector.sol b/framework/src/test/resources/soliditycode_0.7.6/selector.sol deleted file mode 100644 index 5805a6e8d22..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/selector.sol +++ /dev/null @@ -1,21 +0,0 @@ - - -library A { - function getBalance(address) public view returns (uint256) { - return address(this).balance; - } - - function getamount(address) external view returns (uint256) { - return address(this).balance; - } -} - -contract testSelector { - using A for address; - - - function getselector2() public view returns (bytes4, bytes4) { - return (A.getBalance.selector, A.getamount.selector); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/slotAndOffsetNewGrammer.sol b/framework/src/test/resources/soliditycode_0.7.6/slotAndOffsetNewGrammer.sol deleted file mode 100644 index b4c2b0ed516..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/slotAndOffsetNewGrammer.sol +++ /dev/null @@ -1,32 +0,0 @@ -contract A { - uint b; - uint a; - uint c; - uint d; - uint e; - - function getA() external returns(uint,uint) { - uint slot; - uint offset; - assembly { -// old grammer -// slot := a_slot -// offset := a_offset - slot := a.slot - offset := a.offset - } - return (slot, offset); - } - - function getE() external returns(uint,uint) { - uint slot; - uint offset; - assembly { -// slot := e_slot -// offset := e_offset - slot := e.slot - offset := e.offset - } - return (slot, offset); - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/stackContract001.sol b/framework/src/test/resources/soliditycode_0.7.6/stackContract001.sol deleted file mode 100644 index c2e8f2f7611..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/stackContract001.sol +++ /dev/null @@ -1,61 +0,0 @@ - - -contract A{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function test() public{ - emit log(123); - } -} - -contract B{ - event log(uint256); - constructor() payable public{ - emit log(withdrawreward()); - emit log(address(this).rewardbalance); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function rewardBalance(address addr) public view returns (uint256){ - return addr.rewardbalance; - } - - function nullAddressTest() public view returns (uint256) { - return address(0x0).rewardbalance; - } - - function localContractAddrTest() public view returns (uint256) { - address payable localContract = address(uint160(address(this))); - return localContract.rewardbalance; - } - - function withdrawRewardTest() public returns (uint256){ - return withdrawreward(); - } - - function contractBWithdrawRewardTest(address contractB) public returns (uint) { - return B(contractB).withdrawRewardTest(); - } - - function createA() public returns (address){ - return address(new A()); - } - - function callA(address Addr) public{ - A(Addr).test(); - } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/stackSuicide001.sol b/framework/src/test/resources/soliditycode_0.7.6/stackSuicide001.sol deleted file mode 100644 index d1fc520ddb2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/stackSuicide001.sol +++ /dev/null @@ -1,84 +0,0 @@ - -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public payable returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function transfer(address payable add,uint256 num) public { - return add.transfer(num); - } -} - -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - - function deploy(bytes memory code, uint256 salt) public returns(address) { - address addr; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/stateVariableShadowing.sol b/framework/src/test/resources/soliditycode_0.7.6/stateVariableShadowing.sol deleted file mode 100644 index a9109ee296c..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/stateVariableShadowing.sol +++ /dev/null @@ -1,21 +0,0 @@ -contract test { -// uint public x; -// function setValue1(uint _x) public returns (uint){ -// x = _x; -// return x; -// } - uint public y; - function setValue3(uint _x) public returns (uint){ - y = _x; - return y; - } -} - -contract stateVariableShadowing is test { - uint public x; - function setValue2(uint _x) public returns (uint){ - x = _x; - return x; - } -} - diff --git a/framework/src/test/resources/soliditycode_0.7.6/stringSplit.sol b/framework/src/test/resources/soliditycode_0.7.6/stringSplit.sol deleted file mode 100644 index 84231f2d1fe..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/stringSplit.sol +++ /dev/null @@ -1,45 +0,0 @@ - - -contract testStringSplit { -string s1 = "s""1""2"",./"; -string s2 = "s123?\\'."; -string s3 = hex"41"hex"42"; -string s4 = hex"4142"; - -function getS1() public view returns (string memory) { -return s1; -} - -function getS1N1() public pure returns (string memory) { -string memory n1 = "s""1""2"",./"; -return n1; -} - -function getS2() public view returns (string memory) { -return s2; -} - -function getS2N2() public pure returns (string memory) { -string memory n2 = "s123?\'."; -return n2; -} - -function getS3() public view returns (string memory) { -return s3; -} - -function getS3N3() public pure returns (string memory) { -string memory n3 = hex"41"hex"42"; -return n3; -} - -function getS4() public view returns (string memory) { -return s4; -} - -function getS4N4() public pure returns (string memory) { -string memory n4 = hex"4142"; -return n4; -} - -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/suicide001.sol b/framework/src/test/resources/soliditycode_0.7.6/suicide001.sol deleted file mode 100644 index 241a406d6a2..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/suicide001.sol +++ /dev/null @@ -1,32 +0,0 @@ -contract factory { - constructor() payable public { - } - - function create1() payable public returns (address){ - Caller add = (new Caller){value:0}(); - return address(add); - } - - function kill() payable public{ - selfdestruct(msg.sender); - } - - function create2(bytes memory code, uint256 salt) public returns(address){ - Caller addr; - Caller addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - return address(addr); - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/suicide002.sol b/framework/src/test/resources/soliditycode_0.7.6/suicide002.sol deleted file mode 100644 index 160ab64f320..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/suicide002.sol +++ /dev/null @@ -1,43 +0,0 @@ -contract Factory { - uint256 public num; - event Deployed(address addr, uint256 salt, address sender); - constructor() public { - } - function deploy(bytes memory code, uint256 salt) public returns(address){ - TestConstract addr; - TestConstract addr1; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - - addr.testSuicideNonexistentTarget(msg.sender); - addr.set(); - - assembly { - addr1 := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(address(addr), salt, msg.sender); - return address(addr); - } -} - - - -contract TestConstract { - uint public i=1; - constructor () public { - } - - function set() public{ - i=9; - } - function testSuicideNonexistentTarget(address payable nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/testOutOfMem.sol b/framework/src/test/resources/soliditycode_0.7.6/testOutOfMem.sol deleted file mode 100644 index 8d285b28b7d..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/testOutOfMem.sol +++ /dev/null @@ -1,7 +0,0 @@ -contract Test { - function testOutOfMem(uint256 x) public returns(bytes32 r) { - uint[] memory memVar; - memVar = new uint[](x); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/testStakeSuicide.sol b/framework/src/test/resources/soliditycode_0.7.6/testStakeSuicide.sol deleted file mode 100644 index 3342a5607f7..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/testStakeSuicide.sol +++ /dev/null @@ -1,71 +0,0 @@ - -contract testStakeSuicide{ - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } - function SelfdestructTest2(address sr, uint256 amount, address payable target) public{ - stake(sr, amount); - selfdestruct(target); - } - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function Stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function UnStake2() public returns (bool result){ - unstake(); - return unstake(); - } - function WithdrawReward() public { - withdrawreward(); - } - function RewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - function revertTest1(address sr, uint256 amount, address payable transferAddr) public{ - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000);//stake more than balance to fail - transferAddr.transfer(4000000); - } - function revertTest2(address payable transferAddr) public{ - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake();//unstake twice to fail - transferAddr.transfer(4000000); - } - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - function BSelfdestructTest(address payable target) public{ - b.SelfdestructTest(target); - } -} -contract B{ - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - function UnStake() public returns (bool result){ - return unstake(); - } - function SelfdestructTest(address payable target) public{ - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/tryCatch001.sol b/framework/src/test/resources/soliditycode_0.7.6/tryCatch001.sol deleted file mode 100644 index 283db92e159..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/tryCatch001.sol +++ /dev/null @@ -1,105 +0,0 @@ - - -enum ErrorType { - Revert_Error, //0 - RevertWithMsg_Error, //1 - Require_Error, //2 - RequirewithMsg_Error, //3 - Assert_Error, //4 - Tansfer_Error, //5 - Send_Error, //6 - Math_Error, //7 - ArrayOverFlow_Error //8 -} -contract errorContract { - uint256[] arraryUint ; - - function errorSwitch(uint256 errorType) public returns(string memory) { - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - return "success"; - - } - - function callFun(string memory functionStr, string memory argsStr) public{ - address(this).call(abi.encodeWithSignature(functionStr, argsStr)); - } - -} - -contract NewContract { - uint256[] arraryUint ; - - constructor(uint256 errorType) public payable{ - if (ErrorType(errorType) == ErrorType.Revert_Error){ - revert(); - } else if (ErrorType(errorType) == ErrorType.RevertWithMsg_Error){ - revert("Revert Msg."); - } else if (ErrorType(errorType) == ErrorType.Require_Error) { - require(0>1); - } else if (ErrorType(errorType) == ErrorType.RequirewithMsg_Error) { - require(0>1,"Require Msg."); - } else if (ErrorType(errorType) == ErrorType.Assert_Error) { - assert(1<0); - } else if (ErrorType(errorType) == ErrorType.Tansfer_Error) { - payable(msg.sender).transfer(1); - } else if (ErrorType(errorType) == ErrorType.Send_Error) { - payable(msg.sender).send(1); - } else if (ErrorType(errorType) == ErrorType.Math_Error) { - uint256 a = 1; - uint256 b = 0; - uint256 n = a / b; - } else if (ErrorType(errorType) == ErrorType.ArrayOverFlow_Error) { - arraryUint.pop(); - } - } -} - -contract tryTest { - function getData(errorContract inter, string memory functionStr, string memory argsStr) public payable returns(string memory) { - try inter.callFun(functionStr,argsStr) { - return "123"; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "3"; - } - } - - function getErrorSwitch(errorContract add, uint256 errorType ) public payable returns(string memory) { - try add.errorSwitch(errorType) returns (string memory Msg) { - return Msg; - } catch Error(string memory errorMsg/* 出错原因 */) { - return errorMsg; - } catch (bytes memory) { - return "NoErrorMsg"; - } - } - - function catchNewErrorSwitch(uint256 errorType) public returns (address nc){ - try new NewContract(errorType) returns (NewContract nc){ - return address(nc); - }catch { - return address(0x00); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue001.sol b/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue001.sol deleted file mode 100644 index 5388ed68473..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue001.sol +++ /dev/null @@ -1,25 +0,0 @@ - -contract tvmAssetIssue001 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateOtherAccountAsset(string memory url, string memory desc) public returns (bool) { - trcToken tokenId = trcToken(1000004); - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue002.sol b/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue002.sol deleted file mode 100644 index 87c1206b778..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue002.sol +++ /dev/null @@ -1,15 +0,0 @@ - - -contract tvmAssetIssue002 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - assetissue(name, abbr, totalSupply, precision); - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url1, string memory desc1, string memory url2, string memory desc2) public returns (bool) { - updateasset(tokenId, bytes(url1), bytes(desc1)); - return updateasset(tokenId, bytes(url2), bytes(desc2)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue003.sol b/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue003.sol deleted file mode 100644 index f5ce5e0dc3e..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue003.sol +++ /dev/null @@ -1,23 +0,0 @@ - - -contract tvmAssetIssue003 { - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function tokenIssueAndTransfer(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - assetissue(name, abbr, totalSupply, precision); - newaddress.transfer(100000000); - } - - function updateAssetAndTransfer(trcToken tokenId, string memory url, string memory desc, address addr) public { - address payable newaddress = address(uint160(addr)); - newaddress.transfer(100000000); - updateasset(tokenId, bytes(url), bytes(desc)); - newaddress.transfer(100000000); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue004.sol b/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue004.sol deleted file mode 100644 index c8332de8f45..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue004.sol +++ /dev/null @@ -1,39 +0,0 @@ - - -contract A { - - constructor() payable public{} - fallback() payable external {} - - function tokenIssueA(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint){ - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAssetA(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } -} - -contract tvmAssetIssue004 { - - A a; - - constructor() payable public{} - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return a.tokenIssueA(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return a.updateAssetA(tokenId, url, desc); - } - - function getContractAddress() public payable returns (address) { - a = (new A).value(1024000000)(); - return address(a); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue005.sol b/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue005.sol deleted file mode 100644 index 8c36d050ff8..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/tvmAssetIssue005.sol +++ /dev/null @@ -1,45 +0,0 @@ - - -contract tvmAssetIssue005 { - constructor() payable public{} - - fallback() external payable { - } - - function tokenIssue(bytes32 name, bytes32 abbr, uint64 totalSupply, uint8 precision) public returns (uint) { - return assetissue(name, abbr, totalSupply, precision); - } - - function updateAsset(trcToken tokenId, string memory url, string memory desc) public returns (bool) { - return updateasset(tokenId, bytes(url), bytes(desc)); - } - - function updateAssetOnBytes(trcToken tokenId, bytes memory url, bytes memory desc) public returns (bool) { - return updateasset(tokenId, url, desc); - } - - function transferToken(address payable toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} - -contract B { - event Deployed(address addr, uint256 salt); - - function deploy(uint256 salt) public returns (address) { - address addr; - bytes memory code = type(tvmAssetIssue005).creationCode; - assembly { - addr := create2(0, add(code, 0x20), mload(code), salt) - if iszero(extcodesize(addr)) { - revert(0, 0) - } - } - emit Deployed(addr, salt); - return addr; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/typeName.sol b/framework/src/test/resources/soliditycode_0.7.6/typeName.sol deleted file mode 100644 index 5b44abd1bbb..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/typeName.sol +++ /dev/null @@ -1,5 +0,0 @@ -contract TypeName { - function testTypeName() public returns (string memory){ - return type(TypeName).name; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/unStake001.sol b/framework/src/test/resources/soliditycode_0.7.6/unStake001.sol deleted file mode 100644 index 03734fecfa5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/unStake001.sol +++ /dev/null @@ -1,90 +0,0 @@ - - -contract unStakeTest { - B b; - constructor() payable public{} - function deployB() payable public returns (B addrB){ - b = (new B).value(1000000000)(); - return b; - } - - function selfdestructTest(address payable target) public { - selfdestruct(target); - } - - function selfdestructTest2(address sr, uint256 amount, address payable target) public { - stake(sr, amount); - selfdestruct(target); - } - - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function stake2(address sr, uint256 amount) public returns (bool result){ - stake(sr, amount); - return stake(sr, amount); - } - - function unStake() public returns (bool result){ - return unstake(); - } - - function unStake2() public returns (bool result){ - unstake(); - return unstake(); - } - - function withdrawReward() public returns (uint256 amount) { - return withdrawreward(); - } - - function rewardBalance(address addr) view public returns (uint256 balance) { - return addr.rewardbalance; - } - - function revertTest1(address sr, uint256 amount, address payable transferAddr) public { - transferAddr.transfer(1000000); - stake(sr, amount); - transferAddr.transfer(2000000); - stake(sr, 1000000000000000); - //stake more than balance to fail - transferAddr.transfer(4000000); - } - - function revertTest2(address payable transferAddr) public { - transferAddr.transfer(1000000); - unstake(); - transferAddr.transfer(2000000); - unstake(); - //unstake twice to fail - transferAddr.transfer(4000000); - } - - function BStake(address sr, uint256 amount) public returns (bool result){ - return b.Stake(sr, amount); - } - - function BUnStake() public returns (bool result){ - return b.UnStake(); - } - - function BSelfdestructTest(address payable target) public { - b.SelfdestructTest(target); - } -} - -contract B { - constructor() payable public{} - function Stake(address sr, uint256 amount) public returns (bool result){ - return stake(sr, amount); - } - - function UnStake() public returns (bool result){ - return unstake(); - } - - function SelfdestructTest(address payable target) public { - selfdestruct(target); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/validatemultisign001.sol b/framework/src/test/resources/soliditycode_0.7.6/validatemultisign001.sol deleted file mode 100644 index cc0a742d0c5..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/validatemultisign001.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma experimental ABIEncoderV2; - -contract validatemultisignTest { - function testmulti(address a, uint256 perid, bytes32 hash, bytes[] memory signatures) public returns (bool){ - return validatemultisign(a, perid, hash, signatures); - } - - function testbatch(bytes32 hash, bytes[] memory signatures, address[] memory addresses) public returns (bytes32){ - return batchvalidatesign(hash, signatures, addresses); - } - - function testMultiPrecompileContract(bytes memory data) public returns(bool, bytes memory){ - return address(0xa).delegatecall(data); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/verifyTransferProof001.sol b/framework/src/test/resources/soliditycode_0.7.6/verifyTransferProof001.sol deleted file mode 100644 index 587b4defd10..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/verifyTransferProof001.sol +++ /dev/null @@ -1,15 +0,0 @@ -contract verifyTransferProofTest { - - function test1() public returns (bool, bytes memory){ - bytes memory empty = ""; - return address(0x1000002).delegatecall(empty); - } - - function test2(bytes memory data) public returns (bool, bytes memory){ - return address(0x1000002).delegatecall(data); - } - - function test3(bytes32[10][] memory input, bytes32[2][] memory spendAuthoritySignature, bytes32[9][] memory output, bytes32[2] memory bindingSignature, bytes32 signHash, uint64 valueBalance, bytes32[33] memory frontier, uint256 leafCount) public returns (bytes32[] memory){ - return verifyTransferProof(input, spendAuthoritySignature, output, bindingSignature, signHash, valueBalance, frontier, leafCount); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_0.7.6/virtual001.sol b/framework/src/test/resources/soliditycode_0.7.6/virtual001.sol deleted file mode 100644 index f7967626764..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/virtual001.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.6.0; -interface X { - function setValue(uint _x) external; -} -abstract contract Y { - function setBool(bool _y) external virtual ; -} -contract Y2 { - string public z; - function setString(string calldata _z) external virtual { z = "123"; } -} - -contract Z is X,Y,Y2 { - uint public x; - bool public y; - function setValue(uint _x) external override { x = _x; } - function setBool(bool _y) external override { y = _y; } - function setString(string calldata _z) external override { z = _z; } -} diff --git a/framework/src/test/resources/soliditycode_0.7.6/walletTestMutiSign004.sol b/framework/src/test/resources/soliditycode_0.7.6/walletTestMutiSign004.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_0.7.6/walletTestMutiSign004.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed001.sol b/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed001.sol deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed005.sol b/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed005.sol deleted file mode 100644 index d3179a30191..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed005.sol +++ /dev/null @@ -1,106 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - function testTransferTokenCompiledLongMax() payable public{ - address(0x1).transferToken(1,9223372036855775827); - } - - function testTransferTokenCompiledLongMin() payable public{ - //address(0x1).transferToken(1,-9223372036855775828); - } - - function testTransferTokenCompiledLongMin1() payable public{ - address(0x1).tokenBalance(trcToken(-9223372036855775828)); - } - - function testTransferTokenCompiledLongMax1() payable public{ - address(0x1).tokenBalance(trcToken(9223372036855775827)); - } - - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address caller) public returns (bool){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed007.sol b/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed007.sol deleted file mode 100644 index ffd6f10c486..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/TransferFailed007.sol +++ /dev/null @@ -1,90 +0,0 @@ -contract EnergyOfTransferFailedTest { - constructor() payable public { - - } - // InsufficientBalance - function testTransferTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.transfer(i); - } - - function testSendTrxInsufficientBalance(uint256 i) payable public{ - msg.sender.send(i); - } - - function testTransferTokenInsufficientBalance(uint256 i,trcToken tokenId) payable public{ - msg.sender.transferToken(i, tokenId); - } - - function testCallTrxInsufficientBalance(uint256 i,address caller) public returns (bool){ - return caller.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testCreateTrxInsufficientBalance(uint256 i) payable public { - (new Caller).value(i)(); - } - - // NonexistentTarget - - function testSendTrxNonexistentTarget(uint256 i,address nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.send(i); - } - - function testTransferTrxNonexistentTarget(uint256 i,address nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.transfer(i); - } - - function testTransferTokenNonexistentTarget(uint256 i,address nonexistentTarget, trcToken tokenId) payable public { - require(address(this).balance >= i); - nonexistentTarget.transferToken(i, tokenId); - } - - function testCallTrxNonexistentTarget(uint256 i,address nonexistentTarget) payable public { - require(address(this).balance >= i); - nonexistentTarget.call.value(i)(abi.encodeWithSignature("test()")); - } - - function testSuicideNonexistentTarget(address nonexistentTarget) payable public { - selfdestruct(nonexistentTarget); - } - - // target is self - function testTransferTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address self = address(uint160(address(this))); - self.transfer(i); - } - - function testSendTrxSelf(uint256 i) payable public{ - require(address(this).balance >= i); - address self = address(uint160(address(this))); - self.send(i); - } - - function testTransferTokenSelf(uint256 i,trcToken tokenId) payable public{ - require(address(this).balance >= i); - address self = address(uint160(address(this))); - self.transferToken(i, tokenId); - } - - event Deployed(address addr, uint256 salt, address sender); - function deploy(bytes memory code, uint256 salt) public returns(address){ - address addr; - assembly { - addr := create2(10, add(code, 0x20), mload(code), salt) - //if iszero(extcodesize(addr)) { - // revert(0, 0) - //} - } - //emit Deployed(addr, salt, msg.sender); - return addr; - } -} - - - -contract Caller { - constructor() payable public {} - function test() payable public returns (uint256 ){return 1;} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addMsg001Nonpayable.sol b/framework/src/test/resources/soliditycode_v0.4.25/addMsg001Nonpayable.sol deleted file mode 100644 index 7b124f0e870..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addMsg001Nonpayable.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -event log(uint256); -constructor() payable public{} - -function() payable public{} - -function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { -// function transferTokenWithValue(address toAddress, uint256 tokenValue) payable public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addMsg002View.sol b/framework/src/test/resources/soliditycode_v0.4.25/addMsg002View.sol deleted file mode 100644 index 97c07ace501..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addMsg002View.sol +++ /dev/null @@ -1,20 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable public{} - -event log(uint256); - -function transferTokenWithView(address toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} - diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addMsg003Constant.sol b/framework/src/test/resources/soliditycode_v0.4.25/addMsg003Constant.sol deleted file mode 100644 index 4cc69e05c90..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addMsg003Constant.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable public{} - -event log(uint256); - -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addMsg004Pure.sol b/framework/src/test/resources/soliditycode_v0.4.25/addMsg004Pure.sol deleted file mode 100644 index 886e5d2ea0f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addMsg004Pure.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable public{} - -event log(uint256); - -function transferTokenWithPure(address toAddress, uint256 tokenValue) public pure { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken001Nonpayable.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken001Nonpayable.sol deleted file mode 100644 index b6c69fca887..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken001Nonpayable.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - - contract IllegalDecorate { - - constructor() payable public{} - - function() payable public{} - - function transferTokenWithOutPayable(address toAddress, uint256 tokenValue)public { - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken002View.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken002View.sol deleted file mode 100644 index fc390f12b53..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken002View.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - - constructor() payable public{} - - function() payable public{} - - function transferTokenWithView(address toAddress, uint256 tokenValue) public view { - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken003Constant.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken003Constant.sol deleted file mode 100644 index 38c034f6bfb..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken003Constant.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - - constructor() payable public{} - - function() payable public{} - - function transferTokenWithConstant(address toAddress, uint256 tokenValue)public constant { - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken004Pure.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken004Pure.sol deleted file mode 100644 index 085fd1bbbdb..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTransferToken004Pure.sol +++ /dev/null @@ -1,15 +0,0 @@ -//pragma solidity ^0.4.24; - -contract IllegalDecorate { - - constructor() payable public{} - - function() payable public{} - - function transferTokenWithPure(address toAddress, uint256 tokenValue) public pure { - - toAddress.transferToken(tokenValue, 0x6e6d62); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken001Assemble.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken001Assemble.sol deleted file mode 100644 index a0015c9e75b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken001Assemble.sol +++ /dev/null @@ -1,81 +0,0 @@ -//pragma solidity ^0.4.24; - -contract InAssemble { - -mapping(trcToken => uint256) tokenCnt; -mapping(uint256 => mapping(trcToken => trcToken)) cntTokenToken; -constructor () payable {} -function getBalance(address addr) constant returns(uint256 r) { -assembly{ -r := balance(addr) -} -} - -function getTokenBalanceConstant(address addr, trcToken tokenId) constant returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function getTokenBalance(address addr, trcToken tokenId) returns(uint256 r) { -assembly{ -r := tokenbalance(tokenId, addr) -} -} - -function transferTokenInAssembly(address addr, trcToken tokenId, uint256 tokenValue) payable { -bytes4 sig = bytes4(keccak256("()")); // function signature - -assembly { -let x := mload(0x40) // get empty storage location -mstore(x,sig) // 4 bytes - place signature in empty storage - -let ret := calltoken(gas, addr, tokenValue, tokenId, -x, // input -0x04, // input size = 4 bytes -x, // output stored at input location, save space -0x0 // output size = 0 bytes -) - -// let ret := calltoken(gas, addr, tokenValue, -// x, // input -// 0x04, // input size = 4 bytes -// x, // output stored at input location, save space -// 0x0 // output size = 0 bytes -// ) // ERROR - - -mstore(0x40, add(x,0x20)) // update free memory pointer -} - -// assembly { -// let x := mload(0x40) //Find empty storage location using "free memory pointer" -// mstore(x,sig) //Place signature at begining of empty storage -// mstore(add(x,0x04),a) //Place first argument directly next to signature -// mstore(add(x,0x24),b) //Place second argument next to first, padded to 32 bytes - -// let success := call( //This is the critical change (Pop the top stack value) -// 5000, //5k gas -// addr, //To addr -// 0, //No value -// x, /Inputs are stored at location x -// 0x44, //Inputs are 68 bytes long -// x, //Store output over input (saves space) -// 0x20) //Outputs are 32 bytes long - -// c := mload(x) //Assign output value to c -// mstore(0x40,add(x,0x44)) // Set storage pointer to empty space -// } - -} - -function trcTokenInMap(trcToken tokenId, uint256 tokenValue) returns(uint256 r) { -tokenCnt[tokenId] += tokenValue; -r = tokenCnt[tokenId]; -} - -function cntTokenTokenInMap(trcToken tokenId1, trcToken tokenId2, uint256 tokenValue) returns(trcToken r) { -cntTokenToken[tokenValue][tokenId1] = tokenId2; -r = cntTokenToken[tokenValue][tokenId1]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken002Cat.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken002Cat.sol deleted file mode 100644 index 0858c6442fb..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken002Cat.sol +++ /dev/null @@ -1,2017 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - function Ownable() { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(0, _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is KittyBase, ERC721 { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { - var outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { - require(erc721Metadata != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.send(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, this, _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused returns (bool) { - paused = true; - Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused returns (bool) { - paused = false; - Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - function ClockAuction(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address nftAddress = address(nonFungibleContract); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(this.balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - function SiringClockAuction(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - function SaleClockAuction(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, saleAuction); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, siringAuction); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, saleAuction); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(this) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - function KittyCore() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - function unpause(address toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(saleAuction != address(0)); - require(siringAuction != address(0)); - require(geneScience != address(0)); - require(newContractAddress == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = this.balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.send(balance - subtractFees); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken002Cat_withFinny.sol b/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken002Cat_withFinny.sol deleted file mode 100644 index 5839b983a32..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/addTrcToken002Cat_withFinny.sol +++ /dev/null @@ -1,2017 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - function Ownable() { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(0, _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is KittyBase, ERC721 { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { - var outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { - require(erc721Metadata != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 finny; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.send(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, this, _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused returns (bool) { - paused = true; - Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused returns (bool) { - paused = false; - Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - function ClockAuction(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address nftAddress = address(nonFungibleContract); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(this.balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - function SiringClockAuction(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - function SaleClockAuction(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, saleAuction); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, siringAuction); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 finny; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, saleAuction); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(this) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - function KittyCore() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - function unpause(address toAddress, uint256 tokenValue, trcToken tokenId) public onlyCEO whenPaused returns (uint256 r) { - require(saleAuction != address(0)); - require(siringAuction != address(0)); - require(geneScience != address(0)); - require(newContractAddress == address(0)); - toAddress.transferToken(tokenValue, tokenId); - r = address(this).tokenBalance(tokenId); - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = this.balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.send(balance - subtractFees); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest1DivideInt.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest1DivideInt.sol deleted file mode 100644 index 8ed20cd1cab..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest1DivideInt.sol +++ /dev/null @@ -1,7 +0,0 @@ -pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest2FindArgsContractMinTest.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest2FindArgsContractMinTest.sol deleted file mode 100644 index af54558bc98..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest2FindArgsContractMinTest.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma solidity ^0.4.0; -contract findArgsIContract{ -function findArgsByIndex1(uint i)public returns (uint z) { -uint[] memory a = new uint[](3); -a[0]=1; -a[1]=2; -a[2]=3; -return a[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest3ByteMinContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest3ByteMinContract.sol deleted file mode 100644 index d2e8637612d..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest3ByteMinContract.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.0; -contract byteContract { -bytes b; -function testBytesGet(uint i) returns (bytes1){ -b = new bytes(3); -b[0]=12; -b[1]=13; -b[2]=14; -return b[i]; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest4Enum.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest4Enum.sol deleted file mode 100644 index 5d7164d27d1..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest4Enum.sol +++ /dev/null @@ -1,13 +0,0 @@ -pragma solidity ^0.4.4; - -contract enumContract { - enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill } - ActionChoices _choice; - function setGoStraight(ActionChoices choice) public { - _choice = choice; - } - - function getChoice() public returns (ActionChoices) { - return _choice; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest5MoveRight.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest5MoveRight.sol deleted file mode 100644 index c0d15a7aa09..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest5MoveRight.sol +++ /dev/null @@ -1,7 +0,0 @@ -pragma solidity ^0.4.0; - -contract binaryRightContract{ - function binaryMoveR(int i)public returns (int z) { - return z = 5 >> i; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest6UninitializedContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest6UninitializedContract.sol deleted file mode 100644 index dbfa3e01bc0..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest6UninitializedContract.sol +++ /dev/null @@ -1,27 +0,0 @@ -pragma solidity ^0.4.0; -contract uni { -function b(int x, int y) internal returns (int) -{ - return x * y; -} - -function test1() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - funcPtr = b; - - // This call to funcPtr will succeed - return funcPtr(4, 5); -} - -function test2() external returns (int) -{ - // Variable containing a function pointer - function (int, int) internal returns (int) funcPtr; - - // This call will fail because funcPtr is still a zero-initialized function pointer - return funcPtr(4, 5); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest7TestAssertContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest7TestAssertContract.sol deleted file mode 100644 index 842b8c174e5..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/assertExceptiontest7TestAssertContract.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma solidity ^0.4.0; - - -contract TestThrowsContract{ - function testAssert(){ - assert(1==2); - } - function testRequire(){ - require(2==1); - } - function testRevert(){ - revert(); - } - function testThrow(){ - throw; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/codeSaftySupport.sol b/framework/src/test/resources/soliditycode_v0.4.25/codeSaftySupport.sol deleted file mode 100644 index 7ae081877b6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/codeSaftySupport.sol +++ /dev/null @@ -1,19 +0,0 @@ -pragma solidity ^0.4.24; - -contract IllegalDecorate { - -constructor() payable public{} - -function() payable external{} - -event log(uint256); - -function transferToken(address toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/codeSaftyUnsupport.sol b/framework/src/test/resources/soliditycode_v0.4.25/codeSaftyUnsupport.sol deleted file mode 100644 index ff561614780..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/codeSaftyUnsupport.sol +++ /dev/null @@ -1,50 +0,0 @@ - pragma solidity ^0.4.24; -contract SubC { -event log(string); - -function () payable {} - -function receiveToken() payable {} - -function getBalance() constant public returns (uint256 r){ -r = address(this).balance; -} -} -contract UseDot { -constructor() payable public{} -function() payable public{} -mapping(address => mapping(trcToken => uint256)) sender_tokens; - -function trigger1(address addr) payable public { - //SubC(addr).call.value(1000).tokenId(0x6e6d62)(bytes4(sha3("receiveToken()"))); // ERROR -} - -function trigger2(address addr) payable public { - //addr.transferToken.value(10)(10, 0x6e6d62); // ERROR -} - -function trigger3(address addr) payable public { -// SubC(addr).receiveToken.tokenvalue(10)(); // ERROR -} - -function trigger4(address addr) payable public { -// SubC(addr).receiveToken.tokenId(0x6e6d62)(); // ERROR -} - -function trigger5(address addr) payable public { -SubC(addr).receiveToken.value(10)(); -} -function trigger6(address addr, trcToken tokenId) payable public { -SubC(addr).call.value(1000)(bytes4(sha3("transferToken(uint256, trcToken)")), 10, tokenId); -} - -function trigger7(address addr) payable public { - //sender_tokens[msg.sender][msg.tokenid] += msg.tokenvalue; // compile success, no necessary to trigger -} -function trigger8(address addr) public payable returns(bytes r){ - //r = msg.data; // compile success, no necessary to trigger -} -function getBalance() public returns (uint256 r){ -r = address(this).balance; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGetterContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGetterContract.sol deleted file mode 100644 index deed0aeabd2..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGetterContract.sol +++ /dev/null @@ -1,17 +0,0 @@ -//pragma solidity ^0.4.0; - - -contract getterContract{ - -constructor() public payable{} -function() external payable{} - -uint public c = msg.value; - -function getDataUsingAccessor() returns (uint){ - -return c; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test1Grammar001.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test1Grammar001.sol deleted file mode 100644 index f433ed3585f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test1Grammar001.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma solidity ^0.4.16; -contract FunctionSelector { - function select(bool useB, uint x) public returns (uint z) { - var f = a; - if (useB) f = b; - return f(x); - } -function a(uint x) public returns (uint z) { - return x * x; - } -function b(uint x) public returns (uint z) { - return 2 * x; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test2Grammar002.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test2Grammar002.sol deleted file mode 100644 index da9ff8caa56..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test2Grammar002.sol +++ /dev/null @@ -1,44 +0,0 @@ -pragma solidity ^0.4.16; -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert(Data storage self, uint value) public returns (bool) { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public returns (bool) { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public returns (bool) { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register(uint value) { - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - throw; - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test3Grammar003.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test3Grammar003.sol deleted file mode 100644 index 4d3f87ebe3e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test3Grammar003.sol +++ /dev/null @@ -1,44 +0,0 @@ -pragma solidity ^0.4.11; - -library Set { - struct Data { mapping(uint => bool) flags; } - - function insert(Data storage self, uint value) public - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) public - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) public - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - using Set for Set.Data; // this is the crucial change - Set.Data knownValues; - - function register(uint value) { - // Here, all variables of type Set.Data have - // corresponding member functions. - // The following function call is identical to - // Set.insert(knownValues, value) - if (!knownValues.insert(value)) - throw; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test4Grammar004.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test4Grammar004.sol deleted file mode 100644 index 78bc620c81f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test4Grammar004.sol +++ /dev/null @@ -1,31 +0,0 @@ -pragma solidity ^0.4.0; - -library Search { - function indexOf(uint[] storage self, uint value) public returns (uint) { - for (uint i = 0; i < self.length; i++) - if (self[i] == value) return i; - return uint(-1); - } -} - - -contract C { - using Search for uint[]; - uint[] public data; - - function append(uint value) { - data.push(value); - } - - function replace(uint _old, uint _new) { - // This performs the library function call - uint index = data.indexOf(_old); - if (index == uint(-1)) - data.push(_new); - else - data[index] = _new; - } - function getData(uint256 index) public returns(uint256){ - return data[index]; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test5Grammar006.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test5Grammar006.sol deleted file mode 100644 index 5bba3d4bba0..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar001test5Grammar006.sol +++ /dev/null @@ -1,36 +0,0 @@ - pragma solidity ^0.4.0; -contract InfoFeed { -function d1(uint x){ - assembly{ - function f(x) -> y { switch x case 0 { y := 1 } default { y := mul(x, f(sub(x, 1))) } } - } - } - function d2(uint x){ - assembly { x := mul(1, add(2, 3))} - } - function f(uint x) { - assembly { x := sub(x, 1) } - - } - function d(uint x){ - assembly{ - let x := add(2, 3) let y := mload(0x40) x := add(x, y) - } - } - function d4(uint x){ - assembly{let x := 10 repeat: x := sub(x, 1) jumpi(repeat, eq(x, 0)) - } - } - function d5(uint x){ - assembly{ - function f(x) -> y { switch x case 0 { y := mul(x, 2) } default { y := 0 } } - - } - } - - function d6(uint x){ - assembly{ - function f(x) -> y { for { let i := 0 } lt(i, x) { i := add(i, 1) } { y := mul(2, y) } } - } - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test1Grammar007_1.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test1Grammar007_1.sol deleted file mode 100644 index 752d3613be2..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test1Grammar007_1.sol +++ /dev/null @@ -1,60 +0,0 @@ -pragma solidity ^0.4.19; -contract Doug{ - mapping (bytes32 => uint) public contracts; - function Doug() { - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string _name) public view returns(string) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -contract DogInterface { - function getDougAge(uint _age) returns (uint); - function contracts(bytes32 name) returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public view returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) returns (uint) { - - dogContract.contracts(_name); - FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test1Grammar007_2.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test1Grammar007_2.sol deleted file mode 100644 index 8078507e7b2..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test1Grammar007_2.sol +++ /dev/null @@ -1,60 +0,0 @@ -pragma solidity ^0.4.19; -contract Doug{ - mapping (bytes32 => uint) public contracts; - function Doug() { - contracts['hww'] = 1; - contracts['brian'] = 2; - contracts['zzy'] = 7; - } - - function getDougName(string _name) public view returns(string) { - return _name; - } - - function getDougAge(uint _age) public pure returns(uint) { - return 3 ** _age; - } -} - -contract DogInterface { - function getDougAge(uint _age) returns (uint); - function contracts(bytes32 name) returns (uint); -} -contract main{ - - event FetchContract(address dogInterfaceAddress, address sender, bytes32 name); - - address public DOUG; - - address dogInterfaceAddress; - DogInterface dogContract ; - - function setDOUG(address _doug) { - DOUG = _doug; - } - - constructor(address addr) public{ - dogInterfaceAddress = addr; - dogContract = DogInterface(dogInterfaceAddress); - } - - function dougOfage(uint _age) public view returns(uint) { - - uint num = dogContract.getDougAge(_age); - return _age+num; - // return num; - } - - function uintOfName(bytes32 _name) returns (uint) { - - dogContract.contracts(_name); - FetchContract(dogInterfaceAddress, msg.sender, _name); - - } - - // function getTest(string _name) public view returns(string) { - // string memory newName = _name ; - // DogInterface(DOUG).getDougName(newName); - // return newName; - // } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test2Grammar008.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test2Grammar008.sol deleted file mode 100644 index fb4338de0d8..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test2Grammar008.sol +++ /dev/null @@ -1,14 +0,0 @@ -pragma solidity ^0.4.19; -contract Feline { - function utterance() public returns (bytes32); - - function getContractName() public returns (string){ - return "Feline"; - } -} - - -contract Cat is Feline { - function utterance() public returns (bytes32) { return "miaow"; } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test3Grammar010.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test3Grammar010.sol deleted file mode 100644 index 43ff2e0aef3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test3Grammar010.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma solidity ^0.4.0; -contract InfoFeed { -function info() public payable returns (uint ret) { return 42; } -} -contract Consumer { -constructor() payable public{} -InfoFeed feed; -function setFeed(address addr) public { feed = InfoFeed(addr); } -function callFeed() public payable{ feed.info.value(10).gas(800)(); } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test4Grammar011.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test4Grammar011.sol deleted file mode 100644 index 0b673512248..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test4Grammar011.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.0; -contract C { -function f(uint key, uint value) public returns(uint) { -return key; -// do something -} -function g() public { -// named arguments -f({value: 2, key: 3}); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test4Grammar012.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test4Grammar012.sol deleted file mode 100644 index 3c72e608e24..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test4Grammar012.sol +++ /dev/null @@ -1,24 +0,0 @@ -pragma solidity ^0.4.24; -contract rTest { -function info() public payable returns (uint,address,bytes4,uint,uint,uint,address,uint) { -//function info() public payable returns (address ,uint,uint,uint,bytes32,uint,bytes,uint,address,bytes4,uint,uint,uint,address,uint) { -//var a = block.coinbase ; -//var b = block.difficulty; -//var c = block.gaslimit; -//var d = block.number; -//var e = block.blockhash(0); -//var e = d; -//var f = block.timestamp; -//bytes memory g = msg.data; -var h = msg.gas; -var i = msg.sender; -var j = msg.sig; -var k = msg.value; -var l = now; -var m = tx.gasprice; -var n = tx.origin; -var o = this.balance; -return (h,i,j,k,l,m,n,o); -//return (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test6Grammar013.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test6Grammar013.sol deleted file mode 100644 index f29197bccc3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar002test6Grammar013.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.4.4; -contract Counter { -uint count = 0; -address owner; -function Counter() { -owner = msg.sender; -} -function increment() public { -uint step = 10; -if (owner == msg.sender) { -count = count + step; -} -} -function getCount() public returns (uint) { -return count; -} -function kill() { -if (owner == msg.sender) { -selfdestruct(owner); -} -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test1Grammar014.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test1Grammar014.sol deleted file mode 100644 index c55b5b391a3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test1Grammar014.sol +++ /dev/null @@ -1,59 +0,0 @@ -pragma solidity ^0.4.4; -contract A { -uint256 public numberForB; -address public senderForB; -function callTest(address bAddress, uint256 _number) { -bAddress.call(bytes4(sha3("setValue(uint256)")), _number); // B's storage is set, A is not modified -} -function callcodeTest(address bAddress, uint256 _number) { -bAddress.callcode(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -} -function delegatecallTest(address bAddress, uint256 _number) { -bAddress.delegatecall(bytes4(sha3("setValue(uint256)")), _number); // A's storage is set, B is not modified -} - -function callAddTest(address bAddress) { -bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -bAddress.call(bytes4(sha3("add()"))); // B's storage is set, A is not modified -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract B { -uint256 public numberForB; -address public senderForB; -address public addr11; -mapping(uint256=>address) public addr1; -mapping(uint256=>address) public addr2; -function setValue(uint256 _number) { -numberForB = _number; -senderForB = msg.sender; -// senderForB is A if invoked by A's callTest. B's storage will be updated -// senderForB is A if invoked by A's callcodeTest. None of B's storage is updated -// senderForB is OWNER if invoked by A's delegatecallTest. None of B's storage is updated -} - -function add() public{ -numberForB=numberForB+1; -C c1 = new C(); -addr1[numberForB]=c1.getAddress(); -addr11 = c1.getAddress(); -C c2 = new C(); -addr2[numberForB] = c2.getAddress(); -} -function getnumberForB() public returns(uint256){ - return numberForB; - } - function getsenderForB() public returns(address){ - return senderForB; - } -} -contract C { -function getAddress() public view returns(address){ -return address(this); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test2Grammar015.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test2Grammar015.sol deleted file mode 100644 index 4e704628f4b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test2Grammar015.sol +++ /dev/null @@ -1,37 +0,0 @@ -pragma solidity ^0.4.0; - -contract ExecuteFallback{ - - //回退事件,会把调用的数据打印出来 - event FallbackCalled(bytes data); - //fallback函数,注意是没有名字的,没有参数,没有返回值的 - function(){ - FallbackCalled(msg.data); - } - - //调用已存在函数的事件,会把调用的原始数据,请求参数打印出来 - event ExistFuncCalled(bytes data, uint256 para); - //一个存在的函数 - function existFunc(uint256 para){ - ExistFuncCalled(msg.data, para); - } - - // 模拟从外部对一个存在的函数发起一个调用,将直接调用函数 - function callExistFunc(){ - bytes4 funcIdentifier = bytes4(keccak256("existFunc(uint256)")); - this.call(funcIdentifier, uint256(1)); - } - - //模拟从外部对一个不存在的函数发起一个调用,由于匹配不到函数,将调用回退函数 - function callNonExistFunc(){ - bytes4 funcIdentifier = bytes4(keccak256("functionNotExist()")); - this.call(funcIdentifier); - } - - function ExistFuncCalledTopic() view returns(bytes32){ - return keccak256("ExistFuncCalled(bytes,uint256)"); - } - function FallbackCalledTopic() view returns(bytes32){ - return keccak256("FallbackCalled(bytes)"); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test3Grammar016.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test3Grammar016.sol deleted file mode 100644 index a39a0a08d96..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test3Grammar016.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.4.0; -contract C { -uint private data; -function f(uint a) private returns(uint b) { return a + 1; } -function setData(uint a) public { data = a; } -function getData() public returns(uint) { return data; } -function compute(uint a, uint b) internal returns (uint) { return a+b; } -} -contract D { -function readData() public{ -C c = new C(); -//uint local = c.f(7); // error: member "f" is not visible -c.setData(3); -uint local = c.getData(); -// local = c.compute(3, 5); // error: member "compute" is not visible -} -} -contract E is C { -function g() public { -C c = new C(); -uint val = compute(3, 5); // access to internal member (from derived to parent contract) -} -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test4Grammar017.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test4Grammar017.sol deleted file mode 100644 index 3387a9c30bd..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test4Grammar017.sol +++ /dev/null @@ -1,47 +0,0 @@ -pragma solidity ^0.4.0; -contract CrowdFunding{ -struct Funder{ -address addr; -uint amount; -} - -struct Campaign{ -address beneficiary; -uint goal; -uint amount; -uint funderNum; -mapping(uint => Funder) funders; -} - -uint compaingnID; -mapping (uint => Campaign) campaigns; - -function candidate(address beneficiary, uint goal) returns (uint compaingnID){ -// initialize -campaigns[compaingnID++] = Campaign(beneficiary, goal, 0, 0); -} - -function vote(uint compaingnID) payable { -Campaign c = campaigns[compaingnID]; - -//another way to initialize -c.funders[c.funderNum++] = Funder({addr: msg.sender, amount: msg.value}); -c.amount += msg.value; -} - -function check(uint comapingnId) returns (bool){ -Campaign c = campaigns[comapingnId]; - -if(c.amount < c.goal){ -return false; -} - -uint amount = c.amount; -// incase send much more -c.amount = 0; -if(!c.beneficiary.send(amount)){ -throw; -} -return true; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test5Grammar018.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test5Grammar018.sol deleted file mode 100644 index 4fdaf52a29f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test5Grammar018.sol +++ /dev/null @@ -1,36 +0,0 @@ -pragma solidity ^0.4.0; - - -contract Grammar18{ - function testAddmod() public returns (uint z) { - //计算(x + y)%k,其中以任意精度执行加法,并且不在2 ** 256处围绕 - z=addmod(2, 2, 3); - return z; - } - function testMulmod() public returns (uint z) { -//计算(x * y)%k,其中乘法以任意精度执行,并且不会在2 ** 256处循环。 - z=mulmod(2, 3, 4); - return z; - } - - function testKeccak256() public returns(bytes32){ - //计算的(紧凑)参数的Ethereum-SHA-3(Keccak-256)的散列 - return keccak256("11"); - } - - function testSha256() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - return sha256("11"); - } - function testSha3() public returns(bytes32){ - //计算(紧密包装)参数的SHA-256散列 - return sha3("11"); - } - - function testRipemd160() public returns(bytes32){ - //计算(紧密包装)参数的RIPEMD-160哈希值 - return ripemd160("11"); - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test6Grammar019.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test6Grammar019.sol deleted file mode 100644 index 3b2d5f2263c..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test6Grammar019.sol +++ /dev/null @@ -1,12 +0,0 @@ -pragma solidity ^0.4.0; -contract timetest { - -function timetest() public { -require( 1 == 1 seconds); -require(1 minutes == 60 seconds); -require(1 hours == 60 minutes); -require(1 days == 24 hours); -require(1 weeks == 7 days); -require(1 years == 365 days); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test7Grammar020.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test7Grammar020.sol deleted file mode 100644 index d5157c18c47..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractGrammar003test7Grammar020.sol +++ /dev/null @@ -1,7 +0,0 @@ -pragma solidity ^0.4.0; -contract trxtest { - -function test() public { -require(1 trx == 1000000 sun); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInnerContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInnerContract.sol deleted file mode 100644 index 02402acd217..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInnerContract.sol +++ /dev/null @@ -1,31 +0,0 @@ -//pragma solidity ^0.4.0; - - - -contract InnerContract { - - - constructor() public payable{} - function() external payable{} - function messageI() payable returns (uint ret) { - - - - } - -} - - - -contract OuterContract { - - constructor() public payable{} - function() external payable{} - - function callInner(address addr) payable returns (uint) { - - return InnerContract(addr).messageI.value(1)(); - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction001.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction001.sol deleted file mode 100644 index 1f13e067773..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction001.sol +++ /dev/null @@ -1,42 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address cAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - B b2 = new B();//1.2 - b2.transfer(5);//1.3 - b2.callCGetZero(cAddr, 1);//1.4 - b2.callCGetZero(cAddr,2);//1.6 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(bytes4(keccak256("newBAndTransfer()")));//2.1 - cAddress.call.value(amount + 1)(bytes4(keccak256("newBAndTransfer()")));//2.6 - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function callCGetZero(address cAddress,uint256 amount){ - cAddress.call.value(amount)(bytes4(keccak256("getZero()")));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - B b1 = (new B).value(7)();//2.2,2.7 - b1.getOne();//2.3,2.8 - B b2 = (new B).value(3)();//2.4,2.9 - b2.getOne();//2.5,2.10 - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction002.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction002.sol deleted file mode 100644 index b5fd94f5a0e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction002.sol +++ /dev/null @@ -1,20 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)();//2.1 - } -} - - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction003.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction003.sol deleted file mode 100644 index ab8841419e7..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction003.sol +++ /dev/null @@ -1,31 +0,0 @@ -pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - B b = (new B).value(10)();//1 - - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() public returns(uint256){ - return this.balance; - } - function () payable{} - } - diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction004.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction004.sol deleted file mode 100644 index 8a03691b172..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction004.sol +++ /dev/null @@ -1,24 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor () payable public{} - function suicide(address toAddress) public payable{ - selfdestruct(toAddress); - } - function () payable public{} - function getBalance() public view returns(uint256){ - return this.balance; - } -} -contract B{ - function kill(address contractAddres, address toAddress) payable public { - contractAddres.call(bytes4(keccak256("suicide(address)")),address(this)); - } - function kill2(){ - A a = new A(); - a.suicide(this); - } - function getBalance() public view returns(uint256){ - return this.balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction005.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction005.sol deleted file mode 100644 index d4042dba94a..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction005.sol +++ /dev/null @@ -1,54 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1() public payable{ - B b1 = (new B).value(10)();//1.1 - b1.callCGetZero(false); - b1.callCGetZero(true);//1.4 - } - function test2() public payable{ - C c1 = (new C).value(10)();//1.1 - c1.newBAndTransfer(false); - c1.newBAndTransfer(true);//1.4 - - } - function getBalance() view public returns(uint256){ - return this.balance; - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return this.balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction006.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction006.sol deleted file mode 100644 index 885966df74f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction001testInternalTransaction006.sol +++ /dev/null @@ -1,54 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1() public payable{ - B b1 = (new B).value(10)();//1.1 - b1.callCGetZero(true);//1.4 - b1.callCGetZero(false); - } - function test2() public payable{ - C c1 = (new C).value(10)();//1.1 - c1.newBAndTransfer(true);//1.4 - c1.newBAndTransfer(false); - - } - function getBalance() view public returns(uint256){ - return this.balance; - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return this.balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test1InternalTransaction007.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test1InternalTransaction007.sol deleted file mode 100644 index fc1eb39c36e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test1InternalTransaction007.sol +++ /dev/null @@ -1,38 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address cAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - B b2 = new B();//1.2 - b2.transfer(5);//1.3 - b2.callCGetZero();//1.4 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(bytes4(keccak256("newBAndTransfer()")));//2.1 - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function callCGetZero(){ - assert(1==2); - - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test2InternalTransaction008.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test2InternalTransaction008.sol deleted file mode 100644 index f728c2a8bf6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test2InternalTransaction008.sol +++ /dev/null @@ -1,60 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - - function testAssert(address bAddress,uint256 amount) public payable{ - bAddress.call.value(amount).gas(1000000)(bytes4(keccak256("callCGetZero(bool)")),false);//2.1 - bAddress.call.value(amount).gas(1000000)(bytes4(keccak256("callCGetZero(bool)")),true); - } - function testRequire(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount).gas(1000000)(bytes4(keccak256("newBAndTransfer(bool)")),false);//2.1 - cAddress.call.value(amount).gas(1000000)(bytes4(keccak256("newBAndTransfer(bool)")),true); - } - function testAssert1(address bAddress,uint256 amount) public payable{ - bAddress.call.value(amount).gas(1000000)(bytes4(keccak256("callCGetZero(bool)")),true); - bAddress.call.value(amount).gas(1000000)(bytes4(keccak256("callCGetZero(bool)")),false);//2.1 - } - function testtRequire2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount).gas(1000000)(bytes4(keccak256("newBAndTransfer(bool)")),true); - cAddress.call.value(amount).gas(1000000)(bytes4(keccak256("newBAndTransfer(bool)")),false);//2.1 - } - function getBalance() view public returns(uint256){ - return this.balance; - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function callCGetZero(bool success) payable{ - if(!success){ - assert(1==2); - } - } - function getBalance() view public returns(uint256){ - return this.balance; - } -} - -contract C{ - uint256 public flag=0; - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer(bool success) payable public returns(uint256){ - flag = 1; - if(!success){ - require(2==1); - } - } - function getFlag() public returns(uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test3InternalTransaction009.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test3InternalTransaction009.sol deleted file mode 100644 index 199c0884182..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test3InternalTransaction009.sol +++ /dev/null @@ -1,47 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address cAddr,address dcontract,address baddress) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.transfer(5);//1.3 - b1.callCGetZero(cAddr, 1);//1.4 - b1.getOne(dcontract,baddress); - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne(address contractAddres, address toAddress) payable public{ - contractAddres.call(bytes4(keccak256("suicide1(address)")),address(this)); - - } - function callCGetZero(address cAddress,uint256 amount){ - cAddress.call.value(amount)(bytes4(keccak256("getZero()")));//1.5,1.7 - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public{ - B b1 = (new B).value(7)();//2.2,2.7 - B b2 = (new B).value(3)();//2.4,2.9 - } -} - -contract D{ - constructor () payable public{} - function suicide1(address toAddress) public payable{ - selfdestruct(toAddress); - } - function () payable public{} - function getBalance() public view returns(uint256){ - return this.balance; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test4InternalTransaction010.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test4InternalTransaction010.sol deleted file mode 100644 index 7c10d407461..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test4InternalTransaction010.sol +++ /dev/null @@ -1,188 +0,0 @@ -pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - function () payable{} - } - diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test5InternalTransaction012.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test5InternalTransaction012.sol deleted file mode 100644 index 3dd0c1b2cae..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction002test5InternalTransaction012.sol +++ /dev/null @@ -1,51 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address bAddr,address eAddr) public payable{ - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - } - -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable{ - D d1=(new D).value(1000)(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - function() payable public{} - function getOne(address eAddress) payable returns(uint256){ - eAddress.call.value(1)(bytes4(keccak256("getZero()")));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction013.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction013.sol deleted file mode 100644 index 4e48646270f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction013.sol +++ /dev/null @@ -1,56 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address dAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.testNN(dAddr,2);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(bytes4(keccak256("newBAndTransfer()")));//2.1 - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount) public payable{ - // D d1=(new D)(); - dAddress.call.value(amount)(bytes4(keccak256("getOne()")));//2.1 - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - E e = (new E).value(5)(); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction014.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction014.sol deleted file mode 100644 index 46e1f8e0eed..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction014.sol +++ /dev/null @@ -1,40 +0,0 @@ -pragma solidity ^0.4.24; - -contract callerContract { - constructor() payable{} - function() payable{} - function sendToB(address called_address,address c) public payable{ - called_address.delegatecall(bytes4(keccak256("transferTo(address)")),c); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(bytes4(keccak256("transferTo(address)")),c); - } - function sendToB3(address called_address,address c) public payable{ - called_address.callcode(bytes4(keccak256("transferTo(address)")),c); - } -} - - contract calledContract { - function() payable{} - constructor() payable {} - function transferTo(address toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call.value(5)(bytes4(keccak256("setI()"))); - } - - } - - contract c{ - uint256 public i=0; - constructor() public payable{} - function getBalance() public view returns(uint256){ - return this.balance; - } - function setI() payable{ - i=5; - } - function() payable{} - } diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction015.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction015.sol deleted file mode 100644 index 61666b44892..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction015.sol +++ /dev/null @@ -1,60 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address dAddr,address eAddr) public payable{ - B b1 = (new B).value(10)();//1.1 - b1.testNN(dAddr,2,eAddr);//1.6 - // C c1 = (new C).value(1000000000000)();//1.2 - // E e1 = (new E).value(1)();//1.2 - } - function test2(address cAddress,uint256 amount) public payable{ - cAddress.call.value(amount)(bytes4(keccak256("newBAndTransfer()")));//2.1 - } -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function testNN(address dAddress,uint256 amount,address eAddress) public payable{ - // D d1=(new D)(); - dAddress.call.value(amount)(bytes4(keccak256("getOne(address)")),address(this));//2.1 - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } - function suicide(address toAddress) public payable{ - selfdestruct(toAddress); - } -} -contract D{ - constructor() payable public{} - function() payable public{} - function getOne(address eAddress) payable public{ - E e = (new E).value(5)(); - e.suicide(eAddress); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction016.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction016.sol deleted file mode 100644 index b0cbe16af4d..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction016.sol +++ /dev/null @@ -1,184 +0,0 @@ -pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - B b1=(new B).value(1)();//1 - b1.suicide(this); - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - B b1=(new B).value(1)();//1 - b1.suicide(this); - } - function getBalance() returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - function () payable{} - function suicide(address toAddress) public payable{ - selfdestruct(toAddress); - } - } - diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction017.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction017.sol deleted file mode 100644 index 2352e61b733..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction017.sol +++ /dev/null @@ -1,194 +0,0 @@ -pragma solidity ^0.4.24; - - contract A{ - uint256 public num = 0; - constructor() public payable{} - function transfer(address Address) payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - B b=(new B).value(1)();//1 - selfdestruct(Address); - } - function transfer2() payable public{ - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - (new B).value(1)();//1 - - } - function getBalance() public returns(uint256){ - return this.balance; - } - } - contract B{ - uint256 public num = 0; - function f() payable returns(bool) { - return true; - } - constructor() public payable {} - function payC(address c, bool isRevert) public{ - c.transfer(1);//4 - if (isRevert) { - revert(); - } - } - function getBalance() returns(uint256){ - return this.balance; - } - function () payable{} - } - diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction018.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction018.sol deleted file mode 100644 index 6341ee61b06..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractInternalTransaction003testInternalTransaction018.sol +++ /dev/null @@ -1,149 +0,0 @@ -pragma solidity ^0.4.24; - -contract A{ - constructor() payable public{} - function() payable public{} - function test1(address bAddr,address eAddr) public payable{ - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - bAddr.call.value(1)(bytes4(keccak256("testNN(address)")),eAddr);//2.1 - - - } - -} - -contract B{ - constructor() payable public{} - function() payable public{} - function getOne() payable returns(uint256){ - return 1; - } - function testNN(address eAddress) public payable{ - D d1=(new D).value(100)(); - d1.getOne(eAddress); - } -} - -contract C{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract E{ - constructor() payable public{} - function() payable public{} - function getZero() payable public returns(uint256){ - return 0; - } - function newBAndTransfer() payable public returns(uint256){ - require(2==1); - } -} -contract D{ - constructor() payable public{} - function() payable public{} - function getOne(address eAddress) payable returns(uint256){ - eAddress.call.value(1)(bytes4(keccak256("getZero()")));//2.1 - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage001.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage001.sol deleted file mode 100644 index 4c04cf5c6fb..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage001.sol +++ /dev/null @@ -1,9 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -constructor() payable public{} -function() payable external{} -function divideIHaveArgsReturn(int x,int y) public payable returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage002.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage002.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage002.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage003.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage003.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage003.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage004.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage004.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage004.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage005.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage005.sol deleted file mode 100644 index 7b943aee5c1..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage005.sol +++ /dev/null @@ -1,51 +0,0 @@ -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() public { - require(1==1); - } - - function storage8Char() public { - iarray1 = "12345678"; - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - //uint n = 0; - uint yy = 0; - function test() public { - //n += 1; - yy += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage006.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage006.sol deleted file mode 100644 index 9b16ff63368..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractLinkage006.sol +++ /dev/null @@ -1,18 +0,0 @@ -//pragma solidity ^0.4.0; -contract AA{ - uint256 public count=0; - constructor () payable public{} - function init(address addr, uint256 max) payable public { - count =0; - this.hack(addr,max); - } - function hack(address addr, uint256 max) payable public { - while (count < max) { - count = count +1; - this.hack(addr,max); - } - if (count == max) { - addr.send(20); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractOriginEnergyLimit001.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractOriginEnergyLimit001.sol deleted file mode 100644 index af80b15cc8b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractOriginEnergyLimit001.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.0; - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractOriginEnergyLimit004.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractOriginEnergyLimit004.sol deleted file mode 100644 index af80b15cc8b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractOriginEnergyLimit004.sol +++ /dev/null @@ -1,11 +0,0 @@ -pragma solidity ^0.4.0; - -contract findArgsContractTest{ - function findArgsByIndexTest(uint i) public returns (uint z) { - uint[] memory a = new uint[](3); - a[0]=1; - a[1]=2; - a[2]=3; - return a[i]; - } -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractOtherToTrcToken.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractOtherToTrcToken.sol deleted file mode 100644 index 1fcff0c039f..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractOtherToTrcToken.sol +++ /dev/null @@ -1,40 +0,0 @@ -pragma solidity ^0.4.24; -contract ConvertType { - -constructor() payable public{} - -function() payable external{} - -//function stringToTrctoken(address payable toAddress, string memory tokenStr, uint256 tokenValue) public { -// trcToken t = trcToken(tokenStr); // ERROR -// toAddress.transferToken(tokenValue, tokenStr); // ERROR -//} - -function uint256ToTrctoken(address toAddress,uint256 tokenValue, uint256 tokenInt) public { - trcToken t = trcToken(tokenInt); // OK - toAddress.transferToken(tokenValue, t); // OK - toAddress.transferToken(tokenValue, tokenInt); // OK -} - -function addressToTrctoken(address toAddress, uint256 tokenValue, address adr) public { - trcToken t = trcToken(adr); // OK - toAddress.transferToken(tokenValue, t); // OK -//toAddress.transferToken(tokenValue, adr); // ERROR -} - -//function bytesToTrctoken(address payable toAddress, bytes memory b, uint256 tokenValue) public { - // trcToken t = trcToken(b); // ERROR - // toAddress.transferToken(tokenValue, b); // ERROR -//} - -function bytes32ToTrctoken(address toAddress, uint256 tokenValue, bytes32 b32) public { - trcToken t = trcToken(b32); // OK - toAddress.transferToken(tokenValue, t); // OK -// toAddress.transferToken(tokenValue, b32); // ERROR -} - -//function arrayToTrctoken(address payable toAddress, uint256[] memory arr, uint256 tokenValue) public { -//trcToken t = trcToken(arr); // ERROR -// toAddress.transferToken(tokenValue, arr); // ERROR -//} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario001.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario001.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario001.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario002.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario002.sol deleted file mode 100644 index c096bbff619..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario002.sol +++ /dev/null @@ -1,53 +0,0 @@ -//pragma solidity ^0.4.0; -contract TronNative{ - - address public voteContractAddress= address(0x10001); - address public freezeBalanceAddress = address(0x10002); - address public unFreezeBalanceAddress = address(0x10003); - address public withdrawBalanceAddress = address(0x10004); - address public approveProposalAddress = address(0x10005); - address public createProposalAddress = address(0x10006); - address public deleteProposalAddress = address(0x10007); - constructor () payable public {} - - function voteForSingleWitness (address witnessAddr, uint256 voteValue) public{ - // method 1: - voteContractAddress.delegatecall(abi.encode(witnessAddr,voteValue)); - } - - function voteUsingAssembly (address witnessAddr, uint256 voteValue) public{ - // method 2: - assembly{ - mstore(0x80,witnessAddr) - mstore(0xa0,voteValue) - // gas, address, in, size, out, size - if iszero(delegatecall(0, 0x10001, 0x80, 0x40, 0x80, 0x0)) { - revert(0, 0) - } - } - } - - function freezeBalance(uint256 frozen_Balance,uint256 frozen_Duration) public { - freezeBalanceAddress.delegatecall(abi.encode(frozen_Balance,frozen_Duration)); - } - - function unFreezeBalance() public { - unFreezeBalanceAddress.delegatecall(""); - } - - function withdrawBalance() public { - withdrawBalanceAddress.delegatecall(""); - } - - function approveProposal(uint256 id, bool isApprove) public { - approveProposalAddress.delegatecall(abi.encode(id,isApprove)); - } - - function createProposal(bytes32 [] memory data) public { - createProposalAddress.delegatecall(abi.encode(data)); - } - - function deleteProposal(uint256 id) public{ - deleteProposalAddress.delegatecall(abi.encode(id)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario003.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario003.sol deleted file mode 100644 index ca38896acee..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario003.sol +++ /dev/null @@ -1,7 +0,0 @@ -//pragma solidity ^0.4.0; - -contract divideIHaveArgsReturnStorage{ -function divideIHaveArgsReturn(int x,int y) public returns (int z) { -return z = x / y; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario004.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario004.sol deleted file mode 100644 index b3ca2687b4c..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario004.sol +++ /dev/null @@ -1,88 +0,0 @@ -//pragma solidity ^0.4.11; - -contract TronToken { - - string public name = "Tronix"; // token name - string public symbol = "TRX"; // token symbol - uint256 public decimals = 6; // token digit - - mapping (address => uint256) public balanceOf; - mapping (address => mapping (address => uint256)) public allowance; - - uint256 public totalSupply = 0; - bool public stopped = false; - - uint256 constant valueFounder = 100000000000000000; - address owner = address(0x0); - - modifier isOwner { - assert(owner == msg.sender); - _; - } - - modifier isRunning { - assert (!stopped); - _; - } - - modifier validAddress { - assert(address(0x0) != msg.sender); - _; - } - - constructor(address _addressFounder) public { - owner = msg.sender; - totalSupply = valueFounder; - balanceOf[_addressFounder] = valueFounder; - emit Transfer(address(0x0), _addressFounder, valueFounder); - } - - function transfer(address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[msg.sender] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - balanceOf[msg.sender] -= _value; - balanceOf[_to] += _value; - emit Transfer(msg.sender, _to, _value); - return true; - } - - function transferFrom(address _from, address _to, uint256 _value) isRunning validAddress public returns (bool success) { - require(balanceOf[_from] >= _value); - require(balanceOf[_to] + _value >= balanceOf[_to]); - require(allowance[_from][msg.sender] >= _value); - balanceOf[_to] += _value; - balanceOf[_from] -= _value; - allowance[_from][msg.sender] -= _value; - emit Transfer(_from, _to, _value); - return true; - } - - function approve(address _spender, uint256 _value) isRunning validAddress public returns (bool success) { - require(_value == 0 || allowance[msg.sender][_spender] == 0); - allowance[msg.sender][_spender] = _value; - emit Approval(msg.sender, _spender, _value); - return true; - } - - function stop() isOwner public { - stopped = true; - } - - function start() isOwner public { - stopped = false; - } - - function setName(string memory _name) isOwner public { - name = _name; - } - - function burn(uint256 _value) public { - require(balanceOf[msg.sender] >= _value); - balanceOf[msg.sender] -= _value; - balanceOf[address(0x0)] += _value; - emit Transfer(msg.sender, address(0x0), _value); - } - - event Transfer(address indexed _from, address indexed _to, uint256 _value); - event Approval(address indexed _owner, address indexed _spender, uint256 _value); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario005.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario005.sol deleted file mode 100644 index f4bec71761c..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario005.sol +++ /dev/null @@ -1,103 +0,0 @@ -//pragma solidity ^0.4.16; - -interface token { - function transfer(address receiver, uint amount); -} - -contract Crowdsale { - address public beneficiary = 0x1B228F5D9F934C7BB18AAA86F90418932888E7B4; // 募资成功后的收款方 - uint public fundingGoal = 10000000; // 募资额度 - uint public amountRaised = 1000000; // 参与数量 - uint public deadline; // 募资截止期 - - uint public price; // token 与以太坊的汇率 , token卖多少钱 - token public tokenReward; // 要卖的token - - mapping(address => uint256) public balanceOf; - - bool fundingGoalReached = false; // 众筹是否达到目标 - bool crowdsaleClosed = false; // 众筹是否结束 - - /** - * 事件可以用来跟踪信息 - **/ - event GoalReached(address recipient, uint totalAmountRaised); - event FundTransfer(address backer, uint amount, bool isContribution); - - /** - * 构造函数, 设置相关属性 - */ - function Crowdsale( - address ifSuccessfulSendTo, - uint fundingGoalInEthers, - uint durationInMinutes, - uint finneyCostOfEachToken, - address addressOfTokenUsedAsReward) { - beneficiary = ifSuccessfulSendTo; - fundingGoal = fundingGoalInEthers * 1 sun; - deadline = now + durationInMinutes * 1 minutes; - price = finneyCostOfEachToken * 1 sun; - tokenReward = token(addressOfTokenUsedAsReward); // 传入已发布的 token 合约的地址来创建实例 - } - - /** - * 无函数名的Fallback函数, - * 在向合约转账时,这个函数会被调用 - */ - function () payable { - require(!crowdsaleClosed); - uint amount = msg.value; - balanceOf[msg.sender] += amount; - amountRaised += amount; - tokenReward.transfer(msg.sender, amount / price); - FundTransfer(msg.sender, amount, true); - } - - /** - * 定义函数修改器modifier(作用和Python的装饰器很相似) - * 用于在函数执行前检查某种前置条件(判断通过之后才会继续执行该方法) - * _ 表示继续执行之后的代码 - **/ - modifier afterDeadline() { if (now >= deadline) _; } - - /** - * 判断众筹是否完成融资目标, 这个方法使用了afterDeadline函数修改器 - * - */ - function checkGoalReached() afterDeadline { - if (amountRaised >= fundingGoal) { - fundingGoalReached = true; - GoalReached(beneficiary, amountRaised); - } - crowdsaleClosed = true; - } - - - /** - * 完成融资目标时,融资款发送到收款方 - * 未完成融资目标时,执行退款 - * - */ - function safeWithdrawal() afterDeadline { - if (!fundingGoalReached) { - uint amount = balanceOf[msg.sender]; - balanceOf[msg.sender] = 0; - if (amount > 0) { - if (msg.sender.send(amount)) { - FundTransfer(msg.sender, amount, false); - } else { - balanceOf[msg.sender] = amount; - } - } - } - - if (fundingGoalReached && beneficiary == msg.sender) { - if (beneficiary.send(amountRaised)) { - FundTransfer(beneficiary, amountRaised, false); - } else { - //If we fail to send the funds to beneficiary, unlock funders balance - fundingGoalReached = false; - } - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario006.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario006.sol deleted file mode 100644 index af55371cb6e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario006.sol +++ /dev/null @@ -1,1954 +0,0 @@ -//pragma solidity ^0.4.24; - -interface PlayerBookInterface { - function getPlayerID(address _addr) external returns (uint256); - function getPlayerName(uint256 _pID) external view returns (bytes32); - function getPlayerLAff(uint256 _pID) external view returns (uint256); - function getPlayerAddr(uint256 _pID) external view returns (address); - function getNameFee() external view returns (uint256); - function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); - function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); - function isDev(address _who) external view returns(bool); -} - - -/** -* @title -Name Filter- v0.1.9 -* ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ -* │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ -* ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ -* _____ _____ -* (, / /) /) /) (, / /) /) -* ┌─┐ / _ (/_ // // / _ // _ __ _(/ -* ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ -* ┴ ┴ / / .-/ _____ (__ / -* (__ / (_/ (, / /)™ -* / __ __ __ __ _ __ __ _ _/_ _ _(/ -* ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ -* ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ © Jekyll Island Inc. 2018 -* ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ -* _ __ _ ____ ____ _ _ _____ ____ ___ -*=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* -*=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* -* -* ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ -* ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ -* ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ -*/ - -library NameFilter { - /** - * @dev filters name strings - * -converts uppercase to lower case. - * -makes sure it does not start/end with a space - * -makes sure it does not contain multiple spaces in a row - * -cannot be only numbers - * -cannot start with 0x - * -restricts characters to A-Z, a-z, 0-9, and space. - * @return reprocessed string in bytes32 format - */ - function nameFilter(string _input) - internal - pure - returns(bytes32) - { - bytes memory _temp = bytes(_input); - uint256 _length = _temp.length; - - //sorry limited to 32 characters - require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); - // make sure it doesnt start with or end with space - require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); - // make sure first two characters are not 0x - if (_temp[0] == 0x30) - { - require(_temp[1] != 0x78, "string cannot start with 0x"); - require(_temp[1] != 0x58, "string cannot start with 0X"); - } - - // create a bool to track if we have a non number character - bool _hasNonNumber; - - // convert & check - for (uint256 i = 0; i < _length; i++) - { - // if its uppercase A-Z - if (_temp[i] > 0x40 && _temp[i] < 0x5b) - { - // convert to lower case a-z - _temp[i] = byte(uint(_temp[i]) + 32); - - // we have a non number - if (_hasNonNumber == false) - _hasNonNumber = true; - } else { - require - ( - // require character is a space - _temp[i] == 0x20 || - // OR lowercase a-z - (_temp[i] > 0x60 && _temp[i] < 0x7b) || - // or 0-9 - (_temp[i] > 0x2f && _temp[i] < 0x3a), - "string contains invalid characters" - ); - // make sure theres not 2x spaces in a row - if (_temp[i] == 0x20) - require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); - - // see if we have a character other than a number - if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) - _hasNonNumber = true; - } - } - - require(_hasNonNumber == true, "string cannot be only numbers"); - - bytes32 _ret; - assembly { - _ret := mload(add(_temp, 32)) - } - return (_ret); - } -} - - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - if (a == 0) { - return 0; - } - c = a * b; - require(c / a == b, "SafeMath mul failed"); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return c; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) - internal - pure - returns (uint256) - { - require(b <= a, "SafeMath sub failed"); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) - internal - pure - returns (uint256 c) - { - c = a + b; - require(c >= a, "SafeMath add failed"); - return c; - } - - /** - * @dev gives square root of given x. - */ - function sqrt(uint256 x) - internal - pure - returns (uint256 y) - { - uint256 z = ((add(x,1)) / 2); - y = x; - while (z < y) - { - y = z; - z = ((add((x / z),z)) / 2); - } - } - - /** - * @dev gives square. multiplies x by x - */ - function sq(uint256 x) - internal - pure - returns (uint256) - { - return (mul(x,x)); - } - - /** - * @dev x to the power of y - */ - function pwr(uint256 x, uint256 y) - internal - pure - returns (uint256) - { - if (x==0) - return (0); - else if (y==0) - return (1); - else - { - uint256 z = x; - for (uint256 i=1; i < y; i++) - z = mul(z,x); - return (z); - } - } -} - -//============================================================================== -// | _ _ _ | _ . -// |<(/_\/ (_(_||(_ . -//=======/====================================================================== -library F3DKeysCalcLong { - using SafeMath for *; - /** - * @dev calculates number of keys received given X eth - * @param _curEth current amount of eth in contract - * @param _newEth eth being spent - * @return amount of ticket purchased - */ - function keysRec(uint256 _curEth, uint256 _newEth) - internal - pure - returns (uint256) - { - return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); - } - - /** - * @dev calculates amount of eth received if you sold X keys - * @param _curKeys current amount of keys that exist - * @param _sellKeys amount of keys you wish to sell - * @return amount of eth received - */ - function ethRec(uint256 _curKeys, uint256 _sellKeys) - internal - pure - returns (uint256) - { - return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); - } - - /** - * @dev calculates how many keys would exist with given an amount of eth - * @param _eth eth "in contract" - * @return number of keys that would exist - */ - function keys(uint256 _eth) - internal - pure - returns(uint256) - { - return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); - } - - /** - * @dev calculates how much eth would be in contract given a number of keys - * @param _keys number of keys "in contract" - * @return eth that would exists - */ - function eth(uint256 _keys) - internal - pure - returns(uint256) - { - return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); - } -} - -library F3Ddatasets { - //compressedData key - // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] - // 0 - new player (bool) - // 1 - joined round (bool) - // 2 - new leader (bool) - // 3-5 - air drop tracker (uint 0-999) - // 6-16 - round end time - // 17 - winnerTeam - // 18 - 28 timestamp - // 29 - team - // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) - // 31 - airdrop happened bool - // 32 - airdrop tier - // 33 - airdrop amount won - //compressedIDs key - // [77-52][51-26][25-0] - // 0-25 - pID - // 26-51 - winPID - // 52-77 - rID - struct EventReturns { - uint256 compressedData; - uint256 compressedIDs; - address winnerAddr; // winner address - bytes32 winnerName; // winner name - uint256 amountWon; // amount won - uint256 newPot; // amount in new pot - uint256 P3DAmount; // amount distributed to p3d - uint256 genAmount; // amount distributed to gen - uint256 potAmount; // amount added to pot - } - struct Player { - address addr; // player address - bytes32 name; // player name - uint256 win; // winnings vault - uint256 gen; // general vault - uint256 aff; // affiliate vault - uint256 lrnd; // last round played - uint256 laff; // last affiliate id used - } - struct PlayerRounds { - uint256 eth; // eth player has added to round (used for eth limiter) - uint256 keys; // keys - uint256 mask; // player mask - uint256 ico; // ICO phase investment - } - struct Round { - uint256 plyr; // pID of player in lead - uint256 team; // tID of team in lead - uint256 end; // time ends/ended - bool ended; // has round end function been ran - uint256 strt; // time round started - uint256 keys; // keys - uint256 eth; // total eth in - uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) - uint256 mask; // global mask - uint256 ico; // total eth sent in during ICO phase - uint256 icoGen; // total eth for gen during ICO phase - uint256 icoAvg; // average key price for ICO phase - } - struct TeamFee { - uint256 gen; // % of buy in thats paid to key holders of current round - uint256 p3d; // % of buy in thats paid to p3d holders - } - struct PotSplit { - uint256 gen; // % of pot thats paid to key holders of current round - uint256 p3d; // % of pot thats paid to p3d holders - } -} - -contract F3Devents { - // fired whenever a player registers a name - event onNewName - ( - uint256 indexed playerID, - address indexed playerAddress, - bytes32 indexed playerName, - bool isNewPlayer, - uint256 affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 amountPaid, - uint256 timeStamp - ); - - // fired at end of buy or reload - event onEndTx - ( - uint256 compressedData, - uint256 compressedIDs, - bytes32 playerName, - address playerAddress, - uint256 ethIn, - uint256 keysBought, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount, - uint256 potAmount, - uint256 airDropPot - ); - - // fired whenever theres a withdraw - event onWithdraw - ( - uint256 indexed playerID, - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 timeStamp - ); - - // fired whenever a withdraw forces end round to be ran - event onWithdrawAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethOut, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a buy after round timer - // hit zero, and causes end round to be ran. - event onBuyAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 ethIn, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // (fomo3d long only) fired whenever a player tries a reload after round timer - // hit zero, and causes end round to be ran. - event onReLoadAndDistribute - ( - address playerAddress, - bytes32 playerName, - uint256 compressedData, - uint256 compressedIDs, - address winnerAddr, - bytes32 winnerName, - uint256 amountWon, - uint256 newPot, - uint256 P3DAmount, - uint256 genAmount - ); - - // fired whenever an affiliate is paid - event onAffiliatePayout - ( - uint256 indexed affiliateID, - address affiliateAddress, - bytes32 affiliateName, - uint256 indexed roundID, - uint256 indexed buyerID, - uint256 amount, - uint256 timeStamp - ); - - // received pot swap deposit - event onPotSwapDeposit - ( - uint256 roundID, - uint256 amountAddedToPot - ); -} - - - -contract FoMo3Dlong is F3Devents { - using SafeMath for *; - using NameFilter for string; - using F3DKeysCalcLong for uint256; - - address public otherF3D_; - address public Divies; - address public Jekyll_Island_Inc; - PlayerBookInterface public playerBook;// =PlayerBookInterface(0x0dcd2f752394c41875e259e00bb44fd505297caf);//new PlayerBook();// - // TeamJustInterface constant private teamJust = TeamJustInterface(0x3a5f8140b9213a0f733a6a639857c9df43ee3f5a);// new TeamJust();// - - //============================================================================== - // _ _ _ |`. _ _ _ |_ | _ _ . - // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) - //=================_|=========================================================== - string constant public name = "FoMo3D Long Official"; - string constant public symbol = "F3D"; - uint256 private rndExtra_ = 30;//extSettings.getLongExtra(); // length of the very first ICO - uint256 private rndGap_ = 30; //extSettings.getLongGap(); // length of ICO phase, set to 1 year for EOS. - uint256 constant private rndInit_ = 1 hours; // round timer starts at this - uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer - uint256 constant private rndMax_ = 24 hours; // max length a round timer can be - //============================================================================== - // _| _ _|_ _ _ _ _|_ _ . - // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) - //=============================|================================================ - uint256 public airDropPot_; // person who gets the airdrop wins part of this pot - uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop - uint256 public rID_; // round id number / total rounds that have happened - //**************** - // PLAYER DATA - //**************** - mapping(address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address - mapping(bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name - mapping(uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data - mapping(uint256 => mapping(uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id - mapping(uint256 => mapping(bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) - //**************** - // ROUND DATA - //**************** - mapping(uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data - mapping(uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id - //**************** - // TEAM FEE DATA - //**************** - mapping(uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team - mapping(uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team - - function setPlayerBook(address _playerBook) external { - require(msg.sender == owner, 'only dev!'); - require(address(playerBook) == address(0), 'already set!'); - playerBook = PlayerBookInterface(_playerBook); - } - - address public owner; - - //============================================================================== - // _ _ _ __|_ _ __|_ _ _ . - // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) - //============================================================================== - constructor() - public - { - owner = msg.sender; - // Team allocation structures - // 0 = whales - // 1 = bears - // 2 = sneks - // 3 = bulls - - // Team allocation percentages - // (F3D, P3D) + (Pot , Referrals, Community) - // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. - fees_[0] = F3Ddatasets.TeamFee(30, 6); - //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[1] = F3Ddatasets.TeamFee(43, 0); - //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[2] = F3Ddatasets.TeamFee(56, 10); - //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - fees_[3] = F3Ddatasets.TeamFee(43, 8); - //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot - - // how to split up the final pot based on which team was picked - // (F3D, P3D) - potSplit_[0] = F3Ddatasets.PotSplit(15, 10); - //48% to winner, 25% to next round, 2% to com - potSplit_[1] = F3Ddatasets.PotSplit(25, 0); - //48% to winner, 25% to next round, 2% to com - potSplit_[2] = F3Ddatasets.PotSplit(20, 20); - //48% to winner, 10% to next round, 2% to com - potSplit_[3] = F3Ddatasets.PotSplit(30, 10); - //48% to winner, 10% to next round, 2% to com - } - //============================================================================== - // _ _ _ _|. |`. _ _ _ . - // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) - //============================================================================== - /** - * @dev used to make sure no one can interact with contract until it has - * been activated. - */ - modifier isActivated() { - require(activated_ == true, "its not ready yet. check ?eta in discord"); - _; - } - - /** - * @dev prevents contracts from interacting with fomo3d - */ - modifier isHuman() { - address _addr = msg.sender; - uint256 _codeLength; - - assembly {_codeLength := extcodesize(_addr)} - require(_codeLength == 0, "sorry humans only"); - _; - } - - modifier onlyDevs() - { - require(playerBook.isDev(msg.sender) == true, "msg sender is not a dev"); - _; - } - - /** - * @dev sets boundaries for incoming tx - */ - modifier isWithinLimits(uint256 _eth) { - require(_eth >= 1000000000, "pocket lint: not a valid currency"); - require(_eth <= 100000000000000000000000, "no vitalik, no"); - _; - } - - //============================================================================== - // _ |_ |. _ |` _ __|_. _ _ _ . - // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) - //====|========================================================================= - /** - * @dev emergency buy uses last stored affiliate ID and team snek - */ - function() - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // buy core - buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); - } - - /** - * @dev converts all incoming ethereum to keys. - * -functionhash- 0x8f38f309 (using ID for affiliate) - * -functionhash- 0x98a0871d (using address for affiliate) - * -functionhash- 0xa65b37a1 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - */ - function buyXid(uint256 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affCode, _team, _eventData_); - } - - function buyXaddr(address _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - function buyXname(bytes32 _affCode, uint256 _team) - isActivated() - isHuman() - isWithinLimits(msg.value) - public - payable - { - // set up our tx event data and determine if player is new or not - F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); - - // fetch player id - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // buy core - buyCore(_pID, _affID, _team, _eventData_); - } - - /** - * @dev essentially the same as buy, but instead of you sending ether - * from your wallet, it uses your unwithdrawn earnings. - * -functionhash- 0x349cdcac (using ID for affiliate) - * -functionhash- 0x82bfc739 (using address for affiliate) - * -functionhash- 0x079ce327 (using name for affiliate) - * @param _affCode the ID/address/name of the player who gets the affiliate fee - * @param _team what team is the player playing for? - * @param _eth amount of earnings to use (remainder returned to gen vault) - */ - function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == 0 || _affCode == _pID) - { - // use last stored affiliate code - _affCode = plyr_[_pID].laff; - - // if affiliate code was given & its not the same as previously stored - } else if (_affCode != plyr_[_pID].laff) { - // update last affiliate - plyr_[_pID].laff = _affCode; - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affCode, _team, _eth, _eventData_); - } - - function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == address(0) || _affCode == msg.sender) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxAddr_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) - isActivated() - isHuman() - isWithinLimits(_eth) - public - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // manage affiliate residuals - uint256 _affID; - // if no affiliate code was given or player tried to use their own, lolz - if (_affCode == '' || _affCode == plyr_[_pID].name) - { - // use last stored affiliate code - _affID = plyr_[_pID].laff; - - // if affiliate code was given - } else { - // get affiliate ID from aff Code - _affID = pIDxName_[_affCode]; - - // if affID is not the same as previously stored - if (_affID != plyr_[_pID].laff) - { - // update last affiliate - plyr_[_pID].laff = _affID; - } - } - - // verify a valid team was selected - _team = verifyTeam(_team); - - // reload core - reLoadCore(_pID, _affID, _team, _eth, _eventData_); - } - - /** - * @dev withdraws all of your earnings. - * -functionhash- 0x3ccfd60b - */ - function withdraw() - isActivated() - isHuman() - public - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // fetch player ID - uint256 _pID = pIDxAddr_[msg.sender]; - - // setup temp var for player eth - uint256 _eth; - - // check to see if round has ended and no one has run round end yet - if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // set up our tx event data - F3Ddatasets.EventReturns memory _eventData_; - - // end the round (distributes pot) - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire withdraw and distribute event - emit F3Devents.onWithdrawAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eth, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - - // in any other situation - } else { - // get their earnings - _eth = withdrawEarnings(_pID); - - // gib moni - if (_eth > 0) - plyr_[_pID].addr.transfer(_eth); - - // fire withdraw event - emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); - } - } - - /** - * @dev use these to register names. they are just wrappers that will send the - * registration requests to the PlayerBook contract. So registering here is the - * same as registering there. UI will always display the last name you registered. - * but you will still own all previously registered names to use as affiliate - * links. - * - must pay a registration fee. - * - name must be unique - * - names will be converted to lowercase - * - name cannot start or end with a space - * - cannot have more than 1 space in a row - * - cannot be only numbers - * - cannot start with 0x - * - name must be at least 1 char - * - max length of 32 characters long - * - allowed characters: a-z, 0-9, and space - * -functionhash- 0x921dec21 (using ID for affiliate) - * -functionhash- 0x3ddd4698 (using address for affiliate) - * -functionhash- 0x685ffd83 (using name for affiliate) - * @param _nameString players desired name - * @param _affCode affiliate ID, address, or name of who referred you - * @param _all set to true if you want this to push your info to all games - * (this might cost a lot of gas) - */ - function registerNameXID(string _nameString, uint256 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - - function registerNameXaddr(string _nameString, address _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - - function registerNameXname(string _nameString, bytes32 _affCode, bool _all) - isHuman() - public - payable - { - bytes32 _name = _nameString.nameFilter(); - address _addr = msg.sender; - uint256 _paid = msg.value; - (bool _isNewPlayer, uint256 _affID) = playerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); - - uint256 _pID = pIDxAddr_[_addr]; - - // fire event - emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); - } - //============================================================================== - // _ _ _|__|_ _ _ _ . - // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) - //=====_|======================================================================= - /** - * @dev return the price buyer will pay for next 1 individual key. - * -functionhash- 0x018a25e8 - * @return price for next key bought (in wei format) - */ - function getBuyPrice() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000)); - else // rounds over. need price for new round - return (75000000000000); - // init - } - - /** - * @dev returns time left. dont spam this, you'll ddos yourself from your node - * provider - * -functionhash- 0xc7e284b8 - * @return time left in seconds - */ - function getTimeLeft() - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - if (_now < round_[_rID].end) - if (_now > round_[_rID].strt + rndGap_) - return ((round_[_rID].end).sub(_now)); - else - return ((round_[_rID].strt + rndGap_).sub(_now)); - else - return (0); - } - - /** - * @dev returns player earnings per vaults - * -functionhash- 0x63066434 - * @return winnings vault - * @return general vault - * @return affiliate vault - */ - function getPlayerVaults(uint256 _pID) - public - view - returns (uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - // if round has ended. but round end has not been run (so contract has not distributed winnings) - if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) - { - // if player is winner - if (round_[_rID].plyr == _pID) - { - return - ( - (plyr_[_pID].win).add(((round_[_rID].pot).mul(48)) / 100), - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - // if player is not the winner - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask)), - plyr_[_pID].aff - ); - } - - // if round is still going on, or round has ended and round end has been ran - } else { - return - ( - plyr_[_pID].win, - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), - plyr_[_pID].aff - ); - } - } - - /** - * solidity hates stack limits. this lets us avoid that hate - */ - function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) - private - view - returns (uint256) - { - return (((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000)); - } - - /** - * @dev returns all current round info needed for front end - * -functionhash- 0x747dff42 - * @return eth invested during ICO phase - * @return round id - * @return total keys for round - * @return time round ends - * @return time round started - * @return current pot - * @return current team ID & player ID in lead - * @return current player in leads address - * @return current player in leads name - * @return whales eth in for round - * @return bears eth in for round - * @return sneks eth in for round - * @return bulls eth in for round - * @return airdrop tracker # & airdrop pot - */ - function getCurrentRoundInfo() - public - view - returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - return - ( - round_[_rID].ico, //0 - _rID, //1 - round_[_rID].keys, //2 - round_[_rID].end, //3 - round_[_rID].strt, //4 - round_[_rID].pot, //5 - (round_[_rID].team + (round_[_rID].plyr * 10)), //6 - plyr_[round_[_rID].plyr].addr, //7 - plyr_[round_[_rID].plyr].name, //8 - rndTmEth_[_rID][0], //9 - rndTmEth_[_rID][1], //10 - rndTmEth_[_rID][2], //11 - rndTmEth_[_rID][3], //12 - airDropTracker_ + (airDropPot_ * 1000) //13 - ); - } - - /** - * @dev returns player info based on address. if no address is given, it will - * use msg.sender - * -functionhash- 0xee0b5d8b - * @param _addr address of the player you want to lookup - * @return player ID - * @return player name - * @return keys owned (current round) - * @return winnings vault - * @return general vault - * @return affiliate vault - * @return player round eth - */ - function getPlayerInfoByAddress(address _addr) - public - view - returns (uint256, bytes32, uint256, uint256, uint256, uint256, uint256) - { - // setup local rID - uint256 _rID = rID_; - - if (_addr == address(0)) - { - _addr == msg.sender; - } - uint256 _pID = pIDxAddr_[_addr]; - - return - ( - _pID, //0 - plyr_[_pID].name, //1 - plyrRnds_[_pID][_rID].keys, //2 - plyr_[_pID].win, //3 - (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 - plyr_[_pID].aff, //5 - plyrRnds_[_pID][_rID].eth //6 - ); - } - - //============================================================================== - // _ _ _ _ | _ _ . _ . - // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) - //=====================_|======================================================= - /** - * @dev logic runs whenever a buy order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // call core - core(_rID, _pID, msg.value, _affID, _team, _eventData_); - - // if round is not active - } else { - // check to see if end round needs to be ran - if (_now > round_[_rID].end && round_[_rID].ended == false) - { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onBuyAndDistribute - ( - msg.sender, - plyr_[_pID].name, - msg.value, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - - // put eth in players vault - plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); - } - } - - /** - * @dev logic runs whenever a reload order is executed. determines how to handle - * incoming eth depending on if we are in an active round or not - */ - function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) - private - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // if round is active - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - { - // get earnings from all vaults and return unused to gen vault - // because we use a custom safemath library. this will throw if player - // tried to spend more eth than they have. - plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); - - // call core - core(_rID, _pID, _eth, _affID, _team, _eventData_); - - // if round is not active and end round needs to be ran - } else if (_now > round_[_rID].end && round_[_rID].ended == false) { - // end the round (distributes pot) & start new round - round_[_rID].ended = true; - _eventData_ = endRound(_eventData_); - - // build event data - _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; - - // fire buy and distribute event - emit F3Devents.onReLoadAndDistribute - ( - msg.sender, - plyr_[_pID].name, - _eventData_.compressedData, - _eventData_.compressedIDs, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount - ); - } - } - - /** - * @dev this is the core logic for any buy/reload that happens while a round - * is live. - */ - function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - { - // if player is new to round - if (plyrRnds_[_pID][_rID].keys == 0) - _eventData_ = managePlayer(_pID, _eventData_); - - // early round eth limiter - if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) - { - uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); - uint256 _refund = _eth.sub(_availableLimit); - plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); - _eth = _availableLimit; - } - - // if eth left is greater than min eth allowed (sorry no pocket lint) - if (_eth > 1000000000) - { - - // mint the new keys - uint256 _keys = (round_[_rID].eth).keysRec(_eth); - - // if they bought at least 1 whole key - if (_keys >= 1000000000000000000) - { - updateTimer(_keys, _rID); - - // set new leaders - if (round_[_rID].plyr != _pID) - round_[_rID].plyr = _pID; - if (round_[_rID].team != _team) - round_[_rID].team = _team; - - // set the new leader bool to true - _eventData_.compressedData = _eventData_.compressedData + 100; - } - - // manage airdrops - if (_eth >= 100000000000000000) - { - airDropTracker_++; - if (airdrop() == true) - { - // gib muni - uint256 _prize; - if (_eth >= 10000000000000000000) - { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(75)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(50)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 2 prize was won - _eventData_.compressedData += 200000000000000000000000000000000; - } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { - // calculate prize and give it to winner - _prize = ((airDropPot_).mul(25)) / 100; - plyr_[_pID].win = (plyr_[_pID].win).add(_prize); - - // adjust airDropPot - airDropPot_ = (airDropPot_).sub(_prize); - - // let event know a tier 3 prize was won - _eventData_.compressedData += 300000000000000000000000000000000; - } - // set airdrop happened bool to true - _eventData_.compressedData += 10000000000000000000000000000000; - // let event know how much was won - _eventData_.compressedData += _prize * 1000000000000000000000000000000000; - - // reset air drop tracker - airDropTracker_ = 0; - } - } - - // store the air drop tracker number (number of buys since last airdrop) - _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); - - // update player - plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); - plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); - - // update round - round_[_rID].keys = _keys.add(round_[_rID].keys); - round_[_rID].eth = _eth.add(round_[_rID].eth); - rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); - - // distribute eth - _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); - _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); - - // call end tx function to fire end tx event. - endTx(_pID, _team, _eth, _keys, _eventData_); - } - } - //============================================================================== - // _ _ | _ | _ _|_ _ _ _ . - // (_(_||(_|_||(_| | (_)| _\ . - //============================================================================== - /** - * @dev calculates unmasked earnings (just calculates, does not update mask) - * @return earnings in wei format - */ - function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) - private - view - returns (uint256) - { - return ((((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask)); - } - - /** - * @dev returns the amount of keys you would get given an amount of eth. - * -functionhash- 0xce89c80c - * @param _rID round ID you want price for - * @param _eth amount of eth sent in - * @return keys received - */ - function calcKeysReceived(uint256 _rID, uint256 _eth) - public - view - returns (uint256) - { - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].eth).keysRec(_eth)); - else // rounds over. need keys for new round - return ((_eth).keys()); - } - - /** - * @dev returns current eth price for X keys. - * -functionhash- 0xcf808000 - * @param _keys number of keys desired (in 18 decimal format) - * @return amount of eth needed to send - */ - function iWantXKeys(uint256 _keys) - public - view - returns (uint256) - { - // setup local rID - uint256 _rID = rID_; - - // grab time - uint256 _now = now; - - // are we in a round? - if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) - return ((round_[_rID].keys.add(_keys)).ethRec(_keys)); - else // rounds over. need price for new round - return ((_keys).eth()); - } - //============================================================================== - // _|_ _ _ | _ . - // | (_)(_)|_\ . - //============================================================================== - /** - * @dev receives name/player info from names contract - */ - function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (pIDxAddr_[_addr] != _pID) - pIDxAddr_[_addr] = _pID; - if (pIDxName_[_name] != _pID) - pIDxName_[_name] = _pID; - if (plyr_[_pID].addr != _addr) - plyr_[_pID].addr = _addr; - if (plyr_[_pID].name != _name) - plyr_[_pID].name = _name; - if (plyr_[_pID].laff != _laff) - plyr_[_pID].laff = _laff; - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev receives entire player name list - */ - function receivePlayerNameList(uint256 _pID, bytes32 _name) - external - { - require(msg.sender == address(playerBook), "your not playerNames contract... hmmm.."); - if (plyrNames_[_pID][_name] == false) - plyrNames_[_pID][_name] = true; - } - - /** - * @dev gets existing or registers new pID. use this when a player may be new - * @return pID - */ - function determinePID(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns) - { - uint256 _pID = pIDxAddr_[msg.sender]; - // if player is new to this version of fomo3d - if (_pID == 0) - { - // grab their player ID, name and last aff ID, from player names contract - _pID = playerBook.getPlayerID(msg.sender); - bytes32 _name = playerBook.getPlayerName(_pID); - uint256 _laff = playerBook.getPlayerLAff(_pID); - - // set up player account - pIDxAddr_[msg.sender] = _pID; - plyr_[_pID].addr = msg.sender; - - if (_name != "") - { - pIDxName_[_name] = _pID; - plyr_[_pID].name = _name; - plyrNames_[_pID][_name] = true; - } - - if (_laff != 0 && _laff != _pID) - plyr_[_pID].laff = _laff; - - // set the new player bool to true - _eventData_.compressedData = _eventData_.compressedData + 1; - } - return (_eventData_); - } - - /** - * @dev checks to make sure user picked a valid team. if not sets team - * to default (sneks) - */ - function verifyTeam(uint256 _team) - private - pure - returns (uint256) - { - if (_team < 0 || _team > 3) - return (2); - else - return (_team); - } - - /** - * @dev decides if round end needs to be run & new round started. and if - * player unmasked earnings from previously played rounds need to be moved. - */ - function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns) - { - // if player has played a previous round, move their unmasked earnings - // from that round to gen vault. - if (plyr_[_pID].lrnd != 0) - updateGenVault(_pID, plyr_[_pID].lrnd); - - // update player's last round played - plyr_[_pID].lrnd = rID_; - - // set the joined round bool to true - _eventData_.compressedData = _eventData_.compressedData + 10; - - return (_eventData_); - } - - /** - * @dev ends the round. manages paying out winner/splitting up pot - */ - function endRound(F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns) - { - // setup local rID - uint256 _rID = rID_; - - // grab our winning player and team id's - uint256 _winPID = round_[_rID].plyr; - uint256 _winTID = round_[_rID].team; - - // grab our pot amount - uint256 _pot = round_[_rID].pot; - - // calculate our winner share, community rewards, gen share, - // p3d share, and amount reserved for next pot - uint256 _win = (_pot.mul(48)) / 100; - uint256 _com = (_pot / 50); - uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; - uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; - uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d); - - // calculate ppt for round mask - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); - if (_dust > 0) - { - _gen = _gen.sub(_dust); - _res = _res.add(_dust); - } - - // pay our winner - plyr_[_winPID].win = _win.add(plyr_[_winPID].win); - - // community rewards - if (!address(Jekyll_Island_Inc).send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _p3d.add(_com); - _com = 0; - } - - // distribute gen portion to key holders - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // send share for p3d to divies - if (_p3d > 0) - Divies.transfer(_p3d); - - // prepare event data - _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); - _eventData_.winnerAddr = plyr_[_winPID].addr; - _eventData_.winnerName = plyr_[_winPID].name; - _eventData_.amountWon = _win; - _eventData_.genAmount = _gen; - _eventData_.P3DAmount = _p3d; - _eventData_.newPot = _res; - - // start next round - rID_++; - _rID++; - round_[_rID].strt = now; - round_[_rID].end = now.add(rndInit_).add(rndGap_); - round_[_rID].pot = _res; - - return (_eventData_); - } - - /** - * @dev moves any unmasked earnings to gen vault. updates earnings mask - */ - function updateGenVault(uint256 _pID, uint256 _rIDlast) - private - { - uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); - if (_earnings > 0) - { - // put in gen vault - plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); - // zero out their earnings by updating mask - plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); - } - } - - /** - * @dev updates round timer based on number of whole keys bought. - */ - function updateTimer(uint256 _keys, uint256 _rID) - private - { - // grab time - uint256 _now = now; - - // calculate time based on number of keys bought - uint256 _newTime; - if (_now > round_[_rID].end && round_[_rID].plyr == 0) - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); - else - _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); - - // compare to max and set new end time - if (_newTime < (rndMax_).add(_now)) - round_[_rID].end = _newTime; - else - round_[_rID].end = rndMax_.add(_now); - } - - /** - * @dev generates a random number between 0-99 and checks to see if thats - * resulted in an airdrop win - * @return do we have a winner? - */ - function airdrop() - private - view - returns (bool) - { - uint256 seed = uint256(keccak256(abi.encodePacked( - - (block.timestamp).add - (block.difficulty).add - ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add - (block.gaslimit).add - ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add - (block.number) - - ))); - if ((seed - ((seed / 1000) * 1000)) < airDropTracker_) - return (true); - else - return (false); - } - - /** - * @dev distributes eth based on fees to com, aff, and p3d - */ - function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns) - { - // pay 2% out to community rewards - uint256 _com = _eth / 50; - uint256 _p3d; - if (!address(Jekyll_Island_Inc).send(_com)) - { - // This ensures Team Just cannot influence the outcome of FoMo3D with - // bank migrations by breaking outgoing transactions. - // Something we would never do. But that's not the point. - // We spent 2000$ in eth re-deploying just to patch this, we hold the - // highest belief that everything we create should be trustless. - // Team JUST, The name you shouldn't have to trust. - _p3d = _com; - _com = 0; - } - - // pay 1% out to FoMo3D short - uint256 _long = _eth / 100; - otherF3D_.transfer(_long); - - // distribute share to affiliate - uint256 _aff = _eth / 10; - - // decide what to do with affiliate share of fees - // affiliate must not be self, and must have a name registered - if (_affID != _pID && plyr_[_affID].name != '') { - plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); - emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); - } else { - _p3d = _aff; - } - - // pay out p3d - _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); - if (_p3d > 0) - { - // deposit to divies contract - Divies.transfer(_p3d); - - // set up event data - _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); - } - - return (_eventData_); - } - - function potSwap() - external - payable - { - // setup local rID - uint256 _rID = rID_ + 1; - - round_[_rID].pot = round_[_rID].pot.add(msg.value); - emit F3Devents.onPotSwapDeposit(_rID, msg.value); - } - - /** - * @dev distributes eth based on fees to gen and pot - */ - function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - returns (F3Ddatasets.EventReturns) - { - // calculate gen share - uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; - - // toss 1% into airdrop pot - uint256 _air = (_eth / 100); - airDropPot_ = airDropPot_.add(_air); - - // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) - _eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); - - // calculate pot - uint256 _pot = _eth.sub(_gen); - - // distribute gen share (thats what updateMasks() does) and adjust - // balances for dust. - uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); - if (_dust > 0) - _gen = _gen.sub(_dust); - - // add eth to pot - round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); - - // set up event data - _eventData_.genAmount = _gen.add(_eventData_.genAmount); - _eventData_.potAmount = _pot; - - return (_eventData_); - } - - /** - * @dev updates masks for round and player when keys are bought - * @return dust left over - */ - function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) - private - returns (uint256) - { - /* MASKING NOTES - earnings masks are a tricky thing for people to wrap their minds around. - the basic thing to understand here. is were going to have a global - tracker based on profit per share for each round, that increases in - relevant proportion to the increase in share supply. - - the player will have an additional mask that basically says "based - on the rounds mask, my shares, and how much i've already withdrawn, - how much is still owed to me?" - */ - - // calc profit per key & round mask based on this buy: (dust goes to pot) - uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); - round_[_rID].mask = _ppt.add(round_[_rID].mask); - - // calculate player earning from their own buy (only based on the keys - // they just bought). & update player earnings mask - uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); - plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); - - // calculate & return dust - return (_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); - } - - /** - * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 - * @return earnings in wei format - */ - function withdrawEarnings(uint256 _pID) - private - returns (uint256) - { - // update gen vault - updateGenVault(_pID, plyr_[_pID].lrnd); - - // from vaults - uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); - if (_earnings > 0) - { - plyr_[_pID].win = 0; - plyr_[_pID].gen = 0; - plyr_[_pID].aff = 0; - } - - return (_earnings); - } - - /** - * @dev prepares compression data and fires event for buy or reload tx's - */ - function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) - private - { - _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); - _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); - - emit F3Devents.onEndTx - ( - _eventData_.compressedData, - _eventData_.compressedIDs, - plyr_[_pID].name, - msg.sender, - _eth, - _keys, - _eventData_.winnerAddr, - _eventData_.winnerName, - _eventData_.amountWon, - _eventData_.newPot, - _eventData_.P3DAmount, - _eventData_.genAmount, - _eventData_.potAmount, - airDropPot_ - ); - } - //============================================================================== - // (~ _ _ _._|_ . - // _)(/_(_|_|| | | \/ . - //====================/========================================================= - /** upon contract deploy, it will be deactivated. this is a one time - * use function that will activate the contract. we do this so devs - * have time to set things up on the web end **/ - bool public activated_ = false; - - function activate() - public - onlyDevs - { - - // can only be ran once - require(activated_ == false, "fomo3d already activated"); - - // activate the contract - activated_ = true; - - otherF3D_ = msg.sender; - Divies = msg.sender; - Jekyll_Island_Inc = msg.sender; - - // lets start first round - rID_ = 1; - round_[1].strt = now + rndExtra_ - rndGap_; - round_[1].end = now + rndInit_ + rndExtra_; - } - - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario007.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario007.sol deleted file mode 100644 index 44aae1a5e32..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario007.sol +++ /dev/null @@ -1,1433 +0,0 @@ -//pragma solidity 0.4.24; - -/** - * @title ERC165 - * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md - */ -interface ERC165 { - - /** - * @notice Query if a contract implements an interface - * @param _interfaceId The interface identifier, as specified in ERC-165 - * @dev Interface identification is specified in ERC-165. This function - * uses less than 30,000 gas. - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool); - -} - -contract ERC721Basic is ERC165 { - - event Transfer( - address indexed _from, - address indexed _to, - uint256 indexed _tokenId - ); - event Approval( - address indexed _owner, - address indexed _approved, - uint256 indexed _tokenId - ); - event ApprovalForAll( - address indexed _owner, - address indexed _operator, - bool _approved - ); - - function balanceOf(address _owner) public view returns (uint256 _balance); - function ownerOf(uint256 _tokenId) public view returns (address _owner); - function exists(uint256 _tokenId) public view returns (bool _exists); - - function approve(address _to, uint256 _tokenId) public; - function getApproved(uint256 _tokenId) - public view returns (address _operator); - - function setApprovalForAll(address _operator, bool _approved) public; - function isApprovedForAll(address _owner, address _operator) - public view returns (bool); - - function transferFrom(address _from, address _to, uint256 _tokenId) public; - function safeTransferFrom(address _from, address _to, uint256 _tokenId) - public; - - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public; -} - - -/** - * @title SupportsInterfaceWithLookup - * @author Matt Condon (@shrugs) - * @dev Implements ERC165 using a lookup table. - */ -contract SupportsInterfaceWithLookup is ERC165 { - bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7; - /** - * 0x01ffc9a7 === - * bytes4(keccak256('supportsInterface(bytes4)')) - */ - - /** - * @dev a mapping of interface id to whether or not it's supported - */ - mapping(bytes4 => bool) internal supportedInterfaces; - - /** - * @dev A contract implementing SupportsInterfaceWithLookup - * implement ERC165 itself - */ - constructor() public { - _registerInterface(InterfaceId_ERC165); - } - - /** - * @dev implement supportsInterface(bytes4) using a lookup table - */ - function supportsInterface(bytes4 _interfaceId) external view returns (bool) { - return supportedInterfaces[_interfaceId]; - } - - /** - * @dev private method for registering an interface - */ - function _registerInterface(bytes4 _interfaceId) internal { - require(_interfaceId != 0xffffffff); - supportedInterfaces[_interfaceId] = true; - } -} - -contract Governable { - - event Pause(); - event Unpause(); - - address public governor; - bool public paused = false; - - constructor() public { - governor = msg.sender; - } - - function setGovernor(address _gov) public onlyGovernor { - governor = _gov; - } - - modifier onlyGovernor { - require(msg.sender == governor); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is not paused. - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev Modifier to make a function callable only when the contract is paused. - */ - modifier whenPaused() { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyGovernor whenNotPaused public { - paused = true; - emit Pause(); - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyGovernor whenPaused public { - paused = false; - emit Unpause(); - } - -} - -contract CardBase is Governable { - - struct Card { - uint16 proto; - uint16 purity; - } - - function getCard(uint id) public view returns (uint16 proto, uint16 purity) { - Card memory card = cards[id]; - return (card.proto, card.purity); - } - - function getShine(uint16 purity) public pure returns (uint8) { - return uint8(purity / 1000); - } - - Card[] public cards; - -} - -contract CardProto is CardBase { - - event NewProtoCard( - uint16 id, uint8 season, uint8 god, - Rarity rarity, uint8 mana, uint8 attack, - uint8 health, uint8 cardType, uint8 tribe, bool packable - ); - - struct Limit { - uint64 limit; - bool exists; - } - - // limits for mythic cards - mapping(uint16 => Limit) public limits; - - // can only set limits once - function setLimit(uint16 id, uint64 limit) public onlyGovernor { - Limit memory l = limits[id]; - require(!l.exists); - limits[id] = Limit({ - limit: limit, - exists: true - }); - } - - function getLimit(uint16 id) public view returns (uint64 limit, bool set) { - Limit memory l = limits[id]; - return (l.limit, l.exists); - } - - // could make these arrays to save gas - // not really necessary - will be update a very limited no of times - mapping(uint8 => bool) public seasonTradable; - mapping(uint8 => bool) public seasonTradabilityLocked; - uint8 public currentSeason; - - function makeTradable(uint8 season) public onlyGovernor { - seasonTradable[season] = true; - } - - function makeUntradable(uint8 season) public onlyGovernor { - require(!seasonTradabilityLocked[season]); - seasonTradable[season] = false; - } - - function makePermanantlyTradable(uint8 season) public onlyGovernor { - require(seasonTradable[season]); - seasonTradabilityLocked[season] = true; - } - - function isTradable(uint16 proto) public view returns (bool) { - return seasonTradable[protos[proto].season]; - } - - function nextSeason() public onlyGovernor { - //Seasons shouldn't go to 0 if there is more than the uint8 should hold, the governor should know this ¯\_(ツ)_/¯ -M - require(currentSeason <= 255); - - currentSeason++; - mythic.length = 0; - legendary.length = 0; - epic.length = 0; - rare.length = 0; - common.length = 0; - } - - enum Rarity { - Common, - Rare, - Epic, - Legendary, - Mythic - } - - uint8 constant SPELL = 1; - uint8 constant MINION = 2; - uint8 constant WEAPON = 3; - uint8 constant HERO = 4; - - struct ProtoCard { - bool exists; - uint8 god; - uint8 season; - uint8 cardType; - Rarity rarity; - uint8 mana; - uint8 attack; - uint8 health; - uint8 tribe; - } - - // there is a particular design decision driving this: - // need to be able to iterate over mythics only for card generation - // don't store 5 different arrays: have to use 2 ids - // better to bear this cost (2 bytes per proto card) - // rather than 1 byte per instance - - uint16 public protoCount; - - mapping(uint16 => ProtoCard) protos; - - uint16[] public mythic; - uint16[] public legendary; - uint16[] public epic; - uint16[] public rare; - uint16[] public common; - - function addProtos( - uint16[] memory externalIDs, uint8[] memory gods, Rarity[] memory rarities, uint8[] memory manas, uint8[] memory attacks, - uint8[] memory healths, uint8[] memory cardTypes, uint8[] memory tribes, bool[] memory packable - ) public onlyGovernor returns(uint16) { - - for (uint i = 0; i < externalIDs.length; i++) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: gods[i], - season: currentSeason, - cardType: cardTypes[i], - rarity: rarities[i], - mana: manas[i], - attack: attacks[i], - health: healths[i], - tribe: tribes[i] - }); - - _addProto(externalIDs[i], card, packable[i]); - } - - } - - function addProto( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 cardType, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: cardType, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function addWeapon( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 durability, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: WEAPON, - rarity: rarity, - mana: mana, - attack: attack, - health: durability, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addSpell(uint16 externalID, uint8 god, Rarity rarity, uint8 mana, bool packable) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: SPELL, - rarity: rarity, - mana: mana, - attack: 0, - health: 0, - tribe: 0 - }); - - _addProto(externalID, card, packable); - } - - function addMinion( - uint16 externalID, uint8 god, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe, bool packable - ) public onlyGovernor returns(uint16) { - - ProtoCard memory card = ProtoCard({ - exists: true, - god: god, - season: currentSeason, - cardType: MINION, - rarity: rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - - _addProto(externalID, card, packable); - } - - function _addProto(uint16 externalID, ProtoCard memory card, bool packable) internal { - - require(!protos[externalID].exists); - - card.exists = true; - - protos[externalID] = card; - - protoCount++; - - emit NewProtoCard( - externalID, currentSeason, card.god, - card.rarity, card.mana, card.attack, - card.health, card.cardType, card.tribe, packable - ); - - if (packable) { - Rarity rarity = card.rarity; - if (rarity == Rarity.Common) { - common.push(externalID); - } else if (rarity == Rarity.Rare) { - rare.push(externalID); - } else if (rarity == Rarity.Epic) { - epic.push(externalID); - } else if (rarity == Rarity.Legendary) { - legendary.push(externalID); - } else if (rarity == Rarity.Mythic) { - mythic.push(externalID); - } else { - require(false); - } - } - } - - function getProto(uint16 id) public view returns( - bool exists, uint8 god, uint8 season, uint8 cardType, Rarity rarity, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) { - ProtoCard memory proto = protos[id]; - return ( - proto.exists, - proto.god, - proto.season, - proto.cardType, - proto.rarity, - proto.mana, - proto.attack, - proto.health, - proto.tribe - ); - } - - function getRandomCard(Rarity rarity, uint16 random) public view returns (uint16) { - // modulo bias is fine - creates rarity tiers etc - // will obviously revert is there are no cards of that type: this is expected - should never happen - if (rarity == Rarity.Common) { - return common[random % common.length]; - } else if (rarity == Rarity.Rare) { - return rare[random % rare.length]; - } else if (rarity == Rarity.Epic) { - return epic[random % epic.length]; - } else if (rarity == Rarity.Legendary) { - return legendary[random % legendary.length]; - } else if (rarity == Rarity.Mythic) { - // make sure a mythic is available - uint16 id; - uint64 limit; - bool set; - for (uint i = 0; i < mythic.length; i++) { - id = mythic[(random + i) % mythic.length]; - (limit, set) = getLimit(id); - if (set && limit > 0){ - return id; - } - } - // if not, they get a legendary :( - return legendary[random % legendary.length]; - } - require(false); - return 0; - } - - // can never adjust tradable cards - // each season gets a 'balancing beta' - // totally immutable: season, rarity - function replaceProto( - uint16 index, uint8 god, uint8 cardType, uint8 mana, uint8 attack, uint8 health, uint8 tribe - ) public onlyGovernor { - ProtoCard memory pc = protos[index]; - require(!seasonTradable[pc.season]); - protos[index] = ProtoCard({ - exists: true, - god: god, - season: pc.season, - cardType: cardType, - rarity: pc.rarity, - mana: mana, - attack: attack, - health: health, - tribe: tribe - }); - } - -} - -contract ERC721Receiver { - /** - * @dev Magic value to be returned upon successful reception of an NFT - * Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`, - * which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - */ - bytes4 internal constant ERC721_RECEIVED = 0x150b7a02; - - /** - * @notice Handle the receipt of an NFT - * @dev The ERC721 smart contract calls this function on the recipient - * after a `safetransfer`. This function MAY throw to revert and reject the - * transfer. Return of other than the magic value MUST result in the - * transaction being reverted. - * Note: the contract address is always the message sender. - * @param _operator The address which called `safeTransferFrom` function - * @param _from The address which previously owned the token - * @param _tokenId The NFT identifier which is being transfered - * @param _data Additional data with no specified format - * @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - */ - function onERC721Received( - address _operator, - address _from, - uint256 _tokenId, - bytes memory _data - ) - public - returns(bytes4); -} - -library AddressUtils { - - /** - * Returns whether the target address is a contract - * @dev This function will return false if invoked during the constructor of a contract, - * as the code is not actually created until after the constructor finishes. - * @param addr address to check - * @return whether the target address is a contract - */ - function isContract(address addr) internal view returns (bool) { - uint256 size; - // XXX Currently there is no better way to check if there is a contract in an address - // than to check the size of the code at that address. - // See https://ethereum.stackexchange.com/a/14016/36603 - // for more details about how this works. - // TODO Check this again before the Serenity release, because all addresses will be - // contracts then. - // solium-disable-next-line security/no-inline-assembly - assembly { size := extcodesize(addr) } - return size > 0; - } - -} - -library SafeMath { - - /** - * @dev Multiplies two numbers, throws on overflow. - */ - function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { - // Gas optimization: this is cheaper than asserting 'a' not being zero, but the - // benefit is lost if 'b' is also tested. - // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 - if (a == 0) { - return 0; - } - - c = a * b; - assert(c / a == b); - return c; - } - - /** - * @dev Integer division of two numbers, truncating the quotient. - */ - function div(uint256 a, uint256 b) internal pure returns (uint256) { - // assert(b > 0); // Solidity automatically throws when dividing by 0 - // uint256 c = a / b; - // assert(a == b * c + a % b); // There is no case in which this doesn't hold - return a / b; - } - - /** - * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). - */ - function sub(uint256 a, uint256 b) internal pure returns (uint256) { - assert(b <= a); - return a - b; - } - - /** - * @dev Adds two numbers, throws on overflow. - */ - function add(uint256 a, uint256 b) internal pure returns (uint256 c) { - c = a + b; - assert(c >= a); - return c; - } -} - -contract ERC721BasicToken is CardProto, SupportsInterfaceWithLookup, ERC721Basic { - - bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd; - /* - * 0x80ac58cd === - * bytes4(keccak256('balanceOf(address)')) ^ - * bytes4(keccak256('ownerOf(uint256)')) ^ - * bytes4(keccak256('approve(address,uint256)')) ^ - * bytes4(keccak256('getApproved(uint256)')) ^ - * bytes4(keccak256('setApprovalForAll(address,bool)')) ^ - * bytes4(keccak256('isApprovedForAll(address,address)')) ^ - * bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^ - * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) - */ - - bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79; - /* - * 0x4f558e79 === - * bytes4(keccak256('exists(uint256)')) - */ - - using SafeMath for uint256; - using AddressUtils for address; - - // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` - // which can be also obtained as `ERC721Receiver(0).onERC721Received.selector` - bytes4 private constant ERC721_RECEIVED = 0x150b7a02; - - // Mapping from token ID to owner - mapping (uint256 => address) internal tokenOwner; - - // Mapping from token ID to approved address - mapping (uint256 => address) internal tokenApprovals; - - // Mapping from owner to number of owned token - // mapping (address => uint256) internal ownedTokensCount; - - // Mapping from owner to operator approvals - mapping (address => mapping (address => bool)) internal operatorApprovals; - - /** - * @dev Guarantees msg.sender is owner of the given token - * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender - */ - modifier onlyOwnerOf(uint256 _tokenId) { - require(ownerOf(_tokenId) == msg.sender); - _; - } - - /** - * @dev Checks msg.sender can transfer a token, by being owner, approved, or operator - * @param _tokenId uint256 ID of the token to validate - */ - modifier canTransfer(uint256 _tokenId) { - require(isApprovedOrOwner(msg.sender, _tokenId)); - _; - } - - constructor() - public - { - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721); - _registerInterface(InterfaceId_ERC721Exists); - } - - /** - * @dev Gets the balance of the specified address - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256); - - /** - * @dev Gets the owner of the specified token ID - * @param _tokenId uint256 ID of the token to query the owner of - * @return owner address currently marked as the owner of the given token ID - */ - function ownerOf(uint256 _tokenId) public view returns (address) { - address owner = tokenOwner[_tokenId]; - require(owner != address(0)); - return owner; - } - - /** - * @dev Returns whether the specified token exists - * @param _tokenId uint256 ID of the token to query the existence of - * @return whether the token exists - */ - function exists(uint256 _tokenId) public view returns (bool) { - address owner = tokenOwner[_tokenId]; - return owner != address(0); - } - - /** - * @dev Approves another address to transfer the given token ID - * The zero address indicates there is no approved address. - * There can only be one approved address per token at a given time. - * Can only be called by the token owner or an approved operator. - * @param _to address to be approved for the given token ID - * @param _tokenId uint256 ID of the token to be approved - */ - function approve(address _to, uint256 _tokenId) public { - address owner = ownerOf(_tokenId); - require(_to != owner); - require(msg.sender == owner || isApprovedForAll(owner, msg.sender)); - - tokenApprovals[_tokenId] = _to; - emit Approval(owner, _to, _tokenId); - } - - /** - * @dev Gets the approved address for a token ID, or zero if no address set - * @param _tokenId uint256 ID of the token to query the approval of - * @return address currently approved for the given token ID - */ - function getApproved(uint256 _tokenId) public view returns (address) { - return tokenApprovals[_tokenId]; - } - - /** - * @dev Sets or unsets the approval of a given operator - * An operator is allowed to transfer all tokens of the sender on their behalf - * @param _to operator address to set the approval - * @param _approved representing the status of the approval to be set - */ - function setApprovalForAll(address _to, bool _approved) public { - require(_to != msg.sender); - operatorApprovals[msg.sender][_to] = _approved; - emit ApprovalForAll(msg.sender, _to, _approved); - } - - /** - * @dev Tells whether an operator is approved by a given owner - * @param _owner owner address which you want to query the approval of - * @param _operator operator address which you want to query the approval of - * @return bool whether the given operator is approved by the given owner - */ - function isApprovedForAll( - address _owner, - address _operator - ) - public - view - returns (bool) - { - return operatorApprovals[_owner][_operator]; - } - - /** - * @dev Transfers the ownership of a given token ID to another address - * Usage of this method is discouraged, use `safeTransferFrom` whenever possible - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - require(_from != address(0)); - require(_to != address(0)); - - clearApproval(_from, _tokenId); - removeTokenFrom(_from, _tokenId); - addTokenTo(_to, _tokenId); - - emit Transfer(_from, _to, _tokenId); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId - ) - public - canTransfer(_tokenId) - { - // solium-disable-next-line arg-overflow - safeTransferFrom(_from, _to, _tokenId, ""); - } - - /** - * @dev Safely transfers the ownership of a given token ID to another address - * If the target address is a contract, it must implement `onERC721Received`, - * which is called upon a safe transfer, and return the magic value - * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, - * the transfer is reverted. - * Requires the msg sender to be the owner, approved, or operator - * @param _from current owner of the token - * @param _to address to receive the ownership of the given token ID - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes data to send along with a safe transfer check - */ - function safeTransferFrom( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - public - canTransfer(_tokenId) - { - transferFrom(_from, _to, _tokenId); - // solium-disable-next-line arg-overflow - require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data)); - } - - /** - * @dev Returns whether the given spender can transfer a given token ID - * @param _spender address of the spender to query - * @param _tokenId uint256 ID of the token to be transferred - * @return bool whether the msg.sender is approved for the given token ID, - * is an operator of the owner, or is the owner of the token - */ - function isApprovedOrOwner( - address _spender, - uint256 _tokenId - ) - internal - view - returns (bool) - { - address owner = ownerOf(_tokenId); - // Disable solium check because of - // https://github.com/duaraghav8/Solium/issues/175 - // solium-disable-next-line operator-whitespace - return ( - _spender == owner || - getApproved(_tokenId) == _spender || - isApprovedForAll(owner, _spender) - ); - } - - /** - * @dev Internal function to clear current approval of a given token ID - * Reverts if the given address is not indeed the owner of the token - * @param _owner owner of the token - * @param _tokenId uint256 ID of the token to be transferred - */ - function clearApproval(address _owner, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _owner); - if (tokenApprovals[_tokenId] != address(0)) { - tokenApprovals[_tokenId] = address(0); - } - } - - /** - * @dev Internal function to mint a new token - * Reverts if the given token ID already exists - * @param _to The address that will own the minted token - * @param _tokenId uint256 ID of the token to be minted by the msg.sender - */ - function _mint(address _to, uint256 _tokenId) internal { - require(_to != address(0)); - addNewTokenTo(_to, _tokenId); - emit Transfer(address(0), _to, _tokenId); - } - - - /** - * @dev Internal function to burn a specific token - * Reverts if the token does not exist - * @param _tokenId uint256 ID of the token being burned by the msg.sender - */ - function _burn(address _owner, uint256 _tokenId) internal { - clearApproval(_owner, _tokenId); - removeTokenFrom(_owner, _tokenId); - emit Transfer(_owner, address(0), _tokenId); - } - - function addNewTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - require(tokenOwner[_tokenId] == address(0)); - tokenOwner[_tokenId] = _to; - // ownedTokensCount[_to] = ownedTokensCount[_to].add(1); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - require(ownerOf(_tokenId) == _from); - // ownedTokensCount[_from] = ownedTokensCount[_from].sub(1); - tokenOwner[_tokenId] = address(0); - } - - /** - * @dev Internal function to invoke `onERC721Received` on a target address - * The call is not executed if the target address is not a contract - * @param _from address representing the previous owner of the given token ID - * @param _to target address that will receive the tokens - * @param _tokenId uint256 ID of the token to be transferred - * @param _data bytes optional data to send along with the call - * @return whether the call correctly returned the expected magic value - */ - function checkAndCallSafeTransfer( - address _from, - address _to, - uint256 _tokenId, - bytes memory _data - ) - internal - returns (bool) - { - if (!_to.isContract()) { - return true; - } - bytes4 retval = ERC721Receiver(_to).onERC721Received( - msg.sender, _from, _tokenId, _data); - return (retval == ERC721_RECEIVED); - } - -} - - - -contract ERC721Enumerable is ERC721Basic { - function totalSupply() public view returns (uint256); - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256 _tokenId); - - function tokenByIndex(uint256 _index) public view returns (uint256); -} - -contract ERC721Metadata is ERC721Basic { - function name() external view returns (string memory _name); - function symbol() external view returns (string memory _symbol); - function tokenURI(uint256 _tokenId) public view returns (string memory); -} - -contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata { - -} - - - - -library Strings { - - // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory ) { - bytes memory _ba = bytes(_a); - bytes memory _bb = bytes(_b); - bytes memory _bc = bytes(_c); - bytes memory _bd = bytes(_d); - bytes memory _be = bytes(_e); - string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); - bytes memory babcde = bytes(abcde); - uint k = 0; - for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; - for ( i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; - for ( i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; - for ( i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; - for ( i = 0; i < _be.length; i++) babcde[k++] = _be[i]; - return string(babcde); - } - - function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, _d, ""); - } - - function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory ) { - return strConcat(_a, _b, _c, "", ""); - } - - function strConcat(string memory _a, string memory _b) internal pure returns (string memory ) { - return strConcat(_a, _b, "", "", ""); - } - - function uint2str(uint i) internal pure returns (string memory ) { - if (i == 0) return "0"; - uint j = i; - uint len; - while (j != 0){ - len++; - j /= 10; - } - bytes memory bstr = new bytes(len); - uint k = len - 1; - while (i != 0){ - bstr[k--] = byte(uint8(48 + i % 10)); - i /= 10; - } - return string(bstr); - } -} - -contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 { - - using Strings for string; - - bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63; - /** - * 0x780e9d63 === - * bytes4(keccak256('totalSupply()')) ^ - * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^ - * bytes4(keccak256('tokenByIndex(uint256)')) - */ - - bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f; - /** - * 0x5b5e139f === - * bytes4(keccak256('name()')) ^ - * bytes4(keccak256('symbol()')) ^ - * bytes4(keccak256('tokenURI(uint256)')) - */ - - /*** Constants ***/ - // Configure these for your own deployment - string public constant NAME = "Gods Unchained"; - string public constant SYMBOL = "GODS"; - string public tokenMetadataBaseURI = "https://api.godsunchained.com/card/"; - - // Mapping from owner to list of owned token IDs - // EDITED: limit to 2^40 (around 1T) - mapping(address => uint40[]) internal ownedTokens; - - uint32[] ownedTokensIndex; - - /** - * @dev Constructor function - */ - constructor() public { - - // register the supported interfaces to conform to ERC721 via ERC165 - _registerInterface(InterfaceId_ERC721Enumerable); - _registerInterface(InterfaceId_ERC721Metadata); - } - - /** - * @dev Gets the token name - * @return string representing the token name - */ - function name() external view returns (string memory) { - return NAME; - } - - /** - * @dev Gets the token symbol - * @return string representing the token symbol - */ - function symbol() external view returns (string memory) { - return SYMBOL; - } - - /** - * @dev Returns an URI for a given token ID - * Throws if the token ID does not exist. May return an empty string. - * @param _tokenId uint256 ID of the token to query - */ - function tokenURI(uint256 _tokenId) public view returns (string memory) { - return Strings.strConcat( - tokenMetadataBaseURI, - Strings.uint2str(_tokenId) - ); - } - - /** - * @dev Gets the token ID at a given index of the tokens list of the requested owner - * @param _owner address owning the tokens list to be accessed - * @param _index uint256 representing the index to be accessed of the requested tokens list - * @return uint256 token ID at the given index of the tokens list owned by the requested address - */ - function tokenOfOwnerByIndex( - address _owner, - uint256 _index - ) - public - view - returns (uint256) - { - require(_index < balanceOf(_owner)); - return ownedTokens[_owner][_index]; - } - - /** - * @dev Gets the total amount of tokens stored by the contract - * @return uint256 representing the total amount of tokens - */ - function totalSupply() public view returns (uint256) { - return cards.length; - } - - /** - * @dev Gets the token ID at a given index of all the tokens in this contract - * Reverts if the index is greater or equal to the total number of tokens - * @param _index uint256 representing the index to be accessed of the tokens list - * @return uint256 token ID at the given index of the tokens list - */ - function tokenByIndex(uint256 _index) public view returns (uint256) { - require(_index < totalSupply()); - return _index; - } - - /** - * @dev Internal function to add a token ID to the list of a given address - * @param _to address representing the new owner of the given token ID - * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address - */ - function addTokenTo(address _to, uint256 _tokenId) internal { - super.addTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - - ownedTokensIndex[_tokenId] = uint32(length); - } - - // EDITED - // have to have in order to use array rather than mapping - function addNewTokenTo(address _to, uint256 _tokenId) internal { - super.addNewTokenTo(_to, _tokenId); - uint256 length = ownedTokens[_to].length; - // EDITED: prevent overflow - require(length == uint32(length)); - ownedTokens[_to].push(uint40(_tokenId)); - ownedTokensIndex.push(uint32(length)); - } - - /** - * @dev Internal function to remove a token ID from the list of a given address - * @param _from address representing the previous owner of the given token ID - * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address - */ - function removeTokenFrom(address _from, uint256 _tokenId) internal { - super.removeTokenFrom(_from, _tokenId); - - uint32 tokenIndex = ownedTokensIndex[_tokenId]; - uint256 lastTokenIndex = ownedTokens[_from].length.sub(1); - uint40 lastToken = ownedTokens[_from][lastTokenIndex]; - - ownedTokens[_from][tokenIndex] = lastToken; - ownedTokens[_from][lastTokenIndex] = 0; - // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to - // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping - // the lastToken to the first position, and then dropping the element placed in the last position of the list - - ownedTokens[_from].length--; - ownedTokensIndex[_tokenId] = 0; - ownedTokensIndex[lastToken] = tokenIndex; - } - - /** - * @dev Gets the balance of the specified address - overrriden from previous to save gas - * @param _owner address to query the balance of - * @return uint256 representing the amount owned by the passed address - */ - function balanceOf(address _owner) public view returns (uint256) { - return ownedTokens[_owner].length; - } - -} - -contract CardOwnershipTwo is ERC721Token { - - uint public burnCount; - - function getActiveCards() public view returns (uint) { - return totalSupply() - burnCount; - } - - /** - * @param to : the address to which the card will be transferred - * @param id : the id of the card to be transferred - */ - function transfer(address to, uint id) public payable onlyOwnerOf(id) { - require(isTradable(cards[id].proto)); - require(to != address(0)); - - _transfer(msg.sender, to, id); - } - - function _transfer(address from, address to, uint id) internal { - - clearApproval(from, id); - - removeTokenFrom(from, id); - - addTokenTo(to, id); - - emit Transfer(from, to, id); - } - - /** - * @param to : the address to which the cards will be transferred - * @param ids : the ids of the cards to be transferred - */ - function transferAll(address to, uint[] memory ids) public payable { - for (uint i = 0; i < ids.length; i++) { - transfer(to, ids[i]); - } - } - - /** - * @param proposed : the claimed owner of the cards - * @param ids : the ids of the cards to check - * @return whether proposed owns all of the cards - */ - function ownsAll(address proposed, uint[] memory ids) public view returns (bool) { - require(ids.length > 0); - for (uint i = 0; i < ids.length; i++) { - if (!owns(proposed, ids[i])) { - return false; - } - } - return true; - } - - /** - * @param proposed : the claimed owner of the card - * @param id : the id of the card to check - * @return whether proposed owns the card - */ - function owns(address proposed, uint id) public view returns (bool) { - return ownerOf(id) == proposed; - } - - function burn(uint id) public onlyOwnerOf(id) { - burnCount++; - _burn(msg.sender, id); - } - - /** - * @param ids : the indices of the tokens to burn - */ - function burnAll(uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++){ - burn(ids[i]); - } - } - - /** - * @param to : the address to approve for transfer - * @param id : the index of the card to be approved - */ - function approve(address to, uint id) public { - require(isTradable(cards[id].proto)); - super.approve(to, id); - } - - /** - * @param to : the address to approve for transfer - * @param ids : the indices of the cards to be approved - */ - function approveAll(address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - approve(to, ids[i]); - } - } - - /** - * @param to : the address to which the token should be transferred - * @param id : the index of the token to transfer - */ - function transferFrom(address from, address to, uint id) public { - require(isTradable(cards[id].proto)); - super.transferFrom(from, to, id); - } - - /** - * @param to : the address to which the tokens should be transferred - * @param ids : the indices of the tokens to transfer - */ - function transferAllFrom(address from, address to, uint[] memory ids) public { - for (uint i = 0; i < ids.length; i++) { - transferFrom(from, to, ids[i]); - } - } - - /** - * @return the number of cards which have been burned - */ - function getBurnCount() public view returns (uint) { - return burnCount; - } - -} - -contract CardIntegrationTwo is CardOwnershipTwo { - - address[] public packs; - - event CardCreated(uint indexed id, uint16 proto, uint16 purity, address owner); - - function addPack(address approved) public onlyGovernor { - packs.push(approved); - } - - modifier onlyApprovedPacks { - require(_isApprovedPack()); - _; - } - - function _isApprovedPack() private view returns (bool) { - for (uint i = 0; i < packs.length; i++) { - if (msg.sender == address(packs[i])) { - return true; - } - } - return false; - } - - function createCard(address owner, uint16 proto, uint16 purity) public whenNotPaused onlyApprovedPacks returns (uint) { - ProtoCard memory card = protos[proto]; - require(card.season == currentSeason); - if (card.rarity == Rarity.Mythic) { - uint64 limit; - bool exists; - (limit, exists) = getLimit(proto); - require(!exists || limit > 0); - limits[proto].limit--; - } - return _createCard(owner, proto, purity); - } - - function _createCard(address owner, uint16 proto, uint16 purity) internal returns (uint) { - Card memory card = Card({ - proto: proto, - purity: purity - }); - - uint id = cards.push(card) - 1; - - _mint(owner, id); - - emit CardCreated(id, proto, purity, owner); - - return id; - } - - /*function combineCards(uint[] ids) public whenNotPaused { - require(ids.length == 5); - require(ownsAll(msg.sender, ids)); - Card memory first = cards[ids[0]]; - uint16 proto = first.proto; - uint8 shine = _getShine(first.purity); - require(shine < shineLimit); - uint16 puritySum = first.purity - (shine * 1000); - burn(ids[0]); - for (uint i = 1; i < ids.length; i++) { - Card memory next = cards[ids[i]]; - require(next.proto == proto); - require(_getShine(next.purity) == shine); - puritySum += (next.purity - (shine * 1000)); - burn(ids[i]); - } - uint16 newPurity = uint16(((shine + 1) * 1000) + (puritySum / ids.length)); - _createCard(msg.sender, proto, newPurity); - }*/ - - - // PURITY NOTES - // currently, we only - // however, to protect rarity, you'll never be abl - // this is enforced by the restriction in the create-card function - // no cards above this point can be found in packs - - - -} - -contract PreviousInterface { - - function ownerOf(uint id) public view returns (address); - - function getCard(uint id) public view returns (uint16, uint16); - - function totalSupply() public view returns (uint); - - function burnCount() public view returns (uint); - -} - -contract CardMigration is CardIntegrationTwo { - - constructor(PreviousInterface previous) public { - old = previous; - } - - // use interface to lower deployment cost - PreviousInterface old; - - mapping(uint => bool) public migrated; - - function migrate(uint id) public { - - require(!migrated[id]); - - migrated[id] = true; - - address owner = old.ownerOf(id); - - uint16 proto; - uint16 purity; - - (proto, purity) = old.getCard(id); - - _createCard(owner, proto, purity); - } - - function migrateAll(uint[] memory ids) public { - - for (uint i = 0; i < ids.length; i++){ - migrate(ids[i]); - } - - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario008.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario008.sol deleted file mode 100644 index 7336976e2b6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario008.sol +++ /dev/null @@ -1,2016 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - function Ownable() { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(0, _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string) public view returns (bytes32[4] buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is KittyBase, ERC721 { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) { - var outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { - require(erc721Metadata != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.send(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, this, _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused returns (bool) { - paused = true; - Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused returns (bool) { - paused = false; - Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - function ClockAuction(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address nftAddress = address(nonFungibleContract); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(this.balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - function SiringClockAuction(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - function SaleClockAuction(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, saleAuction); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, siringAuction); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, saleAuction); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(this) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - function KittyCore() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - function unpause() public onlyCEO whenPaused { - require(saleAuction != address(0)); - require(siringAuction != address(0)); - require(geneScience != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = this.balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.send(balance - subtractFees); - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario009.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario009.sol deleted file mode 100644 index 215c671848e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario009.sol +++ /dev/null @@ -1,51 +0,0 @@ -//pragma solidity ^0.4.0; - -library Set { - // We define a new struct datatype that will be used to - // hold its data in the calling contract. - struct Data { mapping(uint => bool) flags; } - - // Note that the first parameter is of type "storage - // reference" and thus only its storage address and not - // its contents is passed as part of the call. This is a - // special feature of library functions. It is idiomatic - // to call the first parameter 'self', if the function can - // be seen as a method of that object. - function insert(Data storage self, uint value) - returns (bool) - { - if (self.flags[value]) - return false; // already there - self.flags[value] = true; - return true; - } - - function remove(Data storage self, uint value) - returns (bool) - { - if (!self.flags[value]) - return false; // not there - self.flags[value] = false; - return true; - } - - function contains(Data storage self, uint value) - returns (bool) - { - return self.flags[value]; - } -} - - -contract C { - Set.Data knownValues; - - function register(uint value) { - // The library functions can be called without a - // specific instance of the library, since the - // "instance" will be the current contract. - if (!Set.insert(knownValues, value)) - throw; - } - // In this contract, we can also directly access knownValues.flags, if we want. -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario010.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario010.sol deleted file mode 100644 index f665ea9686e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario010.sol +++ /dev/null @@ -1,107 +0,0 @@ -//pragma solidity ^0.4.11; - -contract TRON_ERC721 { - //name - function name() view public returns (string memory name){ - return "Tron ERC721 Token"; - } - //symbol - function symbol() view public returns (string memory symbol){ - return "T721T"; - } - - //totalSupply - - function totalSupply() view public returns (uint256 supply){ - uint256 totalSupply = 1000000000000; - return totalSupply; - } - - mapping(address => uint) private balances; - function balanceOf(address _owner) view public returns (uint balance) - { - return balances[_owner]; - } - - - mapping(uint256 => address) private tokenOwners; - mapping(uint256 => bool) private tokenExists; - function ownerOf(uint256 _tokenId) view public returns (address owner) { - require(tokenExists[_tokenId]); - return tokenOwners[_tokenId]; - } - - - mapping(address => mapping (address => uint256)) allowed; - function approve(address _to, uint256 _tokenId) public{ - require(msg.sender == ownerOf(_tokenId)); - require(msg.sender != _to); - allowed[msg.sender][_to] = _tokenId; - emit Approval(msg.sender, _to, _tokenId); - } - - - function takeOwnership(uint256 _tokenId) public { - require(tokenExists[_tokenId]); - address oldOwner = ownerOf(_tokenId); - address newOwner = msg.sender; - require(newOwner != oldOwner); - require(allowed[oldOwner][newOwner] == _tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - mapping(address => mapping(uint256 => uint256)) private ownerTokens; - function removeFromTokenList(address owner, uint256 _tokenId) private { - for(uint256 i = 0;ownerTokens[owner][i] != _tokenId;i++){ - ownerTokens[owner][i] = 0; - } - } - - function transfer(address _to, uint256 _tokenId) public{ - address currentOwner = msg.sender; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - function transferFrom(address _from,address _to, uint256 _tokenId) public{ - address currentOwner = _from; - address newOwner = _to; - require(tokenExists[_tokenId]); - require(currentOwner == ownerOf(_tokenId)); - require(currentOwner != newOwner); - require(newOwner != address(0)); - address oldOwner =currentOwner; - removeFromTokenList(oldOwner,_tokenId); - balances[oldOwner] -= 1; - tokenOwners[_tokenId] = newOwner; - balances[newOwner] += 1; - emit Transfer(oldOwner, newOwner, _tokenId); - } - - - function tokenOfOwnerByIndex(address _owner, uint256 _index) view public returns (uint tokenId){ - return ownerTokens[_owner][_index]; - } - - - mapping(uint256 => string) tokenLinks; - function tokenMetadata(uint256 _tokenId) view public returns (string memory infoUrl) { - return tokenLinks[_tokenId]; - } - // Events - event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); - event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario011.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario011.sol deleted file mode 100644 index 4d1e9c1ba12..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario011.sol +++ /dev/null @@ -1,2050 +0,0 @@ -//pragma solidity ^0.4.11; - - -/** - * @title Ownable - * @dev The Ownable contract has an owner address, and provides basic authorization control - * functions, this simplifies the implementation of "user permissions". - */ -contract Ownable { - address public owner; - - - /** - * @dev The Ownable constructor sets the original `owner` of the contract to the sender - * account. - */ - constructor() public { - owner = msg.sender; - } - - - /** - * @dev Throws if called by any account other than the owner. - */ - modifier onlyOwner() { - require(msg.sender == owner); - _; - } - - - /** - * @dev Allows the current owner to transfer control of the contract to a newOwner. - * @param newOwner The address to transfer ownership to. - */ - function transferOwnership(address newOwner) public onlyOwner { - if (newOwner != address(0)) { - owner = newOwner; - } - } - -} - - - - -/// @title A facet of KittyCore that manages special access privileges. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyAccessControl { - // This facet controls access control for CryptoKitties. There are four roles managed here: - // - // - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart - // contracts. It is also the only role that can unpause the smart contract. It is initially - // set to the address that created the smart contract in the KittyCore constructor. - // - // - The CFO: The CFO can withdraw funds from KittyCore and its auction contracts. - // - // - The COO: The COO can release gen0 kitties to auction, and mint promo cats. - // - // It should be noted that these roles are distinct without overlap in their access abilities, the - // abilities listed for each role above are exhaustive. In particular, while the CEO can assign any - // address to any role, the CEO address itself doesn't have the ability to act in those roles. This - // restriction is intentional so that we aren't tempted to use the CEO address frequently out of - // convenience. The less we use an address, the less likely it is that we somehow compromise the - // account. - - /// @dev Emited when contract is upgraded - See README.md for updgrade plan - event ContractUpgrade(address newContract); - - // The addresses of the accounts (or contracts) that can execute actions within each roles. - address public ceoAddress; - address public cfoAddress; - address public cooAddress; - - // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked - bool public paused = false; - - /// @dev Access modifier for CEO-only functionality - modifier onlyCEO() { - require(msg.sender == ceoAddress); - _; - } - - /// @dev Access modifier for CFO-only functionality - modifier onlyCFO() { - require(msg.sender == cfoAddress); - _; - } - - /// @dev Access modifier for COO-only functionality - modifier onlyCOO() { - require(msg.sender == cooAddress); - _; - } - - modifier onlyCLevel() { - require( - msg.sender == cooAddress || - msg.sender == ceoAddress || - msg.sender == cfoAddress - ); - _; - } - - /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. - /// @param _newCEO The address of the new CEO - function setCEO(address _newCEO) external onlyCEO { - require(_newCEO != address(0)); - - ceoAddress = _newCEO; - } - - /// @dev Assigns a new address to act as the CFO. Only available to the current CEO. - /// @param _newCFO The address of the new CFO - function setCFO(address _newCFO) external onlyCEO { - require(_newCFO != address(0)); - - cfoAddress = _newCFO; - } - - /// @dev Assigns a new address to act as the COO. Only available to the current CEO. - /// @param _newCOO The address of the new COO - function setCOO(address _newCOO) external onlyCEO { - require(_newCOO != address(0)); - - cooAddress = _newCOO; - } - - /*** Pausable functionality adapted from OpenZeppelin ***/ - - /// @dev Modifier to allow actions only when the contract IS NOT paused - modifier whenNotPaused() { - require(!paused); - _; - } - - /// @dev Modifier to allow actions only when the contract IS paused - modifier whenPaused { - require(paused); - _; - } - - /// @dev Called by any "C-level" role to pause the contract. Used only when - /// a bug or exploit is detected and we need to limit damage. - function pause() external onlyCLevel whenNotPaused { - paused = true; - } - - /// @dev Unpauses the smart contract. Can only be called by the CEO, since - /// one reason we may pause the contract is when CFO or COO accounts are - /// compromised. - /// @notice This is public rather than external so it can be called by - /// derived contracts. - function unpause() public onlyCEO whenPaused { - // can't unpause if contract was upgraded - paused = false; - } -} - - - - -/// @title Base contract for CryptoKitties. Holds all common structs, events and base variables. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBase is KittyAccessControl { - /*** EVENTS ***/ - - /// @dev The Birth event is fired whenever a new kitten comes into existence. This obviously - /// includes any time a cat is created through the giveBirth method, but it is also called - /// when a new gen0 cat is created. - event Birth(address owner, uint256 kittyId, uint256 matronId, uint256 sireId, uint256 genes); - - /// @dev Transfer event as defined in current draft of ERC721. Emitted every time a kitten - /// ownership is assigned, including births. - event Transfer(address from, address to, uint256 tokenId); - - /*** DATA TYPES ***/ - - /// @dev The main Kitty struct. Every cat in CryptoKitties is represented by a copy - /// of this structure, so great care was taken to ensure that it fits neatly into - /// exactly two 256-bit words. Note that the order of the members in this structure - /// is important because of the byte-packing rules used by Ethereum. - /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html - struct Kitty { - // The Kitty's genetic code is packed into these 256-bits, the format is - // sooper-sekret! A cat's genes never change. - uint256 genes; - - // The timestamp from the block when this cat came into existence. - uint64 birthTime; - - // The minimum timestamp after which this cat can engage in breeding - // activities again. This same timestamp is used for the pregnancy - // timer (for matrons) as well as the siring cooldown. - uint64 cooldownEndBlock; - - // The ID of the parents of this kitty, set to 0 for gen0 cats. - // Note that using 32-bit unsigned integers limits us to a "mere" - // 4 billion cats. This number might seem small until you realize - // that Ethereum currently has a limit of about 500 million - // transactions per year! So, this definitely won't be a problem - // for several years (even as Ethereum learns to scale). - uint32 matronId; - uint32 sireId; - - // Set to the ID of the sire cat for matrons that are pregnant, - // zero otherwise. A non-zero value here is how we know a cat - // is pregnant. Used to retrieve the genetic material for the new - // kitten when the birth transpires. - uint32 siringWithId; - - // Set to the index in the cooldown array (see below) that represents - // the current cooldown duration for this Kitty. This starts at zero - // for gen0 cats, and is initialized to floor(generation/2) for others. - // Incremented by one for each successful breeding action, regardless - // of whether this cat is acting as matron or sire. - uint16 cooldownIndex; - - // The "generation number" of this cat. Cats minted by the CK contract - // for sale are called "gen0" and have a generation number of 0. The - // generation number of all other cats is the larger of the two generation - // numbers of their parents, plus one. - // (i.e. max(matron.generation, sire.generation) + 1) - uint16 generation; - } - - /*** CONSTANTS ***/ - - /// @dev A lookup table indicating the cooldown duration after any successful - /// breeding action, called "pregnancy time" for matrons and "siring cooldown" - /// for sires. Designed such that the cooldown roughly doubles each time a cat - /// is bred, encouraging owners not to just keep breeding the same cat over - /// and over again. Caps out at one week (a cat can breed an unbounded number - /// of times, and the maximum cooldown is always seven days). - uint32[14] public cooldowns = [ - uint32(1 minutes), - uint32(2 minutes), - uint32(5 minutes), - uint32(10 minutes), - uint32(30 minutes), - uint32(1 hours), - uint32(2 hours), - uint32(4 hours), - uint32(8 hours), - uint32(16 hours), - uint32(1 days), - uint32(2 days), - uint32(4 days), - uint32(7 days) - ]; - - // An approximation of currently how many seconds are in between blocks. - uint256 public secondsPerBlock = 15; - - /*** STORAGE ***/ - - /// @dev An array containing the Kitty struct for all Kitties in existence. The ID - /// of each cat is actually an index into this array. Note that ID 0 is a negacat, - /// the unKitty, the mythical beast that is the parent of all gen0 cats. A bizarre - /// creature that is both matron and sire... to itself! Has an invalid genetic code. - /// In other words, cat ID 0 is invalid... ;-) - Kitty[] kitties; - - /// @dev A mapping from cat IDs to the address that owns them. All cats have - /// some valid owner address, even gen0 cats are created with a non-zero owner. - mapping (uint256 => address) public kittyIndexToOwner; - - // @dev A mapping from owner address to count of tokens that address owns. - // Used internally inside balanceOf() to resolve ownership count. - mapping (address => uint256) ownershipTokenCount; - - /// @dev A mapping from KittyIDs to an address that has been approved to call - /// transferFrom(). Each Kitty can only have one approved address for transfer - /// at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public kittyIndexToApproved; - - /// @dev A mapping from KittyIDs to an address that has been approved to use - /// this Kitty for siring via breedWith(). Each Kitty can only have one approved - /// address for siring at any time. A zero value means no approval is outstanding. - mapping (uint256 => address) public sireAllowedToAddress; - - /// @dev The address of the ClockAuction contract that handles sales of Kitties. This - /// same contract handles both peer-to-peer sales as well as the gen0 sales which are - /// initiated every 15 minutes. - SaleClockAuction public saleAuction; - - /// @dev The address of a custom ClockAuction subclassed contract that handles siring - /// auctions. Needs to be separate from saleAuction because the actions taken on success - /// after a sales and siring auction are quite different. - SiringClockAuction public siringAuction; - - /// @dev Assigns ownership of a specific Kitty to an address. - function _transfer(address _from, address _to, uint256 _tokenId) internal { - // Since the number of kittens is capped to 2^32 we can't overflow this - ownershipTokenCount[_to]++; - // transfer ownership - kittyIndexToOwner[_tokenId] = _to; - // When creating new kittens _from is 0x0, but we can't account that address. - if (_from != address(0)) { - ownershipTokenCount[_from]--; - // once the kitten is transferred also clear sire allowances - delete sireAllowedToAddress[_tokenId]; - // clear any previously approved ownership exchange - delete kittyIndexToApproved[_tokenId]; - } - // Emit the transfer event. - emit Transfer(_from, _to, _tokenId); - } - - /// @dev An internal method that creates a new kitty and stores it. This - /// method doesn't do any checking and should only be called when the - /// input data is known to be valid. Will generate both a Birth event - /// and a Transfer event. - /// @param _matronId The kitty ID of the matron of this cat (zero for gen0) - /// @param _sireId The kitty ID of the sire of this cat (zero for gen0) - /// @param _generation The generation number of this cat, must be computed by caller. - /// @param _genes The kitty's genetic code. - /// @param _owner The inital owner of this cat, must be non-zero (except for the unKitty, ID 0) - function _createKitty( - uint256 _matronId, - uint256 _sireId, - uint256 _generation, - uint256 _genes, - address _owner - ) - internal - returns (uint) - { - // These requires are not strictly necessary, our calling code should make - // sure that these conditions are never broken. However! _createKitty() is already - // an expensive call (for storage), and it doesn't hurt to be especially careful - // to ensure our data structures are always valid. - require(_matronId == uint256(uint32(_matronId))); - require(_sireId == uint256(uint32(_sireId))); - require(_generation == uint256(uint16(_generation))); - - // New kitty starts with the same cooldown as parent gen/2 - uint16 cooldownIndex = uint16(_generation / 2); - if (cooldownIndex > 13) { - cooldownIndex = 13; - } - - Kitty memory _kitty = Kitty({ - genes: _genes, - birthTime: uint64(now), - cooldownEndBlock: 0, - matronId: uint32(_matronId), - sireId: uint32(_sireId), - siringWithId: 0, - cooldownIndex: cooldownIndex, - generation: uint16(_generation) - }); - uint256 newKittenId = kitties.push(_kitty) - 1; - - // It's probably never going to happen, 4 billion cats is A LOT, but - // let's just be 100% sure we never let this happen. - require(newKittenId == uint256(uint32(newKittenId))); - - // emit the birth event - emit Birth( - _owner, - newKittenId, - uint256(_kitty.matronId), - uint256(_kitty.sireId), - _kitty.genes - ); - - // This will assign ownership, and also emit the Transfer event as - // per ERC721 draft - _transfer(address(0), _owner, newKittenId); - - return newKittenId; - } - - // Any C-level can fix how many seconds per blocks are currently observed. - function setSecondsPerBlock(uint256 secs) external onlyCLevel { - require(secs < cooldowns[0]); - secondsPerBlock = secs; - } -} - - -/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens -/// @author Dieter Shirley (https://github.com/dete) -contract ERC721 { - // Required methods - function totalSupply() public view returns (uint256 total); - function balanceOf(address _owner) public view returns (uint256 balance); - function ownerOf(uint256 _tokenId) external view returns (address owner); - function approve(address _to, uint256 _tokenId) external; - function transfer(address _to, uint256 _tokenId) external; - function transferFrom(address _from, address _to, uint256 _tokenId) external; - - // Events - event Transfer(address from, address to, uint256 tokenId); - event Approval(address owner, address approved, uint256 tokenId); - - // Optional - // function name() public view returns (string name); - // function symbol() public view returns (string symbol); - // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); - // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); - - // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) - function supportsInterface(bytes4 _interfaceID) external view returns (bool); -} - - -/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev Ref: https://github.com/ethereum/EIPs/issues/721 -/// See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyOwnership is ERC721, KittyBase { - - /// @notice Name and symbol of the non fungible token, as defined in ERC721. - string public constant name = "CryptoKitties"; - string public constant symbol = "CK"; - - // The contract that will return kitty metadata - ERC721Metadata public erc721Metadata; - - bytes4 constant InterfaceSignature_ERC165 = - bytes4(keccak256('supportsInterface(bytes4)')); - - bytes4 constant InterfaceSignature_ERC721 = - bytes4(keccak256('name()')) ^ - bytes4(keccak256('symbol()')) ^ - bytes4(keccak256('totalSupply()')) ^ - bytes4(keccak256('balanceOf(address)')) ^ - bytes4(keccak256('ownerOf(uint256)')) ^ - bytes4(keccak256('approve(address,uint256)')) ^ - bytes4(keccak256('transfer(address,uint256)')) ^ - bytes4(keccak256('transferFrom(address,address,uint256)')) ^ - bytes4(keccak256('tokensOfOwner(address)')) ^ - bytes4(keccak256('tokenMetadata(uint256,string)')); - - /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). - /// Returns true for any standardized interfaces implemented by this contract. We implement - /// ERC-165 (obviously!) and ERC-721. - function supportsInterface(bytes4 _interfaceID) external view returns (bool) - { - // DEBUG ONLY - //require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d)); - - return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); - } - - /// @dev Set the address of the sibling contract that tracks metadata. - /// CEO only. - function setMetadataAddress(address _contractAddress) public onlyCEO { - erc721Metadata = ERC721Metadata(_contractAddress); - } - - // Internal utility functions: These functions all assume that their input arguments - // are valid. We leave it to public methods to sanitize their inputs and follow - // the required logic. - - /// @dev Checks if a given address is the current owner of a particular Kitty. - /// @param _claimant the address we are validating against. - /// @param _tokenId kitten id, only valid when > 0 - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToOwner[_tokenId] == _claimant; - } - - /// @dev Checks if a given address currently has transferApproval for a particular Kitty. - /// @param _claimant the address we are confirming kitten is approved for. - /// @param _tokenId kitten id, only valid when > 0 - function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { - return kittyIndexToApproved[_tokenId] == _claimant; - } - - /// @dev Marks an address as being approved for transferFrom(), overwriting any previous - /// approval. Setting _approved to address(0) clears all transfer approval. - /// NOTE: _approve() does NOT send the Approval event. This is intentional because - /// _approve() and transferFrom() are used together for putting Kitties on auction, and - /// there is no value in spamming the log with Approval events in that case. - function _approve(uint256 _tokenId, address _approved) internal { - kittyIndexToApproved[_tokenId] = _approved; - } - - /// @notice Returns the number of Kitties owned by a specific address. - /// @param _owner The owner address to check. - /// @dev Required for ERC-721 compliance - function balanceOf(address _owner) public view returns (uint256 count) { - return ownershipTokenCount[_owner]; - } - - /// @notice Transfers a Kitty to another address. If transferring to a smart - /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or - /// CryptoKitties specifically) or your Kitty may be lost forever. Seriously. - /// @param _to The address of the recipient, can be a user or contract. - /// @param _tokenId The ID of the Kitty to transfer. - /// @dev Required for ERC-721 compliance. - function transfer( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Disallow transfers to the auction contracts to prevent accidental - // misuse. Auction contracts should only take ownership of kitties - // through the allow + transferFrom flow. - require(_to != address(saleAuction)); - require(_to != address(siringAuction)); - - // You can only send your own cat. - require(_owns(msg.sender, _tokenId)); - - // Reassign ownership, clear pending approvals, emit Transfer event. - _transfer(msg.sender, _to, _tokenId); - } - - /// @notice Grant another address the right to transfer a specific Kitty via - /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. - /// @param _to The address to be granted transfer approval. Pass address(0) to - /// clear all approvals. - /// @param _tokenId The ID of the Kitty that can be transferred if this call succeeds. - /// @dev Required for ERC-721 compliance. - function approve( - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Only an owner can grant transfer approval. - require(_owns(msg.sender, _tokenId)); - - // Register the approval (replacing any previous approval). - _approve(_tokenId, _to); - - // Emit approval event. - emit Approval(msg.sender, _to, _tokenId); - } - - /// @notice Transfer a Kitty owned by another address, for which the calling address - /// has previously been granted transfer approval by the owner. - /// @param _from The address that owns the Kitty to be transfered. - /// @param _to The address that should take ownership of the Kitty. Can be any address, - /// including the caller. - /// @param _tokenId The ID of the Kitty to be transferred. - /// @dev Required for ERC-721 compliance. - function transferFrom( - address _from, - address _to, - uint256 _tokenId - ) - external - whenNotPaused - { - // Safety check to prevent against an unexpected 0x0 default. - require(_to != address(0)); - // Disallow transfers to this contract to prevent accidental misuse. - // The contract should never own any kitties (except very briefly - // after a gen0 cat is created and before it goes on auction). - require(_to != address(this)); - // Check for approval and valid ownership - require(_approvedFor(msg.sender, _tokenId)); - require(_owns(_from, _tokenId)); - - // Reassign ownership (also clears pending approvals and emits Transfer event). - _transfer(_from, _to, _tokenId); - } - - /// @notice Returns the total number of Kitties currently in existence. - /// @dev Required for ERC-721 compliance. - function totalSupply() public view returns (uint) { - return kitties.length - 1; - } - - /// @notice Returns the address currently assigned ownership of a given Kitty. - /// @dev Required for ERC-721 compliance. - function ownerOf(uint256 _tokenId) - external - view - returns (address owner) - { - owner = kittyIndexToOwner[_tokenId]; - - require(owner != address(0)); - } - - /// @notice Returns a list of all Kitty IDs assigned to an address. - /// @param _owner The owner whose Kitties we are interested in. - /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly - /// expensive (it walks the entire Kitty array looking for cats belonging to owner), - /// but it also returns a dynamic array, which is only supported for web3 calls, and - /// not contract-to-contract calls. - function tokensOfOwner(address _owner) external view returns(uint256[] memory ownerTokens) { - uint256 tokenCount = balanceOf(_owner); - - if (tokenCount == 0) { - // Return an empty array - return new uint256[](0); - } else { - uint256[] memory result = new uint256[](tokenCount); - uint256 totalCats = totalSupply(); - uint256 resultIndex = 0; - - // We count on the fact that all cats have IDs starting at 1 and increasing - // sequentially up to the totalCat count. - uint256 catId; - - for (catId = 1; catId <= totalCats; catId++) { - if (kittyIndexToOwner[catId] == _owner) { - result[resultIndex] = catId; - resultIndex++; - } - } - - return result; - } - } - - /// @dev Adapted from memcpy() by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _memcpy(uint _dest, uint _src, uint _len) private view { - // Copy word-length chunks while possible - for(; _len >= 32; _len -= 32) { - assembly { - mstore(_dest, mload(_src)) - } - _dest += 32; - _src += 32; - } - - // Copy remaining bytes - uint256 mask = 256 ** (32 - _len) - 1; - assembly { - let srcpart := and(mload(_src), not(mask)) - let destpart := and(mload(_dest), mask) - mstore(_dest, or(destpart, srcpart)) - } - } - - /// @dev Adapted from toString(slice) by @arachnid (Nick Johnson ) - /// This method is licenced under the Apache License. - /// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol - function _toString(bytes32[4] memory _rawBytes, uint256 _stringLength) private view returns (string memory) { - string memory outputString = new string(_stringLength); - uint256 outputPtr; - uint256 bytesPtr; - - assembly { - outputPtr := add(outputString, 32) - bytesPtr := _rawBytes - } - - _memcpy(outputPtr, bytesPtr, _stringLength); - - return outputString; - } - - /// @notice Returns a URI pointing to a metadata package for this token conforming to - /// ERC-721 (https://github.com/ethereum/EIPs/issues/721) - /// @param _tokenId The ID number of the Kitty whose metadata should be returned. - function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) { - require( address(erc721Metadata) != address(0)); - bytes32[4] memory buffer; - uint256 count; - (buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport); - - return _toString(buffer, count); - } -} - - - - -/// @title A facet of KittyCore that manages Kitty siring, gestation, and birth. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev See the KittyCore contract documentation to understand how the various contract facets are arranged. -contract KittyBreeding is KittyOwnership { - - /// @dev The Pregnant event is fired when two cats successfully breed and the pregnancy - /// timer begins for the matron. - event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 cooldownEndBlock); - - /// @notice The minimum payment required to use breedWithAuto(). This fee goes towards - /// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by - /// the COO role as the gas price changes. - uint256 public autoBirthFee = 2 sun; - - // Keeps track of number of pregnant kitties. - uint256 public pregnantKitties; - - /// @dev The address of the sibling contract that is used to implement the sooper-sekret - /// genetic combination algorithm. - GeneScienceInterface public geneScience; - - /// @dev Update the address of the genetic contract, can only be called by the CEO. - /// @param _address An address of a GeneScience contract instance to be used from this point forward. - function setGeneScienceAddress(address _address) external onlyCEO { - GeneScienceInterface candidateContract = GeneScienceInterface(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isGeneScience()); - - // Set the new contract address - geneScience = candidateContract; - } - - /// @dev Checks that a given kitten is able to breed. Requires that the - /// current cooldown is finished (for sires) and also checks that there is - /// no pending pregnancy. - function _isReadyToBreed(Kitty memory _kit) internal view returns (bool) { - // In addition to checking the cooldownEndBlock, we also need to check to see if - // the cat has a pending birth; there can be some period of time between the end - // of the pregnacy timer and the birth event. - return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number)); - } - - /// @dev Check if a sire has authorized breeding with this matron. True if both sire - /// and matron have the same owner, or if the sire has given siring permission to - /// the matron's owner (via approveSiring()). - function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) { - address matronOwner = kittyIndexToOwner[_matronId]; - address sireOwner = kittyIndexToOwner[_sireId]; - - // Siring is okay if they have same owner, or if the matron's owner was given - // permission to breed with this sire. - return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner); - } - - /// @dev Set the cooldownEndTime for the given Kitty, based on its current cooldownIndex. - /// Also increments the cooldownIndex (unless it has hit the cap). - /// @param _kitten A reference to the Kitty in storage which needs its timer started. - function _triggerCooldown(Kitty storage _kitten) internal { - // Compute an estimation of the cooldown time in blocks (based on current cooldownIndex). - _kitten.cooldownEndBlock = uint64((cooldowns[_kitten.cooldownIndex]/secondsPerBlock) + block.number); - - // Increment the breeding count, clamping it at 13, which is the length of the - // cooldowns array. We could check the array size dynamically, but hard-coding - // this as a constant saves gas. Yay, Solidity! - if (_kitten.cooldownIndex < 13) { - _kitten.cooldownIndex += 1; - } - } - - /// @notice Grants approval to another user to sire with one of your Kitties. - /// @param _addr The address that will be able to sire with your Kitty. Set to - /// address(0) to clear all siring approvals for this Kitty. - /// @param _sireId A Kitty that you own that _addr will now be able to sire with. - function approveSiring(address _addr, uint256 _sireId) - external - whenNotPaused - { - require(_owns(msg.sender, _sireId)); - sireAllowedToAddress[_sireId] = _addr; - } - - /// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only - /// be called by the COO address. (This fee is used to offset the gas cost incurred - /// by the autobirth daemon). - function setAutoBirthFee(uint256 val) external onlyCOO { - autoBirthFee = val; - } - - /// @dev Checks to see if a given Kitty is pregnant and (if so) if the gestation - /// period has passed. - function _isReadyToGiveBirth(Kitty memory _matron) private view returns (bool) { - return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number)); - } - - /// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or - /// in the middle of a siring cooldown). - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isReadyToBreed(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - Kitty storage kit = kitties[_kittyId]; - return _isReadyToBreed(kit); - } - - /// @dev Checks whether a kitty is currently pregnant. - /// @param _kittyId reference the id of the kitten, any user can inquire about it - function isPregnant(uint256 _kittyId) - public - view - returns (bool) - { - require(_kittyId > 0); - // A kitty is pregnant if and only if this field is set - return kitties[_kittyId].siringWithId != 0; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT - /// check ownership permissions (that is up to the caller). - /// @param _matron A reference to the Kitty struct of the potential matron. - /// @param _matronId The matron's ID. - /// @param _sire A reference to the Kitty struct of the potential sire. - /// @param _sireId The sire's ID - function _isValidMatingPair( - Kitty storage _matron, - uint256 _matronId, - Kitty storage _sire, - uint256 _sireId - ) - private - view - returns(bool) - { - // A Kitty can't breed with itself! - if (_matronId == _sireId) { - return false; - } - - // Kitties can't breed with their parents. - if (_matron.matronId == _sireId || _matron.sireId == _sireId) { - return false; - } - if (_sire.matronId == _matronId || _sire.sireId == _matronId) { - return false; - } - - // We can short circuit the sibling check (below) if either cat is - // gen zero (has a matron ID of zero). - if (_sire.matronId == 0 || _matron.matronId == 0) { - return true; - } - - // Kitties can't breed with full or half siblings. - if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) { - return false; - } - if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) { - return false; - } - - // Everything seems cool! Let's get DTF. - return true; - } - - /// @dev Internal check to see if a given sire and matron are a valid mating pair for - /// breeding via auction (i.e. skips ownership and siring approval checks). - function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId) - internal - view - returns (bool) - { - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId); - } - - /// @notice Checks to see if two cats can breed together, including checks for - /// ownership and siring approvals. Does NOT check that both cats are ready for - /// breeding (i.e. breedWith could still fail until the cooldowns are finished). - /// TODO: Shouldn't this check pregnancy and cooldowns?!? - /// @param _matronId The ID of the proposed matron. - /// @param _sireId The ID of the proposed sire. - function canBreedWith(uint256 _matronId, uint256 _sireId) - external - view - returns(bool) - { - require(_matronId > 0); - require(_sireId > 0); - Kitty storage matron = kitties[_matronId]; - Kitty storage sire = kitties[_sireId]; - return _isValidMatingPair(matron, _matronId, sire, _sireId) && - _isSiringPermitted(_sireId, _matronId); - } - - /// @dev Internal utility function to initiate breeding, assumes that all breeding - /// requirements have been checked. - function _breedWith(uint256 _matronId, uint256 _sireId) internal { - // Grab a reference to the Kitties from storage. - Kitty storage sire = kitties[_sireId]; - Kitty storage matron = kitties[_matronId]; - - // Mark the matron as pregnant, keeping track of who the sire is. - matron.siringWithId = uint32(_sireId); - - // Trigger the cooldown for both parents. - _triggerCooldown(sire); - _triggerCooldown(matron); - - // Clear siring permission for both parents. This may not be strictly necessary - // but it's likely to avoid confusion! - delete sireAllowedToAddress[_matronId]; - delete sireAllowedToAddress[_sireId]; - - // Every time a kitty gets pregnant, counter is incremented. - pregnantKitties++; - - // Emit the pregnancy event. - emit Pregnant(kittyIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock); - } - - /// @notice Breed a Kitty you own (as matron) with a sire that you own, or for which you - /// have previously been given Siring approval. Will either make your cat pregnant, or will - /// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth() - /// @param _matronId The ID of the Kitty acting as matron (will end up pregnant if successful) - /// @param _sireId The ID of the Kitty acting as sire (will begin its siring cooldown if successful) - function breedWithAuto(uint256 _matronId, uint256 _sireId) - external - payable - whenNotPaused - { - // Checks for payment. - require(msg.value >= autoBirthFee); - - // Caller must own the matron. - require(_owns(msg.sender, _matronId)); - - // Neither sire nor matron are allowed to be on auction during a normal - // breeding operation, but we don't need to check that explicitly. - // For matron: The caller of this function can't be the owner of the matron - // because the owner of a Kitty on auction is the auction house, and the - // auction house will never call breedWith(). - // For sire: Similarly, a sire on auction will be owned by the auction house - // and the act of transferring ownership will have cleared any oustanding - // siring approval. - // Thus we don't need to spend gas explicitly checking to see if either cat - // is on auction. - - // Check that matron and sire are both owned by caller, or that the sire - // has given siring permission to caller (i.e. matron's owner). - // Will fail for _sireId = 0 - require(_isSiringPermitted(_sireId, _matronId)); - - // Grab a reference to the potential matron - Kitty storage matron = kitties[_matronId]; - - // Make sure matron isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(matron)); - - // Grab a reference to the potential sire - Kitty storage sire = kitties[_sireId]; - - // Make sure sire isn't pregnant, or in the middle of a siring cooldown - require(_isReadyToBreed(sire)); - - // Test that these cats are a valid mating pair. - require(_isValidMatingPair( - matron, - _matronId, - sire, - _sireId - )); - - // All checks passed, kitty gets pregnant! - _breedWith(_matronId, _sireId); - } - - /// @notice Have a pregnant Kitty give birth! - /// @param _matronId A Kitty ready to give birth. - /// @return The Kitty ID of the new kitten. - /// @dev Looks at a given Kitty and, if pregnant and if the gestation period has passed, - /// combines the genes of the two parents to create a new kitten. The new Kitty is assigned - /// to the current owner of the matron. Upon successful completion, both the matron and the - /// new kitten will be ready to breed again. Note that anyone can call this function (if they - /// are willing to pay the gas!), but the new kitten always goes to the mother's owner. - function giveBirth(uint256 _matronId) - external - whenNotPaused - returns(uint256) - { - // Grab a reference to the matron in storage. - Kitty storage matron = kitties[_matronId]; - - // Check that the matron is a valid cat. - require(matron.birthTime != 0); - - // Check that the matron is pregnant, and that its time has come! - require(_isReadyToGiveBirth(matron)); - - // Grab a reference to the sire in storage. - uint256 sireId = matron.siringWithId; - Kitty storage sire = kitties[sireId]; - - // Determine the higher generation number of the two parents - uint16 parentGen = matron.generation; - if (sire.generation > matron.generation) { - parentGen = sire.generation; - } - - // Call the sooper-sekret gene mixing operation. - uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1); - - // Make the new kitten! - address owner = kittyIndexToOwner[_matronId]; - uint256 kittenId = _createKitty(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner); - - // Clear the reference to sire from the matron (REQUIRED! Having siringWithId - // set is what marks a matron as being pregnant.) - delete matron.siringWithId; - - // Every time a kitty gives birth counter is decremented. - pregnantKitties--; - - // Send the balance fee to the person who made birth happen. - msg.sender.transfer(autoBirthFee); - - // return the new kitten's ID - return kittenId; - } -} - - - -/// @title Handles creating auctions for sale and siring of kitties. -/// This wrapper of ReverseAuction exists only so that users can create -/// auctions with only one transaction. -contract KittyAuction is KittyBreeding { - - // @notice The auction contract variables are defined in KittyBase to allow - // us to refer to them in KittyOwnership to prevent accidental transfers. - // `saleAuction` refers to the auction for gen0 and p2p sale of kitties. - // `siringAuction` refers to the auction for siring rights of kitties. - - /// @dev Sets the reference to the sale auction. - /// @param _address - Address of sale contract. - function setSaleAuctionAddress(address _address) external onlyCEO { - SaleClockAuction candidateContract = SaleClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSaleClockAuction()); - - // Set the new contract address - saleAuction = candidateContract; - } - - /// @dev Sets the reference to the siring auction. - /// @param _address - Address of siring contract. - function setSiringAuctionAddress(address _address) external onlyCEO { - SiringClockAuction candidateContract = SiringClockAuction(_address); - - // NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117 - require(candidateContract.isSiringClockAuction()); - - // Set the new contract address - siringAuction = candidateContract; - } - - /// @dev Put a kitty up for auction. - /// Does some ownership trickery to create auctions in one tx. - function createSaleAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - // Ensure the kitty is not pregnant to prevent the auction - // contract accidentally receiving ownership of the child. - // NOTE: the kitty IS allowed to be in a cooldown. - require(!isPregnant(_kittyId)); - _approve(_kittyId, address(saleAuction)); - // Sale auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - saleAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Put a kitty up for auction to be sire. - /// Performs checks to ensure the kitty can be sired, then - /// delegates to reverse auction. - function createSiringAuction( - uint256 _kittyId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration - ) - external - whenNotPaused - { - // Auction contract checks input sizes - // If kitty is already on any auction, this will throw - // because it will be owned by the auction contract. - require(_owns(msg.sender, _kittyId)); - require(isReadyToBreed(_kittyId)); - _approve(_kittyId, address(siringAuction)); - // Siring auction throws if inputs are invalid and clears - // transfer and sire approval after escrowing the kitty. - siringAuction.createAuction( - _kittyId, - _startingPrice, - _endingPrice, - _duration, - msg.sender - ); - } - - /// @dev Completes a siring auction by bidding. - /// Immediately breeds the winning matron with the sire on auction. - /// @param _sireId - ID of the sire on auction. - /// @param _matronId - ID of the matron owned by the bidder. - function bidOnSiringAuction( - uint256 _sireId, - uint256 _matronId - ) - external - payable - whenNotPaused - { - // Auction contract checks input sizes - require(_owns(msg.sender, _matronId)); - require(isReadyToBreed(_matronId)); - require(_canBreedWithViaAuction(_matronId, _sireId)); - - // Define the current price of the auction. - uint256 currentPrice = siringAuction.getCurrentPrice(_sireId); - require(msg.value >= currentPrice + autoBirthFee); - - // Siring auction will throw if the bid fails. - siringAuction.bid.value(msg.value - autoBirthFee)(_sireId); - _breedWith(uint32(_matronId), uint32(_sireId)); - } - - /// @dev Transfers the balance of the sale auction contract - /// to the KittyCore contract. We use two-step withdrawal to - /// prevent two transfer calls in the auction bid function. - function withdrawAuctionBalances() external onlyCLevel { - saleAuction.withdrawBalance(); - siringAuction.withdrawBalance(); - } -} - - -/// @title all functions related to creating kittens -contract KittyMinting is KittyAuction { - - // Limits the number of cats the contract owner can ever create. - uint256 public constant PROMO_CREATION_LIMIT = 5000; - uint256 public constant GEN0_CREATION_LIMIT = 45000; - - // Constants for gen0 auctions. - uint256 public constant GEN0_STARTING_PRICE = 10 sun; - uint256 public constant GEN0_AUCTION_DURATION = 1 days; - - // Counts the number of cats the contract owner has created. - uint256 public promoCreatedCount; - uint256 public gen0CreatedCount; - - /// @dev we can create promo kittens, up to a limit. Only callable by COO - /// @param _genes the encoded genes of the kitten to be created, any value is accepted - /// @param _owner the future owner of the created kittens. Default to contract COO - function createPromoKitty(uint256 _genes, address _owner) external onlyCOO { - address kittyOwner = _owner; - if (kittyOwner == address(0)) { - kittyOwner = cooAddress; - } - require(promoCreatedCount < PROMO_CREATION_LIMIT); - - promoCreatedCount++; - _createKitty(0, 0, 0, _genes, kittyOwner); - } - - /// @dev Creates a new gen0 kitty with the given genes and - /// creates an auction for it. - function createGen0Auction(uint256 _genes) external onlyCOO { - require(gen0CreatedCount < GEN0_CREATION_LIMIT); - - uint256 kittyId = _createKitty(0, 0, 0, _genes, address(this)); - _approve(kittyId, address(saleAuction)); - - saleAuction.createAuction( - kittyId, - _computeNextGen0Price(), - 0, - GEN0_AUCTION_DURATION, - address(uint160(address(this))) - ); - - gen0CreatedCount++; - } - - /// @dev Computes the next gen0 auction starting price, given - /// the average of the past 5 prices + 50%. - function _computeNextGen0Price() internal view returns (uint256) { - uint256 avePrice = saleAuction.averageGen0SalePrice(); - - // Sanity check to ensure we don't overflow arithmetic - require(avePrice == uint256(uint128(avePrice))); - - uint256 nextPrice = avePrice + (avePrice / 2); - - // We never auction for less than starting price - if (nextPrice < GEN0_STARTING_PRICE) { - nextPrice = GEN0_STARTING_PRICE; - } - - return nextPrice; - } -} - - - -/// @title CryptoKitties: Collectible, breedable, and oh-so-adorable cats on the Ethereum blockchain. -/// @author Axiom Zen (https://www.axiomzen.co) -/// @dev The main CryptoKitties contract, keeps track of kittens so they don't wander around and get lost. -contract KittyCore is KittyMinting { - - // This is the main CryptoKitties contract. In order to keep our code seperated into logical sections, - // we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts - // that handle auctions and our super-top-secret genetic combination algorithm. The auctions are - // seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping - // them in their own contracts, we can upgrade them without disrupting the main contract that tracks - // kitty ownership. The genetic combination algorithm is kept seperate so we can open-source all of - // the rest of our code without making it _too_ easy for folks to figure out how the genetics work. - // Don't worry, I'm sure someone will reverse engineer it soon enough! - // - // Secondly, we break the core contract into multiple files using inheritence, one for each major - // facet of functionality of CK. This allows us to keep related code bundled together while still - // avoiding a single giant file with everything in it. The breakdown is as follows: - // - // - KittyBase: This is where we define the most fundamental code shared throughout the core - // functionality. This includes our main data storage, constants and data types, plus - // internal functions for managing these items. - // - // - KittyAccessControl: This contract manages the various addresses and constraints for operations - // that can be executed only by specific roles. Namely CEO, CFO and COO. - // - // - KittyOwnership: This provides the methods required for basic non-fungible token - // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). - // - // - KittyBreeding: This file contains the methods necessary to breed cats together, including - // keeping track of siring offers, and relies on an external genetic combination contract. - // - // - KittyAuctions: Here we have the public methods for auctioning or bidding on cats or siring - // services. The actual auction functionality is handled in two sibling contracts (one - // for sales and one for siring), while auction creation and bidding is mostly mediated - // through this facet of the core contract. - // - // - KittyMinting: This final facet contains the functionality we use for creating new gen0 cats. - // We can make up to 5000 "promo" cats that can be given away (especially important when - // the community is new), and all others can only be created and then immediately put up - // for auction via an algorithmically determined starting price. Regardless of how they - // are created, there is a hard limit of 50k gen0 cats. After that, it's all up to the - // community to breed, breed, breed! - - // Set in case the core contract is broken and an upgrade is required - address public newContractAddress; - - /// @notice Creates the main CryptoKitties smart contract instance. - constructor() public { - // Starts paused. - paused = true; - - // the creator of the contract is the initial CEO - ceoAddress = msg.sender; - - // the creator of the contract is also the initial COO - cooAddress = msg.sender; - - // start with the mythical kitten 0 - so we don't have generation-0 parent issues - _createKitty(0, 0, 0, uint256(-1), address(0)); - } - - /// @dev Used to mark the smart contract as upgraded, in case there is a serious - /// breaking bug. This method does nothing but keep track of the new contract and - /// emit a message indicating that the new address is set. It's up to clients of this - /// contract to update to the new contract address in that case. (This contract will - /// be paused indefinitely if such an upgrade takes place.) - /// @param _v2Address new address - function setNewAddress(address _v2Address) external onlyCEO whenPaused { - // See README.md for updgrade plan - newContractAddress = _v2Address; - emit ContractUpgrade(_v2Address); - } - - /// @notice No tipping! - /// @dev Reject all Ether from being sent here, unless it's from one of the - /// two auction contracts. (Hopefully, we can prevent user accidents.) - function() external payable { - require( - msg.sender == address(saleAuction) || - msg.sender == address(siringAuction) - ); - } - - /// @notice Returns all the relevant information about a specific kitty. - /// @param _id The ID of the kitty of interest. - function getKitty(uint256 _id) - external - view - returns ( - bool isGestating, - bool isReady, - uint256 cooldownIndex, - uint256 nextActionAt, - uint256 siringWithId, - uint256 birthTime, - uint256 matronId, - uint256 sireId, - uint256 generation, - uint256 genes - ) { - Kitty storage kit = kitties[_id]; - - // if this variable is 0 then it's not gestating - isGestating = (kit.siringWithId != 0); - isReady = (kit.cooldownEndBlock <= block.number); - cooldownIndex = uint256(kit.cooldownIndex); - nextActionAt = uint256(kit.cooldownEndBlock); - siringWithId = uint256(kit.siringWithId); - birthTime = uint256(kit.birthTime); - matronId = uint256(kit.matronId); - sireId = uint256(kit.sireId); - generation = uint256(kit.generation); - genes = kit.genes; - } - - /// @dev Override unpause so it requires all external contract addresses - /// to be set before contract can be unpaused. Also, we can't have - /// newContractAddress set either, because then the contract was upgraded. - /// @notice This is public rather than external so we can call super.unpause - /// without using an expensive CALL. - - function unpause() public onlyCEO whenPaused { - require(address(saleAuction) != address(0)); - require(address(siringAuction) != address(0)); - require(address(geneScience) != address(0)); - require(newContractAddress == address(0)); - - // Actually unpause the contract. - super.unpause(); - } - - // @dev Allows the CFO to capture the balance available to the contract. - function withdrawBalance() external onlyCFO { - uint256 balance = address(this).balance; - // Subtract all the currently pregnant kittens we have, plus 1 of margin. - uint256 subtractFees = (pregnantKitties + 1) * autoBirthFee; - - if (balance > subtractFees) { - cfoAddress.transfer(balance - subtractFees); - } - } -} - - - - - - - - - - - - - -// // Auction wrapper functions - - -// Auction wrapper functions - - - - - - - -/// @title SEKRETOOOO -contract GeneScienceInterface { - - function isGeneScience() public pure returns (bool){ - return true; - } - - /// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor - /// @param genes1 genes of mom - /// @param genes2 genes of sire - /// @return the genes that are supposed to be passed down the child - function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256){ - - return (genes1+genes2+targetBlock)/2; - - -} -} - - - - - - - - - - - - - - - - -/// @title The external contract that is responsible for generating metadata for the kitties, -/// it has one function that will return the data as bytes. -contract ERC721Metadata { - /// @dev Given a token Id, returns a byte array that is supposed to be converted into string. - function getMetadata(uint256 _tokenId, string memory) public view returns (bytes32[4] memory buffer, uint256 count) { - if (_tokenId == 1) { - buffer[0] = "Hello World! :D"; - count = 15; - } else if (_tokenId == 2) { - buffer[0] = "I would definitely choose a medi"; - buffer[1] = "um length string."; - count = 49; - } else if (_tokenId == 3) { - buffer[0] = "Lorem ipsum dolor sit amet, mi e"; - buffer[1] = "st accumsan dapibus augue lorem,"; - buffer[2] = " tristique vestibulum id, libero"; - buffer[3] = " suscipit varius sapien aliquam."; - count = 128; - } - } -} - - - - - - - - - - - - - - - -/// @title Auction Core -/// @dev Contains models, variables, and internal methods for the auction. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuctionBase { - - // Represents an auction on an NFT - struct Auction { - // Current owner of NFT - address seller; - // Price (in wei) at beginning of auction - uint128 startingPrice; - // Price (in wei) at end of auction - uint128 endingPrice; - // Duration (in seconds) of auction - uint64 duration; - // Time when auction started - // NOTE: 0 if this auction has been concluded - uint64 startedAt; - } - - // Reference to contract tracking NFT ownership - ERC721 public nonFungibleContract; - - // Cut owner takes on each auction, measured in basis points (1/100 of a percent). - // Values 0-10,000 map to 0%-100% - uint256 public ownerCut; - - // Map from token ID to their corresponding auction. - mapping (uint256 => Auction) tokenIdToAuction; - - event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration); - event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner); - event AuctionCancelled(uint256 tokenId); - - /// @dev Returns true if the claimant owns the token. - /// @param _claimant - Address claiming to own the token. - /// @param _tokenId - ID of token whose ownership to verify. - function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { - return (nonFungibleContract.ownerOf(_tokenId) == _claimant); - } - - /// @dev Escrows the NFT, assigning ownership to this contract. - /// Throws if the escrow fails. - /// @param _owner - Current owner address of token to escrow. - /// @param _tokenId - ID of token whose approval to verify. - function _escrow(address _owner, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transferFrom(_owner, address(this), _tokenId); - } - - /// @dev Transfers an NFT owned by this contract to another address. - /// Returns true if the transfer succeeds. - /// @param _receiver - Address to transfer NFT to. - /// @param _tokenId - ID of token to transfer. - function _transfer(address _receiver, uint256 _tokenId) internal { - // it will throw if transfer fails - nonFungibleContract.transfer(_receiver, _tokenId); - } - - /// @dev Adds an auction to the list of open auctions. Also fires the - /// AuctionCreated event. - /// @param _tokenId The ID of the token to be put on auction. - /// @param _auction Auction to add. - function _addAuction(uint256 _tokenId, Auction memory _auction) internal { - // Require that all auctions have a duration of - // at least one minute. (Keeps our math from getting hairy!) - require(_auction.duration >= 1 minutes); - - tokenIdToAuction[_tokenId] = _auction; - - emit AuctionCreated( - uint256(_tokenId), - uint256(_auction.startingPrice), - uint256(_auction.endingPrice), - uint256(_auction.duration) - ); - } - - /// @dev Cancels an auction unconditionally. - function _cancelAuction(uint256 _tokenId, address _seller) internal { - _removeAuction(_tokenId); - _transfer(_seller, _tokenId); - emit AuctionCancelled(_tokenId); - } - - /// @dev Computes the price and transfers winnings. - /// Does NOT transfer ownership of token. - function _bid(uint256 _tokenId, uint256 _bidAmount) - internal - returns (uint256) - { - // Get a reference to the auction struct - Auction storage auction = tokenIdToAuction[_tokenId]; - - // Explicitly check that this auction is currently live. - // (Because of how Ethereum mappings work, we can't just count - // on the lookup above failing. An invalid _tokenId will just - // return an auction object that is all zeros.) - require(_isOnAuction(auction)); - - // Check that the bid is greater than or equal to the current price - uint256 price = _currentPrice(auction); - require(_bidAmount >= price); - - // Grab a reference to the seller before the auction struct - // gets deleted. - address seller = auction.seller; - - // The bid is good! Remove the auction before sending the fees - // to the sender so we can't have a reentrancy attack. - _removeAuction(_tokenId); - - // Transfer proceeds to seller (if there are any!) - if (price > 0) { - // Calculate the auctioneer's cut. - // (NOTE: _computeCut() is guaranteed to return a - // value <= price, so this subtraction can't go negative.) - uint256 auctioneerCut = _computeCut(price); - uint256 sellerProceeds = price - auctioneerCut; - - // NOTE: Doing a transfer() in the middle of a complex - // method like this is generally discouraged because of - // reentrancy attacks and DoS attacks if the seller is - // a contract with an invalid fallback function. We explicitly - // guard against reentrancy attacks by removing the auction - // before calling transfer(), and the only thing the seller - // can DoS is the sale of their own asset! (And if it's an - // accident, they can call cancelAuction(). ) - seller.transfer(sellerProceeds); - } - - // Calculate any excess funds included with the bid. If the excess - // is anything worth worrying about, transfer it back to bidder. - // NOTE: We checked above that the bid amount is greater than or - // equal to the price so this cannot underflow. - uint256 bidExcess = _bidAmount - price; - - // Return the funds. Similar to the previous transfer, this is - // not susceptible to a re-entry attack because the auction is - // removed before any transfers occur. - msg.sender.transfer(bidExcess); - - // Tell the world! - emit AuctionSuccessful(_tokenId, price, msg.sender); - - return price; - } - - /// @dev Removes an auction from the list of open auctions. - /// @param _tokenId - ID of NFT on auction. - function _removeAuction(uint256 _tokenId) internal { - delete tokenIdToAuction[_tokenId]; - } - - /// @dev Returns true if the NFT is on auction. - /// @param _auction - Auction to check. - function _isOnAuction(Auction storage _auction) internal view returns (bool) { - return (_auction.startedAt > 0); - } - - /// @dev Returns current price of an NFT on auction. Broken into two - /// functions (this one, that computes the duration from the auction - /// structure, and the other that does the price computation) so we - /// can easily test that the price computation works correctly. - function _currentPrice(Auction storage _auction) - internal - view - returns (uint256) - { - uint256 secondsPassed = 0; - - // A bit of insurance against negative values (or wraparound). - // Probably not necessary (since Ethereum guarnatees that the - // now variable doesn't ever go backwards). - if (now > _auction.startedAt) { - secondsPassed = now - _auction.startedAt; - } - - return _computeCurrentPrice( - _auction.startingPrice, - _auction.endingPrice, - _auction.duration, - secondsPassed - ); - } - - /// @dev Computes the current price of an auction. Factored out - /// from _currentPrice so we can run extensive unit tests. - /// When testing, make this function public and turn on - /// `Current price computation` test suite. - function _computeCurrentPrice( - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - uint256 _secondsPassed - ) - internal - pure - returns (uint256) - { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our public functions carefully cap the maximum values for - // time (at 64-bits) and currency (at 128-bits). _duration is - // also known to be non-zero (see the require() statement in - // _addAuction()) - if (_secondsPassed >= _duration) { - // We've reached the end of the dynamic pricing portion - // of the auction, just return the end price. - return _endingPrice; - } else { - // Starting price can be higher than ending price (and often is!), so - // this delta can be negative. - int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice); - - // This multiplication can't overflow, _secondsPassed will easily fit within - // 64-bits, and totalPriceChange will easily fit within 128-bits, their product - // will always fit within 256-bits. - int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration); - - // currentPriceChange can be negative, but if so, will have a magnitude - // less that _startingPrice. Thus, this result will always end up positive. - int256 currentPrice = int256(_startingPrice) + currentPriceChange; - - return uint256(currentPrice); - } - } - - /// @dev Computes owner's cut of a sale. - /// @param _price - Sale price of NFT. - function _computeCut(uint256 _price) internal view returns (uint256) { - // NOTE: We don't use SafeMath (or similar) in this function because - // all of our entry functions carefully cap the maximum values for - // currency (at 128-bits), and ownerCut <= 10000 (see the require() - // statement in the ClockAuction constructor). The result of this - // function is always guaranteed to be <= _price. - return _price * ownerCut / 10000; - } - -} - - - - - - - -/** - * @title Pausable - * @dev Base contract which allows children to implement an emergency stop mechanism. - */ -contract Pausable is Ownable { - event Pause(); - event Unpause(); - - bool public paused = false; - - - /** - * @dev modifier to allow actions only when the contract IS paused - */ - modifier whenNotPaused() { - require(!paused); - _; - } - - /** - * @dev modifier to allow actions only when the contract IS NOT paused - */ - modifier whenPaused { - require(paused); - _; - } - - /** - * @dev called by the owner to pause, triggers stopped state - */ - function pause() onlyOwner whenNotPaused public returns (bool) { - paused = true; - emit Pause(); - return true; - } - - /** - * @dev called by the owner to unpause, returns to normal state - */ - function unpause() onlyOwner whenPaused public returns (bool) { - paused = false; - emit Unpause(); - return true; - } -} - - -/// @title Clock auction for non-fungible tokens. -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract ClockAuction is Pausable, ClockAuctionBase { - - /// @dev The ERC-165 interface signature for ERC-721. - /// Ref: https://github.com/ethereum/EIPs/issues/165 - /// Ref: https://github.com/ethereum/EIPs/issues/721 - bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d); - - /// @dev Constructor creates a reference to the NFT ownership contract - /// and verifies the owner cut is in the valid range. - /// @param _nftAddress - address of a deployed contract implementing - /// the Nonfungible Interface. - /// @param _cut - percent cut the owner takes on each auction, must be - /// between 0-10,000. - constructor(address _nftAddress, uint256 _cut) public { - require(_cut <= 10000); - ownerCut = _cut; - - ERC721 candidateContract = ERC721(_nftAddress); - require(candidateContract.supportsInterface(InterfaceSignature_ERC721)); - nonFungibleContract = candidateContract; - } - - /// @dev Remove all Ether from the contract, which is the owner's cuts - /// as well as any Ether sent directly to the contract address. - /// Always transfers to the NFT contract, but can be called either by - /// the owner or the NFT contract. - function withdrawBalance() external { - address nftAddress = address(uint160(address(nonFungibleContract))); - - require( - msg.sender == owner || - msg.sender == nftAddress - ); - // We are using this boolean method to make sure that even if one fails it will still work - bool res = nftAddress.send(address(this).balance); - } - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of time to move between starting - /// price and ending price (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - whenNotPaused - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(_owns(msg.sender, _tokenId)); - _escrow(msg.sender, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Bids on an open auction, completing the auction and transferring - /// ownership of the NFT if enough Ether is supplied. - /// @param _tokenId - ID of token to bid on. - function bid(uint256 _tokenId) - external - payable - whenNotPaused - { - // _bid will throw if the bid or funds transfer fails - _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - } - - /// @dev Cancels an auction that hasn't been won yet. - /// Returns the NFT to original owner. - /// @notice This is a state-modifying function that can - /// be called while the contract is paused. - /// @param _tokenId - ID of token on auction - function cancelAuction(uint256 _tokenId) - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - address seller = auction.seller; - require(msg.sender == seller); - _cancelAuction(_tokenId, seller); - } - - /// @dev Cancels an auction when the contract is paused. - /// Only the owner may do this, and NFTs are returned to - /// the seller. This should only be used in emergencies. - /// @param _tokenId - ID of the NFT on auction to cancel. - function cancelAuctionWhenPaused(uint256 _tokenId) - whenPaused - onlyOwner - external - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - _cancelAuction(_tokenId, auction.seller); - } - - /// @dev Returns auction info for an NFT on auction. - /// @param _tokenId - ID of NFT on auction. - function getAuction(uint256 _tokenId) - external - view - returns - ( - address seller, - uint256 startingPrice, - uint256 endingPrice, - uint256 duration, - uint256 startedAt - ) { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return ( - auction.seller, - auction.startingPrice, - auction.endingPrice, - auction.duration, - auction.startedAt - ); - } - - /// @dev Returns the current price of an auction. - /// @param _tokenId - ID of the token price we are checking. - function getCurrentPrice(uint256 _tokenId) - external - view - returns (uint256) - { - Auction storage auction = tokenIdToAuction[_tokenId]; - require(_isOnAuction(auction)); - return _currentPrice(auction); - } - -} - - -/// @title Reverse auction modified for siring -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SiringClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSiringAuctionAddress() call. - bool public isSiringClockAuction = true; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. Since this function is wrapped, - /// require sender to be KittyCore contract. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Places a bid for siring. Requires the sender - /// is the KittyCore contract because all bid methods - /// should be wrapped. Also returns the kitty to the - /// seller rather than the winner. - function bid(uint256 _tokenId) - external - payable - { - require(msg.sender == address(nonFungibleContract)); - address seller = tokenIdToAuction[_tokenId].seller; - // _bid checks that token ID is valid and will throw if bid fails - _bid(_tokenId, msg.value); - // We transfer the kitty back to the seller, the winner will get - // the offspring - _transfer(seller, _tokenId); - } - -} - - - - - -/// @title Clock auction modified for sale of kitties -/// @notice We omit a fallback function to prevent accidental sends to this contract. -contract SaleClockAuction is ClockAuction { - - // @dev Sanity check that allows us to ensure that we are pointing to the - // right auction in our setSaleAuctionAddress() call. - bool public isSaleClockAuction = true; - - // Tracks last 5 sale price of gen0 kitty sales - uint256 public gen0SaleCount; - uint256[5] public lastGen0SalePrices; - - // Delegate constructor - constructor(address _nftAddr, uint256 _cut) public - ClockAuction(_nftAddr, _cut) {} - - /// @dev Creates and begins a new auction. - /// @param _tokenId - ID of token to auction, sender must be owner. - /// @param _startingPrice - Price of item (in wei) at beginning of auction. - /// @param _endingPrice - Price of item (in wei) at end of auction. - /// @param _duration - Length of auction (in seconds). - /// @param _seller - Seller, if not the message sender - function createAuction( - uint256 _tokenId, - uint256 _startingPrice, - uint256 _endingPrice, - uint256 _duration, - address _seller - ) - external - { - // Sanity check that no inputs overflow how many bits we've allocated - // to store them in the auction struct. - require(_startingPrice == uint256(uint128(_startingPrice))); - require(_endingPrice == uint256(uint128(_endingPrice))); - require(_duration == uint256(uint64(_duration))); - - require(msg.sender == address(nonFungibleContract)); - _escrow(_seller, _tokenId); - Auction memory auction = Auction( - _seller, - uint128(_startingPrice), - uint128(_endingPrice), - uint64(_duration), - uint64(now) - ); - _addAuction(_tokenId, auction); - } - - /// @dev Updates lastSalePrice if seller is the nft contract - /// Otherwise, works the same as default bid method. - function bid(uint256 _tokenId) - external - payable - { - // _bid verifies token ID size - address seller = tokenIdToAuction[_tokenId].seller; - uint256 price = _bid(_tokenId, msg.value); - _transfer(msg.sender, _tokenId); - - // If not a gen0 auction, exit - if (seller == address(nonFungibleContract)) { - // Track gen0 sale prices - lastGen0SalePrices[gen0SaleCount % 5] = price; - gen0SaleCount++; - } - } - - function averageGen0SalePrice() external view returns (uint256) { - uint256 sum = 0; - for (uint256 i = 0; i < 5; i++) { - sum += lastGen0SalePrices[i]; - } - return sum / 5; - } - -} - - - - - - - diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario012.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario012.sol deleted file mode 100644 index 81f64134298..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario012.sol +++ /dev/null @@ -1,57 +0,0 @@ -//pragma solidity ^0.4.0; -contract PayTest { - -uint256 public n; -constructor() payable public{ -n = 0; -} - -function nPlusOne() public{ -n = n+1; -} - -//get current contract balance -function getBalance() payable public returns (uint) { -return address(this).balance; -} - -function getSenderBalance() public view returns(address, uint) { -return (msg.sender, msg.sender.balance); -} - -address public user; - -//deposit 1 coin to msg.sender -function depositOneCoin() payable public returns(bool success){ -return msg.sender.send(1); -} - -// function transferOneCoin() payable public returns(){ -// address(msg.sender).transfer(1); -// } - -// function depositOneCoin() payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(1)); -// } - -//deposit coin to msg.sender -function deposit(uint256 money) payable public returns(bool success){ -return msg.sender.send(money); -} -// function deposit(uint money) payable public returns(address addr, uint amount, bool success){ -// return (msg.sender, msg.value, msg.sender.send(money)); -// } - -// function () payable { -// msg.sender.send(1); -// } - -function sendToAddress(address _receiver) payable public{ -_receiver.transfer(msg.value); -} - -function sendToAddress2(address _receiver) payable public{ -_receiver.transfer(5); -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario013.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario013.sol deleted file mode 100644 index b91085d018e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario013.sol +++ /dev/null @@ -1,8 +0,0 @@ -//pragma solidity ^0.4.0; -contract timetest { - -function time() public{ -require(1 trx == 1000000 sun); - -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario014.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractScenario014.sol deleted file mode 100644 index 0e00a8f7f9b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractScenario014.sol +++ /dev/null @@ -1,34 +0,0 @@ -//pragma solidity ^0.4.0; -contract Contract1 { - constructor() public payable{} - function send5SunToReceiver(address _receiver) payable public{ - _receiver.transfer(5); - } -} -contract contract2 { - address public payContract; - - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract1(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - } - - function triggerContract1ButRevert(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("send5SunToReceiver(address)",_receiver)); - require(1 == 2); - } - -} -contract contract3 { - address public payContract; - constructor(address _add) payable public{ - payContract = _add; - } - - function triggerContract2(address _receiver) payable public{ - payContract.call(abi.encodeWithSignature("triggerContract1(address)",_receiver)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTest.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTest.sol deleted file mode 100644 index d6c5f34af2d..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTest.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.4; - -contract Test{ - -function a() returns (uint){ - -uint256 count = 0; - -for (uint256 i = 1; i > 0; i++) { - -count++; - -} - -return count; - -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractToMathedFeed.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractToMathedFeed.sol deleted file mode 100644 index 7cbfddfc657..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractToMathedFeed.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.0; - -contract ToMathedFeed { - uint public i=1; - function ToMathed(uint value) { - i=value; - } -} - -contract ToMathedUseINContract { - function ToMathedIUseNR(address a,uint256 n) returns(bool){ - address payContract=a; - return payContract.call(bytes4(keccak256("ToMathedNot(uint256)")),n); - } - function ToMathedIUseNRE(address a,uint256 value) returns(bool){ - address payContract=a; - return payContract.call(bytes4(keccak256("ToMathed(uint256)")),value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken001.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken001.sol deleted file mode 100644 index a7649149263..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken001.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken002.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken002.sol deleted file mode 100644 index a7649149263..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken002.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken003.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken003.sol deleted file mode 100644 index 924513518ea..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken003.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken005.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken005.sol deleted file mode 100644 index 924513518ea..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken005.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken011.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken011.sol deleted file mode 100644 index eee0510ccc3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken011.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable public{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken012.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken012.sol deleted file mode 100644 index 99bb82c48f2..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken012.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken014.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken014.sol deleted file mode 100644 index ada9432a02e..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken014.sol +++ /dev/null @@ -1,34 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable external{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken018.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken018.sol deleted file mode 100644 index 99bb82c48f2..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken018.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken023.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken023.sol deleted file mode 100644 index 16551e2f177..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken023.sol +++ /dev/null @@ -1,26 +0,0 @@ -pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() public payable { - flag = 1; -} - -} -pragma solidity ^0.4.24; -contract C{ - uint256 public flag = 0; - constructor() public payable {} - function() public payable { - //flag = 1; -} - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken026.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken026.sol deleted file mode 100644 index a45d885bbb4..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken026.sol +++ /dev/null @@ -1,30 +0,0 @@ -pragma solidity ^0.4.24; - -contract token{ - constructor() payable public{} - function() payable public{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callAddressC,toAddress,amount,id); - } - } - - - -contract B{ - constructor() public payable{} - function() public payable{} - function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(bytes4(keccak256("trans(address,uint256,trcToken)")),toAddress,amount,id); - } -} -contract C{ - constructor() payable public{} - function() payable public{} - function trans(address toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken027.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken027.sol deleted file mode 100644 index a45d885bbb4..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken027.sol +++ /dev/null @@ -1,30 +0,0 @@ -pragma solidity ^0.4.24; - -contract token{ - constructor() payable public{} - function() payable public{} - function testInCall(address callBAddress,address callCAddress, address toAddress ,uint256 amount,trcToken id) payable public{ - callBAddress.call(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callCAddress,toAddress,amount,id); - } - function testIndelegateCall(address callBddress,address callAddressC, address toAddress,uint256 amount, trcToken id) payable public{ - callBddress.delegatecall(bytes4(keccak256("transC(address,address,uint256,trcToken)")),callAddressC,toAddress,amount,id); - } - } - - - -contract B{ - constructor() public payable{} - function() public payable{} - function transC(address callCAddress,address toAddress,uint256 amount, trcToken id) payable public{ - callCAddress.call(bytes4(keccak256("trans(address,uint256,trcToken)")),toAddress,amount,id); - } -} -contract C{ - constructor() payable public{} - function() payable public{} - function trans(address toAddress,uint256 amount, trcToken id) payable public{ - toAddress.transferToken(amount,id); - } - -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken028.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken028.sol deleted file mode 100644 index 36dad7847a2..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken028.sol +++ /dev/null @@ -1,25 +0,0 @@ -pragma solidity ^0.4.24; - -contract token{ - uint256 public a=1; - constructor() public payable{} - function tokenBalanceWithSameName(trcToken id) public payable{ - B b= new B(); - a= b.tokenBalance(id); - } - function getA() public returns(uint256){ - return a; - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - function() public payable{} - function tokenBalance(trcToken id) payable public returns(uint256){ - flag =9; - return flag; - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken029.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken029.sol deleted file mode 100644 index 93a79a6f774..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken029.sol +++ /dev/null @@ -1,24 +0,0 @@ -pragma solidity ^0.4.24; - -contract token{ - address public a; - constructor() public payable{} - function transferTokenWithSameName(trcToken id,uint256 amount) public payable{ - B b= new B(); - b.transferToken(amount,id); - a= address(b); - } -} - - -contract B{ - uint256 public flag =0; - constructor() public payable{} - function() public payable{} - function transferToken(uint256 amount, trcToken id) payable public returns(bool){ - flag =9; - } - function getFlag() public view returns (uint256){ - return flag; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken030.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken030.sol deleted file mode 100644 index d82c6ab6928..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken030.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma solidity ^0.4.24; - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - function() public payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken031.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken031.sol deleted file mode 100644 index d82c6ab6928..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken031.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma solidity ^0.4.24; - - contract token{ - constructor() public payable{} - - // 4)suicide也会转移token - // 所有token,trx均被转移到toAddress, - // 若toAddress为合约地址本身,则所有token,trx均被烧掉进黑洞 - function kill(address toAddress) payable public{ - selfdestruct(toAddress); - } - - } - -contract B{ - constructor() public payable {} - function() public payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken034.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken034.sol deleted file mode 100644 index 03afab38850..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken034.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.4.24; - - contract token{ - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() public payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken035.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken035.sol deleted file mode 100644 index 03afab38850..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken035.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.4.24; - - contract token{ - - // 2. 异常测试 - // 1)revert, 金额回退 - function failTransferTokenRevert(address toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - require(1==2); - } - - // 2)Error, 金额回退, fee limit 扣光 - function failTransferTokenError(address toAddress,uint256 amount, trcToken id) public payable{ - toAddress.transferToken(amount,id); - assert(1==2); - } - - } - contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() public payable {} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken036.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken036.sol deleted file mode 100644 index b9c81f8cd59..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken036.sol +++ /dev/null @@ -1,65 +0,0 @@ -pragma solidity ^0.4.24; -contract IllegalDecorate { -constructor() payable public{} -function() payable public{} -event log(uint256); -function transferTokenWithPure(address toAddress, uint256 tokenValue) public payable { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate1 { -constructor() payable public{} -function() payable public{} -event log(uint256); -function transferTokenWithConstant(address toAddress, uint256 tokenValue) public constant { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate2 { -constructor() payable public{} -function() payable public{} -event log(uint256); -function transferTokenWithView(address toAddress, uint256 tokenValue) public view { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate3 { -event log(uint256); -constructor() payable public{} -function() payable public{} -function transferTokenWithOutPayable(address toAddress, uint256 tokenValue) public { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} - -contract IllegalDecorate4 { -constructor() payable public{} -function() payable public{} -event log(uint256); -function transferTokenWithPure(address toAddress, uint256 tokenValue) public pure { -emit log(msg.value); -emit log(msg.tokenvalue); -emit log(msg.tokenid); -toAddress.transferToken(msg.tokenvalue, msg.tokenid); -toAddress.transfer(msg.value); -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken037.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken037.sol deleted file mode 100644 index ad19db9a3a6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken037.sol +++ /dev/null @@ -1,23 +0,0 @@ -pragma solidity ^0.4.24; - -contract transferTrc10 { - function receive(address rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - require(0==address(this).tokenBalance(msg.tokenid)); - require(bamount+aamount==rec.tokenBalance(msg.tokenid)); - require(rec.call(bytes4(keccak256("checkTrc10(uint256,trcToken,uint256)")),bamount+aamount,msg.tokenid,0)); - } -} - -contract receiveTrc10 { - function() public payable { - } - function checkTrc10(uint256 amount,trcToken tid,uint256 meamount) public{ - require(amount==address(this).tokenBalance(tid)); - require(meamount==msg.sender.tokenBalance(tid)); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken038.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken038.sol deleted file mode 100644 index 5b1a0babe8b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken038.sol +++ /dev/null @@ -1,22 +0,0 @@ -pragma solidity ^0.4.24; - -contract transferTrc10 { - function receive(address rec) public payable { - uint256 aamount=address(this).tokenBalance(msg.tokenid); - uint256 bamount=rec.tokenBalance(msg.tokenid); - require(msg.tokenvalue==aamount); - require(aamount==msg.tokenvalue); - rec.transferToken(aamount,msg.tokenid); - require(rec.call(bytes4(keccak256("AssertError()")))); - require(aamount==address(this).tokenBalance(msg.tokenid)); - require(bamount==rec.tokenBalance(msg.tokenid)); - } -} - -contract receiveTrc10 { - function() public payable { - } - function AssertError() public{ - assert(1==2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken039.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken039.sol deleted file mode 100644 index 7229e3aaa9a..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken039.sol +++ /dev/null @@ -1,44 +0,0 @@ -pragma solidity ^0.4.24; -/* - * 1. caller账户issue一个token - * 2. caller部署proxy, 传入1000 token,1000 trx - * 3. caller部署A - * 4. caller部署B - * 5. caller调用proxy中upgradetTo函数,传入A的地址 - * 6. caller调用proxy中不存在的trans(uint256,address,trcToken)函数,注意这时trcToken是无意义的,但也带上tokenid。address是任意另外某账户的地址 - * 7. 可以看到目标地址trx增长5,caller账户trx减少5 - * 8. caller调用proxy中upgradeTo函数,传入B的地址 - * 9. caller调用proxy中不存在的trans(uint256,address,trcToken)函数。 - * 10. 可以看到目标地址token增长5,caller账户token减少5 -*/ -contract Proxy { - constructor() payable public{} - address public implementation; - function upgradeTo(address _address) public { - implementation = _address; - } - function() payable public{ - address addr = implementation; - require(addr != address(0)); - assembly { - let freememstart := mload(0x40) - calldatacopy(freememstart, 0, calldatasize()) - let success := delegatecall(not(0), addr, freememstart, calldatasize(), freememstart, 0) - returndatacopy(freememstart, 0, returndatasize()) - switch success - case 0 { revert(freememstart, returndatasize()) } - default { return(freememstart, returndatasize()) } - } - } -} - -contract A { - function trans(uint256 amount, address toAddress, trcToken id) payable public { - toAddress.transfer(amount); - } -} -contract B{ - function trans(uint256 amount, address toAddress, trcToken id) payable public { - toAddress.transferToken(amount,id); - } -} diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken041.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken041.sol deleted file mode 100644 index f70ab112afe..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken041.sol +++ /dev/null @@ -1,20 +0,0 @@ -pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } - -contract B{ - uint256 public flag = 0; - constructor() public payable {} - function() public payable {} - - function setFlag() public payable{ - flag = 1; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken043.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken043.sol deleted file mode 100644 index eee0510ccc3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken043.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable public{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken048.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken048.sol deleted file mode 100644 index de2844608c0..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken048.sol +++ /dev/null @@ -1,14 +0,0 @@ -//pragma solidity ^0.4.24; - - contract Test { - event log(uint256); - function testMsgTokenValue() payable public returns(uint256 value) { - emit log(msg.tokenvalue); - return msg.tokenvalue; - } - - function testMsgValue() payable public returns(uint256 value) { - emit log(msg.value); - return msg.value; - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken049.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken049.sol deleted file mode 100644 index 25b31a4ffd6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken049.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken050.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken050.sol deleted file mode 100644 index 25b31a4ffd6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken050.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken051.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken051.sol deleted file mode 100644 index 25b31a4ffd6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken051.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken052.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken052.sol deleted file mode 100644 index 25b31a4ffd6..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken052.sol +++ /dev/null @@ -1,10 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken054.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken054.sol deleted file mode 100644 index 924513518ea..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken054.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken055.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken055.sol deleted file mode 100644 index 924513518ea..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken055.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken060.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken060.sol deleted file mode 100644 index a7649149263..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken060.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken061.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken061.sol deleted file mode 100644 index a7649149263..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken061.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken064.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken064.sol deleted file mode 100644 index 0378fd90cc1..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken064.sol +++ /dev/null @@ -1,49 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } - function transferTokenTestValueMaxBigInteger(address toAddress) payable public { - toAddress.transferToken(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff, 0); - } - function transferTokenTestValueOverBigInteger(address toAddress) payable public { - toAddress.transferToken(9223372036854775808, 1000001); - } - function transferTokenTestValueMaxLong(address toAddress) payable public { - toAddress.transferToken(9223372036854775807, 1000001); - } - function transferTokenTestValue0IdBigInteger(address toAddress) payable public { - toAddress.transferToken(0, 9223372036854775809); - } -} - - - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable public{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken066.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken066.sol deleted file mode 100644 index eee0510ccc3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken066.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable public{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken067.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken067.sol deleted file mode 100644 index eee0510ccc3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken067.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract transferTokenContract { - constructor() payable public{} - function() payable public{} - function transferTokenTest(address toAddress, uint256 tokenValue, trcToken id) payable public { - toAddress.transferToken(tokenValue, id); - } - function transferTokenTestIDOverBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 9223372036854775809); - } - function transferTokenTestValueRandomIdBigInteger(address toAddress) payable public { - toAddress.transferToken(1, 36893488147420103233); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256){ - trcToken id = msg.tokenid; - uint256 value = msg.tokenvalue; - return (id, value); - } - function getTokenBalanceTest(address accountAddress) payable public returns (uint256){ - trcToken id = 1000001; - return accountAddress.tokenBalance(id); - } - function getTokenBalnce(address toAddress, trcToken tokenId) public payable returns(uint256){ - return toAddress.tokenBalance(tokenId); - } -} - - -contract Result { - event log(uint256,uint256,uint256); - constructor() payable public{} - function() payable public{ - emit log(msg.tokenid,msg.tokenvalue,msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken073.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken073.sol deleted file mode 100644 index b5b6d149565..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken073.sol +++ /dev/null @@ -1,17 +0,0 @@ -//pragma solidity ^0.4.0; - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - - function Dest() payable public {} - - function getToken(trcToken tokenId) payable { - logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function () payable { - logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken075.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken075.sol deleted file mode 100644 index dfcaf8c2a52..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken075.sol +++ /dev/null @@ -1,26 +0,0 @@ -//pragma solidity ^0.4.0; - -contract Dest { - event logFallback(uint256 indexed, uint256 indexed, uint256 indexed); - event logGetToken(uint256 indexed, uint256 indexed, uint256 indexed, uint256); - - function Dest() payable public {} - - function getToken(trcToken tokenId) payable { - logGetToken(msg.sender.tokenBalance(tokenId), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMin() payable { - // long.min - 1000020 - logGetToken(msg.sender.tokenBalance(trcToken(-9223372036855775828)), msg.tokenid, msg.tokenvalue, msg.value); - } - - function getTokenLongMax() payable { - // long.max + 1000020 - logGetToken(msg.sender.tokenBalance(trcToken(9223372036855775827)), msg.tokenid, msg.tokenvalue, msg.value); - } - - function () payable { - logFallback(msg.tokenid, msg.tokenvalue, msg.value); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken076.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken076.sol deleted file mode 100644 index 9de79a327c3..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken076.sol +++ /dev/null @@ -1,19 +0,0 @@ -//pragma solidity ^0.4.24; -contract Test { - address public origin; - address public sender; - bool public result1; - bool public result2; - function test() external { - origin = tx.origin; - sender = msg.sender; - result1 = msg.sender == tx.origin; // true - result2 = origin == sender; // true - } -function getResult1() public returns(bool){ - return result1; -} -function getResult2() public returns(bool){ - return result2; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken077.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken077.sol deleted file mode 100644 index e110f24e2fc..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken077.sol +++ /dev/null @@ -1,11 +0,0 @@ -//pragma solidity ^0.4.24; - -contract trcToken077 { -function addressTest() public returns(bytes32 addressValue) { - assembly{ - let x := mload(0x40) //Find empty storage location using "free memory pointer" - mstore(x,address) //Place current contract address - addressValue := mload(x) - } - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken078.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken078.sol deleted file mode 100644 index 4d51a365e14..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken078.sol +++ /dev/null @@ -1,35 +0,0 @@ -//pragma solidity ^0.4.24; -contract callerContract { - constructor() payable{} - function() payable{} - function sendToB(address called_address,address c) public payable{ - called_address.delegatecall(bytes4(keccak256("transferTo(address)")),c); - } - function sendToB2(address called_address,address c) public payable{ - called_address.call(bytes4(keccak256("transferTo(address)")),c); - } - function sendToB3(address called_address,address c) public payable{ - called_address.callcode(bytes4(keccak256("transferTo(address)")),c); - } -} - contract calledContract { - function() payable{} - constructor() payable {} - function transferTo(address toAddress)public payable{ - toAddress.transfer(5); - } - - function setIinC(address c) public payable{ - c.call.value(5)(bytes4(keccak256("setI()"))); - } - - } - contract c{ - address public origin; - address public sender; - constructor() public payable{} - event log(address,address); - function() payable public{ - emit log(tx.origin,msg.sender); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken079.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken079.sol deleted file mode 100644 index 924513518ea..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken079.sol +++ /dev/null @@ -1,16 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - constructor() public payable{} - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken080.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken080.sol deleted file mode 100644 index a7649149263..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcToken080.sol +++ /dev/null @@ -1,30 +0,0 @@ -//pragma solidity ^0.4.24; - - contract tokenTest{ - trcToken idCon = 0; - uint256 tokenValueCon=0; - uint256 callValueCon = 0; - - // positive case - function TransferTokenTo(address toAddress, trcToken id,uint256 amount) public payable{ - //trcToken id = 0x74657374546f6b656e; - toAddress.transferToken(amount,id); - } - - function msgTokenValueAndTokenIdTest() public payable returns(trcToken, uint256, uint256){ - trcToken id = msg.tokenid; - uint256 tokenValue = msg.tokenvalue; - uint256 callValue = msg.value; - return (id, tokenValue, callValue); - } - - constructor() public payable { - idCon = msg.tokenid; - tokenValueCon = msg.tokenvalue; - callValueCon = msg.value; - } - - function getResultInCon() public payable returns(trcToken, uint256, uint256) { - return (idCon, tokenValueCon, callValueCon); - } - } \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcTokenToOther.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractTrcTokenToOther.sol deleted file mode 100644 index e9ebd0ae865..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractTrcTokenToOther.sol +++ /dev/null @@ -1,44 +0,0 @@ -//pragma solidity ^0.4.24; - -contract ConvertType { - -constructor() payable public{} - -function() payable public{} - -// function trcTokenOnStorage(trcToken storage token) internal { // ERROR Storage location can only be given for array or struct types -// } - -function trcTokenToString(trcToken token) public constant returns(string r){ -// string s = token; // ERROR -// string s2 = string(token); // ERROR -} - -function trcTokenToUint256(trcToken token) public constant returns(uint256 r){ -uint256 u = token; // OK -uint256 u2 = uint256(token); // OK -r = u2; -} - -function trcTokenToAddress(trcToken token) public constant returns(address r){ -// address a = token; // ERROR -token = 0x1234567812345678123456781234567812345678123456781234567812345678; -address a2 = address(token); // OK -r = a2; -} - -function trcTokenToBytes(trcToken token) public constant returns(bytes r){ -// bytes b = token; // ERROR -// bytes b2 = bytes(token); // ERROR -} - -function trcTokenToBytes32(trcToken token) public constant returns(bytes32 r){ -// bytes32 b = token; // ERROR -bytes32 b2 = bytes32(token); // OK -r = b2; -} - -function trcTokenToArray(trcToken token) public constant returns(uint[] r){ -// uint[] a = token; // ERROR -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/contractUnknownException.sol b/framework/src/test/resources/soliditycode_v0.4.25/contractUnknownException.sol deleted file mode 100644 index be8af8f7451..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/contractUnknownException.sol +++ /dev/null @@ -1,65 +0,0 @@ - pragma solidity ^0.4.24; - -contract testA { - constructor() public payable { - A a = (new A).value(10)(); - a.fun(); - } -} - -contract testB { - constructor() public payable { - B b = (new B).value(10)(); - b.fun(); - } -} - - -contract testC { - constructor() public payable{ - C c = (new C).value(10)(); - c.fun(); - } -} - -contract testD { - constructor() public payable{ - D d = (new D).value(10)(); - d.fun(); - } -} - - -contract A { - constructor() public payable{ - selfdestruct(msg.sender); - } - function fun() { - } - -} - -contract B { - constructor() public payable { - revert(); - } - function fun() { - } -} - - -contract C { - constructor() public payable { - assert(1==2); - } - function fun() { - } -} - -contract D { - constructor() public payable { - require(1==2); - } - function fun() { - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest1TestRequireContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest1TestRequireContract.sol deleted file mode 100644 index a7c874ebd92..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest1TestRequireContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma solidity ^0.4.0; -contract TestThrowsContract{ - function testAssert(){ - assert(1==2); - } - function testRequire(){ - require(2==1); - } - function testRevert(){ - revert(); - } - function testThrow(){ - throw; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest2TestThrowsContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest2TestThrowsContract.sol deleted file mode 100644 index a7c874ebd92..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest2TestThrowsContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma solidity ^0.4.0; -contract TestThrowsContract{ - function testAssert(){ - assert(1==2); - } - function testRequire(){ - require(2==1); - } - function testRevert(){ - revert(); - } - function testThrow(){ - throw; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest3TestRevertContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest3TestRevertContract.sol deleted file mode 100644 index a7c874ebd92..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest3TestRevertContract.sol +++ /dev/null @@ -1,15 +0,0 @@ -pragma solidity ^0.4.0; -contract TestThrowsContract{ - function testAssert(){ - assert(1==2); - } - function testRequire(){ - require(2==1); - } - function testRevert(){ - revert(); - } - function testThrow(){ - throw; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest4noPayableContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest4noPayableContract.sol deleted file mode 100644 index 59c15a1b1ab..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest4noPayableContract.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma solidity ^0.4.0; - -contract noPayableContract { - -function noPayable() public returns (uint){ -return msg.value; -} -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest5noPayableConstructor.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest5noPayableConstructor.sol deleted file mode 100644 index c1138704b8b..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest5noPayableConstructor.sol +++ /dev/null @@ -1,10 +0,0 @@ -pragma solidity ^0.4.0; - -contract MyContract { - uint money; - - function MyContract(uint _money) { - require(msg.value >= _money); - money = _money; - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest6transferTestContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest6transferTestContract.sol deleted file mode 100644 index b0d93d238cf..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest6transferTestContract.sol +++ /dev/null @@ -1,8 +0,0 @@ -pragma solidity ^0.4.0; - -contract transferTestContract { - function tranferTest(address addr) public payable{ - addr.transfer(10); - - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest7payableFallbakContract.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest7payableFallbakContract.sol deleted file mode 100644 index af290a06804..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest7payableFallbakContract.sol +++ /dev/null @@ -1,13 +0,0 @@ -pragma solidity ^0.4.0; - -contract Test { - function() { x = 1; } - uint x; -} - - -contract Caller { - function callTest(Test test) { - test.call(0xabcdef01); // hash does not exist - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest8newContractGasNoenough.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest8newContractGasNoenough.sol deleted file mode 100644 index 79066c2bfc8..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest8newContractGasNoenough.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma solidity ^0.4.0; - -contract Account{ - uint256 public accId; - - function Account(uint accountId) payable{ - accId = accountId; - } -} - -contract Initialize{ - // Account public account = new Account(10); - - function newAccount(){ - Account account = new Account(1); - } - -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest9MessageUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest9MessageUsedErrorFeed.sol deleted file mode 100644 index f6187a6c3d1..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontest9MessageUsedErrorFeed.sol +++ /dev/null @@ -1,18 +0,0 @@ -pragma solidity ^0.4.0; - -contract MathedFeed { - - function divideMathed() public returns (uint ret) { - uint x=1; - uint y=0; - return x/y; - } -} - - -contract MathedUseContract { - - function MathedUse(address addr) public returns (uint) { - return MathedFeed(addr).divideMathed(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontestFunctionUsedErrorFeed.sol b/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontestFunctionUsedErrorFeed.sol deleted file mode 100644 index cc1e8c88306..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/requireExceptiontestFunctionUsedErrorFeed.sol +++ /dev/null @@ -1,17 +0,0 @@ -pragma solidity ^0.4.0; - -contract MessageFeed { - - function mValue() payable returns (uint ret) { - return msg.value; - } -} - -contract MessageUseContract { - function inputValue() payable returns (uint){ - return msg.value; - } - function messageUse(address addr) payable returns (uint) { - return MessageFeed(addr).mValue.value(1)(); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/soliditycode_v0.4.25/walletTestMutiSign004.sol b/framework/src/test/resources/soliditycode_v0.4.25/walletTestMutiSign004.sol deleted file mode 100644 index 7de52e9f155..00000000000 --- a/framework/src/test/resources/soliditycode_v0.4.25/walletTestMutiSign004.sol +++ /dev/null @@ -1,52 +0,0 @@ -//pragma solidity ^0.4.0; - -contract timeoutTest { - string public iarray1; - // cpu - function oneCpu() { - require(1==1); - } - - function storage8Char() { - iarray1 = "12345678"; - - } - - function testUseCpu(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - } - return count; - } - - - uint256[] public iarray; - uint public calculatedFibNumber; - mapping(address=>mapping(address=>uint256)) public m; - - function testUseStorage(uint256 a) public returns (uint256){ - uint256 count = 0; - for (uint256 i = 0; i < a; i++) { - count++; - iarray.push(i); - } - return count; - } - - // stack - uint n = 0; - function test() { - n += 1; - test(); - } - - function setFibonacci(uint n) public returns (uint256){ - calculatedFibNumber = fibonacci(n); - return calculatedFibNumber; - } - - function fibonacci(uint n) internal returns (uint) { - return fibonacci(n - 1) + fibonacci(n - 2); - } -} \ No newline at end of file diff --git a/framework/src/test/resources/testng.conf b/framework/src/test/resources/testng.conf deleted file mode 100644 index 2e5b9a375e0..00000000000 --- a/framework/src/test/resources/testng.conf +++ /dev/null @@ -1,539 +0,0 @@ -net { - type = mainnet -} - -fullnode = { - ip.list = [ - #Docker env - "127.0.0.1:50051", - "127.0.0.1:50052", - - #New beat1 - "39.106.145.222:50051", - "101.200.46.37:50051", - #"101.200.46.37:50051", - - #New beta2 - "101.200.46.37:50052", - "39.106.145.222:50052", - "101.200.46.37:50052", - - #Stress env - #"47.94.243.150:50051", - #"39.106.110.112:50051", - - #MainNet env - #"47.95.206.44:50051", - #"47.95.206.44:50051", - - - ] -} - -solidityNode = { - ip.list = [ - #Docker env - "127.0.0.1:50053", - "127.0.0.1:50062", - "127.0.0.1:50071", - - #New beat 1 - "39.106.145.222:50061", - "39.106.145.222:50061", - #"39.106.145.222:50071", - - #New beat 2 - "101.200.46.37:50053", - "101.200.46.37:50062", - "101.200.46.37:50071", - #"101.200.46.37:50071", - - - #Main Net env - #"47.95.206.44:50061", - ] -} - -httpnode = { - ip.list = [ - #docker env - "127.0.0.1:8090", - "127.0.0.1:8093", - "127.0.0.1:8097", - "127.0.0.1:8091", - "127.0.0.1:8098", - - - #New beta 2 - "101.200.46.37:50091", - "39.106.145.222:50091", - "101.200.46.37:50192", - "101.200.46.37:50094", - "101.200.46.37:50082", - #"101.200.46.37:50082", - ] -} - -eventnode = { - ip.list = [ - "tcp://127.0.0.1:50096", - #"tcp://39.106.145.222:50096", - ] -} - -jsonRpcNode = { - ip.list = [ - #"101.200.46.37:50545", - "127.0.0.1:50545", - "127.0.0.1:50555", - ] -} - -ethHttpsNode = { - host.list = [ - "mainnet.infura.io", - #"47.95.206.44:50545", - ] -} - - -foundationAccount = { - key1 = FC8BF0238748587B9617EB6D15D47A66C0E07C1A1959033CF249C6532DC29FE6 - key2 = 6815B367FDDE637E53E9ADC8E69424E07724333C9A2B973CFA469975E20753FC - #Main_in_mock_foundationAccount_key - #key1 = 324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096c6bacb8 - #key2 = 2925e186bb1e88988855f11ebf20ea3a6e19ed92328b0ffb576122e769d45b68 -} - - -witness = { - key1 = 369F095838EB6EED45D4F6312AF962D5B9DE52927DA9F04174EE49F9AF54BC77 - key2 = 9FD8E129DE181EA44C6129F727A6871440169568ADE002943EAD0E7A16D8EDAC - key3 = 291C233A5A7660FB148BAE07FCBCF885224F2DF453239BD983F859E8E5AA4602 - key4 = 99676348CBF9501D07819BD4618ED885210CB5A03FEAF6BFF28F0AF8E1DE7DBE - key5 = FA090CFB9F3A6B00BE95FE185E82BBCFC4DA959CA6A795D275635ECF5D58466D - #replay env witness - #key1 = 0528dc17428585fc4dece68b79fa7912270a1fe8e85f244372f59eb7e8925e04 - #key2 = 553c7b0dee17d3f5b334925f5a90fe99fb0b93d47073d69ec33eead8459d171e - #key3 = 324a2052e491e99026442d81df4d2777292840c1b3949e20696c49096c6bacb8 - #key4 = ff5d867c4434ac17d264afc6696e15365832d5e8000f75733ebb336d66df148d - #key5 = 2925e186bb1e88988855f11ebf20ea3a6e19ed92328b0ffb576122e769d45b68 -} - -mainWitness = { - key1 = 22a6aca17f8ec257cc57e190902767d7fedf908bba920b4fbeaab8f158e0da17 - key2 = b6d8d3382c32d4d066c4f830a7e53c3da9ad8b9665dda4ca081b6cd4e807d09c - key3 = 03caf867c46aaf86d56aa446db80cb49305126b77bfaccfe57ab17bdb4993ccc - key4 = 763009595dd132aaf2d248999f2c6e7ba0acbbd9a9dfd88f7c2c158d97327645 - key5 = a21a3074d4d84685efaffcd7c04e3eccb541ec4c85f61c41a099cd598ad39825 - key6 = 541a2d585fcea7e9b1803df4eb49af0eb09f1fa2ce06aa5b8ed60ac95655d66d - key7 = 7d5a7396d6430edb7f66aa5736ef388f2bea862c9259de8ad8c2cfe080f6f5a0 - key8 = 7c4977817417495f4ca0c35ab3d5a25e247355d68f89f593f3fea2ab62c8644f - key9 = 4521c13f65cc9f5c1daa56923b8598d4015801ad28379675c64106f5f6afec30 - key10 = f33101ea976d90491dcb9669be568db8bbc1ad23d90be4dede094976b67d550e - key11 = 1bb32958909299db452d3c9bbfd15fd745160d63e4985357874ee57708435a00 - key12 = 29c91bd8b27c807d8dc2d2991aa0fbeafe7f54f4de9fac1e1684aa57242e3922 - key13 = 97317d4d68a0c5ce14e74ad04dfc7521f142f5c0f247b632c8f94c755bdbe669 - key14 = 1fe1d91bbe3ac4ac5dc9866c157ef7615ec248e3fd4f7d2b49b0428da5e046b2 - key15 = 7c37ef485e186e07952bcc8e30cd911a6cd9f2a847736c89132762fb67a42329 - key16 = bcc142d57d872cd2cc1235bca454f2efd5a87f612856c979cc5b45a7399272a8 - key17 = 6054824dc03546f903a06da1f405e72409379b83395d0bbb3d4563f56e828d52 - key18 = 87cc8832b1b4860c3c69994bbfcdae9b520e6ce40cbe2a90566e707a7e04fc70 - key19 = c96c92c8a5f68ffba2ced3f7cd4baa6b784838a366f62914efdc79c6c18cd7d0 - key20 = d29e34899a21dc801c2be88184bed29a66246b5d85f26e8c77922ee2403a1934 - key21 = dc51f31e4de187c1c2530d65fb8f2958dff4c37f8cea430ce98d254baae37564 - key22 = ff43b371d67439bb8b6fa6c4ff615c954682008343d4cb2583b19f50adbac90f - key23 = dbc78781ad27f3751358333412d5edc85b13e5eee129a1a77f7232baadafae0e - key24 = a79a37a3d868e66456d76b233cb894d664b75fd91861340f3843db05ab3a8c66 - key25 = a8107ea1c97c90cd4d84e79cd79d327def6362cc6fd498fc3d3766a6a71924f6 - key26 = b5076206430b2ca069ae2f4dc6f20dd0d74551559878990d1df12a723c228039 - key27 = 442513e2e801bc42d14d33b8148851dae756d08eeb48881a44e1b2002b3fb700 -} - -defaultParameter = { - maxFeeLimit = 1000000000 - assetDescription = stest-assetissue - assetUrl = github.com/tronprotocol/wallet/stest - multiSignFee = 1000000 - updateAccountPermissionFee = 100000000 - httpConnectionTimeout = 19000 - httpSoTimeout = 18000 - createWitnessAmount = 9999000000 - operations = 7fff1fc0033e3300000000000000000000000000000000000000000000000000 - delayTransactionFee = 100000 - cancleDelayTransactionFee = 50000 - solidityCompilerVersion = "v5" - solidityCompile = "../solcDIR/solc" - zenTokenOwnerKey = 2925e186bb1e88988855f11ebf20ea3a6e19ed92328b0ffb576122e769d45b68 - zenTokenId = 1000001 - zenTokenFee = 10000000 - zenTokenWhenCreateNewAddress = 1000000 - zenTrc20TokenOwnerKey = ede941a01eb8234866f60c7e8e95db4614bb0d05298d82bae0abea81f1861046 - jsonRpcOwnerKey = dbc78781ad27f3751358333412d5edc85b13e5eee129a1a77f7232baadafae0e - blackHoleAddress = THmtHi1Rzq4gSKYGEKv1DPkV7au6xU1AUB -} - - -code = { - code_AssertException_testdivideInt = "608060405234801561001057600080fd5b5060ac8061001f6000396000f300608060405260043610603d5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166226ff5581146042575b600080fd5b348015604d57600080fd5b50605a600435602435606c565b60408051918252519081900360200190f35b60008183811515607857fe5b0593925050505600a165627a7a72305820b587002bc926764a997a3925613203906e484069ff4e2f8324b4dce6088326220029" - code_AssertException_testfindArgsContractMinTest = "608060405234801561001057600080fd5b50610134806100206000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663329000b58114610045575b600080fd5b34801561005157600080fd5b5061005d60043561006f565b60408051918252519081900360200190f35b604080516003808252608082019092526000916060919060208201838038833901905050905060018160008151811015156100a657fe5b602090810290910101528051600290829060019081106100c257fe5b602090810290910101528051600390829060029081106100de57fe5b6020908102909101015280518190849081106100f657fe5b906020019060200201519150509190505600a165627a7a72305820e426d63fe06962cb78b523edb9295a369bc2cc1b82cac5740d74e924b1a398c40029" - code_AssertException_testbyteMinContract = "608060405234801561001057600080fd5b50610305806100206000396000f3006080604052600436106100405763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166383be82a38114610045575b600080fd5b34801561005157600080fd5b5061005d600435610092565b604080517fff000000000000000000000000000000000000000000000000000000000000009092168252519081900360200190f35b60408051600380825281830190925260009160208201606080388339505081516100c392600092506020019061023e565b50600c60f860020a0260008081546001816001161561010002031660029004811015156100ec57fe5b81546001161561010b5790600052602060002090602091828204019190065b601f036101000a81548160ff0219169060f860020a84040217905550600d60f860020a0260006001815460018160011615610100020316600290048110151561015057fe5b81546001161561016f5790600052602060002090602091828204019190065b601f036101000a81548160ff0219169060f860020a84040217905550600e60f860020a026000600281546001816001161561010002031660029004811015156101b457fe5b8154600116156101d35790600052602060002090602091828204019190065b601f036101000a81548160ff0219169060f860020a84040217905550600082815460018160011615610100020316600290048110151561020f57fe5b81546001161561022e5790600052602060002090602091828204019190065b905460f860020a911a0292915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061027f57805160ff19168380011785556102ac565b828001600101855582156102ac579182015b828111156102ac578251825591602001919060010190610291565b506102b89291506102bc565b5090565b6102d691905b808211156102b857600081556001016102c2565b905600a165627a7a72305820c42a0dcadb40b736d1d61cf46a58a66e740573568264ed5ce2f9b1de442d39fe0029" - code_AssertException_testenum = "608060405234801561001057600080fd5b5060f18061001f6000396000f30060806040526004361060485763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166367cb61b68114604d578063fb76fa52146082575b600080fd5b348015605857600080fd5b50605f609c565b60405180826003811115606e57fe5b60ff16815260200191505060405180910390f35b348015608d57600080fd5b50609a60ff6004351660a5565b005b60005460ff1690565b6000805482919060ff1916600183600381111560bd57fe5b0217905550505600a165627a7a723058201ad3f79794ab99b9429a737984c9e0722214f7412fa23f4f8895f58032e222360029" - code_AssertException_testmoveRight = "608060405234801561001057600080fd5b5060b38061001f6000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630599d3dc81146043575b600080fd5b348015604e57600080fd5b506058600435606a565b60408051918252519081900360200190f35b60008160056000821215607957fe5b60029190910a9005929150505600a165627a7a72305820e944c4077f7d4f205074c52900d041d56d5f700a779aed8ced4af969f99464760029" - code_AssertException_testuninitializedContract = "608060405234801561001057600080fd5b5060e18061001f6000396000f30060806040526004361060485763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166366e41cb78114604d5780636b59084d146071575b600080fd5b348015605857600080fd5b50605f6083565b60408051918252519081900360200190f35b348015607c57600080fd5b50605f609c565b600060b36096600460058363ffffffff16565b91505090565b600060af60966004600563ffffffff8416565b0290565bfe00a165627a7a72305820adcb5758cba4260d0f840e31e0b97435395f43728ddfe8024de688c29583dd220029" - code_AssertException_testTestAssertContract = "608060405234801561001057600080fd5b5060b58061001f6000396000f300608060405260043610605c5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416632b813bc081146061578063357815c414607557806350bff6bf146075578063a26388bb146075575b600080fd5b348015606c57600080fd5b5060736087565b005b348015608057600080fd5b506073605c565bfe00a165627a7a723058209284d2c51e121903dde36db88dae131b1b20dc83b987a6f491dcac2d9b2d30db0029" - - code_ContractGrammar001_testGrammar001 = "608060405234801561001057600080fd5b50610105806100206000396000f30060806040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630a75057381146057578063cd580ff3146083578063f0fdf834146098575b600080fd5b348015606257600080fd5b506071600435151560243560ad565b60408051918252519081900360200190f35b348015608e57600080fd5b50607160043560ce565b34801560a357600080fd5b50607160043560d4565b600060d4831560ba575060ce5b60c6838263ffffffff16565b949350505050565b60020290565b8002905600a165627a7a7230582032df33d18c9876ca1a32117c2b4c526215a9dd8feeb3c9d849690539b3a992ac0029" - code_ContractGrammar001_testGrammar002 = "610199610030600b82828239805160001a6073146000811461002057610022565bfe5b5030600052607381538281f300730000000000000000000000000000000000000000301460806040526004361061006d5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663483b8a1481146100725780636ce8e081146100a1578063831cb739146100bc575b600080fd5b81801561007e57600080fd5b5061008d6004356024356100d7565b604080519115158252519081900360200190f35b8180156100ad57600080fd5b5061008d600435602435610117565b8180156100c857600080fd5b5061008d60043560243561012d565b60008181526020839052604081205460ff1615156100f757506000610111565b506000818152602083905260409020805460ff1916905560015b92915050565b6000908152602091909152604090205460ff1690565b60008181526020839052604081205460ff161561014c57506000610111565b50600090815260209190915260409020805460ff19166001908117909155905600a165627a7a723058205198109bfdc1087cafa3e909576bdb656bb058100cf618ef42eecaeb64e30b7f0029" - code1_ContractGrammar001_testGrammar002 = "608060405234801561001057600080fd5b50610139806100206000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663f207564e8114610045575b600080fd5b34801561005157600080fd5b5061005d60043561005f565b005b73__browser/TvmTest_p1_Grammar_002.sol:S__63831cb7396000836040518363ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808381526020018281526020019250505060206040518083038186803b1580156100d357600080fd5b505af41580156100e7573d6000803e3d6000fd5b505050506040513d60208110156100fd57600080fd5b5051151561010a57600080fd5b505600a165627a7a7230582044978981980e6552ad10452a66a2038edf7739f149dcced7705b0e329d594f300029" - code_ContractGrammar001_testGrammar003 = "610199610030600b82828239805160001a6073146000811461002057610022565bfe5b5030600052607381538281f300730000000000000000000000000000000000000000301460806040526004361061006d5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663483b8a1481146100725780636ce8e081146100a1578063831cb739146100bc575b600080fd5b81801561007e57600080fd5b5061008d6004356024356100d7565b604080519115158252519081900360200190f35b8180156100ad57600080fd5b5061008d600435602435610117565b8180156100c857600080fd5b5061008d60043560243561012d565b60008181526020839052604081205460ff1615156100f757506000610111565b506000818152602083905260409020805460ff1916905560015b92915050565b6000908152602091909152604090205460ff1690565b60008181526020839052604081205460ff161561014c57506000610111565b50600090815260209190915260409020805460ff19166001908117909155905600a165627a7a72305820026d1eee826a0f8eb329643f3547e967fb7631f83b1855c607bdd82706af37520029" - code1_ContractGrammar001_testGrammar003 = "608060405234801561001057600080fd5b50610137806100206000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663f207564e8114610045575b600080fd5b34801561005157600080fd5b5061005d60043561005f565b005b604080517f831cb7390000000000000000000000000000000000000000000000000000000081526000600482015260248101839052905173__browser/TvmTest_p1_Grammar_003.sol:S__9163831cb739916044808301926020929190829003018186803b1580156100d157600080fd5b505af41580156100e5573d6000803e3d6000fd5b505050506040513d60208110156100fb57600080fd5b5051151561010857600080fd5b505600a165627a7a72305820de817c43c8f916d8e300ee0f317061f220ba7971379253fc437c52ab40295d6f0029" - code_ContractGrammar001_testGrammar004 = "60f561002f600b82828239805160001a6073146000811461001f57610021565bfe5b5030600052607381538281f300730000000000000000000000000000000000000000301460806040526004361060555763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166324fef5c88114605a575b600080fd5b818015606557600080fd5b5060726004356024356084565b60408051918252519081900360200190f35b6000805b835481101560bc57828482815481101515609e57fe5b9060005260206000200154141560b55780915060c2565b6001016088565b60001991505b50929150505600a165627a7a72305820dd50badae5d39d8013dd477274519025531d3c7c11cd98cd10290fbace71b9510029" - code1_ContractGrammar001_testGrammar004 = "608060405234801561001057600080fd5b50610281806100206000396000f3006080604052600436106100615763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630178fe3f8114610066578063e33b870714610090578063e81cf24c146100aa578063f0ba8440146100c5575b600080fd5b34801561007257600080fd5b5061007e6004356100dd565b60408051918252519081900360200190f35b34801561009c57600080fd5b506100a86004356100ff565b005b3480156100b657600080fd5b506100a8600435602435610131565b3480156100d157600080fd5b5061007e600435610236565b600080828154811015156100ed57fe5b90600052602060002001549050919050565b600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5630155565b604080517f24fef5c800000000000000000000000000000000000000000000000000000000815260006004820181905260248201859052915173__browser/TvmTest_p1_Grammar_004.sol:S__916324fef5c8916044808301926020929190829003018186803b1580156101a557600080fd5b505af41580156101b9573d6000803e3d6000fd5b505050506040513d60208110156101cf57600080fd5b5051905060001981141561021457600080546001810182559080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301829055610231565b8160008281548110151561022457fe5b6000918252602090912001555b505050565b600080548290811061024457fe5b6000918252602090912001549050815600a165627a7a72305820e8c6ea7734c94bd93e5388cb46b5a5ba3807df808e86fb52d4fa2a792685d9280029" - code_ContractGrammar001_testGrammar006 = "608060405234801561001057600080fd5b50610159806100206000396000f3006080604052600436106100825763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166321183e8d81146100875780637f6b590c146100a15780638de6f511146100b9578063b3de648b146100a1578063e668f6b6146100b9578063e7708d03146100b9578063fb095f2e146100a1575b600080fd5b34801561009357600080fd5b5061009f6004356100d1565b005b3480156100ad57600080fd5b5061009f6004356100e2565b3480156100c557600080fd5b5061009f6004356100e5565b600a5b6000190180156100d4575050565b50565b6100e2565b50919050565b828110156100ea576002909102906001016100f0565b60008180156101245761011b60018403610106565b830291506100ea565b506001929150505600a165627a7a723058209488a62acdb28a3bac209504cc3dd53d2ef7bf56cbb835e431c507bbc2b0b20b0029" - - code_ContractGrammar002_testGrammar007 = "608060405234801561001057600080fd5b506000602081905260017fe831479d2c88b7e2c4154b0e3fd4b67c62580aba2734ac954410a8c097fac7c35560027f156aefbe71d87b3f83e37064ce76ea7eb25ea897d2708aad4c1d03439058d3a3557f7a7a790000000000000000000000000000000000000000000000000000000000905260077fd0d0b23e4a00f3e9683c2bc8ad2b8ee67c66dc4b2ae07ae98ee14d014badcf83556101b2806100b66000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166337721ab7811461005b578063a633d8d414610129578063ec56a37314610153575b600080fd5b34801561006757600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526100b494369492936024939284019190819084018382808284375094975061016b9650505050505050565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100ee5781810151838201526020016100d6565b50505050905090810190601f16801561011b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561013557600080fd5b5061014160043561016e565b60408051918252519081900360200190f35b34801561015f57600080fd5b50610141600435610174565b90565b60030a90565b600060208190529081526040902054815600a165627a7a72305820dda8d0ad404466b0389ba7a490a63e5acc2d4eaf8ee3f4937e09084fba1f5a5a0029" - code1_ContractGrammar002_testGrammar007 = "608060405234801561001057600080fd5b5060405160208061033d833981016040525160018054600160a060020a0319908116600160a060020a039384161791829055600280549290931691161790556102df8061005e6000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166349de3f08811461005b5780639e3151a814610085578063f6598275146100b5575b600080fd5b34801561006757600080fd5b506100736004356100cd565b60408051918252519081900360200190f35b34801561009157600080fd5b506100b373ffffffffffffffffffffffffffffffffffffffff600435166101c9565b005b3480156100c157600080fd5b50610073600435610205565b600254604080517fec56a37300000000000000000000000000000000000000000000000000000000815260048101849052905160009273ffffffffffffffffffffffffffffffffffffffff169163ec56a37391602480830192602092919082900301818787803b15801561014057600080fd5b505af1158015610154573d6000803e3d6000fd5b505050506040513d602081101561016a57600080fd5b50506001546040805173ffffffffffffffffffffffffffffffffffffffff9092168252336020830152818101849052517f09208868f8090ea021d1f0e2ed8182e6a6f23a1f447267430e531bf2003c09199181900360600190a1919050565b6000805473ffffffffffffffffffffffffffffffffffffffff191673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b600254604080517fa633d8d4000000000000000000000000000000000000000000000000000000008152600481018490529051600092839273ffffffffffffffffffffffffffffffffffffffff9091169163a633d8d49160248082019260209290919082900301818787803b15801561027d57600080fd5b505af1158015610291573d6000803e3d6000fd5b505050506040513d60208110156102a757600080fd5b505192909201929150505600a165627a7a723058208c58520ab7ab3c09ab693d81d3c7746deb66b7515d4258f26a379367fca4b95d0029" - code_ContractGrammar002_testGrammar008 = "608060405234801561001057600080fd5b50610188806100206000396000f30060806040526004361061004b5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663dba7ab6c8114610050578063f5f5ba7214610077575b600080fd5b34801561005c57600080fd5b50610065610101565b60408051918252519081900360200190f35b34801561008357600080fd5b5061008c610125565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100c65781810151838201526020016100ae565b50505050905090810190601f1680156100f35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b7f6d69616f7700000000000000000000000000000000000000000000000000000090565b60408051808201909152600681527f46656c696e6500000000000000000000000000000000000000000000000000006020820152905600a165627a7a723058206cd9ce9902b03355d5f4bd8e0e4c4d9cd5b5d65364c50454f2418305ab515b4f0029" - code_ContractGrammar002_testGrammar010 = "608060405234801561001057600080fd5b506101b7806100206000396000f30060806040526004361061004b5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166355b775ea8114610050578063f198f5df14610080575b600080fd5b34801561005c57600080fd5b5061007e73ffffffffffffffffffffffffffffffffffffffff60043516610095565b005b34801561008c57600080fd5b5061007e6100d1565b6000805473ffffffffffffffffffffffffffffffffffffffff191673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1663370158ea600a610320906040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004016020604051808303818589803b15801561015b57600080fd5b5088f115801561016f573d6000803e3d6000fd5b5050505050506040513d602081101561018757600080fd5b50505600a165627a7a72305820f2b3e0e175369ea0df0aef7c6b9e8644b34c144efe85d21cb38539d1abd32e970029" - code_ContractGrammar002_testGrammar011 = "608060405234801561001057600080fd5b5060c88061001f6000396000f30060806040526004361060485763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166313d1aa2e8114604d578063e2179b8e146077575b600080fd5b348015605857600080fd5b506065600435602435608b565b60408051918252519081900360200190f35b348015608257600080fd5b506089608f565b005b5090565b609960036002608b565b505600a165627a7a723058202aeac1a0dbc6913a9378d4e8294f1061e5798083067aa9db5d95d8d78f24d5430029" - code_ContractGrammar002_testGrammar012 = "608060405234801561001057600080fd5b50610169806100206000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663370158ea8114610045575b600080fd5b61004d6100c7565b6040805198895273ffffffffffffffffffffffffffffffffffffffff97881660208a01527bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19909616888701526060880194909452608087019290925260a086015290921660c084015260e083019190915251908190036101000190f35b6000806000806000806000806000806000806000806000805a9f50339e50507bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19600035169c50349b50429a503a995032985050303196508d95508c94508b93508a925089915088905050505050505090919293949596975600a165627a7a72305820ba2fd5e479d9fa3924efa9cef8dde8690cf0618a742fe972533b7eb5b2b3ca990029" - code_ContractGrammar002_testGrammar013 = "60806040526000805534801561001457600080fd5b5060018054600160a060020a0319163317905561014c806100366000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166341c0e1b5811461005b578063a87d942c14610072578063d09de08a14610099575b600080fd5b34801561006757600080fd5b506100706100ae565b005b34801561007e57600080fd5b506100876100eb565b60408051918252519081900360200190f35b3480156100a557600080fd5b506100706100f1565b60015473ffffffffffffffffffffffffffffffffffffffff163314156100e95760015473ffffffffffffffffffffffffffffffffffffffff16ff5b565b60005490565b600154600a9073ffffffffffffffffffffffffffffffffffffffff1633141561011d5760008054820190555b505600a165627a7a72305820604072633e1ae10ab2bb71c55f8678aafe925bee8ebffa82a1eddc5c2ed1fc2d0029" - - code_ContractGrammar003_testGrammar014 = "608060405234801561001057600080fd5b50610435806100206000396000f3006080604052600436106100745763ffffffff60e060020a6000350416633da5d187811461007957806343c3a43a1461009f578063b053ebd4146100c3578063c8287909146100f4578063d7d21f5b14610109578063dd92afef1461012d578063ee9e398114610154578063fa06834b14610175575b600080fd5b34801561008557600080fd5b5061009d600160a060020a036004351660243561018a565b005b3480156100ab57600080fd5b5061009d600160a060020a0360043516602435610205565b3480156100cf57600080fd5b506100d8610282565b60408051600160a060020a039092168252519081900360200190f35b34801561010057600080fd5b506100d8610291565b34801561011557600080fd5b5061009d600160a060020a03600435166024356102a0565b34801561013957600080fd5b5061014261031d565b60408051918252519081900360200190f35b34801561016057600080fd5b5061009d600160a060020a0360043516610323565b34801561018157600080fd5b50610142610403565b81600160a060020a031660405180807f73657456616c75652875696e74323536290000000000000000000000000000008152506011019050604051809103902060e060020a9004826040518263ffffffff1660e060020a02815260040180828152602001915050600060405180830381865af4505050505050565b81600160a060020a031660405180807f73657456616c75652875696e74323536290000000000000000000000000000008152506011019050604051809103902060e060020a9004826040518263ffffffff1660e060020a028152600401808281526020019150506000604051808303816000875af1505050505050565b600154600160a060020a031681565b600154600160a060020a031690565b81600160a060020a031660405180807f73657456616c75652875696e74323536290000000000000000000000000000008152506011019050604051809103902060e060020a9004826040518263ffffffff1660e060020a028152600401808281526020019150506000604051808303816000875af2505050505050565b60005481565b80600160a060020a031660405180807f61646428290000000000000000000000000000000000000000000000000000008152506005019050604051809103902060e060020a90046040518163ffffffff1660e060020a0281526004016000604051808303816000875af1925050505080600160a060020a031660405180807f61646428290000000000000000000000000000000000000000000000000000008152506005019050604051809103902060e060020a90046040518163ffffffff1660e060020a0281526004016000604051808303816000875af15050505050565b600054905600a165627a7a7230582093a7a067c2321655a53783d1d54310cf8d57828093eeb9cf511536f8834f2de50029" - code1_ContractGrammar003_testGrammar014 = "608060405234801561001057600080fd5b5061055d806100206000396000f30060806040526004361061007f5763ffffffff60e060020a6000350416630eec1aba81146100845780631645c6c8146100b5578063466427c0146100cd5780634f2be91f146100e557806355241077146100fc578063b053ebd414610114578063c828790914610129578063dd92afef1461013e578063fa06834b14610165575b600080fd5b34801561009057600080fd5b5061009961017a565b60408051600160a060020a039092168252519081900360200190f35b3480156100c157600080fd5b50610099600435610189565b3480156100d957600080fd5b506100996004356101a4565b3480156100f157600080fd5b506100fa6101bf565b005b34801561010857600080fd5b506100fa600435610407565b34801561012057600080fd5b5061009961042b565b34801561013557600080fd5b5061009961043a565b34801561014a57600080fd5b50610153610449565b60408051918252519081900360200190f35b34801561017157600080fd5b5061015361044f565b600254600160a060020a031681565b600460205260009081526040902054600160a060020a031681565b600360205260009081526040902054600160a060020a031681565b600080546001018155806101d1610455565b604051809103906000f0801580156101ed573d6000803e3d6000fd5b50915081600160a060020a03166338cc48316040518163ffffffff1660e060020a028152600401602060405180830381600087803b15801561022e57600080fd5b505af1158015610242573d6000803e3d6000fd5b505050506040513d602081101561025857600080fd5b5051600080548152600360209081526040808320805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0395861617905580517f38cc48310000000000000000000000000000000000000000000000000000000081529051938616936338cc483193600480840194938390030190829087803b1580156102e157600080fd5b505af11580156102f5573d6000803e3d6000fd5b505050506040513d602081101561030b57600080fd5b50516002805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03909216919091179055610341610455565b604051809103906000f08015801561035d573d6000803e3d6000fd5b50905080600160a060020a03166338cc48316040518163ffffffff1660e060020a028152600401602060405180830381600087803b15801561039e57600080fd5b505af11580156103b2573d6000803e3d6000fd5b505050506040513d60208110156103c857600080fd5b5051600080548152600460205260409020805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a039092169190911790555050565b6000556001805473ffffffffffffffffffffffffffffffffffffffff191633179055565b600154600160a060020a031681565b600154600160a060020a031690565b60005481565b60005490565b60405160cd80610465833901905600608060405234801561001057600080fd5b5060ae8061001f6000396000f300608060405260043610603e5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166338cc483181146043575b600080fd5b348015604e57600080fd5b506055607e565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b30905600a165627a7a7230582002da030c3a635a762a2cd57a6d82b2c8a097197a64cad72ca827e7e227e67dd90029a165627a7a7230582023d343e99ca6abe7ec5591fd8706cb1a6d5bb25e9868b17445ad3171a6e295fd0029" - code_ContractGrammar003_testGrammar015 = "608060405234801561001057600080fd5b50610317806100206000396000f3006080604052600436106100535763ffffffff60e060020a600035041663292a1c6881146100b357806342a78883146100da57806342bb5a26146100f457806366b0bae0146101095780637c06885a1461011e575b34801561005f57600080fd5b507f17c1956f6e992470102c5fc953bf560fda31fabee8737cf8e77bdde00eb5698d6000366040518080602001828103825284848281815260200192508082843760405192018290039550909350505050a1005b3480156100bf57600080fd5b506100c8610133565b60408051918252519081900360200190f35b3480156100e657600080fd5b506100f2600435610168565b005b34801561010057600080fd5b506100c86101c4565b34801561011557600080fd5b506100f26101f9565b34801561012a57600080fd5b506100f261027c565b604080517f457869737446756e6343616c6c65642862797465732c75696e743235362900008152905190819003601e01902090565b7fb776d49293459725ca7d6a5abc60e389d2f3d067d4f028ba9cd790f69659984660003683604051808060200183815260200182810382528585828181526020019250808284376040519201829003965090945050505050a150565b604080517f46616c6c6261636b43616c6c65642862797465732900000000000000000000008152905190819003601501902090565b600060405180807f66756e6374696f6e4e6f744578697374282900000000000000000000000000008152506012019050604051809103902090503073ffffffffffffffffffffffffffffffffffffffff168160e060020a90046040518163ffffffff1660e060020a0281526004016000604051808303816000875af15050505050565b604080517f657869737446756e632875696e743235362900000000000000000000000000008152815190819003601201812063ffffffff60e060020a8083049182160283526001600484015292519092309290916024808301926000929190829003018183875af150505050505600a165627a7a7230582065d5e244faea44396a1826f0c2919055c883a00eef975f72a579ee7f0c654a0b0029" - code_ContractGrammar003_testGrammar016 = "608060405234801561001057600080fd5b50610270806100206000396000f3006080604052600436106100275763ffffffff60e060020a600035041663bef55ef3811461002c575b600080fd5b34801561003857600080fd5b50610041610043565b005b60008061004e610157565b604051809103906000f08015801561006a573d6000803e3d6000fd5b5091508173ffffffffffffffffffffffffffffffffffffffff16635b4b73a960036040518263ffffffff1660e060020a02815260040180828152602001915050600060405180830381600087803b1580156100c457600080fd5b505af11580156100d8573d6000803e3d6000fd5b505050508173ffffffffffffffffffffffffffffffffffffffff16633bc5de306040518163ffffffff1660e060020a028152600401602060405180830381600087803b15801561012757600080fd5b505af115801561013b573d6000803e3d6000fd5b505050506040513d602081101561015157600080fd5b50505050565b60405160de80610167833901905600608060405234801561001057600080fd5b5060bf8061001f6000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633bc5de308114604d5780635b4b73a9146071575b600080fd5b348015605857600080fd5b50605f6088565b60408051918252519081900360200190f35b348015607c57600080fd5b506086600435608e565b005b60005490565b6000555600a165627a7a72305820f4a95b9ecc5b7f7b57cbf2caff1c5f2f5e6e2dbd28464523cc05abde5864fd010029a165627a7a723058207ab90bb4123df32a1805dc37faaac054a403d1ab28007eb48c99ea48fefae6e90029" - code1_ContractGrammar003_testGrammar016 = "608060405234801561001057600080fd5b50610214806100206000396000f3006080604052600436106100565763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633bc5de30811461005b5780635b4b73a914610082578063e2179b8e1461009c575b600080fd5b34801561006757600080fd5b506100706100b1565b60408051918252519081900360200190f35b34801561008e57600080fd5b5061009a6004356100b7565b005b3480156100a857600080fd5b5061009a6100bc565b60005490565b600055565b6000806100c76100fb565b604051809103906000f0801580156100e3573d6000803e3d6000fd5b5091506100f2600360056100f7565b505050565b0190565b60405160de8061010b833901905600608060405234801561001057600080fd5b5060bf8061001f6000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633bc5de308114604d5780635b4b73a9146071575b600080fd5b348015605857600080fd5b50605f6088565b60408051918252519081900360200190f35b348015607c57600080fd5b506086600435608e565b005b60005490565b6000555600a165627a7a72305820f4a95b9ecc5b7f7b57cbf2caff1c5f2f5e6e2dbd28464523cc05abde5864fd010029a165627a7a723058205eb1e089faa9ff3eba073d682ee515d9d086d2ce3d4043109292b99a8a91d15f0029" - code_ContractGrammar003_testGrammar017 = "608060405234801561001057600080fd5b50610306806100206000396000f3006080604052600436106100565763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630121b93f811461005b5780635f72f4501461006857806397a9dae914610094575b600080fd5b6100666004356100d7565b005b34801561007457600080fd5b50610080600435610160565b604080519115158252519081900360200190f35b3480156100a057600080fd5b506100c573ffffffffffffffffffffffffffffffffffffffff600435166024356101e4565b60408051918252519081900360200190f35b60009081526001602081815260408084208151808301835233815234818501818152600384018054808901909155885260048401909552929095209451855473ffffffffffffffffffffffffffffffffffffffff191673ffffffffffffffffffffffffffffffffffffffff90911617855591519390920192909255600290910180549091019055565b600081815260016020819052604082209081015460028201548391111561018a57600092506101dd565b506002810180546000918290558254604051919273ffffffffffffffffffffffffffffffffffffffff9091169183156108fc0291849190818181858888f1935050505015156101d857600080fd5b600192505b5050919050565b6040805160808101825273ffffffffffffffffffffffffffffffffffffffff9384168152602080820193845260009282018381526060830184815293805260019182905291517fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb49805473ffffffffffffffffffffffffffffffffffffffff1916919096161790945591517fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4a5590517fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4b55517fa6eef7e35abe7026729641147f7915573c7e97b47efa546f5f6e3230263bcb4c55905600a165627a7a72305820774c07868cec7fa6d603c6bffa4ad224b2c7523a44248047a445872f15b064980029" - code_ContractGrammar003_testGrammar018 = "608060405234801561001057600080fd5b5061025b806100206000396000f3006080604052600436106100775763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166307423b35811461007c5780634c15d6db146100a35780635ee41656146100b8578063a449e8eb146100cd578063b7a0961a146100e2578063d23d7e8a1461007c575b600080fd5b34801561008857600080fd5b506100916100f7565b60408051918252519081900360200190f35b3480156100af57600080fd5b5061009161012c565b3480156100c457600080fd5b5061009161013a565b3480156100d957600080fd5b50610091610147565b3480156100ee57600080fd5b506100916101b4565b604080517f31310000000000000000000000000000000000000000000000000000000000008152905190819003600201902090565b600060046003600209905090565b6000600360028008905090565b6000600260405180807f313100000000000000000000000000000000000000000000000000000000000081525060020190506020604051808303816000865af1158015610198573d6000803e3d6000fd5b5050506040513d60208110156101ad57600080fd5b5051905090565b6000600360405180807f313100000000000000000000000000000000000000000000000000000000000081525060020190506020604051808303816000865af1158015610205573d6000803e3d6000fd5b505050604051516c01000000000000000000000000026bffffffffffffffffffffffff19169050905600a165627a7a72305820af56e004716c8ccf6d0609f6bcdc39fa45fda7fbc38e049ef6bab4609abf86e10029" - code_ContractGrammar003_testGrammar019 = "6080604052348015600f57600080fd5b50603580601d6000396000f3006080604052600080fd00a165627a7a7230582027e85e5bf589c5cecb1dd0d8712fa54ff07ff16b4dca5a602c53587c17898b2f0029" - code_ContractGrammar003_testGrammar020 = "608060405234801561001057600080fd5b5060a48061001f6000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063ccb5f721146044575b600080fd5b348015604f57600080fd5b5060566058565b005b620f424080141515606857600080fd5b600180141515607657600080fd5b5600a165627a7a72305820fdd16dc5b670249de6546a7474b1c29f5894578d17a251188bc616cc4476022c0029" - code_ContractScenario004_deployErc20TronToken = "60c0604052600660808190527f54726f6e6978000000000000000000000000000000000000000000000000000060a090815261003e916000919061013c565b506040805180820190915260038082527f545258000000000000000000000000000000000000000000000000000000000060209092019182526100839160019161013c565b506006600281905560006005558054600160a860020a03191690553480156100aa57600080fd5b50604051602080610abc83398101604081815291516006805461010060a860020a031916336101000217905567016345785d8a00006005819055600160a060020a03821660008181526003602090815286822084905592855294519294909390927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a3506101d7565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061017d57805160ff19168380011785556101aa565b828001600101855582156101aa579182015b828111156101aa57825182559160200191906001019061018f565b506101b69291506101ba565b5090565b6101d491905b808211156101b657600081556001016101c0565b90565b6108d6806101e66000396000f3006080604052600436106100cf5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100d457806307da68f51461015e578063095ea7b31461017557806318160ddd146101ad57806323b872dd146101d4578063313ce567146101fe57806342966c681461021357806370a082311461022b57806375f12b211461024c57806395d89b4114610261578063a9059cbb14610276578063be9a65551461029a578063c47f0027146102af578063dd62ed3e14610308575b600080fd5b3480156100e057600080fd5b506100e961032f565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561012357818101518382015260200161010b565b50505050905090810190601f1680156101505780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561016a57600080fd5b506101736103bd565b005b34801561018157600080fd5b50610199600160a060020a03600435166024356103e5565b604080519115158252519081900360200190f35b3480156101b957600080fd5b506101c261049e565b60408051918252519081900360200190f35b3480156101e057600080fd5b50610199600160a060020a03600435811690602435166044356104a4565b34801561020a57600080fd5b506101c26105c1565b34801561021f57600080fd5b506101736004356105c7565b34801561023757600080fd5b506101c2600160a060020a036004351661065e565b34801561025857600080fd5b50610199610670565b34801561026d57600080fd5b506100e9610679565b34801561028257600080fd5b50610199600160a060020a03600435166024356106d3565b3480156102a657600080fd5b5061017361079d565b3480156102bb57600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526101739436949293602493928401919081908401838280828437509497506107c29650505050505050565b34801561031457600080fd5b506101c2600160a060020a03600435811690602435166107f2565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103b55780601f1061038a576101008083540402835291602001916103b5565b820191906000526020600020905b81548152906001019060200180831161039857829003601f168201915b505050505081565b6006546101009004600160a060020a031633146103d657fe5b6006805460ff19166001179055565b60065460009060ff16156103f557fe5b3315156103fe57fe5b81158061042c5750336000908152600460209081526040808320600160a060020a0387168452909152902054155b151561043757600080fd5b336000818152600460209081526040808320600160a060020a03881680855290835292819020869055805186815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a350600192915050565b60055481565b60065460009060ff16156104b457fe5b3315156104bd57fe5b600160a060020a0384166000908152600360205260409020548211156104e257600080fd5b600160a060020a038316600090815260036020526040902054828101101561050957600080fd5b600160a060020a038416600090815260046020908152604080832033845290915290205482111561053957600080fd5b600160a060020a03808416600081815260036020908152604080832080548801905593881680835284832080548890039055600482528483203384528252918490208054879003905583518681529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35060019392505050565b60025481565b336000908152600360205260409020548111156105e357600080fd5b336000818152600360209081526040808320805486900390558280527f3617319a054d772f909f7c479a2cebe5066e836a939412e32403c99029b92eff805486019055805185815290519293927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a350565b60036020526000908152604090205481565b60065460ff1681565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103b55780601f1061038a576101008083540402835291602001916103b5565b60065460009060ff16156106e357fe5b3315156106ec57fe5b3360009081526003602052604090205482111561070857600080fd5b600160a060020a038316600090815260036020526040902054828101101561072f57600080fd5b33600081815260036020908152604080832080548790039055600160a060020a03871680845292819020805487019055805186815290519293927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a350600192915050565b6006546101009004600160a060020a031633146107b657fe5b6006805460ff19169055565b6006546101009004600160a060020a031633146107db57fe5b80516107ee90600090602084019061080f565b5050565b600460209081526000928352604080842090915290825290205481565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061085057805160ff191683800117855561087d565b8280016001018555821561087d579182015b8281111561087d578251825591602001919060010190610862565b5061088992915061088d565b5090565b6108a791905b808211156108895760008155600101610893565b905600a165627a7a72305820d00bcb788ca406de94859b8bc4bda50c3c65ca67e1217ccccee92f59a92ae5e20029" - code_ContractScenario005_deployIcoContract = "60c0604052600660808190527f54726f6e6978000000000000000000000000000000000000000000000000000060a090815261003e916000919061013c565b506040805180820190915260038082527f545258000000000000000000000000000000000000000000000000000000000060209092019182526100839160019161013c565b506006600281905560006005558054600160a860020a03191690553480156100aa57600080fd5b50604051602080610abc83398101604081815291516006805461010060a860020a031916336101000217905567016345785d8a00006005819055600160a060020a03821660008181526003602090815286822084905592855294519294909390927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a3506101d7565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061017d57805160ff19168380011785556101aa565b828001600101855582156101aa579182015b828111156101aa57825182559160200191906001019061018f565b506101b69291506101ba565b5090565b6101d491905b808211156101b657600081556001016101c0565b90565b6108d6806101e66000396000f3006080604052600436106100cf5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100d457806307da68f51461015e578063095ea7b31461017557806318160ddd146101ad57806323b872dd146101d4578063313ce567146101fe57806342966c681461021357806370a082311461022b57806375f12b211461024c57806395d89b4114610261578063a9059cbb14610276578063be9a65551461029a578063c47f0027146102af578063dd62ed3e14610308575b600080fd5b3480156100e057600080fd5b506100e961032f565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561012357818101518382015260200161010b565b50505050905090810190601f1680156101505780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561016a57600080fd5b506101736103bd565b005b34801561018157600080fd5b50610199600160a060020a03600435166024356103e5565b604080519115158252519081900360200190f35b3480156101b957600080fd5b506101c261049e565b60408051918252519081900360200190f35b3480156101e057600080fd5b50610199600160a060020a03600435811690602435166044356104a4565b34801561020a57600080fd5b506101c26105c1565b34801561021f57600080fd5b506101736004356105c7565b34801561023757600080fd5b506101c2600160a060020a036004351661065e565b34801561025857600080fd5b50610199610670565b34801561026d57600080fd5b506100e9610679565b34801561028257600080fd5b50610199600160a060020a03600435166024356106d3565b3480156102a657600080fd5b5061017361079d565b3480156102bb57600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526101739436949293602493928401919081908401838280828437509497506107c29650505050505050565b34801561031457600080fd5b506101c2600160a060020a03600435811690602435166107f2565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103b55780601f1061038a576101008083540402835291602001916103b5565b820191906000526020600020905b81548152906001019060200180831161039857829003601f168201915b505050505081565b6006546101009004600160a060020a031633146103d657fe5b6006805460ff19166001179055565b60065460009060ff16156103f557fe5b3315156103fe57fe5b81158061042c5750336000908152600460209081526040808320600160a060020a0387168452909152902054155b151561043757600080fd5b336000818152600460209081526040808320600160a060020a03881680855290835292819020869055805186815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a350600192915050565b60055481565b60065460009060ff16156104b457fe5b3315156104bd57fe5b600160a060020a0384166000908152600360205260409020548211156104e257600080fd5b600160a060020a038316600090815260036020526040902054828101101561050957600080fd5b600160a060020a038416600090815260046020908152604080832033845290915290205482111561053957600080fd5b600160a060020a03808416600081815260036020908152604080832080548801905593881680835284832080548890039055600482528483203384528252918490208054879003905583518681529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35060019392505050565b60025481565b336000908152600360205260409020548111156105e357600080fd5b336000818152600360209081526040808320805486900390558280527f3617319a054d772f909f7c479a2cebe5066e836a939412e32403c99029b92eff805486019055805185815290519293927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a350565b60036020526000908152604090205481565b60065460ff1681565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103b55780601f1061038a576101008083540402835291602001916103b5565b60065460009060ff16156106e357fe5b3315156106ec57fe5b3360009081526003602052604090205482111561070857600080fd5b600160a060020a038316600090815260036020526040902054828101101561072f57600080fd5b33600081815260036020908152604080832080548790039055600160a060020a03871680845292819020805487019055805186815290519293927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a350600192915050565b6006546101009004600160a060020a031633146107b657fe5b6006805460ff19169055565b6006546101009004600160a060020a031633146107db57fe5b80516107ee90600090602084019061080f565b5050565b600460209081526000928352604080842090915290825290205481565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061085057805160ff191683800117855561087d565b8280016001018555821561087d579182015b8281111561087d578251825591602001919060010190610862565b5061088992915061088d565b5090565b6108a791905b808211156108895760008155600101610893565b905600a165627a7a72305820d00bcb788ca406de94859b8bc4bda50c3c65ca67e1217ccccee92f59a92ae5e20029" - code_ContractScenario006_deployFomo3D = "60c0604052600660808190527f464f4d4f3344000000000000000000000000000000000000000000000000000060a0908152620000409160009190620000b8565b506040805180820190915260038082527f463344000000000000000000000000000000000000000000000000000000000060209092019182526200008791600191620000b8565b5068056bc75e2d631000006002556000600855600b805460ff19169055348015620000b157600080fd5b506200015d565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620000fb57805160ff19168380011785556200012b565b828001600101855582156200012b579182015b828111156200012b5782518255916020019190600101906200010e565b50620001399291506200013d565b5090565b6200015a91905b8082111562000139576000815560010162000144565b90565b611688806200016d6000396000f3006080604052600436106101685763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166265318b811461017657806306fdde03146101a957806310d0ffdd1461023357806318160ddd1461024b578063226093731461026057806327defa1f14610278578063313ce567146102a1578063392efb52146102cc5780633ccfd60b146102e45780634b750334146102fb57806356d399e814610310578063688abbf7146103255780636b2f46321461033f57806370a08231146103545780638328b610146103755780638620410b1461038d57806389135ae9146103a25780638fea64bd146103bf578063949e8acd146103d457806395d89b41146103e9578063a8e04f34146103fe578063a9059cbb14610413578063b84c824614610437578063c47f002714610490578063e4849b32146104e9578063e9fad8ee14610501578063f088d54714610516578063fdb5a03e1461052a575b61017334600061053f565b50005b34801561018257600080fd5b50610197600160a060020a0360043516610b15565b60408051918252519081900360200190f35b3480156101b557600080fd5b506101be610b50565b6040805160208082528351818301528351919283929083019185019080838360005b838110156101f85781810151838201526020016101e0565b50505050905090810190601f1680156102255780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561023f57600080fd5b50610197600435610bde565b34801561025757600080fd5b50610197610c0e565b34801561026c57600080fd5b50610197600435610c15565b34801561028457600080fd5b5061028d610c4e565b604080519115158252519081900360200190f35b3480156102ad57600080fd5b506102b6610c57565b6040805160ff9092168252519081900360200190f35b3480156102d857600080fd5b5061028d600435610c5c565b3480156102f057600080fd5b506102f9610c71565b005b34801561030757600080fd5b50610197610d44565b34801561031c57600080fd5b50610197610d98565b34801561033157600080fd5b506101976004351515610d9e565b34801561034b57600080fd5b50610197610de1565b34801561036057600080fd5b50610197600160a060020a0360043516610de6565b34801561038157600080fd5b506102f9600435610e01565b34801561039957600080fd5b50610197610e48565b3480156103ae57600080fd5b506102f96004356024351515610e90565b3480156103cb57600080fd5b506102f9610ef2565b3480156103e057600080fd5b50610197610ef4565b3480156103f557600080fd5b506101be610f07565b34801561040a57600080fd5b506102f9610f61565b34801561041f57600080fd5b5061028d600160a060020a0360043516602435610faf565b34801561044357600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526102f99436949293602493928401919081908401838280828437509497506111699650505050505050565b34801561049c57600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526102f99436949293602493928401919081908401838280828437509497506111c29650505050505050565b3480156104f557600080fd5b506102f9600435611216565b34801561050d57600080fd5b506102f9611367565b610197600160a060020a0360043516611394565b34801561053657600080fd5b506102f96113a0565b60008060008060008060008060008a6000339050600b60009054906101000a900460ff16801561058157506801158e460913d000008261057d610de1565b0311155b1561088e57600160a060020a03811660009081526003602052604090205460ff16151560011480156105d65750600160a060020a038116600090815260076020526040902054670de0b6b3a764000090830111155b15156105e157600080fd5b600160a060020a0381166000908152600760205260409020546106049083611456565b600160a060020a03821660009081526007602052604090205533995061062b8d600561146c565b985061063889600361146c565b97506106448989611483565b96506106508d8a611483565b955061065b86611495565b9450680100000000000000008702935060008511801561068557506008546106838682611456565b115b151561069057600080fd5b600160a060020a038c16158015906106ba575089600160a060020a03168c600160a060020a031614155b80156106e05750600254600160a060020a038d1660009081526004602052604090205410155b1561072657600160a060020a038c166000908152600560205260409020546107089089611456565b600160a060020a038d16600090815260056020526040902055610741565b6107308789611456565b965068010000000000000000870293505b600060085411156107a55761075860085486611456565b600881905568010000000000000000880281151561077257fe5b6009805492909104909101905560085468010000000000000000880281151561079757fe5b0485028403840393506107ab565b60088590555b600160a060020a038a166000908152600460205260409020546107ce9086611456565b600460008c600160a060020a0316600160a060020a031681526020019081526020016000208190555083856009540203925082600660008c600160a060020a0316600160a060020a03168152602001908152602001600020600082825401925050819055508b600160a060020a03168a600160a060020a03167f022c0d992e4d873a3748436d960d5140c1f9721cf73f7ca5ec679d3d9f4fe2d58f88604051808381526020018281526020019250505060405180910390a3849a50610b05565b600b805460ff191690553399506108a68d600561146c565b98506108b389600361146c565b97506108bf8989611483565b96506108cb8d8a611483565b95506108d686611495565b9450680100000000000000008702935060008511801561090057506008546108fe8682611456565b115b151561090b57600080fd5b600160a060020a038c1615801590610935575089600160a060020a03168c600160a060020a031614155b801561095b5750600254600160a060020a038d1660009081526004602052604090205410155b156109a157600160a060020a038c166000908152600560205260409020546109839089611456565b600160a060020a038d166000908152600560205260409020556109bc565b6109ab8789611456565b965068010000000000000000870293505b60006008541115610a20576109d360085486611456565b60088190556801000000000000000088028115156109ed57fe5b60098054929091049091019055600854680100000000000000008802811515610a1257fe5b048502840384039350610a26565b60088590555b600160a060020a038a16600090815260046020526040902054610a499086611456565b600460008c600160a060020a0316600160a060020a031681526020019081526020016000208190555083856009540203925082600660008c600160a060020a0316600160a060020a03168152602001908152602001600020600082825401925050819055508b600160a060020a03168a600160a060020a03167f022c0d992e4d873a3748436d960d5140c1f9721cf73f7ca5ec679d3d9f4fe2d58f88604051808381526020018281526020019250505060405180910390a3849a505b5050505050505050505092915050565b600160a060020a0316600090815260066020908152604080832054600490925290912054600954680100000000000000009102919091030490565b6000805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610bd65780601f10610bab57610100808354040283529160200191610bd6565b820191906000526020600020905b815481529060010190602001808311610bb957829003601f168201915b505050505081565b6000808080610bee85600561146c565b9250610bfa8584611483565b9150610c0582611495565b95945050505050565b6008545b90565b6000806000806008548511151515610c2c57600080fd5b610c358561152d565b9250610c4283600561146c565b9150610c058383611483565b600b5460ff1681565b601281565b600a6020526000908152604090205460ff1681565b6000806000610c806001610d9e565b11610c8a57600080fd5b339150610c976000610d9e565b600160a060020a038316600081815260066020908152604080832080546801000000000000000087020190556005909152808220805490839055905193019350909183156108fc0291849190818181858888f19350505050158015610d00573d6000803e3d6000fd5b50604080518281529051600160a060020a038416917fccad973dcd043c7d680389db4378bd6b9775db7124092e9e0422c9e46d7985dc919081900360200190a25050565b60008060008060085460001415610d62576414f46b04009350610d92565b610d73670de0b6b3a764000061152d565b9250610d8083600561146c565b9150610d8c8383611483565b90508093505b50505090565b60025481565b60003382610db457610daf81610b15565b610dd8565b600160a060020a038116600090815260056020526040902054610dd682610b15565b015b91505b50919050565b303190565b600160a060020a031660009081526004602052604090205490565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff161515610e4257600080fd5b50600255565b60008060008060085460001415610e665764199c82cc009350610d92565b610e77670de0b6b3a764000061152d565b9250610e8483600561146c565b9150610d8c8383611456565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff161515610ed157600080fd5b506000918252600a6020526040909120805460ff1916911515919091179055565b565b600033610f0081610de6565b91505b5090565b60018054604080516020600284861615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610bd65780601f10610bab57610100808354040283529160200191610bd6565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff161515610fa257600080fd5b50600b805460ff19169055565b600080600080600080610fc0610ef4565b11610fca57600080fd5b600b5433945060ff16158015610ff85750600160a060020a0384166000908152600460205260409020548611155b151561100357600080fd5b600061100f6001610d9e565b111561101d5761101d610c71565b61102886600561146c565b92506110348684611483565b915061103f8361152d565b905061104d60085484611483565b600855600160a060020a0384166000908152600460205260409020546110739087611483565b600160a060020a0380861660009081526004602052604080822093909355908916815220546110a29083611456565b600160a060020a0388811660008181526004602090815260408083209590955560098054948a16835260069091528482208054948c02909403909355825491815292909220805492850290920190915554600854611116919068010000000000000000840281151561111057fe5b04611456565b600955604080518381529051600160a060020a03808a1692908716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35060019695505050505050565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff1615156111aa57600080fd5b81516111bd9060019060208501906115ce565b505050565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff16151561120357600080fd5b81516111bd9060009060208501906115ce565b6000806000806000806000611229610ef4565b1161123357600080fd5b3360008181526004602052604090205490965087111561125257600080fd5b86945061125e8561152d565b935061126b84600561146c565b92506112778484611483565b915061128560085486611483565b600855600160a060020a0386166000908152600460205260409020546112ab9086611483565b600160a060020a0387166000908152600460209081526040808320939093556009546006909152918120805492880268010000000000000000860201928390039055600854919250101561131b5761131760095460085468010000000000000000860281151561111057fe5b6009555b60408051868152602081018490528151600160a060020a038916927fc4823739c5787d2ca17e404aa47d5569ae71dfb49cbf21b3f6152ed238a31139928290030190a250505050505050565b33600081815260046020526040812054908111156113885761138881611216565b611390610c71565b5050565b6000610ddb348361053f565b6000806000806113b06001610d9e565b116113ba57600080fd5b6113c46000610d9e565b3360008181526006602090815260408083208054680100000000000000008702019055600590915281208054908290559092019450925061140690849061053f565b905081600160a060020a03167fbe339fc14b041c2b0e0f3dd2cd325d0c3668b78378001e53160eab36153264588483604051808381526020018281526020019250505060405180910390a2505050565b60008282018381101561146557fe5b9392505050565b600080828481151561147a57fe5b04949350505050565b60008282111561148f57fe5b50900390565b6008546000906c01431e0fae6d7217caa00000009082906402540be40061151a611514730380d4bd8a8678c1bb542c80deb4800000000000880268056bc75e2d631000006002860a02017005e0a1fd2712875988becaad0000000000850201780197d4df19d605767337e9f14d3eec8920e40000000000000001611599565b85611483565b81151561152357fe5b0403949350505050565b600854600090670de0b6b3a76400008381019181019083906115866414f46b04008285046402540be40002018702600283670de0b6b3a763ffff1982890a8b900301046402540be4000281151561158057fe5b04611483565b81151561158f57fe5b0495945050505050565b80600260018201045b81811015610ddb5780915060028182858115156115bb57fe5b04018115156115c657fe5b0490506115a2565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061160f57805160ff191683800117855561163c565b8280016001018555821561163c579182015b8281111561163c578251825591602001919060010190611621565b50610f0392610c129250905b80821115610f0357600081556001016116485600a165627a7a723058202986f1ef7924e33e9f5613300f260c5fd9f05700de3217343d70f3a5fea5f76d0029" - code_ContractScenario007_deployErc721CardMigration = "6000805460a060020a60ff021916905560e0604052602360808190527f68747470733a2f2f6170692e676f6473756e636861696e65642e636f6d2f636160a09081527f72642f000000000000000000000000000000000000000000000000000000000060c0526200007491601091906200023e565b503480156200008257600080fd5b5060405160208062004212833981016040525160008054600160a060020a03191633179055620000db7f01ffc9a700000000000000000000000000000000000000000000000000000000640100000000620001d1810204565b6200010f7f80ac58cd00000000000000000000000000000000000000000000000000000000640100000000620001d1810204565b620001437f4f558e7900000000000000000000000000000000000000000000000000000000640100000000620001d1810204565b620001777f780e9d6300000000000000000000000000000000000000000000000000000000640100000000620001d1810204565b620001ab7f5b5e139f00000000000000000000000000000000000000000000000000000000640100000000620001d1810204565b60158054600160a060020a031916600160a060020a0392909216919091179055620002e3565b7fffffffff0000000000000000000000000000000000000000000000000000000080821614156200020157600080fd5b7fffffffff00000000000000000000000000000000000000000000000000000000166000908152600c60205260409020805460ff19166001179055565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106200028157805160ff1916838001178555620002b1565b82800160010185558215620002b1579182015b82811115620002b157825182559160200191906001019062000294565b50620002bf929150620002c3565b5090565b620002e091905b80821115620002bf5760008155600101620002ca565b90565b613f1f80620002f36000396000f3006080604052600436106103425763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166301ffc9a7811461034757806305c4af9d1461037d57806306fdde031461040c578063081812fc14610496578063095ea7b3146104ca5780630bbe0ee3146104f05780630c340a241461055b5780630e359f1614610570578063100cdd911461058857806318160ddd146105dd57806319fa8f50146106045780631fa24aa71461063657806323b872dd1461065157806324a96d701461067b5780632f745c59146106c5578063396ed600146106e95780633cb4ff3c146107015780633f4ba83a1461071657806342842e0e1461072b57806342966c6814610755578063454b06081461076d5780634cc90115146107855780634f558e791461079d5780634f6ccce7146107b55780634fb31a6a146107cd578063524773ce1461080d5780635bd9d9a5146108225780635c975abb1461083d5780635dcbd8bb146108525780636352211e1461087b57806367025dcf1461089357806370a08231146108e95780637a8b9b851461090a578063818d4b5d14610925578063821f830f146109495780638456cb591461096a578063850e37601461097f5780638dc10768146109b15780638e7e879f146109ea5780639188d31214610a3f578063943b82f114610a5757806395d89b4114610a97578063986e82f214610aac578063a22cb46514610ac8578063a3f4df7e14610aee578063a5487e5114610b03578063a71aec7314610b1b578063a9059cbb14610b37578063ad94d90114610b4e578063b5cab1ce14610bb1578063b84c139214610bc6578063b88d4fde14610bde578063bc734f0f14610c4d578063bcb3962114610c62578063c42cf53514610c77578063c87b56dd14610c98578063c968aab314610cb0578063caa1916814610ccb578063ce9fdb7014610ced578063ced28d7714610d2c578063d7643e1814610d78578063d80f862114610d8d578063dfb6a75f14610da5578063e3c7336b14610dea578063e7cf548c14611007578063e985e9c51461101c578063eeffbe4e14611043578063f03034521461105b578063f5f23b52146110be578063f76f8d78146110d9578063fb36eba1146110ee575b600080fd5b34801561035357600080fd5b50610369600160e060020a03196004351661111c565b604080519115158252519081900360200190f35b34801561038957600080fd5b5061039961ffff6004351661113b565b604080518a1515815260ff808b166020830152898116928201929092529087166060820152608081018660048111156103ce57fe5b60ff90811682529586166020820152938516604080860191909152928516606085015250909216608082015290519081900360a00195509350505050f35b34801561041857600080fd5b50610421611296565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561045b578181015183820152602001610443565b50505050905090810190601f1680156104885780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156104a257600080fd5b506104ae6004356112ce565b60408051600160a060020a039092168252519081900360200190f35b3480156104d657600080fd5b506104ee600160a060020a03600435166024356112e9565b005b3480156104fc57600080fd5b5060408051602060046044358181013583810280860185019096528085526104ee958335600160a060020a0390811696602480359092169636969560649592949301928291850190849080828437509497506113299650505050505050565b34801561056757600080fd5b506104ae611365565b34801561057c57600080fd5b50610369600435611374565b34801561059457600080fd5b50604080516020600480358082013583810280860185019096528085526104ee953695939460249493850192918291850190849080828437509497506113899650505050505050565b3480156105e957600080fd5b506105f26113bd565b60408051918252519081900360200190f35b34801561061057600080fd5b506106196113c3565b60408051600160e060020a03199092168252519081900360200190f35b34801561064257600080fd5b506104ee60ff600435166113e7565b34801561065d57600080fd5b506104ee600160a060020a036004358116906024351660443561143c565b34801561068757600080fd5b506106ae61ffff6004351660ff602435811690604435811690606435166084351515611469565b6040805161ffff9092168252519081900360200190f35b3480156106d157600080fd5b506105f2600160a060020a03600435166024356114ff565b3480156106f557600080fd5b506106ae60043561156f565b34801561070d57600080fd5b506105f26115a5565b34801561072257600080fd5b506104ee6115b8565b34801561073757600080fd5b506104ee600160a060020a036004358116906024351660443561162e565b34801561076157600080fd5b506104ee600435611660565b34801561077957600080fd5b506104ee600435611691565b34801561079157600080fd5b506106ae60043561180c565b3480156107a957600080fd5b5061036960043561181a565b3480156107c157600080fd5b506105f2600435611837565b3480156107d957600080fd5b506104ee61ffff6004351660ff60243581169060443581169060643581169060843581169060a43581169060c43516611850565b34801561081957600080fd5b506105f2611b03565b34801561082e57600080fd5b5061036960ff60043516611b09565b34801561084957600080fd5b50610369611b1e565b34801561085e57600080fd5b506104ee61ffff6004351667ffffffffffffffff60243516611b2e565b34801561088757600080fd5b506104ae600435611c0c565b6040805160206004602480358281013584810280870186019097528086526104ee968435600160a060020a031696369660449591949091019291829185019084908082843750949750611c369650505050505050565b3480156108f557600080fd5b506105f2600160a060020a0360043516611c6b565b34801561091657600080fd5b5061036960ff60043516611c86565b34801561093157600080fd5b50610369600160a060020a0360043516602435611c9b565b34801561095557600080fd5b506104ee600160a060020a0360043516611cc1565b34801561097657600080fd5b506104ee611d37565b34801561098b57600080fd5b5061099b61ffff60043516611db2565b6040805160ff9092168252519081900360200190f35b3480156109bd57600080fd5b506109c9600435611dc0565b6040805161ffff938416815291909216602082015281519081900390910190f35b3480156109f657600080fd5b50604080516020600480358082013583810280860185019096528085526104ee95369593946024949385019291829185019084908082843750949750611ded9650505050505050565b348015610a4b57600080fd5b506109c9600435611e21565b348015610a6357600080fd5b50610a7361ffff60043516611e75565b6040805167ffffffffffffffff909316835290151560208301528051918290030190f35b348015610aa357600080fd5b50610421611ecc565b348015610ab857600080fd5b50610a7361ffff60043516611f03565b348015610ad457600080fd5b506104ee600160a060020a03600435166024351515611f30565b348015610afa57600080fd5b50610421611fb4565b348015610b0f57600080fd5b506106ae600435611feb565b348015610b2757600080fd5b5061036961ffff60043516611ff9565b6104ee600160a060020a0360043516602435612029565b348015610b5a57600080fd5b50604080516020600460248035828101358481028087018601909752808652610369968435600160a060020a0316963696604495919490910192918291850190849080828437509497506120849650505050505050565b348015610bbd57600080fd5b506104216120e8565b348015610bd257600080fd5b506104ae600435612176565b348015610bea57600080fd5b50604080516020601f6064356004818101359283018490048402850184019095528184526104ee94600160a060020a03813581169560248035909216956044359536956084940191819084018382808284375094975061219e9650505050505050565b348015610c5957600080fd5b506104ee6121d6565b348015610c6e57600080fd5b5061099b61225e565b348015610c8357600080fd5b506104ee600160a060020a0360043516612267565b348015610ca457600080fd5b506104216004356122ad565b348015610cbc57600080fd5b506104ee60ff6004351661234f565b348015610cd757600080fd5b506106ae60ff6004351661ffff602435166123a0565b348015610cf957600080fd5b506106ae61ffff6004351660ff60243581169060443581169060643581169060843581169060a4351660c4351515612534565b348015610d3857600080fd5b506106ae61ffff6004351660ff60243581169060443581169060643581169060843581169060a43581169060c43581169060e435166101043515156125cc565b348015610d8457600080fd5b506106ae61266c565b348015610d9957600080fd5b506106ae60043561267b565b348015610db157600080fd5b506106ae61ffff6004351660ff60243581169060443581169060643581169060843581169060a43581169060c4351660e4351515612689565b348015610df657600080fd5b50604080516020600480358082013583810280860185019096528085526106ae95369593946024949385019291829185019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a998901989297509082019550935083925085019084908082843750506040805187358901803560208181028481018201909552818452989b9a9989019892975090820195509350839250850190849080828437509497506127269650505050505050565b34801561101357600080fd5b506105f26128b5565b34801561102857600080fd5b50610369600160a060020a03600435811690602435166128bb565b34801561104f57600080fd5b506106ae6004356128e9565b34801561106757600080fd5b506040805160206004602480358281013584810280870186019097528086526104ee968435600160a060020a0316963696604495919490910192918291850190849080828437509497506128f79650505050505050565b3480156110ca57600080fd5b506104ee60ff6004351661292c565b3480156110e557600080fd5b50610421612961565b3480156110fa57600080fd5b506105f2600160a060020a036004351661ffff60243581169060443516612998565b600160e060020a0319166000908152600c602052604090205460ff1690565b6000806000806000806000806000611151613df2565b61ffff8b16600090815260066020908152604091829020825161012081018452815460ff8082161515835261010082048116948301949094526201000081048416948201949094526301000000840483166060820152929091608084019164010000000090041660048111156111c357fe5b60048111156111ce57fe5b81526020016000820160059054906101000a900460ff1660ff1660ff1681526020016000820160069054906101000a900460ff1660ff1660ff1681526020016000820160079054906101000a900460ff1660ff1660ff1681526020016000820160089054906101000a900460ff1660ff1660ff16815250509050806000015181602001518260400151836060015184608001518560a001518660c001518760e00151886101000151995099509950995099509950995099509950509193959799909294969850565b60408051808201909152600e81527f476f647320556e636861696e656400000000000000000000000000000000000060208201525b90565b6000908152600e6020526040902054600160a060020a031690565b6113106001828154811015156112fb57fe5b60009182526020909120015461ffff16611ff9565b151561131b57600080fd5b6113258282612b50565b5050565b60005b815181101561135f576113578484848481518110151561134857fe5b9060200190602002015161143c565b60010161132c565b50505050565b600054600160a060020a031681565b60166020526000908152604090205460ff1681565b60005b8151811015611325576113b582828151811015156113a657fe5b90602001906020020151611660565b60010161138c565b60015490565b7f01ffc9a70000000000000000000000000000000000000000000000000000000081565b600054600160a060020a031633146113fe57600080fd5b60ff80821660009081526003602052604090205416151561141e57600080fd5b60ff166000908152600460205260409020805460ff19166001179055565b61144e6001828154811015156112fb57fe5b151561145957600080fd5b611464838383612c06565b505050565b6000611473613df2565b600054600160a060020a0316331461148a57600080fd5b6040805161012081018252600180825260ff808a16602084015260055416928201929092526060810191909152608081018660048111156114c757fe5b815260ff861660208201526000604082018190526060820181905260809091015290506114f5878285612c99565b5095945050505050565b600061150a83611c6b565b821061151557600080fd5b600160a060020a038316600090815260116020526040902080548390811061153957fe5b90600052602060002090600691828204019190066005029054906101000a900464ffffffffff1664ffffffffff16905092915050565b600b80548290811061157d57fe5b9060005260206000209060109182820401919006600202915054906101000a900461ffff1681565b60006013546115b26113bd565b03905090565b600054600160a060020a031633146115cf57600080fd5b60005460a060020a900460ff1615156115e757600080fd5b6000805474ff0000000000000000000000000000000000000000191681556040517f7805862f689e2f13df9f062ff482ad3ad112aca9e0847911ed832e158c525b339190a1565b80611639338261312c565b151561164457600080fd5b61135f848484602060405190810160405280600081525061219e565b803361166b82611c0c565b600160a060020a03161461167e57600080fd5b601380546001019055611325338361318b565b6000818152601660205260408120548190819060ff16156116b157600080fd5b6000848152601660209081526040808320805460ff1916600117905560155481517f6352211e000000000000000000000000000000000000000000000000000000008152600481018990529151600160a060020a0390911693636352211e93602480850194919392918390030190829087803b15801561173057600080fd5b505af1158015611744573d6000803e3d6000fd5b505050506040513d602081101561175a57600080fd5b5051601554604080517f9188d312000000000000000000000000000000000000000000000000000000008152600481018890528151939650600160a060020a0390921692639188d3129260248082019392918290030181600087803b1580156117c257600080fd5b505af11580156117d6573d6000803e3d6000fd5b505050506040513d60408110156117ec57600080fd5b50805160209091015190925090506118058383836131c9565b5050505050565b600780548290811061157d57fe5b6000908152600d6020526040902054600160a060020a0316151590565b60006118416113bd565b821061184c57600080fd5b5090565b611858613df2565b600054600160a060020a0316331461186f57600080fd5b61ffff8816600090815260066020908152604091829020825161012081018452815460ff8082161515835261010082048116948301949094526201000081048416948201949094526301000000840483166060820152929091608084019164010000000090041660048111156118e157fe5b60048111156118ec57fe5b8152905460ff650100000000008204811660208085019190915266010000000000008304821660408086019190915267010000000000000084048316606086015268010000000000000000909304821660809094019390935283820151811660009081526003909352912054919250161561196657600080fd5b610120604051908101604052806001151581526020018860ff168152602001826040015160ff1681526020018760ff168152602001826080015160048111156119ab57fe5b815260ff87811660208084019190915287821660408085019190915287831660608086019190915287841660809586015261ffff8e166000908152600684528290208651815494880151938801519288015160ff199095169015151761ff001916610100938616939093029290921762ff0000191662010000918516919091021763ff00000019166301000000929093169190910291909117808255918301519091829064ff000000001916640100000000836004811115611a6957fe5b021790555060a0820151815460c084015160e08501516101009095015165ff0000000000199092166501000000000060ff948516021766ff00000000000019166601000000000000918416919091021767ff000000000000001916670100000000000000948316949094029390931768ff000000000000000019166801000000000000000091909316029190911790555050505050505050565b60135481565b60046020526000908152604090205460ff1681565b60005460a060020a900460ff1681565b611b36613e3e565b600054600160a060020a03163314611b4d57600080fd5b5061ffff821660009081526002602090815260409182902082518084019093525467ffffffffffffffff8116835268010000000000000000900460ff1615801591830191909152611b9d57600080fd5b5060408051808201825267ffffffffffffffff92831681526001602080830191825261ffff90951660009081526002909552919093209251835491511515680100000000000000000268ff0000000000000000199190931667ffffffffffffffff199092169190911716179055565b6000818152600d6020526040812054600160a060020a0316801515611c3057600080fd5b92915050565b60005b815181101561146457611c63838383815181101515611c5457fe5b90602001906020020151612029565b600101611c39565b600160a060020a031660009081526011602052604090205490565b60036020526000908152604090205460ff1681565b600082600160a060020a0316611cb083611c0c565b600160a060020a0316149392505050565b600054600160a060020a03163314611cd857600080fd5b601480546001810182556000919091527fce6d7b5282bd9a3661ae061feed1dbda4e52ab073b1f9285be6e155d9c38d4ec01805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b600054600160a060020a03163314611d4e57600080fd5b60005460a060020a900460ff1615611d6557600080fd5b6000805474ff0000000000000000000000000000000000000000191660a060020a1781556040517f6985a02210a168e66602d3235cb6db0e70f92b3ba4d376a33c0f3d9434bff6259190a1565b6103e861ffff919091160490565b6001805482908110611dce57fe5b60009182526020909120015461ffff8082169250620100009091041682565b60005b815181101561132557611e198282815181101515611e0a57fe5b90602001906020020151611691565b600101611df0565b600080611e2c613e3e565b6001805485908110611e3a57fe5b60009182526020918290206040805180820190915291015461ffff808216808452620100009092041691909201819052909590945092505050565b600080611e80613e3e565b50505061ffff1660009081526002602090815260409182902082518084019093525467ffffffffffffffff81168084526801000000000000000090910460ff1615159290910182905291565b60408051808201909152600481527f474f445300000000000000000000000000000000000000000000000000000000602082015290565b60026020526000908152604090205467ffffffffffffffff81169068010000000000000000900460ff1682565b600160a060020a038216331415611f4657600080fd5b336000818152600f60209081526040808320600160a060020a03871680855290835292819020805460ff1916861515908117909155815190815290519293927f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31929181900390910190a35050565b60408051808201909152600e81527f476f647320556e636861696e6564000000000000000000000000000000000000602082015281565b600a80548290811061157d57fe5b61ffff1660009081526006602090815260408083205462010000900460ff90811684526003909252909120541690565b803361203482611c0c565b600160a060020a03161461204757600080fd5b6120596001838154811015156112fb57fe5b151561206457600080fd5b600160a060020a038316151561207957600080fd5b6114643384846132ae565b6000806000835111151561209757600080fd5b5060005b82518110156120dc576120c58484838151811015156120b657fe5b90602001906020020151611c9b565b15156120d457600091506120e1565b60010161209b565b600191505b5092915050565b6010805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152929183018282801561216e5780601f106121435761010080835404028352916020019161216e565b820191906000526020600020905b81548152906001019060200180831161215157829003601f168201915b505050505081565b601480548290811061218457fe5b600091825260209091200154600160a060020a0316905081565b816121a9338261312c565b15156121b457600080fd5b6121bf85858561143c565b6121cb85858585613300565b151561180557600080fd5b600054600160a060020a031633146121ed57600080fd5b60055460ff908116111561220057600080fd5b6005805460ff8082166001011660ff199091161790556000612223600782613e55565b506000612231600882613e55565b50600061223f600982613e55565b50600061224d600a82613e55565b50600061225b600b82613e55565b50565b60055460ff1681565b600054600160a060020a0316331461227e57600080fd5b6000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b6010805460408051602060026001851615610100026000190190941693909304601f8101849004840282018401909252818152606093611c30939192909183018282801561233c5780601f106123115761010080835404028352916020019161233c565b820191906000526020600020905b81548152906001019060200180831161231f57829003601f168201915b505050505061234a8461346d565b613560565b600054600160a060020a0316331461236657600080fd5b60ff808216600090815260046020526040902054161561238557600080fd5b60ff166000908152600360205260409020805460ff19169055565b600080808080808760048111156123b357fe5b141561240357600b805461ffff88168115156123cb57fe5b068154811015156123d857fe5b90600052602060002090601091828204019190066002029054906101000a900461ffff16945061252a565b600187600481111561241157fe5b141561242957600a805461ffff88168115156123cb57fe5b600287600481111561243757fe5b141561244f576009805461ffff88168115156123cb57fe5b600387600481111561245d57fe5b1415612475576008805461ffff88168115156123cb57fe5b600487600481111561248357fe5b1415610342575060005b600754811015612518576007805461ffff881683018115156124ab57fe5b068154811015156124b857fe5b90600052602060002090601091828204019190066002029054906101000a900461ffff1693506124e784611e75565b9093509150818015612503575060008367ffffffffffffffff16115b156125105783945061252a565b60010161248d565b6008805461ffff88168115156123cb57fe5b5050505092915050565b600061253e613df2565b600054600160a060020a0316331461255557600080fd5b60408051610120810182526001815260ff808b1660208301526005541691810191909152600360608201526080810188600481111561259057fe5b815260ff8089166020830152878116604083015286166060820152600060809091015290506125c0898285612c99565b50979650505050505050565b60006125d6613df2565b600054600160a060020a031633146125ed57600080fd5b60408051610120810182526001815260ff808d1660208301526005548116928201929092529086166060820152608081018a600481111561262a57fe5b81526020018960ff1681526020018860ff1681526020018760ff1681526020018560ff16815250905061265e8b8285612c99565b509998505050505050505050565b600554610100900461ffff1681565b600980548290811061157d57fe5b6000612693613df2565b600054600160a060020a031633146126aa57600080fd5b60408051610120810182526001815260ff808c166020830152600554169181019190915260026060820152608081018960048111156126e557fe5b81526020018860ff1681526020018760ff1681526020018660ff1681526020018560ff1681525090506127198a8285612c99565b5098975050505050505050565b600080612731613df2565b600054600160a060020a0316331461274857600080fd5b600091505b8b518210156128a657610120604051908101604052806001151581526020018c8481518110151561277a57fe5b602090810290910181015160ff9081168352600554169082015287516040909101908890859081106127a857fe5b9060200190602002015160ff1681526020018b848151811015156127c857fe5b9060200190602002015160048111156127dd57fe5b81526020018a848151811015156127f057fe5b9060200190602002015160ff168152602001898481518110151561281057fe5b9060200190602002015160ff168152602001888481518110151561283057fe5b9060200190602002015160ff168152602001868481518110151561285057fe5b9060200190602002015160ff16815250905061289b8c8381518110151561287357fe5b9060200190602002015182868581518110151561288c57fe5b90602001906020020151612c99565b60019091019061274d565b50509998505050505050505050565b60135490565b600160a060020a039182166000908152600f6020908152604080832093909416825291909152205460ff1690565b600880548290811061157d57fe5b60005b81518110156114645761292483838381518110151561291557fe5b906020019060200201516112e9565b6001016128fa565b600054600160a060020a0316331461294357600080fd5b60ff166000908152600360205260409020805460ff19166001179055565b60408051808201909152600481527f474f445300000000000000000000000000000000000000000000000000000000602082015281565b60006129a2613df2565b60008054819060a060020a900460ff16156129bc57600080fd5b6129c461359c565b15156129cf57600080fd5b61ffff8616600090815260066020908152604091829020825161012081018452815460ff808216151583526101008204811694830194909452620100008104841694820194909452630100000084048316606082015292909160808401916401000000009004166004811115612a4157fe5b6004811115612a4c57fe5b8152905460ff6501000000000082048116602084015266010000000000008204811660408085019190915267010000000000000083048216606085015268010000000000000000909204811660809093019290925260055490830151929550918116911614612aba57600080fd5b600483608001516004811115612acc57fe5b1415612b3a57612adb86611e75565b9092509050801580612af7575060008267ffffffffffffffff16115b1515612b0257600080fd5b61ffff86166000908152600260205260409020805467ffffffffffffffff19811667ffffffffffffffff918216600019019091161790555b612b458787876131c9565b979650505050505050565b6000612b5b82611c0c565b9050600160a060020a038381169082161415612b7657600080fd5b33600160a060020a0382161480612b925750612b9281336128bb565b1515612b9d57600080fd5b6000828152600e6020526040808220805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b80612c11338261312c565b1515612c1c57600080fd5b600160a060020a0384161515612c3157600080fd5b600160a060020a0383161515612c4657600080fd5b612c5084836135ed565b612c5a848361365c565b612c6483836138bd565b8183600160a060020a031685600160a060020a0316600080516020613ed483398151915260405160405180910390a450505050565b61ffff831660009081526006602052604081205460ff1615612cba57600080fd5b6001835261ffff8416600090815260066020908152604091829020855181549287015193870151606088015160ff199094169115159190911761ff00191661010060ff958616021762ff0000191662010000918516919091021763ff000000191663010000009390921692909202178082556080850151859291829064ff000000001916640100000000836004811115612d5057fe5b021790555060a08201518160000160056101000a81548160ff021916908360ff16021790555060c08201518160000160066101000a81548160ff021916908360ff16021790555060e08201518160000160076101000a81548160ff021916908360ff1602179055506101008201518160000160086101000a81548160ff021916908360ff1602179055509050506005600181819054906101000a900461ffff168092919060010191906101000a81548161ffff021916908361ffff160217905550507f2f7e8f79713fd202353aaa4d413bb73a3bc66d59a540f646415fd9acee7e59c684600560009054906101000a900460ff16856020015186608001518760a001518860c001518960e001518a606001518b61010001518b604051808b61ffff1661ffff1681526020018a60ff1660ff1681526020018960ff1660ff168152602001886004811115612e9f57fe5b60ff90811682529788166020820152958716604080880191909152948716606087015250918516608085015290931660a083015291151560c082015290519081900360e001945092505050a1811561135f575060808201516000816004811115612f0557fe5b1415612f6857600b80546001810182556000919091527f0175b7a638427703f0dbe7bb9bbf987a2551717b34e79f33b5b1008d1fa01db960108204018054600f9092166002026101000a61ffff818102199093169287160291909117905561135f565b6001816004811115612f7657fe5b1415612fd957600a80546001810182556000919091527fc65a7bb8d6351c1cf70c95a316cc6a92839c986682d98bc35f958f4883f9d2a860108204018054600f9092166002026101000a61ffff818102199093169287160291909117905561135f565b6002816004811115612fe757fe5b141561304a57600980546001810182556000919091527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af60108204018054600f9092166002026101000a61ffff818102199093169287160291909117905561135f565b600381600481111561305857fe5b14156130bb57600880546001810182556000919091527ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee360108204018054600f9092166002026101000a61ffff818102199093169287160291909117905561135f565b60048160048111156130c957fe5b141561034257600780546001810182556000919091527fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c68860108204018054600f9092166002026101000a61ffff818102199093169287160291909117905561135f565b60008061313883611c0c565b905080600160a060020a031684600160a060020a03161480613173575083600160a060020a0316613168846112ce565b600160a060020a0316145b80613183575061318381856128bb565b949350505050565b61319582826135ed565b61319f828261365c565b6040518190600090600160a060020a03851690600080516020613ed4833981519152908390a45050565b60006131d3613e3e565b506040805180820190915261ffff80851682528381166020830190815260018054808201825560009190915283517fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf68201805493518516620100000263ffff0000199290951661ffff199094169390931716929092179055613255868261398e565b6040805161ffff808816825286166020820152600160a060020a03881681830152905182917fe8a3345b7ca502cc541c08a705987fa4c03d9f59c0427175387a64cbd8f46594919081900360600190a295945050505050565b6132b883826135ed565b6132c2838261365c565b6132cc82826138bd565b8082600160a060020a031684600160a060020a0316600080516020613ed483398151915260405160405180910390a4505050565b60008061331585600160a060020a03166139d7565b15156133245760019150613464565b6040517f150b7a020000000000000000000000000000000000000000000000000000000081523360048201818152600160a060020a03898116602485015260448401889052608060648501908152875160848601528751918a169463150b7a0294938c938b938b93909160a490910190602085019080838360005b838110156133b757818101518382015260200161339f565b50505050905090810190601f1680156133e45780820380516001836020036101000a031916815260200191505b5095505050505050602060405180830381600087803b15801561340657600080fd5b505af115801561341a573d6000803e3d6000fd5b505050506040513d602081101561343057600080fd5b5051600160e060020a031981167f150b7a020000000000000000000000000000000000000000000000000000000014925090505b50949350505050565b606060008082818515156134b65760408051808201909152600181527f300000000000000000000000000000000000000000000000000000000000000060208201529450613557565b8593505b83156134d157600190920191600a840493506134ba565b826040519080825280601f01601f1916602001820160405280156134ff578160200160208202803883390190505b5091505060001982015b851561355357815160001982019160f860020a6030600a8a06010291849190811061353057fe5b906020010190600160f860020a031916908160001a905350600a86049550613509565b8194505b50505050919050565b6040805160208181018352600080835283518083018552818152845192830190945281526060926135959286928692906139df565b9392505050565b6000805b6014548110156135e55760148054829081106135b857fe5b600091825260209091200154600160a060020a03163314156135dd576001915061184c565b6001016135a0565b600091505090565b81600160a060020a031661360082611c0c565b600160a060020a03161461361357600080fd5b6000818152600e6020526040902054600160a060020a031615611325576000908152600e60205260409020805473ffffffffffffffffffffffffffffffffffffffff1916905550565b600080600061366b8585613c40565b601280548590811061367957fe5b60009182526020808320600883040154600160a060020a0389168452601190915260409092205460079091166004026101000a90910463ffffffff90811694506136c79190600190613c9216565b600160a060020a0386166000908152601160205260409020805491935090839081106136ef57fe5b90600052602060002090600691828204019190066005029054906101000a900464ffffffffff169050806011600087600160a060020a0316600160a060020a031681526020019081526020016000208463ffffffff1681548110151561375157fe5b90600052602060002090600691828204019190066005026101000a81548164ffffffffff021916908364ffffffffff16021790555060006011600087600160a060020a0316600160a060020a03168152602001908152602001600020838154811015156137ba57fe5b90600052602060002090600691828204019190066005026101000a81548164ffffffffff021916908364ffffffffff1602179055506011600086600160a060020a0316600160a060020a031681526020019081526020016000208054809190600190036138279190613e89565b50600060128581548110151561383957fe5b90600052602060002090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff1602179055508260128264ffffffffff1681548110151561388357fe5b90600052602060002090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff1602179055505050505050565b60006138c98383613ca4565b50600160a060020a03821660009081526011602052604090205463ffffffff811681146138f557600080fd5b600160a060020a038316600090815260116020908152604082208054600181018255908352912060068083049091018054919092066005026101000a64ffffffffff8181021990921691851602179055601280548291908490811061395657fe5b90600052602060002090600891828204019190066004026101000a81548163ffffffff021916908363ffffffff160217905550505050565b600160a060020a03821615156139a357600080fd5b6139ad8282613d01565b6040518190600160a060020a03841690600090600080516020613ed4833981519152908290a45050565b6000903b1190565b6060806060806060806060806000808e98508d97508c96508b95508a94508451865188518a518c51010101016040519080825280601f01601f191660200182016040528015613a38578160200160208202803883390190505b50935083925060009150600090505b8851811015613aa5578881815181101515613a5e57fe5b90602001015160f860020a900460f860020a028383806001019450815181101515613a8557fe5b906020010190600160f860020a031916908160001a905350600101613a47565b5060005b8751811015613b07578781815181101515613ac057fe5b90602001015160f860020a900460f860020a028383806001019450815181101515613ae757fe5b906020010190600160f860020a031916908160001a905350600101613aa9565b5060005b8651811015613b69578681815181101515613b2257fe5b90602001015160f860020a900460f860020a028383806001019450815181101515613b4957fe5b906020010190600160f860020a031916908160001a905350600101613b0b565b5060005b8551811015613bcb578581815181101515613b8457fe5b90602001015160f860020a900460f860020a028383806001019450815181101515613bab57fe5b906020010190600160f860020a031916908160001a905350600101613b6d565b5060005b8451811015613c2d578481815181101515613be657fe5b90602001015160f860020a900460f860020a028383806001019450815181101515613c0d57fe5b906020010190600160f860020a031916908160001a905350600101613bcf565b50909d9c50505050505050505050505050565b81600160a060020a0316613c5382611c0c565b600160a060020a031614613c6657600080fd5b6000908152600d60205260409020805473ffffffffffffffffffffffffffffffffffffffff1916905550565b600082821115613c9e57fe5b50900390565b6000818152600d6020526040902054600160a060020a031615613cc657600080fd5b6000908152600d60205260409020805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b6000613d0d8383613ca4565b50600160a060020a03821660009081526011602052604090205463ffffffff81168114613d3957600080fd5b600160a060020a039290921660009081526011602090815260408220805460018082018355918452918320600680840490910180549190930660050261010090810a64ffffffffff818102199093169690921691909102949094179091556012805491820181559091527fbb8a6a4669ba250d26cd7a459eca9d215f8307e33aebe50379bc5a3617ec344460088204018054600790921660040290920a63ffffffff818102199092169190931692909202919091179055565b6040805161012081018252600080825260208201819052918101829052606081018290529060808201908152600060208201819052604082018190526060820181905260809091015290565b604080518082019091526000808252602082015290565b81548183558181111561146457600f016010900481600f016010900483600052602060002091820191016114649190613eb9565b81548183558181111561146457600501600690048160050160069004836000526020600020918201910161146491905b6112cb91905b8082111561184c5760008155600101613ebf5600ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3efa165627a7a7230582010fa10dfd0372688e0f7a010b360af415423fe495c99c201f4e1bfab3b1c44210029000000000000000000000000512fbd15bde6570ff09e4438af27ede604024515" - code_ContractScenario008_deployErc721CryptoKitties = "606060409081526002805460a060020a60ff02191690556101c090519081016040908152603c82526078602083015261012c9082015261025860608201526107086080820152610e1060a0820152611c2060c082015261384060e082015261708061010082015261e100610120820152620151806101408201526202a3006101608201526205460061018082015262093a806101a0820152620000a790600390600e620004e4565b50600f60055566071afd498d0000600e553415620000c457600080fd5b6002805460008054600160a060020a033316600160a060020a03199182168117835560a060020a60ff02199093167401000000000000000000000000000000000000000017169091179091556200012f90808060001981640100000000620028f06200013682021704565b5062000649565b6000806200014362000587565b600063ffffffff891689146200015857600080fd5b63ffffffff881688146200016b57600080fd5b61ffff871687146200017c57600080fd5b600287049250600d8361ffff1611156200019557600d92505b61010060405190810160409081528782526001604060020a0342166020830152600090820181905263ffffffff808c1660608401528a16608083015260a082015261ffff80851660c0830152881660e082015260068054919350600191808301620002018382620005cb565b6000928352602090922085916002020181518155602082015160018201805467ffffffffffffffff19166001604060020a039290921691909117905560408201518160010160086101000a8154816001604060020a0302191690836001604060020a0316021790555060608201518160010160106101000a81548163ffffffff021916908363ffffffff16021790555060808201518160010160146101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160010160186101000a81548163ffffffff021916908363ffffffff16021790555060c082015181600101601c6101000a81548161ffff021916908361ffff16021790555060e08201516001909101805461ffff929092167e0100000000000000000000000000000000000000000000000000000000000002600160f060020a039092169190911790555003905063ffffffff811681146200035e57600080fd5b7f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad58582846060015163ffffffff16856080015163ffffffff168651604051600160a060020a03909516855260208501939093526040808501929092526060840152608083019190915260a0909101905180910390a1620003ef60008683640100000000620025e0620003fb82021704565b98975050505050505050565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a03191690911790558316156200048f57600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef838383604051600160a060020a039384168152919092166020820152604080820192909252606001905180910390a1505050565b600283019183908215620005755791602002820160005b838211156200054157835183826101000a81548163ffffffff021916908363ffffffff1602179055509260200192600401602081600301049283019260010302620004fb565b8015620005735782816101000a81549063ffffffff021916905560040160208160030104928301926001030262000541565b505b5062000583929150620005ff565b5090565b6101006040519081016040908152600080835260208301819052908201819052606082018190526080820181905260a0820181905260c0820181905260e082015290565b815481835581811511620005fa57600202816002028360005260206000209182019101620005fa919062000626565b505050565b6200062391905b808211156200058357805463ffffffff1916815560010162000606565b90565b6200062391905b808211156200058357600080825560018201556002016200062d565b61309380620006596000396000f3006060604052600436106102a55763ffffffff60e060020a60003504166301ffc9a781146102dd5780630519ce79146103295780630560ff441461035857806305e45546146103f157806306fdde0314610416578063095ea7b3146104295780630a0f81681461044b5780630e583df01461045e57806314001f4c1461047157806318160ddd14610490578063183a7947146104a35780631940a936146104b657806319c2f201146104cc57806321717ebf146104df57806323b872dd146104f257806324e7a38a1461051a57806327d7874c146105395780632ba73c15146105585780633d7d3f5a146105775780633f4ba83a1461059657806346116e6f146105a957806346d22c70146105bf578063481af3d3146105d85780634ad8c938146105ee5780634b85fd551461060d5780634dfff04f146106235780634e0a33791461064557806356129134146106645780635663896e146106865780635c975abb1461069c5780635fd8c710146106af5780636352211e146106c2578063680eba27146106d85780636af04a57146106eb5780636fbde40d146106fe57806370a082311461071d578063715879881461073c5780637a7d49371461075b5780638456cb591461076e5780638462151c1461078157806388c2a0bf146107f357806391876e571461080957806395d89b411461081c5780639d6fac6f1461082f578063a45f4bfc1461085e578063a9059cbb14610874578063b047fb5014610896578063b0c35c05146108a9578063bc4006f5146108bc578063c3bea9af146108cf578063d3e6f49f146108e5578063defb9584146108fb578063e17b25af1461090e578063e6cbe3511461092d578063e98b7f4d14610940578063ed60ade6146109ae578063f1ca9410146109bc578063f2b47d52146109cf578063f7d8c883146109e2575b600b5433600160a060020a03908116911614806102d05750600c5433600160a060020a039081169116145b15156102db57600080fd5b005b34156102e857600080fd5b6103157fffffffff00000000000000000000000000000000000000000000000000000000600435166109f0565b604051901515815260200160405180910390f35b341561033457600080fd5b61033c610c77565b604051600160a060020a03909116815260200160405180910390f35b341561036357600080fd5b61037a600480359060248035908101910135610c86565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156103b657808201518382015260200161039e565b50505050905090810190601f1680156103e35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156103fc57600080fd5b610404610d63565b60405190815260200160405180910390f35b341561042157600080fd5b61037a610d69565b341561043457600080fd5b6102db600160a060020a0360043516602435610da0565b341561045657600080fd5b61033c610e2a565b341561046957600080fd5b610404610e39565b341561047c57600080fd5b6102db600160a060020a0360043516610e44565b341561049b57600080fd5b610404610ef1565b34156104ae57600080fd5b610404610efc565b34156104c157600080fd5b610315600435610f02565b34156104d757600080fd5b610404610f47565b34156104ea57600080fd5b61033c610f4e565b34156104fd57600080fd5b6102db600160a060020a0360043581169060243516604435610f5d565b341561052557600080fd5b6102db600160a060020a0360043516610fe4565b341561054457600080fd5b6102db600160a060020a0360043516611091565b341561056357600080fd5b6102db600160a060020a03600435166110e3565b341561058257600080fd5b6102db600435602435604435606435611135565b34156105a157600080fd5b6102db611214565b34156105b457600080fd5b61033c6004356112ac565b34156105ca57600080fd5b6103156004356024356112c7565b34156105e357600080fd5b61033c600435611347565b34156105f957600080fd5b6102db600435602435604435606435611362565b341561061857600080fd5b6102db600435611428565b341561062e57600080fd5b6102db600160a060020a0360043516602435611448565b341561065057600080fd5b6102db600160a060020a03600435166114a2565b341561066f57600080fd5b6102db600435600160a060020a03602435166114f4565b341561069157600080fd5b6102db600435611560565b34156106a757600080fd5b6103156115c8565b34156106ba57600080fd5b6102db6115d8565b34156106cd57600080fd5b61033c600435611649565b34156106e357600080fd5b61040461166d565b34156106f657600080fd5b61033c611673565b341561070957600080fd5b6102db600160a060020a0360043516611682565b341561072857600080fd5b610404600160a060020a036004351661172f565b341561074757600080fd5b6102db600160a060020a036004351661174a565b341561076657600080fd5b6104046117d8565b341561077957600080fd5b6102db6117de565b341561078c57600080fd5b6107a0600160a060020a036004351661186a565b60405160208082528190810183818151815260200191508051906020019060200280838360005b838110156107df5780820151838201526020016107c7565b505050509050019250505060405180910390f35b34156107fe57600080fd5b61040460043561194b565b341561081457600080fd5b6102db611c1b565b341561082757600080fd5b61037a611d0e565b341561083a57600080fd5b610845600435611d45565b60405163ffffffff909116815260200160405180910390f35b341561086957600080fd5b61033c600435611d72565b341561087f57600080fd5b6102db600160a060020a0360043516602435611d8d565b34156108a157600080fd5b61033c611e30565b34156108b457600080fd5b610404611e3f565b34156108c757600080fd5b61033c611e45565b34156108da57600080fd5b6102db600435611e54565b34156108f057600080fd5b610315600435611f47565b341561090657600080fd5b610404612010565b341561091957600080fd5b6102db600160a060020a0360043516612016565b341561093857600080fd5b61033c612053565b341561094b57600080fd5b610956600435612062565b6040519915158a5297151560208a01526040808a01979097526060890195909552608088019390935260a087019190915260c086015260e0850152610100840152610120830191909152610140909101905180910390f35b6102db6004356024356121c3565b34156109c757600080fd5b610404612316565b34156109da57600080fd5b61033c61231c565b6102db60043560243561232b565b60006040517f737570706f727473496e7465726661636528627974657334290000000000000081526019016040518091039020600160e060020a03191682600160e060020a0319161480610c6f57506040517f746f6b656e4d657461646174612875696e743235362c737472696e67290000008152601d0160405180910390206040517f746f6b656e734f664f776e657228616464726573732900000000000000000000815260160160405180910390206040517f7472616e7366657246726f6d28616464726573732c616464726573732c75696e81527f7432353629000000000000000000000000000000000000000000000000000000602082015260250160405180910390206040517f7472616e7366657228616464726573732c75696e743235362900000000000000815260190160405180910390206040517f617070726f766528616464726573732c75696e74323536290000000000000000815260180160405180910390206040517f6f776e65724f662875696e743235362900000000000000000000000000000000815260100160405180910390206040517f62616c616e63654f662861646472657373290000000000000000000000000000815260120160405180910390206040517f746f74616c537570706c792829000000000000000000000000000000000000008152600d0160405180910390206040517f73796d626f6c2829000000000000000000000000000000000000000000000000815260080160405180910390206040517f6e616d652829000000000000000000000000000000000000000000000000000081526006016040518091039020181818181818181818600160e060020a03191682600160e060020a031916145b90505b919050565b600154600160a060020a031681565b610c8e612fa0565b610c96612fb2565b600d54600090600160a060020a03161515610cb057600080fd5b600d54600160a060020a031663cb4799f2878787600060405160a0015260405160e060020a63ffffffff861602815260048101848152604060248301908152604483018490529091606401848480828437820191505094505050505060a060405180830381600087803b1515610d2557600080fd5b6102c65a03f11515610d3657600080fd5b50505060405180608001805160209091016040529092509050610d59828261251d565b9695505050505050565b60115481565b60408051908101604052600d81527f43727970746f4b69747469657300000000000000000000000000000000000000602082015281565b60025460a060020a900460ff1615610db757600080fd5b610dc13382612572565b1515610dcc57600080fd5b610dd68183612592565b7f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925338383604051600160a060020a039384168152919092166020820152604080820192909252606001905180910390a15050565b600054600160a060020a031681565b662386f26fc1000081565b6000805433600160a060020a03908116911614610e6057600080fd5b5080600160a060020a0381166376190f8f6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610ea857600080fd5b6102c65a03f11515610eb957600080fd5b505050604051805190501515610ece57600080fd5b600c8054600160a060020a031916600160a060020a039290921691909117905550565b600654600019015b90565b600f5481565b6000808211610f1057600080fd5b6006805483908110610f1e57fe5b600091825260209091206002909102016001015460c060020a900463ffffffff16151592915050565b6201518081565b600c54600160a060020a031681565b60025460a060020a900460ff1615610f7457600080fd5b600160a060020a0382161515610f8957600080fd5b30600160a060020a031682600160a060020a031614151515610faa57600080fd5b610fb433826125c0565b1515610fbf57600080fd5b610fc98382612572565b1515610fd457600080fd5b610fdf8383836125e0565b505050565b6000805433600160a060020a0390811691161461100057600080fd5b5080600160a060020a0381166354c15b826000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561104857600080fd5b6102c65a03f1151561105957600080fd5b50505060405180519050151561106e57600080fd5b60108054600160a060020a031916600160a060020a039290921691909117905550565b60005433600160a060020a039081169116146110ac57600080fd5b600160a060020a03811615156110c157600080fd5b60008054600160a060020a031916600160a060020a0392909216919091179055565b60005433600160a060020a039081169116146110fe57600080fd5b600160a060020a038116151561111357600080fd5b60028054600160a060020a031916600160a060020a0392909216919091179055565b60025460a060020a900460ff161561114c57600080fd5b6111563385612572565b151561116157600080fd5b61116a84610f02565b1561117457600080fd5b600b5461118b908590600160a060020a0316612592565b600b54600160a060020a03166327ebe40a858585853360405160e060020a63ffffffff88160281526004810195909552602485019390935260448401919091526064830152600160a060020a0316608482015260a401600060405180830381600087803b15156111fa57600080fd5b6102c65a03f1151561120b57600080fd5b50505050505050565b60005433600160a060020a0390811691161461122f57600080fd5b60025460a060020a900460ff16151561124757600080fd5b600b54600160a060020a0316151561125e57600080fd5b600c54600160a060020a0316151561127557600080fd5b601054600160a060020a0316151561128c57600080fd5b601354600160a060020a0316156112a257600080fd5b6112aa6126c8565b565b600a60205260009081526040902054600160a060020a031681565b600080808085116112d757600080fd5b600084116112e457600080fd5b60068054869081106112f257fe5b9060005260206000209060020201915060068481548110151561131157fe5b9060005260206000209060020201905061132d8286838761271b565b801561133e575061133e848661289b565b95945050505050565b600960205260009081526040902054600160a060020a031681565b60025460a060020a900460ff161561137957600080fd5b6113833385612572565b151561138e57600080fd5b61139784611f47565b15156113a257600080fd5b600c546113b9908590600160a060020a0316612592565b600c54600160a060020a03166327ebe40a858585853360405160e060020a63ffffffff88160281526004810195909552602485019390935260448401919091526064830152600160a060020a0316608482015260a401600060405180830381600087803b15156111fa57600080fd5b60025433600160a060020a0390811691161461144357600080fd5b600e55565b60025460a060020a900460ff161561145f57600080fd5b6114693382612572565b151561147457600080fd5b6000908152600a602052604090208054600160a060020a031916600160a060020a0392909216919091179055565b60005433600160a060020a039081169116146114bd57600080fd5b600160a060020a03811615156114d257600080fd5b60018054600160a060020a031916600160a060020a0392909216919091179055565b60025460009033600160a060020a0390811691161461151257600080fd5b5080600160a060020a03811615156115325750600254600160a060020a03165b601154611388901061154357600080fd5b60118054600101905561155a6000808086856128f0565b50505050565b60025433600160a060020a039081169116148061158b575060005433600160a060020a039081169116145b806115a4575060015433600160a060020a039081169116145b15156115af57600080fd5b60035463ffffffff1681106115c357600080fd5b600555565b60025460a060020a900460ff1681565b600154600090819033600160a060020a039081169116146115f857600080fd5b30600160a060020a0316319150600e54600f546001010290508082111561164557600154600160a060020a031681830380156108fc0290604051600060405180830381858888f150505050505b5050565b600081815260076020526040902054600160a060020a0316801515610c7257600080fd5b61afc881565b601354600160a060020a031681565b6000805433600160a060020a0390811691161461169e57600080fd5b5080600160a060020a0381166385b861886000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156116e657600080fd5b6102c65a03f115156116f757600080fd5b50505060405180519050151561170c57600080fd5b600b8054600160a060020a031916600160a060020a039290921691909117905550565b600160a060020a031660009081526008602052604090205490565b60005433600160a060020a0390811691161461176557600080fd5b60025460a060020a900460ff16151561177d57600080fd5b60138054600160a060020a031916600160a060020a0383161790557f450db8da6efbe9c22f2347f7c2021231df1fc58d3ae9a2fa75d39fa44619930581604051600160a060020a03909116815260200160405180910390a150565b60055481565b60025433600160a060020a0390811691161480611809575060005433600160a060020a039081169116145b80611822575060015433600160a060020a039081169116145b151561182d57600080fd5b60025460a060020a900460ff161561184457600080fd5b6002805474ff0000000000000000000000000000000000000000191660a060020a179055565b611872612fa0565b600061187c612fa0565b600080600061188a8761172f565b94508415156118ba5760006040518059106118a25750595b90808252806020026020018201604052509550611941565b846040518059106118c85750595b908082528060200260200182016040525093506118e3610ef1565b925060009150600190505b82811161193d57600081815260076020526040902054600160a060020a0388811691161415611935578084838151811061192457fe5b602090810290910101526001909101905b6001016118ee565b8395505b5050505050919050565b600080600080600080600080600260149054906101000a900460ff1615151561197357600080fd5b600680548a90811061198157fe5b60009182526020909120600290910201600181015490975067ffffffffffffffff1615156119ae57600080fd5b611a438761010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612b9c565b1515611a4e57600080fd5b60018701546006805460c060020a90920463ffffffff1697509087908110611a7257fe5b600091825260209091206001808a015460029093029091019081015490965061ffff60f060020a92839004811696509190041684901115611ac057600185015460f060020a900461ffff1693505b6010548754865460018a0154600160a060020a0390931692630d9f5aed92919068010000000000000000900467ffffffffffffffff166000190160006040516020015260405160e060020a63ffffffff86160281526004810193909352602483019190915267ffffffffffffffff166044820152606401602060405180830381600087803b1515611b5057600080fd5b6102c65a03f11515611b6157600080fd5b505050604051805160008b81526007602052604090205460018a810154929650600160a060020a039091169450611bb092508b9160c060020a900463ffffffff1690870161ffff1686866128f0565b6001880180547bffffffff00000000000000000000000000000000000000000000000019169055600f8054600019019055600e54909150600160a060020a0333169080156108fc0290604051600060405180830381858888f150939c9b505050505050505050505050565b60025433600160a060020a0390811691161480611c46575060005433600160a060020a039081169116145b80611c5f575060015433600160a060020a039081169116145b1515611c6a57600080fd5b600b54600160a060020a0316635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b1515611ca957600080fd5b6102c65a03f11515611cba57600080fd5b5050600c54600160a060020a03169050635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b1515611cfd57600080fd5b6102c65a03f11515610fdf57600080fd5b60408051908101604052600281527f434b000000000000000000000000000000000000000000000000000000000000602082015281565b600381600e8110611d5257fe5b60089182820401919006600402915054906101000a900463ffffffff1681565b600760205260009081526040902054600160a060020a031681565b60025460a060020a900460ff1615611da457600080fd5b600160a060020a0382161515611db957600080fd5b30600160a060020a031682600160a060020a031614151515611dda57600080fd5b600b54600160a060020a0383811691161415611df557600080fd5b600c54600160a060020a0383811691161415611e1057600080fd5b611e1a3382612572565b1515611e2557600080fd5b6116453383836125e0565b600254600160a060020a031681565b600e5481565b600d54600160a060020a031681565b60025460009033600160a060020a03908116911614611e7257600080fd5b60125461afc89010611e8357600080fd5b611e92600080600085306128f0565b600b54909150611eac908290600160a060020a0316612592565b600b54600160a060020a03166327ebe40a82611ec6612bd4565b6000620151803060405160e060020a63ffffffff88160281526004810195909552602485019390935260448401919091526064830152600160a060020a0316608482015260a401600060405180830381600087803b1515611f2657600080fd5b6102c65a03f11515611f3757600080fd5b5050601280546001019055505050565b600080808311611f5657600080fd5b6006805484908110611f6457fe5b906000526020600020906002020190506120098161010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612c82565b9392505050565b61138881565b60005433600160a060020a0390811691161461203157600080fd5b600d8054600160a060020a031916600160a060020a0392909216919091179055565b600b54600160a060020a031681565b600080600080600080600080600080600060068c81548110151561208257fe5b906000526020600020906002020190508060010160189054906101000a900463ffffffff1663ffffffff16600014159a50438160010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff161115995080600101601c9054906101000a900461ffff1661ffff1698508060010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff1697508060010160189054906101000a900463ffffffff1663ffffffff1696508060010160009054906101000a900467ffffffffffffffff1667ffffffffffffffff1695508060010160109054906101000a900463ffffffff1663ffffffff1694508060010160149054906101000a900463ffffffff1663ffffffff16935080600101601e9054906101000a900461ffff1661ffff16925080600001549150509193959799509193959799565b60025460009060a060020a900460ff16156121dd57600080fd5b6121e73383612572565b15156121f257600080fd5b6121fb82611f47565b151561220657600080fd5b6122108284612cb9565b151561221b57600080fd5b600c54600160a060020a031663c55d0f568460006040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561226c57600080fd5b6102c65a03f1151561227d57600080fd5b5050506040518051600e549092508201341015905061229b57600080fd5b600c54600e54600160a060020a039091169063454a2ab39034038560405160e060020a63ffffffff851602815260048101919091526024016000604051808303818588803b15156122eb57600080fd5b6125ee5a03f115156122fc57600080fd5b50505050610fdf8263ffffffff168463ffffffff16612d08565b60125481565b601054600160a060020a031681565b600254600090819060a060020a900460ff161561234757600080fd5b600e5434101561235657600080fd5b6123603385612572565b151561236b57600080fd5b612375838561289b565b151561238057600080fd5b600680548590811061238e57fe5b906000526020600020906002020191506124338261010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612c82565b151561243e57600080fd5b600680548490811061244c57fe5b906000526020600020906002020190506124f18161010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612c82565b15156124fc57600080fd5b6125088285838661271b565b151561251357600080fd5b61155a8484612d08565b612525612fa0565b61252d612fa0565b6000808460405180591061253e5750595b818152601f19601f8301168101602001604052905092505060208201905084612568828287612e72565b5090949350505050565b600090815260076020526040902054600160a060020a0391821691161490565b6000918252600960205260409091208054600160a060020a031916600160a060020a03909216919091179055565b600090815260096020526040902054600160a060020a0391821691161490565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a031916909117905583161561267357600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef838383604051600160a060020a039384168152919092166020820152604080820192909252606001905180910390a1505050565b60005433600160a060020a039081169116146126e357600080fd5b60025460a060020a900460ff1615156126fb57600080fd5b6002805474ff000000000000000000000000000000000000000019169055565b60008184141561272d57506000612893565b6001850154608060020a900463ffffffff1682148061275c5750600185015460a060020a900463ffffffff1682145b1561276957506000612893565b6001830154608060020a900463ffffffff168414806127985750600183015460a060020a900463ffffffff1684145b156127a557506000612893565b6001830154608060020a900463ffffffff1615806127d257506001850154608060020a900463ffffffff16155b156127df57506001612893565b60018581015490840154608060020a9182900463ffffffff9081169290910416148061282a575060018086015490840154608060020a900463ffffffff90811660a060020a90920416145b1561283757506000612893565b6001808601549084015460a060020a900463ffffffff908116608060020a90920416148061288257506001858101549084015460a060020a9182900463ffffffff9081169290910416145b1561288f57506000612893565b5060015b949350505050565b6000818152600760205260408082205484835290822054600160a060020a0391821691168082148061133e57506000858152600a6020526040902054600160a060020a03908116908316149250505092915050565b6000806128fb612fdb565b600063ffffffff8916891461290f57600080fd5b63ffffffff8816881461292157600080fd5b61ffff8716871461293157600080fd5b600287049250600d8361ffff16111561294957600d92505b610100604051908101604090815287825267ffffffffffffffff42166020830152600090820181905263ffffffff808c1660608401528a16608083015260a082015261ffff80851660c0830152881660e0820152600680549193506001918083016129b4838261301f565b6000928352602090922085916002020181518155602082015160018201805467ffffffffffffffff191667ffffffffffffffff9290921691909117905560408201518160010160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160106101000a81548163ffffffff021916908363ffffffff16021790555060808201518160010160146101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160010160186101000a81548163ffffffff021916908363ffffffff16021790555060c082015181600101601c6101000a81548161ffff021916908361ffff16021790555060e08201516001909101805461ffff9290921660f060020a027dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092169190911790555003905063ffffffff81168114612b0f57600080fd5b7f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad58582846060015163ffffffff16856080015163ffffffff168651604051600160a060020a03909516855260208501939093526040808501929092526060840152608083019190915260a0909101905180910390a1612b90600086836125e0565b98975050505050505050565b60008160a0015163ffffffff1615801590610c6f57504367ffffffffffffffff16826040015167ffffffffffffffff16111592915050565b600b5460009081908190600160a060020a031663eac9d94c82604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515612c2257600080fd5b6102c65a03f11515612c3357600080fd5b50505060405180519250506fffffffffffffffffffffffffffffffff82168214612c5c57600080fd5b50600281048101662386f26fc10000811015612c7c5750662386f26fc100005b92915050565b60008160a0015163ffffffff16158015610c6f57504367ffffffffffffffff16826040015167ffffffffffffffff16111592915050565b6000806000600685815481101515612ccd57fe5b90600052602060002090600202019150600684815481101515612cec57fe5b9060005260206000209060020201905061133e8286838761271b565b600080600683815481101515612d1a57fe5b90600052602060002090600202019150600684815481101515612d3957fe5b600091825260209091206002909102016001810180547bffffffff000000000000000000000000000000000000000000000000191660c060020a63ffffffff8716021790559050612d8982612eb7565b612d9281612eb7565b6000848152600a602090815260408083208054600160a060020a031990811690915586845281842080549091169055600f8054600190810190915587845260079092529182902054908301547f241ea03ca20251805084d27d4440371c34a0b85ff108f6bb5611248f73818b8092600160a060020a0390921691879187916801000000000000000090910467ffffffffffffffff1690518085600160a060020a0316600160a060020a031681526020018481526020018381526020018267ffffffffffffffff16815260200194505050505060405180910390a150505050565b60005b60208210612e985782518452602084019350602083019250602082039150612e75565b6001826020036101000a03905080198351168185511617909352505050565b600554600182015443919060039060e060020a900461ffff16600e8110612eda57fe5b600891828204019190066004029054906101000a900463ffffffff1663ffffffff16811515612f0557fe5b6001840180546fffffffffffffffff0000000000000000191668010000000000000000939092049390930167ffffffffffffffff16919091021790819055600d60e060020a90910461ffff161015612f9d576001818101805461ffff60e060020a8083048216909401169092027fffff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092169190911790555b50565b60206040519081016040526000815290565b60806040519081016040526004815b60008152600019919091019060200181612fc15790505090565b6101006040519081016040908152600080835260208301819052908201819052606082018190526080820181905260a0820181905260c0820181905260e082015290565b815481835581811511610fdf57600083815260209020610fdf91610ef99160029182028101918502015b808211156130635760008082556001820155600201613049565b50905600a165627a7a72305820a6465fc1ce7ab1a92906ff7206b23d80a21bbd50b85b4bde6a91f8e6b2e3edde0029" - code_ContractScenario009_deployContainLibraryContract = "608060405234801561001057600080fd5b50610139806100206000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663f207564e8114610045575b600080fd5b34801561005157600080fd5b5061005d60043561005f565b005b73610199610030600b82828239805160001a6073146000811461002057610022565bfe5b5030600052607381538281f300730000000000000000000000000000000000000000301460806040526004361061006d5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663483b8a1481146100725780636ce8e081146100a1578063831cb739146100bc575b600080fd5b81801561007e57600080fd5b5061008d6004356024356100d7565b604080519115158252519081900360200190f35b8180156100ad57600080fd5b5061008d600435602435610117565b8180156100c857600080fd5b5061008d60043560243561012d565b60008181526020839052604081205460ff1615156100f757506000610111565b506000818152602083905260409020805460ff1916905560015b92915050565b6000908152602091909152604090205460ff1690565b60008181526020839052604081205460ff161561014c57506000610111565b50600090815260209190915260409020805460ff19166001908117909155905600a165627a7a723058200bc4068752b78840d32288f8eeffe2618c356d76fe09451d92f808cf28d4d22e0029" - code_ContractScenario010_deployContainLibraryContract = "608060405234801561001057600080fd5b50610731806100206000396000f3006080604052600436106100a35763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100a8578063095ea7b31461013257806318160ddd146101585780632f745c591461017f5780636352211e146101a35780636914db60146101d757806370a08231146101ef57806395d89b4114610210578063a9059cbb14610225578063b2e6ceeb14610249575b600080fd5b3480156100b457600080fd5b506100bd610261565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100f75781810151838201526020016100df565b50505050905090810190601f1680156101245780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561013e57600080fd5b50610156600160a060020a0360043516602435610298565b005b34801561016457600080fd5b5061016d61032d565b60408051918252519081900360200190f35b34801561018b57600080fd5b5061016d600160a060020a0360043516602435610336565b3480156101af57600080fd5b506101bb60043561035e565b60408051600160a060020a039092168252519081900360200190f35b3480156101e357600080fd5b506100bd600435610397565b3480156101fb57600080fd5b5061016d600160a060020a0360043516610438565b34801561021c57600080fd5b506100bd610453565b34801561023157600080fd5b50610156600160a060020a036004351660243561048a565b34801561025557600080fd5b5061015660043561059d565b60408051808201909152601181527f54726f6e2045524337323120546f6b656e000000000000000000000000000000602082015290565b6102a18161035e565b600160a060020a031633146102b557600080fd5b33600160a060020a03831614156102cb57600080fd5b336000818152600360209081526040808320600160a060020a03871680855290835292819020859055805185815290519293927f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925929181900390910190a35050565b64e8d4a5100090565b600160a060020a03919091166000908152600460209081526040808320938352929052205490565b60008181526002602052604081205460ff16151561037b57600080fd5b50600090815260016020526040902054600160a060020a031690565b60008181526005602090815260409182902080548351601f600260001961010060018616150201909316929092049182018490048402810184019094528084526060939283018282801561042c5780601f106104015761010080835404028352916020019161042c565b820191906000526020600020905b81548152906001019060200180831161040f57829003601f168201915b50505050509050919050565b600160a060020a031660009081526020819052604090205490565b60408051808201909152600581527f5437323154000000000000000000000000000000000000000000000000000000602082015290565b6000818152600260205260408120543391849160ff1615156104ab57600080fd5b6104b48461035e565b600160a060020a038481169116146104cb57600080fd5b600160a060020a0383811690831614156104e457600080fd5b600160a060020a03821615156104f957600080fd5b508161050581856106a7565b600160a060020a0381811660008181526020818152604080832080546000190190558883526001808352818420805473ffffffffffffffffffffffffffffffffffffffff19169689169687179055858452838352928190208054909301909255815188815291517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050505050565b600081815260026020526040812054819060ff1615156105bc57600080fd5b6105c58361035e565b9150339050600160a060020a0382168114156105e057600080fd5b600160a060020a03808316600090815260036020908152604080832093851683529290522054831461061157600080fd5b600160a060020a0382811660008181526020818152604080832080546000190190558783526001808352818420805473ffffffffffffffffffffffffffffffffffffffff19169688169687179055858452838352928190208054909301909255815187815291517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a3505050565b60005b600160a060020a0383166000908152600460209081526040808320848452909152902054821461070057600160a060020a03831660009081526004602090815260408083208484529091528120556001016106aa565b5050505600a165627a7a72305820d3ca2ca957b72f4c5028c633a6ad4bafe13572bf949793fabe72e34eb640d2c50029" - code_ContractScenario012_deployTransactionCoin = "60806040526000805561029f806100176000396000f3006080604052600436106100985763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166312065fe0811461009d5780632e52d606146100b7578063483f5a7f146100cc5780634f8632ba146100e25780635896476c146101135780638b47145f14610128578063b6b55f2514610144578063f46771d91461014f578063ff18253b14610163575b600080fd5b6100a561019b565b60408051918252519081900360200190f35b3480156100c357600080fd5b506100a56101a0565b6100e0600160a060020a03600435166101a6565b005b3480156100ee57600080fd5b506100f76101df565b60408051600160a060020a039092168252519081900360200190f35b34801561011f57600080fd5b506100e06101ee565b6101306101f9565b604080519115158252519081900360200190f35b610130600435610217565b6100e0600160a060020a036004351661023a565b34801561016f57600080fd5b5061017861026c565b60408051600160a060020a03909316835260208301919091528051918290030190f35b303190565b60005481565b604051600160a060020a038216903480156108fc02916000818181858888f193505050501580156101db573d6000803e3d6000fd5b5050565b600154600160a060020a031681565b600080546001019055565b6040516000903390829060019082818181858883f194505050505090565b604051600090339083156108fc0290849084818181858888f19695505050505050565b604051600160a060020a0382169060009060059082818181858883f193505050501580156101db573d6000803e3d6000fd5b33803190915600a165627a7a72305820fd081d59bd77b97252e4a657177023ae7352e1fe802dd638ec6b9fa5df59d6110029" - code_ContractScenario013_deployTronTrxAndSunContract = "6080604052348015600f57600080fd5b50600180141515601e57600080fd5b603c80141515602c57600080fd5b610e1080141515603b57600080fd5b6201518080141515604b57600080fd5b62093a8080141515605b57600080fd5b6301e1338080141515606c57600080fd5b620f424080141515607c57600080fd5b60358060896000396000f3006080604052600080fd00a165627a7a723058206a36395ee2292959a89e7956d6826a7107c490331e4505fc319010873c26392b0029" - code_ContractScenario013_triggerTronTrxAndSunContract = "608060405234801561001057600080fd5b5061011a806100206000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806316ada547146044575b600080fd5b348015604f57600080fd5b506056606c565b6040518082815260200191505060405180910390f35b6000600180141515607c57600080fd5b603c80141515608a57600080fd5b610e1080141515609957600080fd5b620151808014151560a957600080fd5b62093a808014151560b957600080fd5b6301e133808014151560ca57600080fd5b620f42408014151560da57600080fd5b60018014151560e857600080fd5b429050905600a165627a7a72305820eacfee595582d9244a2fb5f052905bd240f87864fb8f602f85fd31fe3b89cda80029" - code_ContractScenario014_testTripleTrigger = "608060405260d2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633d96d24c81146043575b600080fd5b606273ffffffffffffffffffffffffffffffffffffffff600435166064565b005b60405173ffffffffffffffffffffffffffffffffffffffff82169060009060059082818181858883f1935050505015801560a2573d6000803e3d6000fd5b50505600a165627a7a72305820e2d0e2bbf60a802771a52693e71a934ef01e5c5f6a584b5a3f24f5088866de4d0029" - code1_ContractScenario014_testTripleTrigger = "6080604052604051602080610263833981016040525160008054600160a060020a03909216600160a060020a031990921691909117905561021e806100456000396000f30060806040526004361061003d5763ffffffff60e060020a600035041663b3b638ab8114610042578063df5dd9c814610065578063ecb0b86214610086575b600080fd5b61006373ffffffffffffffffffffffffffffffffffffffff600435166100c4565b005b61006373ffffffffffffffffffffffffffffffffffffffff6004351661014e565b34801561009257600080fd5b5061009b6101d6565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b60008054604080517f73656e643553756e546f526563656976657228616464726573732900000000008152815190819003601b01812063ffffffff60e060020a91829004908116909102825273ffffffffffffffffffffffffffffffffffffffff8681166004840152925192909316936024808301939192829003018183875af150505050600080fd5b60008054604080517f73656e643553756e546f526563656976657228616464726573732900000000008152815190819003601b01812063ffffffff60e060020a91829004908116909102825273ffffffffffffffffffffffffffffffffffffffff8681166004840152925192909316936024808301939192829003018183875af15050505050565b60005473ffffffffffffffffffffffffffffffffffffffff16815600a165627a7a7230582065632ad682ad1abe06031e0f1471af18b8caeaddc98c67de6765b9f01ce8aa320029" - code2_ContractScenario014_testTripleTrigger = "60806040526040516020806101df833981016040525160008054600160a060020a03909216600160a060020a031990921691909117905561019a806100456000396000f30060806040526004361061004b5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663025750698114610050578063ecb0b86214610073575b600080fd5b61007173ffffffffffffffffffffffffffffffffffffffff600435166100b1565b005b34801561007f57600080fd5b50610088610152565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b60008054604080517f74726967676572436f6e747261637431286164647265737329000000000000008152815190819003601901812063ffffffff7c010000000000000000000000000000000000000000000000000000000091829004908116909102825273ffffffffffffffffffffffffffffffffffffffff8681166004840152925192909316936024808301939192829003018183875af15050505050565b60005473ffffffffffffffffffffffffffffffffffffffff16815600a165627a7a723058205a66bc83322abbfb01da52698e6f5a6b2ca2ff7c17793c1ff9db3a6c7e7f6cb10029" - code_TronDice_tronDice = "6080604052620ef420600155600060678190558054600160a060020a03191633179055610699806100316000396000f3006080604052600436106100825763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633ccfd60b81146100875780638da5cb5b146100ae578063acfff377146100df578063d0e30db0146100ea578063d263b7eb146100f4578063f2fde38b14610109578063fd2ba8b01461012a575b600080fd5b34801561009357600080fd5b5061009c61013f565b60408051918252519081900360200190f35b3480156100ba57600080fd5b506100c3610221565b60408051600160a060020a039092168252519081900360200190f35b61009c600435610230565b6100f26104b8565b005b34801561010057600080fd5b506100f2610504565b34801561011557600080fd5b506100f2600160a060020a0360043516610529565b34801561013657600080fd5b5061009c6105bd565b3360009081526002602052604081205481811161015b57600080fd5b336000818152600260205260408082208290555183156108fc0291849190818181858888f19350505050151561019057600080fd5b33600360646067548115156101a157fe5b06606481106101ac57fe5b01805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055606780546001019055604080513381526020810183905281517f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364929181900390910190a1919050565b600054600160a060020a031681565b600080600080600080600080600060618a10801561024e575060018a115b151561025957600080fd5b620f42403410158015610270575064174876e80034105b151561027b57600080fd5b336003606460675481151561028c57fe5b066064811061029757fe5b01805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03929092169190911790556067805460010190553497504360001901409650600360648806606481106102e757fe5b015460675460408051600160a060020a039093168a81014182019081014201909301845290519283900360200190922091975095506064900660010193508984101561045c576103388a60016105d0565b9250610346600154846105e4565b91507fdef9eb05d56d654703e420fad711aa89f7a03dc78c4d1c9a9d6d2548dad540653031610377846127106105e4565b60408051928352349190910260208301528051918290030190a161039d826127106105e4565b34023031116103ab57600080fd5b6103c06103b88984610622565b6127106105e4565b336000908152600260205260409020549091506103dd9082610646565b3360008181526002602090815260409182902093909355805191825234928201929092528082018c9052606081018690526080810185905260a0810184905260c0810183905260e081018a905290517fec1c9e10dd62d178aa9c345b3dc5e131cd479d8388331e77b668a16b8f95bdc0918190036101000190a16104aa565b604080513381523460208201528082018c905260608101869052608081018a905290517fc16d5d73a3ed9d2611bf92d1b1bcfa0568410a9b7c94ba5c70135d3a4657a8989181900360a00190a15b509198975050505050505050565b600054600160a060020a031633146104cf57600080fd5b6040805134815290517f4d6ce1e535dbade1c23defba91e23b8f791ce5edc0cc320257a2b364e4e384269181900360200190a1565b600054600160a060020a0316331461051b57600080fd5b600054600160a060020a0316ff5b600054600160a060020a0316331461054057600080fd5b600160a060020a038116151561055557600080fd5b60008054604051600160a060020a03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a36000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b3360009081526002602052604090205490565b60006105de8383111561065e565b50900390565b6000806105f36000841161065e565b82848115156105fe57fe5b04905061061b838581151561060f57fe5b0682850201851461065e565b9392505050565b600082820261061b841580610641575083858381151561063e57fe5b04145b61065e565b600082820161061b8482108015906106415750838210155b80151561066a57600080fd5b505600a165627a7a7230582094b570d711e59ef03fa2e2ac5e6b4b46cd0bec830c732bc75460783f0392ea000029" - code_TvmContract_deployErc721CryptoKitties = "606060409081526002805460a060020a60ff02191690556101c090519081016040908152603c82526078602083015261012c9082015261025860608201526107086080820152610e1060a0820152611c2060c082015261384060e082015261708061010082015261e100610120820152620151806101408201526202a3006101608201526205460061018082015262093a806101a0820152620000a790600390600e620004e4565b50600f60055566071afd498d0000600e553415620000c457600080fd5b6002805460008054600160a060020a033316600160a060020a03199182168117835560a060020a60ff02199093167401000000000000000000000000000000000000000017169091179091556200012f90808060001981640100000000620028f06200013682021704565b5062000649565b6000806200014362000587565b600063ffffffff891689146200015857600080fd5b63ffffffff881688146200016b57600080fd5b61ffff871687146200017c57600080fd5b600287049250600d8361ffff1611156200019557600d92505b61010060405190810160409081528782526001604060020a0342166020830152600090820181905263ffffffff808c1660608401528a16608083015260a082015261ffff80851660c0830152881660e082015260068054919350600191808301620002018382620005cb565b6000928352602090922085916002020181518155602082015160018201805467ffffffffffffffff19166001604060020a039290921691909117905560408201518160010160086101000a8154816001604060020a0302191690836001604060020a0316021790555060608201518160010160106101000a81548163ffffffff021916908363ffffffff16021790555060808201518160010160146101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160010160186101000a81548163ffffffff021916908363ffffffff16021790555060c082015181600101601c6101000a81548161ffff021916908361ffff16021790555060e08201516001909101805461ffff929092167e0100000000000000000000000000000000000000000000000000000000000002600160f060020a039092169190911790555003905063ffffffff811681146200035e57600080fd5b7f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad58582846060015163ffffffff16856080015163ffffffff168651604051600160a060020a03909516855260208501939093526040808501929092526060840152608083019190915260a0909101905180910390a1620003ef60008683640100000000620025e0620003fb82021704565b98975050505050505050565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a03191690911790558316156200048f57600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef838383604051600160a060020a039384168152919092166020820152604080820192909252606001905180910390a1505050565b600283019183908215620005755791602002820160005b838211156200054157835183826101000a81548163ffffffff021916908363ffffffff1602179055509260200192600401602081600301049283019260010302620004fb565b8015620005735782816101000a81549063ffffffff021916905560040160208160030104928301926001030262000541565b505b5062000583929150620005ff565b5090565b6101006040519081016040908152600080835260208301819052908201819052606082018190526080820181905260a0820181905260c0820181905260e082015290565b815481835581811511620005fa57600202816002028360005260206000209182019101620005fa919062000626565b505050565b6200062391905b808211156200058357805463ffffffff1916815560010162000606565b90565b6200062391905b808211156200058357600080825560018201556002016200062d565b61309380620006596000396000f3006060604052600436106102a55763ffffffff60e060020a60003504166301ffc9a781146102dd5780630519ce79146103295780630560ff441461035857806305e45546146103f157806306fdde0314610416578063095ea7b3146104295780630a0f81681461044b5780630e583df01461045e57806314001f4c1461047157806318160ddd14610490578063183a7947146104a35780631940a936146104b657806319c2f201146104cc57806321717ebf146104df57806323b872dd146104f257806324e7a38a1461051a57806327d7874c146105395780632ba73c15146105585780633d7d3f5a146105775780633f4ba83a1461059657806346116e6f146105a957806346d22c70146105bf578063481af3d3146105d85780634ad8c938146105ee5780634b85fd551461060d5780634dfff04f146106235780634e0a33791461064557806356129134146106645780635663896e146106865780635c975abb1461069c5780635fd8c710146106af5780636352211e146106c2578063680eba27146106d85780636af04a57146106eb5780636fbde40d146106fe57806370a082311461071d578063715879881461073c5780637a7d49371461075b5780638456cb591461076e5780638462151c1461078157806388c2a0bf146107f357806391876e571461080957806395d89b411461081c5780639d6fac6f1461082f578063a45f4bfc1461085e578063a9059cbb14610874578063b047fb5014610896578063b0c35c05146108a9578063bc4006f5146108bc578063c3bea9af146108cf578063d3e6f49f146108e5578063defb9584146108fb578063e17b25af1461090e578063e6cbe3511461092d578063e98b7f4d14610940578063ed60ade6146109ae578063f1ca9410146109bc578063f2b47d52146109cf578063f7d8c883146109e2575b600b5433600160a060020a03908116911614806102d05750600c5433600160a060020a039081169116145b15156102db57600080fd5b005b34156102e857600080fd5b6103157fffffffff00000000000000000000000000000000000000000000000000000000600435166109f0565b604051901515815260200160405180910390f35b341561033457600080fd5b61033c610c77565b604051600160a060020a03909116815260200160405180910390f35b341561036357600080fd5b61037a600480359060248035908101910135610c86565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156103b657808201518382015260200161039e565b50505050905090810190601f1680156103e35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156103fc57600080fd5b610404610d63565b60405190815260200160405180910390f35b341561042157600080fd5b61037a610d69565b341561043457600080fd5b6102db600160a060020a0360043516602435610da0565b341561045657600080fd5b61033c610e2a565b341561046957600080fd5b610404610e39565b341561047c57600080fd5b6102db600160a060020a0360043516610e44565b341561049b57600080fd5b610404610ef1565b34156104ae57600080fd5b610404610efc565b34156104c157600080fd5b610315600435610f02565b34156104d757600080fd5b610404610f47565b34156104ea57600080fd5b61033c610f4e565b34156104fd57600080fd5b6102db600160a060020a0360043581169060243516604435610f5d565b341561052557600080fd5b6102db600160a060020a0360043516610fe4565b341561054457600080fd5b6102db600160a060020a0360043516611091565b341561056357600080fd5b6102db600160a060020a03600435166110e3565b341561058257600080fd5b6102db600435602435604435606435611135565b34156105a157600080fd5b6102db611214565b34156105b457600080fd5b61033c6004356112ac565b34156105ca57600080fd5b6103156004356024356112c7565b34156105e357600080fd5b61033c600435611347565b34156105f957600080fd5b6102db600435602435604435606435611362565b341561061857600080fd5b6102db600435611428565b341561062e57600080fd5b6102db600160a060020a0360043516602435611448565b341561065057600080fd5b6102db600160a060020a03600435166114a2565b341561066f57600080fd5b6102db600435600160a060020a03602435166114f4565b341561069157600080fd5b6102db600435611560565b34156106a757600080fd5b6103156115c8565b34156106ba57600080fd5b6102db6115d8565b34156106cd57600080fd5b61033c600435611649565b34156106e357600080fd5b61040461166d565b34156106f657600080fd5b61033c611673565b341561070957600080fd5b6102db600160a060020a0360043516611682565b341561072857600080fd5b610404600160a060020a036004351661172f565b341561074757600080fd5b6102db600160a060020a036004351661174a565b341561076657600080fd5b6104046117d8565b341561077957600080fd5b6102db6117de565b341561078c57600080fd5b6107a0600160a060020a036004351661186a565b60405160208082528190810183818151815260200191508051906020019060200280838360005b838110156107df5780820151838201526020016107c7565b505050509050019250505060405180910390f35b34156107fe57600080fd5b61040460043561194b565b341561081457600080fd5b6102db611c1b565b341561082757600080fd5b61037a611d0e565b341561083a57600080fd5b610845600435611d45565b60405163ffffffff909116815260200160405180910390f35b341561086957600080fd5b61033c600435611d72565b341561087f57600080fd5b6102db600160a060020a0360043516602435611d8d565b34156108a157600080fd5b61033c611e30565b34156108b457600080fd5b610404611e3f565b34156108c757600080fd5b61033c611e45565b34156108da57600080fd5b6102db600435611e54565b34156108f057600080fd5b610315600435611f47565b341561090657600080fd5b610404612010565b341561091957600080fd5b6102db600160a060020a0360043516612016565b341561093857600080fd5b61033c612053565b341561094b57600080fd5b610956600435612062565b6040519915158a5297151560208a01526040808a01979097526060890195909552608088019390935260a087019190915260c086015260e0850152610100840152610120830191909152610140909101905180910390f35b6102db6004356024356121c3565b34156109c757600080fd5b610404612316565b34156109da57600080fd5b61033c61231c565b6102db60043560243561232b565b60006040517f737570706f727473496e7465726661636528627974657334290000000000000081526019016040518091039020600160e060020a03191682600160e060020a0319161480610c6f57506040517f746f6b656e4d657461646174612875696e743235362c737472696e67290000008152601d0160405180910390206040517f746f6b656e734f664f776e657228616464726573732900000000000000000000815260160160405180910390206040517f7472616e7366657246726f6d28616464726573732c616464726573732c75696e81527f7432353629000000000000000000000000000000000000000000000000000000602082015260250160405180910390206040517f7472616e7366657228616464726573732c75696e743235362900000000000000815260190160405180910390206040517f617070726f766528616464726573732c75696e74323536290000000000000000815260180160405180910390206040517f6f776e65724f662875696e743235362900000000000000000000000000000000815260100160405180910390206040517f62616c616e63654f662861646472657373290000000000000000000000000000815260120160405180910390206040517f746f74616c537570706c792829000000000000000000000000000000000000008152600d0160405180910390206040517f73796d626f6c2829000000000000000000000000000000000000000000000000815260080160405180910390206040517f6e616d652829000000000000000000000000000000000000000000000000000081526006016040518091039020181818181818181818600160e060020a03191682600160e060020a031916145b90505b919050565b600154600160a060020a031681565b610c8e612fa0565b610c96612fb2565b600d54600090600160a060020a03161515610cb057600080fd5b600d54600160a060020a031663cb4799f2878787600060405160a0015260405160e060020a63ffffffff861602815260048101848152604060248301908152604483018490529091606401848480828437820191505094505050505060a060405180830381600087803b1515610d2557600080fd5b6102c65a03f11515610d3657600080fd5b50505060405180608001805160209091016040529092509050610d59828261251d565b9695505050505050565b60115481565b60408051908101604052600d81527f43727970746f4b69747469657300000000000000000000000000000000000000602082015281565b60025460a060020a900460ff1615610db757600080fd5b610dc13382612572565b1515610dcc57600080fd5b610dd68183612592565b7f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925338383604051600160a060020a039384168152919092166020820152604080820192909252606001905180910390a15050565b600054600160a060020a031681565b662386f26fc1000081565b6000805433600160a060020a03908116911614610e6057600080fd5b5080600160a060020a0381166376190f8f6000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515610ea857600080fd5b6102c65a03f11515610eb957600080fd5b505050604051805190501515610ece57600080fd5b600c8054600160a060020a031916600160a060020a039290921691909117905550565b600654600019015b90565b600f5481565b6000808211610f1057600080fd5b6006805483908110610f1e57fe5b600091825260209091206002909102016001015460c060020a900463ffffffff16151592915050565b6201518081565b600c54600160a060020a031681565b60025460a060020a900460ff1615610f7457600080fd5b600160a060020a0382161515610f8957600080fd5b30600160a060020a031682600160a060020a031614151515610faa57600080fd5b610fb433826125c0565b1515610fbf57600080fd5b610fc98382612572565b1515610fd457600080fd5b610fdf8383836125e0565b505050565b6000805433600160a060020a0390811691161461100057600080fd5b5080600160a060020a0381166354c15b826000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b151561104857600080fd5b6102c65a03f1151561105957600080fd5b50505060405180519050151561106e57600080fd5b60108054600160a060020a031916600160a060020a039290921691909117905550565b60005433600160a060020a039081169116146110ac57600080fd5b600160a060020a03811615156110c157600080fd5b60008054600160a060020a031916600160a060020a0392909216919091179055565b60005433600160a060020a039081169116146110fe57600080fd5b600160a060020a038116151561111357600080fd5b60028054600160a060020a031916600160a060020a0392909216919091179055565b60025460a060020a900460ff161561114c57600080fd5b6111563385612572565b151561116157600080fd5b61116a84610f02565b1561117457600080fd5b600b5461118b908590600160a060020a0316612592565b600b54600160a060020a03166327ebe40a858585853360405160e060020a63ffffffff88160281526004810195909552602485019390935260448401919091526064830152600160a060020a0316608482015260a401600060405180830381600087803b15156111fa57600080fd5b6102c65a03f1151561120b57600080fd5b50505050505050565b60005433600160a060020a0390811691161461122f57600080fd5b60025460a060020a900460ff16151561124757600080fd5b600b54600160a060020a0316151561125e57600080fd5b600c54600160a060020a0316151561127557600080fd5b601054600160a060020a0316151561128c57600080fd5b601354600160a060020a0316156112a257600080fd5b6112aa6126c8565b565b600a60205260009081526040902054600160a060020a031681565b600080808085116112d757600080fd5b600084116112e457600080fd5b60068054869081106112f257fe5b9060005260206000209060020201915060068481548110151561131157fe5b9060005260206000209060020201905061132d8286838761271b565b801561133e575061133e848661289b565b95945050505050565b600960205260009081526040902054600160a060020a031681565b60025460a060020a900460ff161561137957600080fd5b6113833385612572565b151561138e57600080fd5b61139784611f47565b15156113a257600080fd5b600c546113b9908590600160a060020a0316612592565b600c54600160a060020a03166327ebe40a858585853360405160e060020a63ffffffff88160281526004810195909552602485019390935260448401919091526064830152600160a060020a0316608482015260a401600060405180830381600087803b15156111fa57600080fd5b60025433600160a060020a0390811691161461144357600080fd5b600e55565b60025460a060020a900460ff161561145f57600080fd5b6114693382612572565b151561147457600080fd5b6000908152600a602052604090208054600160a060020a031916600160a060020a0392909216919091179055565b60005433600160a060020a039081169116146114bd57600080fd5b600160a060020a03811615156114d257600080fd5b60018054600160a060020a031916600160a060020a0392909216919091179055565b60025460009033600160a060020a0390811691161461151257600080fd5b5080600160a060020a03811615156115325750600254600160a060020a03165b601154611388901061154357600080fd5b60118054600101905561155a6000808086856128f0565b50505050565b60025433600160a060020a039081169116148061158b575060005433600160a060020a039081169116145b806115a4575060015433600160a060020a039081169116145b15156115af57600080fd5b60035463ffffffff1681106115c357600080fd5b600555565b60025460a060020a900460ff1681565b600154600090819033600160a060020a039081169116146115f857600080fd5b30600160a060020a0316319150600e54600f546001010290508082111561164557600154600160a060020a031681830380156108fc0290604051600060405180830381858888f150505050505b5050565b600081815260076020526040902054600160a060020a0316801515610c7257600080fd5b61afc881565b601354600160a060020a031681565b6000805433600160a060020a0390811691161461169e57600080fd5b5080600160a060020a0381166385b861886000604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b15156116e657600080fd5b6102c65a03f115156116f757600080fd5b50505060405180519050151561170c57600080fd5b600b8054600160a060020a031916600160a060020a039290921691909117905550565b600160a060020a031660009081526008602052604090205490565b60005433600160a060020a0390811691161461176557600080fd5b60025460a060020a900460ff16151561177d57600080fd5b60138054600160a060020a031916600160a060020a0383161790557f450db8da6efbe9c22f2347f7c2021231df1fc58d3ae9a2fa75d39fa44619930581604051600160a060020a03909116815260200160405180910390a150565b60055481565b60025433600160a060020a0390811691161480611809575060005433600160a060020a039081169116145b80611822575060015433600160a060020a039081169116145b151561182d57600080fd5b60025460a060020a900460ff161561184457600080fd5b6002805474ff0000000000000000000000000000000000000000191660a060020a179055565b611872612fa0565b600061187c612fa0565b600080600061188a8761172f565b94508415156118ba5760006040518059106118a25750595b90808252806020026020018201604052509550611941565b846040518059106118c85750595b908082528060200260200182016040525093506118e3610ef1565b925060009150600190505b82811161193d57600081815260076020526040902054600160a060020a0388811691161415611935578084838151811061192457fe5b602090810290910101526001909101905b6001016118ee565b8395505b5050505050919050565b600080600080600080600080600260149054906101000a900460ff1615151561197357600080fd5b600680548a90811061198157fe5b60009182526020909120600290910201600181015490975067ffffffffffffffff1615156119ae57600080fd5b611a438761010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612b9c565b1515611a4e57600080fd5b60018701546006805460c060020a90920463ffffffff1697509087908110611a7257fe5b600091825260209091206001808a015460029093029091019081015490965061ffff60f060020a92839004811696509190041684901115611ac057600185015460f060020a900461ffff1693505b6010548754865460018a0154600160a060020a0390931692630d9f5aed92919068010000000000000000900467ffffffffffffffff166000190160006040516020015260405160e060020a63ffffffff86160281526004810193909352602483019190915267ffffffffffffffff166044820152606401602060405180830381600087803b1515611b5057600080fd5b6102c65a03f11515611b6157600080fd5b505050604051805160008b81526007602052604090205460018a810154929650600160a060020a039091169450611bb092508b9160c060020a900463ffffffff1690870161ffff1686866128f0565b6001880180547bffffffff00000000000000000000000000000000000000000000000019169055600f8054600019019055600e54909150600160a060020a0333169080156108fc0290604051600060405180830381858888f150939c9b505050505050505050505050565b60025433600160a060020a0390811691161480611c46575060005433600160a060020a039081169116145b80611c5f575060015433600160a060020a039081169116145b1515611c6a57600080fd5b600b54600160a060020a0316635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b1515611ca957600080fd5b6102c65a03f11515611cba57600080fd5b5050600c54600160a060020a03169050635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b1515611cfd57600080fd5b6102c65a03f11515610fdf57600080fd5b60408051908101604052600281527f434b000000000000000000000000000000000000000000000000000000000000602082015281565b600381600e8110611d5257fe5b60089182820401919006600402915054906101000a900463ffffffff1681565b600760205260009081526040902054600160a060020a031681565b60025460a060020a900460ff1615611da457600080fd5b600160a060020a0382161515611db957600080fd5b30600160a060020a031682600160a060020a031614151515611dda57600080fd5b600b54600160a060020a0383811691161415611df557600080fd5b600c54600160a060020a0383811691161415611e1057600080fd5b611e1a3382612572565b1515611e2557600080fd5b6116453383836125e0565b600254600160a060020a031681565b600e5481565b600d54600160a060020a031681565b60025460009033600160a060020a03908116911614611e7257600080fd5b60125461afc89010611e8357600080fd5b611e92600080600085306128f0565b600b54909150611eac908290600160a060020a0316612592565b600b54600160a060020a03166327ebe40a82611ec6612bd4565b6000620151803060405160e060020a63ffffffff88160281526004810195909552602485019390935260448401919091526064830152600160a060020a0316608482015260a401600060405180830381600087803b1515611f2657600080fd5b6102c65a03f11515611f3757600080fd5b5050601280546001019055505050565b600080808311611f5657600080fd5b6006805484908110611f6457fe5b906000526020600020906002020190506120098161010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612c82565b9392505050565b61138881565b60005433600160a060020a0390811691161461203157600080fd5b600d8054600160a060020a031916600160a060020a0392909216919091179055565b600b54600160a060020a031681565b600080600080600080600080600080600060068c81548110151561208257fe5b906000526020600020906002020190508060010160189054906101000a900463ffffffff1663ffffffff16600014159a50438160010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff161115995080600101601c9054906101000a900461ffff1661ffff1698508060010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff1697508060010160189054906101000a900463ffffffff1663ffffffff1696508060010160009054906101000a900467ffffffffffffffff1667ffffffffffffffff1695508060010160109054906101000a900463ffffffff1663ffffffff1694508060010160149054906101000a900463ffffffff1663ffffffff16935080600101601e9054906101000a900461ffff1661ffff16925080600001549150509193959799509193959799565b60025460009060a060020a900460ff16156121dd57600080fd5b6121e73383612572565b15156121f257600080fd5b6121fb82611f47565b151561220657600080fd5b6122108284612cb9565b151561221b57600080fd5b600c54600160a060020a031663c55d0f568460006040516020015260405160e060020a63ffffffff84160281526004810191909152602401602060405180830381600087803b151561226c57600080fd5b6102c65a03f1151561227d57600080fd5b5050506040518051600e549092508201341015905061229b57600080fd5b600c54600e54600160a060020a039091169063454a2ab39034038560405160e060020a63ffffffff851602815260048101919091526024016000604051808303818588803b15156122eb57600080fd5b6125ee5a03f115156122fc57600080fd5b50505050610fdf8263ffffffff168463ffffffff16612d08565b60125481565b601054600160a060020a031681565b600254600090819060a060020a900460ff161561234757600080fd5b600e5434101561235657600080fd5b6123603385612572565b151561236b57600080fd5b612375838561289b565b151561238057600080fd5b600680548590811061238e57fe5b906000526020600020906002020191506124338261010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612c82565b151561243e57600080fd5b600680548490811061244c57fe5b906000526020600020906002020190506124f18161010060405190810160409081528254825260019092015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152612c82565b15156124fc57600080fd5b6125088285838661271b565b151561251357600080fd5b61155a8484612d08565b612525612fa0565b61252d612fa0565b6000808460405180591061253e5750595b818152601f19601f8301168101602001604052905092505060208201905084612568828287612e72565b5090949350505050565b600090815260076020526040902054600160a060020a0391821691161490565b6000918252600960205260409091208054600160a060020a031916600160a060020a03909216919091179055565b600090815260096020526040902054600160a060020a0391821691161490565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a031916909117905583161561267357600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef838383604051600160a060020a039384168152919092166020820152604080820192909252606001905180910390a1505050565b60005433600160a060020a039081169116146126e357600080fd5b60025460a060020a900460ff1615156126fb57600080fd5b6002805474ff000000000000000000000000000000000000000019169055565b60008184141561272d57506000612893565b6001850154608060020a900463ffffffff1682148061275c5750600185015460a060020a900463ffffffff1682145b1561276957506000612893565b6001830154608060020a900463ffffffff168414806127985750600183015460a060020a900463ffffffff1684145b156127a557506000612893565b6001830154608060020a900463ffffffff1615806127d257506001850154608060020a900463ffffffff16155b156127df57506001612893565b60018581015490840154608060020a9182900463ffffffff9081169290910416148061282a575060018086015490840154608060020a900463ffffffff90811660a060020a90920416145b1561283757506000612893565b6001808601549084015460a060020a900463ffffffff908116608060020a90920416148061288257506001858101549084015460a060020a9182900463ffffffff9081169290910416145b1561288f57506000612893565b5060015b949350505050565b6000818152600760205260408082205484835290822054600160a060020a0391821691168082148061133e57506000858152600a6020526040902054600160a060020a03908116908316149250505092915050565b6000806128fb612fdb565b600063ffffffff8916891461290f57600080fd5b63ffffffff8816881461292157600080fd5b61ffff8716871461293157600080fd5b600287049250600d8361ffff16111561294957600d92505b610100604051908101604090815287825267ffffffffffffffff42166020830152600090820181905263ffffffff808c1660608401528a16608083015260a082015261ffff80851660c0830152881660e0820152600680549193506001918083016129b4838261301f565b6000928352602090922085916002020181518155602082015160018201805467ffffffffffffffff191667ffffffffffffffff9290921691909117905560408201518160010160086101000a81548167ffffffffffffffff021916908367ffffffffffffffff16021790555060608201518160010160106101000a81548163ffffffff021916908363ffffffff16021790555060808201518160010160146101000a81548163ffffffff021916908363ffffffff16021790555060a08201518160010160186101000a81548163ffffffff021916908363ffffffff16021790555060c082015181600101601c6101000a81548161ffff021916908361ffff16021790555060e08201516001909101805461ffff9290921660f060020a027dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092169190911790555003905063ffffffff81168114612b0f57600080fd5b7f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad58582846060015163ffffffff16856080015163ffffffff168651604051600160a060020a03909516855260208501939093526040808501929092526060840152608083019190915260a0909101905180910390a1612b90600086836125e0565b98975050505050505050565b60008160a0015163ffffffff1615801590610c6f57504367ffffffffffffffff16826040015167ffffffffffffffff16111592915050565b600b5460009081908190600160a060020a031663eac9d94c82604051602001526040518163ffffffff1660e060020a028152600401602060405180830381600087803b1515612c2257600080fd5b6102c65a03f11515612c3357600080fd5b50505060405180519250506fffffffffffffffffffffffffffffffff82168214612c5c57600080fd5b50600281048101662386f26fc10000811015612c7c5750662386f26fc100005b92915050565b60008160a0015163ffffffff16158015610c6f57504367ffffffffffffffff16826040015167ffffffffffffffff16111592915050565b6000806000600685815481101515612ccd57fe5b90600052602060002090600202019150600684815481101515612cec57fe5b9060005260206000209060020201905061133e8286838761271b565b600080600683815481101515612d1a57fe5b90600052602060002090600202019150600684815481101515612d3957fe5b600091825260209091206002909102016001810180547bffffffff000000000000000000000000000000000000000000000000191660c060020a63ffffffff8716021790559050612d8982612eb7565b612d9281612eb7565b6000848152600a602090815260408083208054600160a060020a031990811690915586845281842080549091169055600f8054600190810190915587845260079092529182902054908301547f241ea03ca20251805084d27d4440371c34a0b85ff108f6bb5611248f73818b8092600160a060020a0390921691879187916801000000000000000090910467ffffffffffffffff1690518085600160a060020a0316600160a060020a031681526020018481526020018381526020018267ffffffffffffffff16815260200194505050505060405180910390a150505050565b60005b60208210612e985782518452602084019350602083019250602082039150612e75565b6001826020036101000a03905080198351168185511617909352505050565b600554600182015443919060039060e060020a900461ffff16600e8110612eda57fe5b600891828204019190066004029054906101000a900463ffffffff1663ffffffff16811515612f0557fe5b6001840180546fffffffffffffffff0000000000000000191668010000000000000000939092049390930167ffffffffffffffff16919091021790819055600d60e060020a90910461ffff161015612f9d576001818101805461ffff60e060020a8083048216909401169092027fffff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092169190911790555b50565b60206040519081016040526000815290565b60806040519081016040526004815b60008152600019919091019060200181612fc15790505090565b6101006040519081016040908152600080835260208301819052908201819052606082018190526080820181905260a0820181905260c0820181905260e082015290565b815481835581811511610fdf57600083815260209020610fdf91610ef99160029182028101918502015b808211156130635760008082556001820155600201613049565b50905600a165627a7a72305820a6465fc1ce7ab1a92906ff7206b23d80a21bbd50b85b4bde6a91f8e6b2e3edde0029" - code_ContractScenario011_deployErc721KittyCore = "6002805460a060020a60ff0219169055610240604052603c6080908152607860a05261012c60c05261025860e05261070861010052610e1061012052611c2061014052613840610160526170806101805261e1006101a052620151806101c0526202a3006101e052620546006102005262093a80610220526200008790600390600e620004e3565b50600f6005556301312d00600e55348015620000a257600080fd5b506002805460008054600160a060020a031990811633908117835560a060020a60ff0219909316740100000000000000000000000000000000000000001716909117909155620001019080806000198164010000000062000108810204565b50620005f1565b6000806200011562000586565b600063ffffffff891689146200012a57600080fd5b63ffffffff881688146200013d57600080fd5b61ffff871687146200014e57600080fd5b600287049250600d8361ffff1611156200016757600d92505b505060408051610100810182528581524267ffffffffffffffff90811660208301908152600093830184815263ffffffff8c8116606086019081528c82166080870190815260a0870188815261ffff8a811660c08a019081528f821660e08b01908152600680546001810182559c528a517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f60028e029081019190915598517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40909901805498519651955194519251915167ffffffffffffffff19909916998b1699909917604060020a608060020a0319166801000000000000000096909a169590950298909817608060020a63ffffffff021916700100000000000000000000000000000000938616939093029290921760a060020a63ffffffff02191674010000000000000000000000000000000000000000918516919091021760c060020a63ffffffff0219167801000000000000000000000000000000000000000000000000968416969096029590951760e060020a61ffff0219167c01000000000000000000000000000000000000000000000000000000009186169190910217600160f060020a03167e010000000000000000000000000000000000000000000000000000000000009290941691909102929092179055909190811681146200036f57600080fd5b606080830151608080850151855160408051600160a060020a038c1681526020810188905263ffffffff95861681830152929094169482019490945290810192909252517f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad59181900360a00190a1620003f46000868364010000000062000400810204565b98975050505050505050565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a03191690911790558316156200049457600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b60408051600160a060020a0380861682528416602082015280820183905290517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360600190a1505050565b600283019183908215620005745791602002820160005b838211156200054057835183826101000a81548163ffffffff021916908363ffffffff1602179055509260200192600401602081600301049283019260010302620004fa565b8015620005725782816101000a81549063ffffffff021916905560040160208160030104928301926001030262000540565b505b5062000582929150620005ca565b5090565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b620005ee91905b808211156200058257805463ffffffff19168155600101620005d1565b90565b6130f380620006016000396000f3006080604052600436106102a55763ffffffff60e060020a60003504166301ffc9a781146102d55780630519ce79146103205780630560ff441461035157806305e45546146103ea57806306fdde0314610411578063095ea7b3146104265780630a0f81681461044a5780630e583df01461045f57806314001f4c1461047457806318160ddd14610495578063183a7947146104aa5780631940a936146104bf57806319c2f201146104d757806321717ebf146104ec57806323b872dd1461050157806324e7a38a1461052b57806327d7874c1461054c5780632ba73c151461056d5780633d7d3f5a1461058e5780633f4ba83a146105af57806346116e6f146105c457806346d22c70146105dc578063481af3d3146105f75780634ad8c9381461060f5780634b85fd55146106305780634dfff04f146106485780634e0a33791461066c578063561291341461068d5780635663896e146106b15780635c975abb146106c95780635fd8c710146106de5780636352211e146106f3578063680eba271461070b5780636af04a57146107205780636fbde40d1461073557806370a082311461075657806371587988146107775780637a7d4937146107985780638456cb59146107ad5780638462151c146107c257806388c2a0bf1461083357806391876e571461084b57806395d89b41146108605780639d6fac6f14610875578063a45f4bfc146108a6578063a9059cbb146108be578063b047fb50146108e2578063b0c35c05146108f7578063bc4006f51461090c578063c3bea9af14610921578063d3e6f49f14610939578063defb958414610951578063e17b25af14610966578063e6cbe35114610987578063e98b7f4d1461099c578063ed60ade614610a06578063f1ca941014610a14578063f2b47d5214610a29578063f7d8c88314610a3e575b600b54600160a060020a03163314806102c85750600c54600160a060020a031633145b15156102d357600080fd5b005b3480156102e157600080fd5b5061030c7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1960043516610a4c565b604080519115158252519081900360200190f35b34801561032c57600080fd5b50610335610cdf565b60408051600160a060020a039092168252519081900360200190f35b34801561035d57600080fd5b50610375600480359060248035908101910135610cee565b6040805160208082528351818301528351919283929083019185019080838360005b838110156103af578181015183820152602001610397565b50505050905090810190601f1680156103dc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156103f657600080fd5b506103ff610df1565b60408051918252519081900360200190f35b34801561041d57600080fd5b50610375610df7565b34801561043257600080fd5b506102d3600160a060020a0360043516602435610e2e565b34801561045657600080fd5b50610335610eb0565b34801561046b57600080fd5b506103ff610ebf565b34801561048057600080fd5b506102d3600160a060020a0360043516610ec6565b3480156104a157600080fd5b506103ff610f79565b3480156104b657600080fd5b506103ff610f83565b3480156104cb57600080fd5b5061030c600435610f89565b3480156104e357600080fd5b506103ff610fce565b3480156104f857600080fd5b50610335610fd5565b34801561050d57600080fd5b506102d3600160a060020a0360043581169060243516604435610fe4565b34801561053757600080fd5b506102d3600160a060020a0360043516611060565b34801561055857600080fd5b506102d3600160a060020a0360043516611113565b34801561057957600080fd5b506102d3600160a060020a0360043516611161565b34801561059a57600080fd5b506102d36004356024356044356064356111af565b3480156105bb57600080fd5b506102d36112a4565b3480156105d057600080fd5b50610335600435611338565b3480156105e857600080fd5b5061030c600435602435611353565b34801561060357600080fd5b506103356004356113d3565b34801561061b57600080fd5b506102d36004356024356044356064356113ee565b34801561063c57600080fd5b506102d36004356114c6565b34801561065457600080fd5b506102d3600160a060020a03600435166024356114e2565b34801561067857600080fd5b506102d3600160a060020a036004351661153c565b34801561069957600080fd5b506102d3600435600160a060020a036024351661158a565b3480156106bd57600080fd5b506102d36004356115f1565b3480156106d557600080fd5b5061030c61164d565b3480156106ea57600080fd5b506102d361165d565b3480156106ff57600080fd5b506103356004356116c1565b34801561071757600080fd5b506103ff6116e5565b34801561072c57600080fd5b506103356116eb565b34801561074157600080fd5b506102d3600160a060020a03600435166116fa565b34801561076257600080fd5b506103ff600160a060020a03600435166117ad565b34801561078357600080fd5b506102d3600160a060020a03600435166117c8565b3480156107a457600080fd5b506103ff61184b565b3480156107b957600080fd5b506102d3611851565b3480156107ce57600080fd5b506107e3600160a060020a03600435166118d1565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561081f578181015183820152602001610807565b505050509050019250505060405180910390f35b34801561083f57600080fd5b506103ff6004356119a3565b34801561085757600080fd5b506102d3611c7f565b34801561086c57600080fd5b50610375611d94565b34801561088157600080fd5b5061088d600435611dcb565b6040805163ffffffff9092168252519081900360200190f35b3480156108b257600080fd5b50610335600435611df8565b3480156108ca57600080fd5b506102d3600160a060020a0360043516602435611e13565b3480156108ee57600080fd5b50610335611eab565b34801561090357600080fd5b506103ff611eba565b34801561091857600080fd5b50610335611ec0565b34801561092d57600080fd5b506102d3600435611ecf565b34801561094557600080fd5b5061030c600435611fb9565b34801561095d57600080fd5b506103ff612088565b34801561097257600080fd5b506102d3600160a060020a036004351661208e565b34801561099357600080fd5b506103356120c7565b3480156109a857600080fd5b506109b46004356120d6565b604080519a15158b5298151560208b0152898901979097526060890195909552608088019390935260a087019190915260c086015260e085015261010084015261012083015251908190036101400190f35b6102d3600435602435612237565b348015610a2057600080fd5b506103ff6123d1565b348015610a3557600080fd5b506103356123d7565b6102d36004356024356123e6565b604080517f737570706f727473496e74657266616365286279746573342900000000000000815290519081900360190190206000907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1983811691161480610cd75750604080517f746f6b656e4d657461646174612875696e743235362c737472696e67290000008152815190819003601d0181207f746f6b656e734f664f776e657228616464726573732900000000000000000000825282519182900360160182207f7472616e7366657246726f6d28616464726573732c616464726573732c75696e83527f7432353629000000000000000000000000000000000000000000000000000000602084015283519283900360250183207f7472616e7366657228616464726573732c75696e743235362900000000000000845284519384900360190184207f617070726f766528616464726573732c75696e74323536290000000000000000855285519485900360180185207f6f776e65724f662875696e743235362900000000000000000000000000000000865286519586900360100186207f62616c616e63654f662861646472657373290000000000000000000000000000875287519687900360120187207f746f74616c537570706c792829000000000000000000000000000000000000008852885197889003600d0188207f73796d626f6c2829000000000000000000000000000000000000000000000000895289519889900360080189207f6e616d65282900000000000000000000000000000000000000000000000000008a529951988990036006019098207bffffffffffffffffffffffffffffffffffffffffffffffffffffffff198c811691909a189098181818181818181891909116145b90505b919050565b600154600160a060020a031681565b6060610cf8613064565b600d54600090600160a060020a03161515610d1257600080fd5b600d54604080517fcb4799f2000000000000000000000000000000000000000000000000000000008152600481018981526024820192835260448201889052600160a060020a039093169263cb4799f2928a928a928a929091606401848480828437820191505094505050505060a060405180830381600087803b158015610d9957600080fd5b505af1158015610dad573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525060a0811015610dd257600080fd5b5060808101519092509050610de782826125e4565b9695505050505050565b60115481565b60408051808201909152600d81527f43727970746f4b69747469657300000000000000000000000000000000000000602082015281565b60025460a060020a900460ff1615610e4557600080fd5b610e4f3382612638565b1515610e5a57600080fd5b610e648183612658565b60408051338152600160a060020a038416602082015280820183905290517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259181900360600190a15050565b600054600160a060020a031681565b6298968081565b60008054600160a060020a03163314610ede57600080fd5b81905080600160a060020a03166376190f8f6040518163ffffffff1660e060020a028152600401602060405180830381600087803b158015610f1f57600080fd5b505af1158015610f33573d6000803e3d6000fd5b505050506040513d6020811015610f4957600080fd5b50511515610f5657600080fd5b600c8054600160a060020a031916600160a060020a039290921691909117905550565b6006546000190190565b600f5481565b6000808211610f9757600080fd5b6006805483908110610fa557fe5b600091825260209091206002909102016001015460c060020a900463ffffffff16151592915050565b6201518081565b600c54600160a060020a031681565b60025460a060020a900460ff1615610ffb57600080fd5b600160a060020a038216151561101057600080fd5b600160a060020a03821630141561102657600080fd5b6110303382612686565b151561103b57600080fd5b6110458382612638565b151561105057600080fd5b61105b8383836126a6565b505050565b60008054600160a060020a0316331461107857600080fd5b81905080600160a060020a03166354c15b826040518163ffffffff1660e060020a028152600401602060405180830381600087803b1580156110b957600080fd5b505af11580156110cd573d6000803e3d6000fd5b505050506040513d60208110156110e357600080fd5b505115156110f057600080fd5b60108054600160a060020a031916600160a060020a039290921691909117905550565b600054600160a060020a0316331461112a57600080fd5b600160a060020a038116151561113f57600080fd5b60008054600160a060020a031916600160a060020a0392909216919091179055565b600054600160a060020a0316331461117857600080fd5b600160a060020a038116151561118d57600080fd5b60028054600160a060020a031916600160a060020a0392909216919091179055565b60025460a060020a900460ff16156111c657600080fd5b6111d03385612638565b15156111db57600080fd5b6111e484610f89565b156111ee57600080fd5b600b54611205908590600160a060020a0316612658565b600b54604080517f27ebe40a000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606481018490523360848201529051600160a060020a03909216916327ebe40a9160a48082019260009290919082900301818387803b15801561128657600080fd5b505af115801561129a573d6000803e3d6000fd5b5050505050505050565b600054600160a060020a031633146112bb57600080fd5b60025460a060020a900460ff1615156112d357600080fd5b600b54600160a060020a031615156112ea57600080fd5b600c54600160a060020a0316151561130157600080fd5b601054600160a060020a0316151561131857600080fd5b601354600160a060020a03161561132e57600080fd5b611336612788565b565b600a60205260009081526040902054600160a060020a031681565b6000808080851161136357600080fd5b6000841161137057600080fd5b600680548690811061137e57fe5b9060005260206000209060020201915060068481548110151561139d57fe5b906000526020600020906002020190506113b9828683876127d7565b80156113ca57506113ca8486612957565b95945050505050565b600960205260009081526040902054600160a060020a031681565b60025460a060020a900460ff161561140557600080fd5b61140f3385612638565b151561141a57600080fd5b61142384611fb9565b151561142e57600080fd5b600c54611445908590600160a060020a0316612658565b600c54604080517f27ebe40a000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606481018490523360848201529051600160a060020a03909216916327ebe40a9160a48082019260009290919082900301818387803b15801561128657600080fd5b600254600160a060020a031633146114dd57600080fd5b600e55565b60025460a060020a900460ff16156114f957600080fd5b6115033382612638565b151561150e57600080fd5b6000908152600a602052604090208054600160a060020a031916600160a060020a0392909216919091179055565b600054600160a060020a0316331461155357600080fd5b600160a060020a038116151561156857600080fd5b60018054600160a060020a031916600160a060020a0392909216919091179055565b600254600090600160a060020a031633146115a457600080fd5b5080600160a060020a03811615156115c45750600254600160a060020a03165b601154611388116115d457600080fd5b6011805460010190556115eb6000808086856129ac565b50505050565b600254600160a060020a03163314806116145750600054600160a060020a031633145b806116295750600154600160a060020a031633145b151561163457600080fd5b60035463ffffffff16811061164857600080fd5b600555565b60025460a060020a900460ff1681565b6001546000908190600160a060020a0316331461167957600080fd5b5050600e54600f54303191600190910102808211156116bd57600154604051600160a060020a039091169082840380156108fc02916000818181858888f150505050505b5050565b600081815260076020526040902054600160a060020a0316801515610cda57600080fd5b61afc881565b601354600160a060020a031681565b60008054600160a060020a0316331461171257600080fd5b81905080600160a060020a03166385b861886040518163ffffffff1660e060020a028152600401602060405180830381600087803b15801561175357600080fd5b505af1158015611767573d6000803e3d6000fd5b505050506040513d602081101561177d57600080fd5b5051151561178a57600080fd5b600b8054600160a060020a031916600160a060020a039290921691909117905550565b600160a060020a031660009081526008602052604090205490565b600054600160a060020a031633146117df57600080fd5b60025460a060020a900460ff1615156117f757600080fd5b60138054600160a060020a038316600160a060020a0319909116811790915560408051918252517f450db8da6efbe9c22f2347f7c2021231df1fc58d3ae9a2fa75d39fa4461993059181900360200190a150565b60055481565b600254600160a060020a03163314806118745750600054600160a060020a031633145b806118895750600154600160a060020a031633145b151561189457600080fd5b60025460a060020a900460ff16156118ab57600080fd5b6002805474ff0000000000000000000000000000000000000000191660a060020a179055565b60606000606060008060006118e5876117ad565b9450841515611904576040805160008152602081019091529550611999565b8460405190808252806020026020018201604052801561192e578160200160208202803883390190505b509350611939610f79565b925060009150600190505b82811161199557600081815260076020526040902054600160a060020a038881169116141561198d5780848381518110151561197c57fe5b602090810290910101526001909101905b600101611944565b8395505b5050505050919050565b600080600080600080600080600260149054906101000a900460ff161515156119cb57600080fd5b600680548a9081106119d957fe5b60009182526020909120600290910201600181015490975067ffffffffffffffff161515611a0657600080fd5b604080516101008101825288548152600189015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152611a9790612c89565b1515611aa257600080fd5b60018701546006805460c060020a90920463ffffffff1697509087908110611ac657fe5b600091825260209091206001808a015460029093029091019081015490965061ffff60f060020a928390048116965091900416841015611b1357600185015460f060020a900461ffff1693505b6010548754865460018a0154604080517f0d9f5aed0000000000000000000000000000000000000000000000000000000081526004810194909452602484019290925260001967ffffffffffffffff6801000000000000000090920482160116604483015251600160a060020a0390921691630d9f5aed916064808201926020929091908290030181600087803b158015611bad57600080fd5b505af1158015611bc1573d6000803e3d6000fd5b505050506040513d6020811015611bd757600080fd5b505160008a815260076020526040902054600189810154929550600160a060020a039091169350611c20918b9160c060020a90910463ffffffff1690870161ffff1686866129ac565b6001880180547bffffffff00000000000000000000000000000000000000000000000019169055600f8054600019019055600e54604051919250339181156108fc0291906000818181858888f150939c9b505050505050505050505050565b600254600160a060020a0316331480611ca25750600054600160a060020a031633145b80611cb75750600154600160a060020a031633145b1515611cc257600080fd5b600b60009054906101000a9004600160a060020a0316600160a060020a0316635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b158015611d1557600080fd5b505af1158015611d29573d6000803e3d6000fd5b50505050600c60009054906101000a9004600160a060020a0316600160a060020a0316635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b158015611d8057600080fd5b505af11580156115eb573d6000803e3d6000fd5b60408051808201909152600281527f434b000000000000000000000000000000000000000000000000000000000000602082015281565b600381600e8110611dd857fe5b60089182820401919006600402915054906101000a900463ffffffff1681565b600760205260009081526040902054600160a060020a031681565b60025460a060020a900460ff1615611e2a57600080fd5b600160a060020a0382161515611e3f57600080fd5b600160a060020a038216301415611e5557600080fd5b600b54600160a060020a0383811691161415611e7057600080fd5b600c54600160a060020a0383811691161415611e8b57600080fd5b611e953382612638565b1515611ea057600080fd5b6116bd3383836126a6565b600254600160a060020a031681565b600e5481565b600d54600160a060020a031681565b600254600090600160a060020a03163314611ee957600080fd5b60125461afc811611ef957600080fd5b611f08600080600085306129ac565b600b54909150611f22908290600160a060020a0316612658565b600b54600160a060020a03166327ebe40a82611f3c612cb9565b6040805160e060020a63ffffffff861602815260048101939093526024830191909152600060448301819052620151806064840152306084840152905160a48084019382900301818387803b158015611f9457600080fd5b505af1158015611fa8573d6000803e3d6000fd5b505060128054600101905550505050565b600080808311611fc857600080fd5b6006805484908110611fd657fe5b60009182526020918290206040805161010081018252600290930290910180548352600181015467ffffffffffffffff808216958501959095526801000000000000000081049094169183019190915263ffffffff608060020a84048116606084015260a060020a84048116608084015260c060020a84041660a083015261ffff60e060020a8404811660c084015260f060020a90930490921660e082015290915061208190612d7b565b9392505050565b61138881565b600054600160a060020a031633146120a557600080fd5b600d8054600160a060020a031916600160a060020a0392909216919091179055565b600b54600160a060020a031681565b600080600080600080600080600080600060068c8154811015156120f657fe5b906000526020600020906002020190508060010160189054906101000a900463ffffffff1663ffffffff16600014159a50438160010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff161115995080600101601c9054906101000a900461ffff1661ffff1698508060010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff1697508060010160189054906101000a900463ffffffff1663ffffffff1696508060010160009054906101000a900467ffffffffffffffff1667ffffffffffffffff1695508060010160109054906101000a900463ffffffff1663ffffffff1694508060010160149054906101000a900463ffffffff1663ffffffff16935080600101601e9054906101000a900461ffff1661ffff16925080600001549150509193959799509193959799565b60025460009060a060020a900460ff161561225157600080fd5b61225b3383612638565b151561226657600080fd5b61226f82611fb9565b151561227a57600080fd5b6122848284612daa565b151561228f57600080fd5b600c54604080517fc55d0f56000000000000000000000000000000000000000000000000000000008152600481018690529051600160a060020a039092169163c55d0f56916024808201926020929091908290030181600087803b1580156122f657600080fd5b505af115801561230a573d6000803e3d6000fd5b505050506040513d602081101561232057600080fd5b5051600e54909150810134101561233657600080fd5b600c54600e54604080517f454a2ab3000000000000000000000000000000000000000000000000000000008152600481018790529051600160a060020a039093169263454a2ab39234039160248082019260009290919082900301818588803b1580156123a257600080fd5b505af11580156123b6573d6000803e3d6000fd5b505050505061105b8263ffffffff168463ffffffff16612df9565b60125481565b601054600160a060020a031681565b600254600090819060a060020a900460ff161561240257600080fd5b600e5434101561241157600080fd5b61241b3385612638565b151561242657600080fd5b6124308385612957565b151561243b57600080fd5b600680548590811061244957fe5b60009182526020918290206040805161010081018252600290930290910180548352600181015467ffffffffffffffff808216958501959095526801000000000000000081049094169183019190915263ffffffff608060020a84048116606084015260a060020a84048116608084015260c060020a84041660a083015261ffff60e060020a8404811660c084015260f060020a90930490921660e08201529092506124f490612d7b565b15156124ff57600080fd5b600680548490811061250d57fe5b60009182526020918290206040805161010081018252600290930290910180548352600181015467ffffffffffffffff808216958501959095526801000000000000000081049094169183019190915263ffffffff608060020a84048116606084015260a060020a84048116608084015260c060020a84041660a083015261ffff60e060020a8404811660c084015260f060020a90930490921660e08201529091506125b890612d7b565b15156125c357600080fd5b6125cf828583866127d7565b15156125da57600080fd5b6115eb8484612df9565b606080600080846040519080825280601f01601f191660200182016040528015612618578160200160208202803883390190505b509250506020820190508461262e828287612f37565b5090949350505050565b600090815260076020526040902054600160a060020a0391821691161490565b6000918252600960205260409091208054600160a060020a031916600160a060020a03909216919091179055565b600090815260096020526040902054600160a060020a0391821691161490565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a031916909117905583161561273957600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b60408051600160a060020a0380861682528416602082015280820183905290517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360600190a1505050565b600054600160a060020a0316331461279f57600080fd5b60025460a060020a900460ff1615156127b757600080fd5b6002805474ff000000000000000000000000000000000000000019169055565b6000818414156127e95750600061294f565b6001850154608060020a900463ffffffff168214806128185750600185015460a060020a900463ffffffff1682145b156128255750600061294f565b6001830154608060020a900463ffffffff168414806128545750600183015460a060020a900463ffffffff1684145b156128615750600061294f565b6001830154608060020a900463ffffffff16158061288e57506001850154608060020a900463ffffffff16155b1561289b5750600161294f565b60018581015490840154608060020a9182900463ffffffff908116929091041614806128e6575060018086015490840154608060020a900463ffffffff90811660a060020a90920416145b156128f35750600061294f565b6001808601549084015460a060020a900463ffffffff908116608060020a90920416148061293e57506001858101549084015460a060020a9182900463ffffffff9081169290910416145b1561294b5750600061294f565b5060015b949350505050565b6000818152600760205260408082205484835290822054600160a060020a039182169116808214806113ca57506000858152600a6020526040902054600160a060020a03908116908316149250505092915050565b6000806129b7613083565b600063ffffffff891689146129cb57600080fd5b63ffffffff881688146129dd57600080fd5b61ffff871687146129ed57600080fd5b600287049250600d8361ffff161115612a0557600d92505b505060408051610100810182528581524267ffffffffffffffff90811660208301908152600093830184815263ffffffff8c8116606086019081528c82166080870190815260a0870188815261ffff8a811660c08a019081528f821660e08b01908152600680546001810182559c528a517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f60028e029081019190915598517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40909901805498519651955194519251915167ffffffffffffffff19909916998b16999099176fffffffffffffffff000000000000000019166801000000000000000096909a16959095029890981773ffffffff000000000000000000000000000000001916608060020a938616939093029290921777ffffffff0000000000000000000000000000000000000000191660a060020a91851691909102177bffffffff000000000000000000000000000000000000000000000000191660c060020a96841696909602959095177fffff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff1660e060020a91861691909102177dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1660f060020a929094169190910292909217905590919081168114612c0357600080fd5b606080830151608080850151855160408051600160a060020a038c1681526020810188905263ffffffff95861681830152929094169482019490945290810192909252517f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad59181900360a00190a1612c7d600086836126a6565b98975050505050505050565b60008160a0015163ffffffff16600014158015610cd75750506040015167ffffffffffffffff4381169116111590565b6000806000600b60009054906101000a9004600160a060020a0316600160a060020a031663eac9d94c6040518163ffffffff1660e060020a028152600401602060405180830381600087803b158015612d1157600080fd5b505af1158015612d25573d6000803e3d6000fd5b505050506040513d6020811015612d3b57600080fd5b505191506fffffffffffffffffffffffffffffffff82168214612d5d57600080fd5b5060028104810162989680811015612d755750629896805b92915050565b60008160a0015163ffffffff166000148015610cd75750506040015167ffffffffffffffff4381169116111590565b6000806000600685815481101515612dbe57fe5b90600052602060002090600202019150600684815481101515612ddd57fe5b906000526020600020906002020190506113ca828683876127d7565b600080600683815481101515612e0b57fe5b90600052602060002090600202019150600684815481101515612e2a57fe5b600091825260209091206002909102016001810180547bffffffff000000000000000000000000000000000000000000000000191660c060020a63ffffffff8716021790559050612e7a82612f7b565b612e8381612f7b565b6000848152600a602090815260408083208054600160a060020a031990811690915586845281842080549091169055600f80546001908101909155878452600783529281902054928401548151600160a060020a0390941684529183018790528281018690526801000000000000000090910467ffffffffffffffff166060830152517f241ea03ca20251805084d27d4440371c34a0b85ff108f6bb5611248f73818b80916080908290030190a150505050565b60005b60208210612f5c578251845260209384019390920191601f1990910190612f3a565b50905182516020929092036101000a6000190180199091169116179052565b600554600182015443919060039060e060020a900461ffff16600e8110612f9e57fe5b600891828204019190066004029054906101000a900463ffffffff1663ffffffff16811515612fc957fe5b6001840180546fffffffffffffffff0000000000000000191668010000000000000000939092049390930167ffffffffffffffff16919091021790819055600d60e060020a90910461ffff161015613061576001818101805461ffff60e060020a8083048216909401169092027fffff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092169190911790555b50565b6080604051908101604052806004906020820280388339509192915050565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810191909152905600a165627a7a723058201424bf1db41fa7ec76f5506a53d8bbcb84ed5b5a6ade2df0bac8deaacb118a8b0029" - code_ContractScenario011_deploySaleClockAuction = "60806040526000805460a060020a60ff02191690556004805460ff1916600117905534801561002d57600080fd5b50604051604080610ee883398101604052805160209091015160008054600160a060020a031916331781558290829061271082111561006b57600080fd5b506002819055604080517f01ffc9a70000000000000000000000000000000000000000000000000000000081527f9a20483d00000000000000000000000000000000000000000000000000000000600482015290518391600160a060020a038316916301ffc9a7916024808201926020929091908290030181600087803b1580156100f557600080fd5b505af1158015610109573d6000803e3d6000fd5b505050506040513d602081101561011f57600080fd5b5051151561012c57600080fd5b60018054600160a060020a03909216600160a060020a031990921691909117905550505050610d88806101606000396000f3006080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166327ebe40a81146101005780633f4ba83a1461012f578063454a2ab314610158578063484eccb4146101635780635c975abb1461018d5780635fd8c710146101a257806378bd7935146101b757806383b5ff8b146102045780638456cb591461021957806385b861881461022e578063878eb368146102435780638a98a9cc1461025b5780638da5cb5b1461027057806396b5a755146102a1578063c55d0f56146102b9578063dd1b7a0f146102d1578063eac9d94c146102e6578063f2fde38b146102fb575b600080fd5b34801561010c57600080fd5b5061012d600435602435604435606435600160a060020a036084351661031c565b005b34801561013b57600080fd5b50610144610414565b604080519115158252519081900360200190f35b61012d60043561048f565b34801561016f57600080fd5b5061017b6004356104f9565b60408051918252519081900360200190f35b34801561019957600080fd5b5061014461050d565b3480156101ae57600080fd5b5061012d61051d565b3480156101c357600080fd5b506101cf60043561057a565b60408051600160a060020a03909616865260208601949094528484019290925260608401526080830152519081900360a00190f35b34801561021057600080fd5b5061017b610610565b34801561022557600080fd5b50610144610616565b34801561023a57600080fd5b50610144610696565b34801561024f57600080fd5b5061012d60043561069f565b34801561026757600080fd5b5061017b61070c565b34801561027c57600080fd5b50610285610712565b60408051600160a060020a039092168252519081900360200190f35b3480156102ad57600080fd5b5061012d600435610721565b3480156102c557600080fd5b5061017b600435610766565b3480156102dd57600080fd5b50610285610798565b3480156102f257600080fd5b5061017b6107a7565b34801561030757600080fd5b5061012d600160a060020a03600435166107db565b610324610d2e565b6fffffffffffffffffffffffffffffffff8516851461034257600080fd5b6fffffffffffffffffffffffffffffffff8416841461036057600080fd5b67ffffffffffffffff8316831461037657600080fd5b600154600160a060020a0316331461038d57600080fd5b610397828761082d565b60a06040519081016040528083600160a060020a03168152602001866fffffffffffffffffffffffffffffffff168152602001856fffffffffffffffffffffffffffffffff1681526020018467ffffffffffffffff1681526020014267ffffffffffffffff16815250905061040c86826108b5565b505050505050565b60008054600160a060020a0316331461042c57600080fd5b60005460a060020a900460ff16151561044457600080fd5b6000805474ff0000000000000000000000000000000000000000191681556040517f7805862f689e2f13df9f062ff482ad3ad112aca9e0847911ed832e158c525b339190a150600190565b600081815260036020526040812054600160a060020a0316906104b28334610a09565b90506104be3384610b2f565b600154600160a060020a03838116911614156104f45760058054829160069106600581106104e857fe5b01556005805460010190555b505050565b6006816005811061050657fe5b0154905081565b60005460a060020a900460ff1681565b60015460008054600160a060020a039283169216331480610546575033600160a060020a038316145b151561055157600080fd5b604051600160a060020a03831690303180156108fc02916000818181858888f150505050505050565b6000818152600360205260408120819081908190819061059981610b9d565b15156105a457600080fd5b80546001820154600290920154600160a060020a03909116986fffffffffffffffffffffffffffffffff8084169950700100000000000000000000000000000000909304909216965067ffffffffffffffff808216965068010000000000000000909104169350915050565b60025481565b60008054600160a060020a0316331461062e57600080fd5b60005460a060020a900460ff161561064557600080fd5b6000805474ff0000000000000000000000000000000000000000191660a060020a1781556040517f6985a02210a168e66602d3235cb6db0e70f92b3ba4d376a33c0f3d9434bff6259190a150600190565b60045460ff1681565b6000805460a060020a900460ff1615156106b857600080fd5b600054600160a060020a031633146106cf57600080fd5b5060008181526003602052604090206106e781610b9d565b15156106f257600080fd5b8054610708908390600160a060020a0316610bbe565b5050565b60055481565b600054600160a060020a031681565b60008181526003602052604081209061073982610b9d565b151561074457600080fd5b508054600160a060020a031633811461075c57600080fd5b6104f48382610bbe565b600081815260036020526040812061077d81610b9d565b151561078857600080fd5b61079181610c08565b9392505050565b600154600160a060020a031681565b600080805b60058110156107d157600681600581106107c257fe5b015491909101906001016107ac565b5060059004919050565b600054600160a060020a031633146107f257600080fd5b600160a060020a0381161561082a576000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0383161790555b50565b600154604080517f23b872dd000000000000000000000000000000000000000000000000000000008152600160a060020a03858116600483015230602483015260448201859052915191909216916323b872dd91606480830192600092919082900301818387803b1580156108a157600080fd5b505af115801561040c573d6000803e3d6000fd5b603c816060015167ffffffffffffffff16101515156108d357600080fd5b60008281526003602090815260409182902083518154600160a060020a0390911673ffffffffffffffffffffffffffffffffffffffff1990911617815581840151600182018054858701516fffffffffffffffffffffffffffffffff90811670010000000000000000000000000000000081029482166fffffffffffffffffffffffffffffffff19909316831790911693909317909155606080870151600290940180546080808a015167ffffffffffffffff90811668010000000000000000026fffffffffffffffff0000000000000000199190981667ffffffffffffffff1990931683171696909617909155865189815295860192909252848601929092529083015291517fa9c8dfcda5664a5a124c713e386da27de87432d5b668e79458501eb296389ba7929181900390910190a15050565b60008281526003602052604081208180808080610a2586610b9d565b1515610a3057600080fd5b610a3986610c08565b945084881015610a4857600080fd5b8554600160a060020a03169350610a5e89610c98565b6000851115610ab057610a7085610ce5565b6040519093508386039250600160a060020a0385169083156108fc029084906000818181858888f19350505050158015610aae573d6000803e3d6000fd5b505b5060405184880390339082156108fc029083906000818181858888f19350505050158015610ae2573d6000803e3d6000fd5b50604080518a815260208101879052338183015290517f4fcc30d90a842164dd58501ab874a101a3749c3d4747139cefe7c876f4ccebd29181900360600190a15092979650505050505050565b600154604080517fa9059cbb000000000000000000000000000000000000000000000000000000008152600160a060020a038581166004830152602482018590529151919092169163a9059cbb91604480830192600092919082900301818387803b1580156108a157600080fd5b6002015460006801000000000000000090910467ffffffffffffffff161190565b610bc782610c98565b610bd18183610b2f565b6040805183815290517f2809c7e17bf978fbc7194c0a694b638c4215e9140cacc6c38ca36010b45697df9181900360200190a15050565b6002810154600090819068010000000000000000900467ffffffffffffffff16421115610c4e5750600282015468010000000000000000900467ffffffffffffffff1642035b60018301546002840154610791916fffffffffffffffffffffffffffffffff80821692700100000000000000000000000000000000909204169067ffffffffffffffff1684610cf1565b6000908152600360205260408120805473ffffffffffffffffffffffffffffffffffffffff19168155600181019190915560020180546fffffffffffffffffffffffffffffffff19169055565b60025461271091020490565b6000808080858510610d0557869350610d23565b878703925085858402811515610d1757fe5b05915081880190508093505b505050949350505050565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152905600a165627a7a723058203c3d7d4039d9d9a82dd65c7bc046590e8fe3580af952a66fe24052959889bef50029" - code_ContractScenario011_deploySiringClockAuction = "60806040526000805460a060020a60ff02191690556004805460ff1916600117905534801561002d57600080fd5b50604051604080610e1a83398101604052805160209091015160008054600160a060020a031916331781558290829061271082111561006b57600080fd5b506002819055604080517f01ffc9a70000000000000000000000000000000000000000000000000000000081527f9a20483d00000000000000000000000000000000000000000000000000000000600482015290518391600160a060020a038316916301ffc9a7916024808201926020929091908290030181600087803b1580156100f557600080fd5b505af1158015610109573d6000803e3d6000fd5b505050506040513d602081101561011f57600080fd5b5051151561012c57600080fd5b60018054600160a060020a03909216600160a060020a031990921691909117905550505050610cba806101606000396000f3006080604052600436106100da5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166327ebe40a81146100df5780633f4ba83a1461010e578063454a2ab3146101375780635c975abb146101425780635fd8c7101461015757806376190f8f1461016c57806378bd79351461018157806383b5ff8b146101ce5780638456cb59146101f5578063878eb3681461020a5780638da5cb5b1461022257806396b5a75514610253578063c55d0f561461026b578063dd1b7a0f14610283578063f2fde38b14610298575b600080fd5b3480156100eb57600080fd5b5061010c600435602435604435606435600160a060020a03608435166102b9565b005b34801561011a57600080fd5b506101236103b1565b604080519115158252519081900360200190f35b61010c60043561042c565b34801561014e57600080fd5b50610123610478565b34801561016357600080fd5b5061010c610488565b34801561017857600080fd5b506101236104e5565b34801561018d57600080fd5b506101996004356104ee565b60408051600160a060020a03909616865260208601949094528484019290925260608401526080830152519081900360a00190f35b3480156101da57600080fd5b506101e3610584565b60408051918252519081900360200190f35b34801561020157600080fd5b5061012361058a565b34801561021657600080fd5b5061010c60043561060a565b34801561022e57600080fd5b50610237610673565b60408051600160a060020a039092168252519081900360200190f35b34801561025f57600080fd5b5061010c600435610682565b34801561027757600080fd5b506101e36004356106cc565b34801561028f57600080fd5b506102376106fe565b3480156102a457600080fd5b5061010c600160a060020a036004351661070d565b6102c1610c60565b6fffffffffffffffffffffffffffffffff851685146102df57600080fd5b6fffffffffffffffffffffffffffffffff841684146102fd57600080fd5b67ffffffffffffffff8316831461031357600080fd5b600154600160a060020a0316331461032a57600080fd5b610334828761075f565b60a06040519081016040528083600160a060020a03168152602001866fffffffffffffffffffffffffffffffff168152602001856fffffffffffffffffffffffffffffffff1681526020018467ffffffffffffffff1681526020014267ffffffffffffffff1681525090506103a986826107e7565b505050505050565b60008054600160a060020a031633146103c957600080fd5b60005460a060020a900460ff1615156103e157600080fd5b6000805474ff0000000000000000000000000000000000000000191681556040517f7805862f689e2f13df9f062ff482ad3ad112aca9e0847911ed832e158c525b339190a150600190565b600154600090600160a060020a0316331461044657600080fd5b50600081815260036020526040902054600160a060020a0316610469823461093b565b506104748183610a61565b5050565b60005460a060020a900460ff1681565b60015460008054600160a060020a0392831692163314806104b1575033600160a060020a038316145b15156104bc57600080fd5b604051600160a060020a03831690303180156108fc02916000818181858888f150505050505050565b60045460ff1681565b6000818152600360205260408120819081908190819061050d81610acf565b151561051857600080fd5b80546001820154600290920154600160a060020a03909116986fffffffffffffffffffffffffffffffff8084169950700100000000000000000000000000000000909304909216965067ffffffffffffffff808216965068010000000000000000909104169350915050565b60025481565b60008054600160a060020a031633146105a257600080fd5b60005460a060020a900460ff16156105b957600080fd5b6000805474ff0000000000000000000000000000000000000000191660a060020a1781556040517f6985a02210a168e66602d3235cb6db0e70f92b3ba4d376a33c0f3d9434bff6259190a150600190565b6000805460a060020a900460ff16151561062357600080fd5b600054600160a060020a0316331461063a57600080fd5b50600081815260036020526040902061065281610acf565b151561065d57600080fd5b8054610474908390600160a060020a0316610af0565b600054600160a060020a031681565b60008181526003602052604081209061069a82610acf565b15156106a557600080fd5b508054600160a060020a03163381146106bd57600080fd5b6106c78382610af0565b505050565b60008181526003602052604081206106e381610acf565b15156106ee57600080fd5b6106f781610b3a565b9392505050565b600154600160a060020a031681565b600054600160a060020a0316331461072457600080fd5b600160a060020a0381161561075c576000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0383161790555b50565b600154604080517f23b872dd000000000000000000000000000000000000000000000000000000008152600160a060020a03858116600483015230602483015260448201859052915191909216916323b872dd91606480830192600092919082900301818387803b1580156107d357600080fd5b505af11580156103a9573d6000803e3d6000fd5b603c816060015167ffffffffffffffff161015151561080557600080fd5b60008281526003602090815260409182902083518154600160a060020a0390911673ffffffffffffffffffffffffffffffffffffffff1990911617815581840151600182018054858701516fffffffffffffffffffffffffffffffff90811670010000000000000000000000000000000081029482166fffffffffffffffffffffffffffffffff19909316831790911693909317909155606080870151600290940180546080808a015167ffffffffffffffff90811668010000000000000000026fffffffffffffffff0000000000000000199190981667ffffffffffffffff1990931683171696909617909155865189815295860192909252848601929092529083015291517fa9c8dfcda5664a5a124c713e386da27de87432d5b668e79458501eb296389ba7929181900390910190a15050565b6000828152600360205260408120818080808061095786610acf565b151561096257600080fd5b61096b86610b3a565b94508488101561097a57600080fd5b8554600160a060020a0316935061099089610bca565b60008511156109e2576109a285610c17565b6040519093508386039250600160a060020a0385169083156108fc029084906000818181858888f193505050501580156109e0573d6000803e3d6000fd5b505b5060405184880390339082156108fc029083906000818181858888f19350505050158015610a14573d6000803e3d6000fd5b50604080518a815260208101879052338183015290517f4fcc30d90a842164dd58501ab874a101a3749c3d4747139cefe7c876f4ccebd29181900360600190a15092979650505050505050565b600154604080517fa9059cbb000000000000000000000000000000000000000000000000000000008152600160a060020a038581166004830152602482018590529151919092169163a9059cbb91604480830192600092919082900301818387803b1580156107d357600080fd5b6002015460006801000000000000000090910467ffffffffffffffff161190565b610af982610bca565b610b038183610a61565b6040805183815290517f2809c7e17bf978fbc7194c0a694b638c4215e9140cacc6c38ca36010b45697df9181900360200190a15050565b6002810154600090819068010000000000000000900467ffffffffffffffff16421115610b805750600282015468010000000000000000900467ffffffffffffffff1642035b600183015460028401546106f7916fffffffffffffffffffffffffffffffff80821692700100000000000000000000000000000000909204169067ffffffffffffffff1684610c23565b6000908152600360205260408120805473ffffffffffffffffffffffffffffffffffffffff19168155600181019190915560020180546fffffffffffffffffffffffffffffffff19169055565b60025461271091020490565b6000808080858510610c3757869350610c55565b878703925085858402811515610c4957fe5b05915081880190508093505b505050949350505050565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152905600a165627a7a723058208d1842c4569ecc7005642ae981f6c77b856b1d9a921f3792bdb4219144ae25e00029" - code_ContractScenario011_deployGeneScienceInterface = "608060405234801561001057600080fd5b5060dc8061001f6000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630d9f5aed8114604d57806354c15b8214607a575b600080fd5b348015605857600080fd5b50606860043560243560443560a0565b60408051918252519081900360200190f35b348015608557600080fd5b50608c60ab565b604080519115158252519081900360200190f35b600292909101010490565b6001905600a165627a7a72305820d9550024d511527e5124d542daf0a0f3168b9bece6a238bcbccba8b61d3f0bdb0029" - code_WalletTestAccount012_storageAndCpu = "608060405234801561001057600080fd5b5061045c806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806304c58438146100725780634f2be91f1461009f578063812db772146100b657806393cd5755146100e3578063d1cd64e914610189575b600080fd5b34801561007e57600080fd5b5061009d600480360381019080803590602001909291905050506101a0565b005b3480156100ab57600080fd5b506100b4610230565b005b3480156100c257600080fd5b506100e1600480360381019080803590602001909291905050506102a2565b005b3480156100ef57600080fd5b5061010e600480360381019080803590602001909291905050506102c3565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561014e578082015181840152602081019050610133565b50505050905090810190601f16801561017b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561019557600080fd5b5061019e61037e565b005b6000600190505b8181101561022c5760008060018154018082558091505090600182039060005260206000200160006040805190810160405280600881526020017f31323334353637380000000000000000000000000000000000000000000000008152509091909150908051906020019061021d92919061038b565b505080806001019150506101a7565b5050565b60008060018154018082558091505090600182039060005260206000200160006040805190810160405280600881526020017f61626364656667680000000000000000000000000000000000000000000000008152509091909150908051906020019061029e92919061038b565b5050565b6000600190505b81811115156102bf5780806001019150506102a9565b5050565b6000818154811015156102d257fe5b906000526020600020016000915090508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103765780601f1061034b57610100808354040283529160200191610376565b820191906000526020600020905b81548152906001019060200180831161035957829003601f168201915b505050505081565b6000808060010191505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103cc57805160ff19168380011785556103fa565b828001600101855582156103fa579182015b828111156103f95782518255916020019190600101906103de565b5b509050610407919061040b565b5090565b61042d91905b80821115610429576000816000905550600101610411565b5090565b905600a165627a7a7230582087d9880a135295a17100f63b8941457f4369204d3ccc9ce4a1abf99820eb68480029" - code_TestExceptionCodeAndAbi_testtimeout = "6080604052600060035534801561001557600080fd5b5061027b806100256000396000f3006080604052600436106100825763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633755cd3c81146100875780637d965688146100b1578063a05b2577146100c9578063b0d6304d146100e1578063bbe1d75b14610115578063f8a8fd6d1461012a578063fe75faab14610141575b600080fd5b34801561009357600080fd5b5061009f600435610159565b60408051918252519081900360200190f35b3480156100bd57600080fd5b5061009f600435610178565b3480156100d557600080fd5b5061009f600435610198565b3480156100ed57600080fd5b5061009f73ffffffffffffffffffffffffffffffffffffffff600435811690602435166101e2565b34801561012157600080fd5b5061009f6101ff565b34801561013657600080fd5b5061013f610205565b005b34801561014d57600080fd5b5061009f600435610218565b600080548290811061016757fe5b600091825260209091200154905081565b600080805b83811015610191576001918201910161017d565b5092915050565b600080805b838110156101915760008054600181810183559180527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301829055918201910161019d565b600260209081526000928352604080842090915290825290205481565b60015481565b600380546001019055610216610205565b565b60006102238261022e565b600181905592915050565b600061023c6002830361022e565b6102486001840361022e565b01929150505600a165627a7a7230582077fd7ac1cd0908622d05db388922d485d6f8e3a546590b97ec8398f87f0c8a580029" - code_TestMapBigLongAndNumbers_deployErc721KittyCore = "608060405234801561001057600080fd5b506108e3806100206000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663058294c5811461009d5780630f8286c61461011d57806327e235e3146101b35780634a53ac83146101e65780637d9656881461020757806386b714e21461021f578063931fdba214610234578063babfe8e114610258578063e68c24ae146102bc575b600080fd5b3480156100a957600080fd5b506040805160206004803580820135601f810184900484028501840190955284845261010194369492936024939284019190819084018382808284375094975050509235600160a060020a031693506102e092505050565b60408051600160a060020a039092168252519081900360200190f35b34801561012957600080fd5b5061013e600160a060020a0360043516610310565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610178578181015183820152602001610160565b50505050905090810190601f1680156101a55780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101bf57600080fd5b506101d4600160a060020a03600435166103aa565b60408051918252519081900360200190f35b3480156101f257600080fd5b5061013e600160a060020a03600435166103bc565b34801561021357600080fd5b506101d4600435610422565b34801561022b57600080fd5b5061013e610442565b34801561024057600080fd5b50610101600160a060020a036004351660243561049d565b34801561026457600080fd5b506040805160206004803580820135601f810184900484028501840190955284845261010194369492936024939284019190819084018382808284375094975050509235600160a060020a0316935061066892505050565b3480156102c857600080fd5b50610101600435600160a060020a0360243516610690565b600160a060020a03811660009081526002602090815260408220845161030892860190610790565b509092915050565b60016020818152600092835260409283902080548451600294821615610100026000190190911693909304601f81018390048302840183019094528383529192908301828280156103a25780601f10610377576101008083540402835291602001916103a2565b820191906000526020600020905b81548152906001019060200180831161038557829003601f168201915b505050505081565b60006020819052908152604090205481565b600260208181526000928352604092839020805484516001821615610100026000190190911693909304601f81018390048302840183019094528383529192908301828280156103a25780601f10610377576101008083540402835291602001916103a2565b600080805b8381101561043b5760019182019101610427565b5092915050565b6003805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103a25780601f10610377576101008083540402835291602001916103a2565b6040805180820190915260018082527f6100000000000000000000000000000000000000000000000000000000000000602090920191825260009182916104e691600391610790565b50600090505b82811015610619576003805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181526105fc9361058e93919290918301828280156105845780601f1061055957610100808354040283529160200191610584565b820191906000526020600020905b81548152906001019060200180831161056757829003601f168201915b50505050506106af565b60038054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526105f093909290918301828280156105845780601f1061055957610100808354040283529160200191610584565b9063ffffffff6106d516565b805161061091600391602090910190610790565b506001016104ec565b60036001600086600160a060020a0316600160a060020a03168152602001908152602001600020908054600181600116156101000203166002900461065f92919061080e565b50929392505050565b600160a060020a03811660009081526001602090815260408220845161030892860190610790565b600160a060020a03811660009081526020819052604090209190915590565b6106b7610883565b50604080518082019091528151815260209182019181019190915290565b606080600083600001518560000151016040519080825280601f01601f191660200182016040528015610712578160200160208202803883390190505b50915060208201905061072e818660200151876000015161074c565b845160208501518551610744928401919061074c565b509392505050565b60005b60208210610771578251845260209384019390920191601f199091019061074f565b50905182516020929092036101000a6000190180199091169116179052565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106107d157805160ff19168380011785556107fe565b828001600101855582156107fe579182015b828111156107fe5782518255916020019190600101906107e3565b5061080a92915061089a565b5090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061084757805485556107fe565b828001600101855582156107fe57600052602060002091601f016020900482015b828111156107fe578254825591600101919060010190610868565b604080518082019091526000808252602082015290565b6108b491905b8082111561080a57600081556001016108a0565b905600a165627a7a72305820f826fbe07a4ee048e7cd47a00e3ca43677011f846fb9e00e1f8202a84a5159540029" - code_TestNetErc721Cat_deployErc721KittyCore = "6002805460a060020a60ff0219169055610240604052603c6080908152607860a05261012c60c05261025860e05261070861010052610e1061012052611c2061014052613840610160526170806101805261e1006101a052620151806101c0526202a3006101e052620546006102005262093a80610220526200008790600390600e620004e3565b50600f6005556301312d00600e55348015620000a257600080fd5b506002805460008054600160a060020a031990811633908117835560a060020a60ff0219909316740100000000000000000000000000000000000000001716909117909155620001019080806000198164010000000062000108810204565b50620005f1565b6000806200011562000586565b600063ffffffff891689146200012a57600080fd5b63ffffffff881688146200013d57600080fd5b61ffff871687146200014e57600080fd5b600287049250600d8361ffff1611156200016757600d92505b505060408051610100810182528581524267ffffffffffffffff90811660208301908152600093830184815263ffffffff8c8116606086019081528c82166080870190815260a0870188815261ffff8a811660c08a019081528f821660e08b01908152600680546001810182559c528a517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f60028e029081019190915598517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40909901805498519651955194519251915167ffffffffffffffff19909916998b1699909917604060020a608060020a0319166801000000000000000096909a169590950298909817608060020a63ffffffff021916700100000000000000000000000000000000938616939093029290921760a060020a63ffffffff02191674010000000000000000000000000000000000000000918516919091021760c060020a63ffffffff0219167801000000000000000000000000000000000000000000000000968416969096029590951760e060020a61ffff0219167c01000000000000000000000000000000000000000000000000000000009186169190910217600160f060020a03167e010000000000000000000000000000000000000000000000000000000000009290941691909102929092179055909190811681146200036f57600080fd5b606080830151608080850151855160408051600160a060020a038c1681526020810188905263ffffffff95861681830152929094169482019490945290810192909252517f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad59181900360a00190a1620003f46000868364010000000062000400810204565b98975050505050505050565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a03191690911790558316156200049457600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b60408051600160a060020a0380861682528416602082015280820183905290517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360600190a1505050565b600283019183908215620005745791602002820160005b838211156200054057835183826101000a81548163ffffffff021916908363ffffffff1602179055509260200192600401602081600301049283019260010302620004fa565b8015620005725782816101000a81549063ffffffff021916905560040160208160030104928301926001030262000540565b505b5062000582929150620005ca565b5090565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915290565b620005ee91905b808211156200058257805463ffffffff19168155600101620005d1565b90565b6130f380620006016000396000f3006080604052600436106102a55763ffffffff60e060020a60003504166301ffc9a781146102d55780630519ce79146103205780630560ff441461035157806305e45546146103ea57806306fdde0314610411578063095ea7b3146104265780630a0f81681461044a5780630e583df01461045f57806314001f4c1461047457806318160ddd14610495578063183a7947146104aa5780631940a936146104bf57806319c2f201146104d757806321717ebf146104ec57806323b872dd1461050157806324e7a38a1461052b57806327d7874c1461054c5780632ba73c151461056d5780633d7d3f5a1461058e5780633f4ba83a146105af57806346116e6f146105c457806346d22c70146105dc578063481af3d3146105f75780634ad8c9381461060f5780634b85fd55146106305780634dfff04f146106485780634e0a33791461066c578063561291341461068d5780635663896e146106b15780635c975abb146106c95780635fd8c710146106de5780636352211e146106f3578063680eba271461070b5780636af04a57146107205780636fbde40d1461073557806370a082311461075657806371587988146107775780637a7d4937146107985780638456cb59146107ad5780638462151c146107c257806388c2a0bf1461083357806391876e571461084b57806395d89b41146108605780639d6fac6f14610875578063a45f4bfc146108a6578063a9059cbb146108be578063b047fb50146108e2578063b0c35c05146108f7578063bc4006f51461090c578063c3bea9af14610921578063d3e6f49f14610939578063defb958414610951578063e17b25af14610966578063e6cbe35114610987578063e98b7f4d1461099c578063ed60ade614610a06578063f1ca941014610a14578063f2b47d5214610a29578063f7d8c88314610a3e575b600b54600160a060020a03163314806102c85750600c54600160a060020a031633145b15156102d357600080fd5b005b3480156102e157600080fd5b5061030c7bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1960043516610a4c565b604080519115158252519081900360200190f35b34801561032c57600080fd5b50610335610cdf565b60408051600160a060020a039092168252519081900360200190f35b34801561035d57600080fd5b50610375600480359060248035908101910135610cee565b6040805160208082528351818301528351919283929083019185019080838360005b838110156103af578181015183820152602001610397565b50505050905090810190601f1680156103dc5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156103f657600080fd5b506103ff610df1565b60408051918252519081900360200190f35b34801561041d57600080fd5b50610375610df7565b34801561043257600080fd5b506102d3600160a060020a0360043516602435610e2e565b34801561045657600080fd5b50610335610eb0565b34801561046b57600080fd5b506103ff610ebf565b34801561048057600080fd5b506102d3600160a060020a0360043516610ec6565b3480156104a157600080fd5b506103ff610f79565b3480156104b657600080fd5b506103ff610f83565b3480156104cb57600080fd5b5061030c600435610f89565b3480156104e357600080fd5b506103ff610fce565b3480156104f857600080fd5b50610335610fd5565b34801561050d57600080fd5b506102d3600160a060020a0360043581169060243516604435610fe4565b34801561053757600080fd5b506102d3600160a060020a0360043516611060565b34801561055857600080fd5b506102d3600160a060020a0360043516611113565b34801561057957600080fd5b506102d3600160a060020a0360043516611161565b34801561059a57600080fd5b506102d36004356024356044356064356111af565b3480156105bb57600080fd5b506102d36112a4565b3480156105d057600080fd5b50610335600435611338565b3480156105e857600080fd5b5061030c600435602435611353565b34801561060357600080fd5b506103356004356113d3565b34801561061b57600080fd5b506102d36004356024356044356064356113ee565b34801561063c57600080fd5b506102d36004356114c6565b34801561065457600080fd5b506102d3600160a060020a03600435166024356114e2565b34801561067857600080fd5b506102d3600160a060020a036004351661153c565b34801561069957600080fd5b506102d3600435600160a060020a036024351661158a565b3480156106bd57600080fd5b506102d36004356115f1565b3480156106d557600080fd5b5061030c61164d565b3480156106ea57600080fd5b506102d361165d565b3480156106ff57600080fd5b506103356004356116c1565b34801561071757600080fd5b506103ff6116e5565b34801561072c57600080fd5b506103356116eb565b34801561074157600080fd5b506102d3600160a060020a03600435166116fa565b34801561076257600080fd5b506103ff600160a060020a03600435166117ad565b34801561078357600080fd5b506102d3600160a060020a03600435166117c8565b3480156107a457600080fd5b506103ff61184b565b3480156107b957600080fd5b506102d3611851565b3480156107ce57600080fd5b506107e3600160a060020a03600435166118d1565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561081f578181015183820152602001610807565b505050509050019250505060405180910390f35b34801561083f57600080fd5b506103ff6004356119a3565b34801561085757600080fd5b506102d3611c7f565b34801561086c57600080fd5b50610375611d94565b34801561088157600080fd5b5061088d600435611dcb565b6040805163ffffffff9092168252519081900360200190f35b3480156108b257600080fd5b50610335600435611df8565b3480156108ca57600080fd5b506102d3600160a060020a0360043516602435611e13565b3480156108ee57600080fd5b50610335611eab565b34801561090357600080fd5b506103ff611eba565b34801561091857600080fd5b50610335611ec0565b34801561092d57600080fd5b506102d3600435611ecf565b34801561094557600080fd5b5061030c600435611fb9565b34801561095d57600080fd5b506103ff612088565b34801561097257600080fd5b506102d3600160a060020a036004351661208e565b34801561099357600080fd5b506103356120c7565b3480156109a857600080fd5b506109b46004356120d6565b604080519a15158b5298151560208b0152898901979097526060890195909552608088019390935260a087019190915260c086015260e085015261010084015261012083015251908190036101400190f35b6102d3600435602435612237565b348015610a2057600080fd5b506103ff6123d1565b348015610a3557600080fd5b506103356123d7565b6102d36004356024356123e6565b604080517f737570706f727473496e74657266616365286279746573342900000000000000815290519081900360190190206000907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff1983811691161480610cd75750604080517f746f6b656e4d657461646174612875696e743235362c737472696e67290000008152815190819003601d0181207f746f6b656e734f664f776e657228616464726573732900000000000000000000825282519182900360160182207f7472616e7366657246726f6d28616464726573732c616464726573732c75696e83527f7432353629000000000000000000000000000000000000000000000000000000602084015283519283900360250183207f7472616e7366657228616464726573732c75696e743235362900000000000000845284519384900360190184207f617070726f766528616464726573732c75696e74323536290000000000000000855285519485900360180185207f6f776e65724f662875696e743235362900000000000000000000000000000000865286519586900360100186207f62616c616e63654f662861646472657373290000000000000000000000000000875287519687900360120187207f746f74616c537570706c792829000000000000000000000000000000000000008852885197889003600d0188207f73796d626f6c2829000000000000000000000000000000000000000000000000895289519889900360080189207f6e616d65282900000000000000000000000000000000000000000000000000008a529951988990036006019098207bffffffffffffffffffffffffffffffffffffffffffffffffffffffff198c811691909a189098181818181818181891909116145b90505b919050565b600154600160a060020a031681565b6060610cf8613064565b600d54600090600160a060020a03161515610d1257600080fd5b600d54604080517fcb4799f2000000000000000000000000000000000000000000000000000000008152600481018981526024820192835260448201889052600160a060020a039093169263cb4799f2928a928a928a929091606401848480828437820191505094505050505060a060405180830381600087803b158015610d9957600080fd5b505af1158015610dad573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525060a0811015610dd257600080fd5b5060808101519092509050610de782826125e4565b9695505050505050565b60115481565b60408051808201909152600d81527f43727970746f4b69747469657300000000000000000000000000000000000000602082015281565b60025460a060020a900460ff1615610e4557600080fd5b610e4f3382612638565b1515610e5a57600080fd5b610e648183612658565b60408051338152600160a060020a038416602082015280820183905290517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259181900360600190a15050565b600054600160a060020a031681565b6298968081565b60008054600160a060020a03163314610ede57600080fd5b81905080600160a060020a03166376190f8f6040518163ffffffff1660e060020a028152600401602060405180830381600087803b158015610f1f57600080fd5b505af1158015610f33573d6000803e3d6000fd5b505050506040513d6020811015610f4957600080fd5b50511515610f5657600080fd5b600c8054600160a060020a031916600160a060020a039290921691909117905550565b6006546000190190565b600f5481565b6000808211610f9757600080fd5b6006805483908110610fa557fe5b600091825260209091206002909102016001015460c060020a900463ffffffff16151592915050565b6201518081565b600c54600160a060020a031681565b60025460a060020a900460ff1615610ffb57600080fd5b600160a060020a038216151561101057600080fd5b600160a060020a03821630141561102657600080fd5b6110303382612686565b151561103b57600080fd5b6110458382612638565b151561105057600080fd5b61105b8383836126a6565b505050565b60008054600160a060020a0316331461107857600080fd5b81905080600160a060020a03166354c15b826040518163ffffffff1660e060020a028152600401602060405180830381600087803b1580156110b957600080fd5b505af11580156110cd573d6000803e3d6000fd5b505050506040513d60208110156110e357600080fd5b505115156110f057600080fd5b60108054600160a060020a031916600160a060020a039290921691909117905550565b600054600160a060020a0316331461112a57600080fd5b600160a060020a038116151561113f57600080fd5b60008054600160a060020a031916600160a060020a0392909216919091179055565b600054600160a060020a0316331461117857600080fd5b600160a060020a038116151561118d57600080fd5b60028054600160a060020a031916600160a060020a0392909216919091179055565b60025460a060020a900460ff16156111c657600080fd5b6111d03385612638565b15156111db57600080fd5b6111e484610f89565b156111ee57600080fd5b600b54611205908590600160a060020a0316612658565b600b54604080517f27ebe40a000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606481018490523360848201529051600160a060020a03909216916327ebe40a9160a48082019260009290919082900301818387803b15801561128657600080fd5b505af115801561129a573d6000803e3d6000fd5b5050505050505050565b600054600160a060020a031633146112bb57600080fd5b60025460a060020a900460ff1615156112d357600080fd5b600b54600160a060020a031615156112ea57600080fd5b600c54600160a060020a0316151561130157600080fd5b601054600160a060020a0316151561131857600080fd5b601354600160a060020a03161561132e57600080fd5b611336612788565b565b600a60205260009081526040902054600160a060020a031681565b6000808080851161136357600080fd5b6000841161137057600080fd5b600680548690811061137e57fe5b9060005260206000209060020201915060068481548110151561139d57fe5b906000526020600020906002020190506113b9828683876127d7565b80156113ca57506113ca8486612957565b95945050505050565b600960205260009081526040902054600160a060020a031681565b60025460a060020a900460ff161561140557600080fd5b61140f3385612638565b151561141a57600080fd5b61142384611fb9565b151561142e57600080fd5b600c54611445908590600160a060020a0316612658565b600c54604080517f27ebe40a000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606481018490523360848201529051600160a060020a03909216916327ebe40a9160a48082019260009290919082900301818387803b15801561128657600080fd5b600254600160a060020a031633146114dd57600080fd5b600e55565b60025460a060020a900460ff16156114f957600080fd5b6115033382612638565b151561150e57600080fd5b6000908152600a602052604090208054600160a060020a031916600160a060020a0392909216919091179055565b600054600160a060020a0316331461155357600080fd5b600160a060020a038116151561156857600080fd5b60018054600160a060020a031916600160a060020a0392909216919091179055565b600254600090600160a060020a031633146115a457600080fd5b5080600160a060020a03811615156115c45750600254600160a060020a03165b601154611388116115d457600080fd5b6011805460010190556115eb6000808086856129ac565b50505050565b600254600160a060020a03163314806116145750600054600160a060020a031633145b806116295750600154600160a060020a031633145b151561163457600080fd5b60035463ffffffff16811061164857600080fd5b600555565b60025460a060020a900460ff1681565b6001546000908190600160a060020a0316331461167957600080fd5b5050600e54600f54303191600190910102808211156116bd57600154604051600160a060020a039091169082840380156108fc02916000818181858888f150505050505b5050565b600081815260076020526040902054600160a060020a0316801515610cda57600080fd5b61afc881565b601354600160a060020a031681565b60008054600160a060020a0316331461171257600080fd5b81905080600160a060020a03166385b861886040518163ffffffff1660e060020a028152600401602060405180830381600087803b15801561175357600080fd5b505af1158015611767573d6000803e3d6000fd5b505050506040513d602081101561177d57600080fd5b5051151561178a57600080fd5b600b8054600160a060020a031916600160a060020a039290921691909117905550565b600160a060020a031660009081526008602052604090205490565b600054600160a060020a031633146117df57600080fd5b60025460a060020a900460ff1615156117f757600080fd5b60138054600160a060020a038316600160a060020a0319909116811790915560408051918252517f450db8da6efbe9c22f2347f7c2021231df1fc58d3ae9a2fa75d39fa4461993059181900360200190a150565b60055481565b600254600160a060020a03163314806118745750600054600160a060020a031633145b806118895750600154600160a060020a031633145b151561189457600080fd5b60025460a060020a900460ff16156118ab57600080fd5b6002805474ff0000000000000000000000000000000000000000191660a060020a179055565b60606000606060008060006118e5876117ad565b9450841515611904576040805160008152602081019091529550611999565b8460405190808252806020026020018201604052801561192e578160200160208202803883390190505b509350611939610f79565b925060009150600190505b82811161199557600081815260076020526040902054600160a060020a038881169116141561198d5780848381518110151561197c57fe5b602090810290910101526001909101905b600101611944565b8395505b5050505050919050565b600080600080600080600080600260149054906101000a900460ff161515156119cb57600080fd5b600680548a9081106119d957fe5b60009182526020909120600290910201600181015490975067ffffffffffffffff161515611a0657600080fd5b604080516101008101825288548152600189015467ffffffffffffffff8082166020840152680100000000000000008204169282019290925263ffffffff608060020a83048116606083015260a060020a83048116608083015260c060020a83041660a082015261ffff60e060020a8304811660c083015260f060020a90920490911660e0820152611a9790612c89565b1515611aa257600080fd5b60018701546006805460c060020a90920463ffffffff1697509087908110611ac657fe5b600091825260209091206001808a015460029093029091019081015490965061ffff60f060020a928390048116965091900416841015611b1357600185015460f060020a900461ffff1693505b6010548754865460018a0154604080517f0d9f5aed0000000000000000000000000000000000000000000000000000000081526004810194909452602484019290925260001967ffffffffffffffff6801000000000000000090920482160116604483015251600160a060020a0390921691630d9f5aed916064808201926020929091908290030181600087803b158015611bad57600080fd5b505af1158015611bc1573d6000803e3d6000fd5b505050506040513d6020811015611bd757600080fd5b505160008a815260076020526040902054600189810154929550600160a060020a039091169350611c20918b9160c060020a90910463ffffffff1690870161ffff1686866129ac565b6001880180547bffffffff00000000000000000000000000000000000000000000000019169055600f8054600019019055600e54604051919250339181156108fc0291906000818181858888f150939c9b505050505050505050505050565b600254600160a060020a0316331480611ca25750600054600160a060020a031633145b80611cb75750600154600160a060020a031633145b1515611cc257600080fd5b600b60009054906101000a9004600160a060020a0316600160a060020a0316635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b158015611d1557600080fd5b505af1158015611d29573d6000803e3d6000fd5b50505050600c60009054906101000a9004600160a060020a0316600160a060020a0316635fd8c7106040518163ffffffff1660e060020a028152600401600060405180830381600087803b158015611d8057600080fd5b505af11580156115eb573d6000803e3d6000fd5b60408051808201909152600281527f434b000000000000000000000000000000000000000000000000000000000000602082015281565b600381600e8110611dd857fe5b60089182820401919006600402915054906101000a900463ffffffff1681565b600760205260009081526040902054600160a060020a031681565b60025460a060020a900460ff1615611e2a57600080fd5b600160a060020a0382161515611e3f57600080fd5b600160a060020a038216301415611e5557600080fd5b600b54600160a060020a0383811691161415611e7057600080fd5b600c54600160a060020a0383811691161415611e8b57600080fd5b611e953382612638565b1515611ea057600080fd5b6116bd3383836126a6565b600254600160a060020a031681565b600e5481565b600d54600160a060020a031681565b600254600090600160a060020a03163314611ee957600080fd5b60125461afc811611ef957600080fd5b611f08600080600085306129ac565b600b54909150611f22908290600160a060020a0316612658565b600b54600160a060020a03166327ebe40a82611f3c612cb9565b6040805160e060020a63ffffffff861602815260048101939093526024830191909152600060448301819052620151806064840152306084840152905160a48084019382900301818387803b158015611f9457600080fd5b505af1158015611fa8573d6000803e3d6000fd5b505060128054600101905550505050565b600080808311611fc857600080fd5b6006805484908110611fd657fe5b60009182526020918290206040805161010081018252600290930290910180548352600181015467ffffffffffffffff808216958501959095526801000000000000000081049094169183019190915263ffffffff608060020a84048116606084015260a060020a84048116608084015260c060020a84041660a083015261ffff60e060020a8404811660c084015260f060020a90930490921660e082015290915061208190612d7b565b9392505050565b61138881565b600054600160a060020a031633146120a557600080fd5b600d8054600160a060020a031916600160a060020a0392909216919091179055565b600b54600160a060020a031681565b600080600080600080600080600080600060068c8154811015156120f657fe5b906000526020600020906002020190508060010160189054906101000a900463ffffffff1663ffffffff16600014159a50438160010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff161115995080600101601c9054906101000a900461ffff1661ffff1698508060010160089054906101000a900467ffffffffffffffff1667ffffffffffffffff1697508060010160189054906101000a900463ffffffff1663ffffffff1696508060010160009054906101000a900467ffffffffffffffff1667ffffffffffffffff1695508060010160109054906101000a900463ffffffff1663ffffffff1694508060010160149054906101000a900463ffffffff1663ffffffff16935080600101601e9054906101000a900461ffff1661ffff16925080600001549150509193959799509193959799565b60025460009060a060020a900460ff161561225157600080fd5b61225b3383612638565b151561226657600080fd5b61226f82611fb9565b151561227a57600080fd5b6122848284612daa565b151561228f57600080fd5b600c54604080517fc55d0f56000000000000000000000000000000000000000000000000000000008152600481018690529051600160a060020a039092169163c55d0f56916024808201926020929091908290030181600087803b1580156122f657600080fd5b505af115801561230a573d6000803e3d6000fd5b505050506040513d602081101561232057600080fd5b5051600e54909150810134101561233657600080fd5b600c54600e54604080517f454a2ab3000000000000000000000000000000000000000000000000000000008152600481018790529051600160a060020a039093169263454a2ab39234039160248082019260009290919082900301818588803b1580156123a257600080fd5b505af11580156123b6573d6000803e3d6000fd5b505050505061105b8263ffffffff168463ffffffff16612df9565b60125481565b601054600160a060020a031681565b600254600090819060a060020a900460ff161561240257600080fd5b600e5434101561241157600080fd5b61241b3385612638565b151561242657600080fd5b6124308385612957565b151561243b57600080fd5b600680548590811061244957fe5b60009182526020918290206040805161010081018252600290930290910180548352600181015467ffffffffffffffff808216958501959095526801000000000000000081049094169183019190915263ffffffff608060020a84048116606084015260a060020a84048116608084015260c060020a84041660a083015261ffff60e060020a8404811660c084015260f060020a90930490921660e08201529092506124f490612d7b565b15156124ff57600080fd5b600680548490811061250d57fe5b60009182526020918290206040805161010081018252600290930290910180548352600181015467ffffffffffffffff808216958501959095526801000000000000000081049094169183019190915263ffffffff608060020a84048116606084015260a060020a84048116608084015260c060020a84041660a083015261ffff60e060020a8404811660c084015260f060020a90930490921660e08201529091506125b890612d7b565b15156125c357600080fd5b6125cf828583866127d7565b15156125da57600080fd5b6115eb8484612df9565b606080600080846040519080825280601f01601f191660200182016040528015612618578160200160208202803883390190505b509250506020820190508461262e828287612f37565b5090949350505050565b600090815260076020526040902054600160a060020a0391821691161490565b6000918252600960205260409091208054600160a060020a031916600160a060020a03909216919091179055565b600090815260096020526040902054600160a060020a0391821691161490565b600160a060020a03808316600081815260086020908152604080832080546001019055858352600790915290208054600160a060020a031916909117905583161561273957600160a060020a03831660009081526008602090815260408083208054600019019055838352600a82528083208054600160a060020a03199081169091556009909252909120805490911690555b60408051600160a060020a0380861682528416602082015280820183905290517fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360600190a1505050565b600054600160a060020a0316331461279f57600080fd5b60025460a060020a900460ff1615156127b757600080fd5b6002805474ff000000000000000000000000000000000000000019169055565b6000818414156127e95750600061294f565b6001850154608060020a900463ffffffff168214806128185750600185015460a060020a900463ffffffff1682145b156128255750600061294f565b6001830154608060020a900463ffffffff168414806128545750600183015460a060020a900463ffffffff1684145b156128615750600061294f565b6001830154608060020a900463ffffffff16158061288e57506001850154608060020a900463ffffffff16155b1561289b5750600161294f565b60018581015490840154608060020a9182900463ffffffff908116929091041614806128e6575060018086015490840154608060020a900463ffffffff90811660a060020a90920416145b156128f35750600061294f565b6001808601549084015460a060020a900463ffffffff908116608060020a90920416148061293e57506001858101549084015460a060020a9182900463ffffffff9081169290910416145b1561294b5750600061294f565b5060015b949350505050565b6000818152600760205260408082205484835290822054600160a060020a039182169116808214806113ca57506000858152600a6020526040902054600160a060020a03908116908316149250505092915050565b6000806129b7613083565b600063ffffffff891689146129cb57600080fd5b63ffffffff881688146129dd57600080fd5b61ffff871687146129ed57600080fd5b600287049250600d8361ffff161115612a0557600d92505b505060408051610100810182528581524267ffffffffffffffff90811660208301908152600093830184815263ffffffff8c8116606086019081528c82166080870190815260a0870188815261ffff8a811660c08a019081528f821660e08b01908152600680546001810182559c528a517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f60028e029081019190915598517ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d40909901805498519651955194519251915167ffffffffffffffff19909916998b16999099176fffffffffffffffff000000000000000019166801000000000000000096909a16959095029890981773ffffffff000000000000000000000000000000001916608060020a938616939093029290921777ffffffff0000000000000000000000000000000000000000191660a060020a91851691909102177bffffffff000000000000000000000000000000000000000000000000191660c060020a96841696909602959095177fffff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff1660e060020a91861691909102177dffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1660f060020a929094169190910292909217905590919081168114612c0357600080fd5b606080830151608080850151855160408051600160a060020a038c1681526020810188905263ffffffff95861681830152929094169482019490945290810192909252517f0a5311bd2a6608f08a180df2ee7c5946819a649b204b554bb8e39825b2c50ad59181900360a00190a1612c7d600086836126a6565b98975050505050505050565b60008160a0015163ffffffff16600014158015610cd75750506040015167ffffffffffffffff4381169116111590565b6000806000600b60009054906101000a9004600160a060020a0316600160a060020a031663eac9d94c6040518163ffffffff1660e060020a028152600401602060405180830381600087803b158015612d1157600080fd5b505af1158015612d25573d6000803e3d6000fd5b505050506040513d6020811015612d3b57600080fd5b505191506fffffffffffffffffffffffffffffffff82168214612d5d57600080fd5b5060028104810162989680811015612d755750629896805b92915050565b60008160a0015163ffffffff166000148015610cd75750506040015167ffffffffffffffff4381169116111590565b6000806000600685815481101515612dbe57fe5b90600052602060002090600202019150600684815481101515612ddd57fe5b906000526020600020906002020190506113ca828683876127d7565b600080600683815481101515612e0b57fe5b90600052602060002090600202019150600684815481101515612e2a57fe5b600091825260209091206002909102016001810180547bffffffff000000000000000000000000000000000000000000000000191660c060020a63ffffffff8716021790559050612e7a82612f7b565b612e8381612f7b565b6000848152600a602090815260408083208054600160a060020a031990811690915586845281842080549091169055600f80546001908101909155878452600783529281902054928401548151600160a060020a0390941684529183018790528281018690526801000000000000000090910467ffffffffffffffff166060830152517f241ea03ca20251805084d27d4440371c34a0b85ff108f6bb5611248f73818b80916080908290030190a150505050565b60005b60208210612f5c578251845260209384019390920191601f1990910190612f3a565b50905182516020929092036101000a6000190180199091169116179052565b600554600182015443919060039060e060020a900461ffff16600e8110612f9e57fe5b600891828204019190066004029054906101000a900463ffffffff1663ffffffff16811515612fc957fe5b6001840180546fffffffffffffffff0000000000000000191668010000000000000000939092049390930167ffffffffffffffff16919091021790819055600d60e060020a90910461ffff161015613061576001818101805461ffff60e060020a8083048216909401169092027fffff0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff9092169190911790555b50565b6080604051908101604052806004906020820280388339509192915050565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810191909152905600a165627a7a723058201424bf1db41fa7ec76f5506a53d8bbcb84ed5b5a6ade2df0bac8deaacb118a8b0029" - code_TestNetErc721Cat_deploySaleClockAuction = "60806040526000805460a060020a60ff02191690556004805460ff1916600117905534801561002d57600080fd5b50604051604080610ee883398101604052805160209091015160008054600160a060020a031916331781558290829061271082111561006b57600080fd5b506002819055604080517f01ffc9a70000000000000000000000000000000000000000000000000000000081527f9a20483d00000000000000000000000000000000000000000000000000000000600482015290518391600160a060020a038316916301ffc9a7916024808201926020929091908290030181600087803b1580156100f557600080fd5b505af1158015610109573d6000803e3d6000fd5b505050506040513d602081101561011f57600080fd5b5051151561012c57600080fd5b60018054600160a060020a03909216600160a060020a031990921691909117905550505050610d88806101606000396000f3006080604052600436106100fb5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166327ebe40a81146101005780633f4ba83a1461012f578063454a2ab314610158578063484eccb4146101635780635c975abb1461018d5780635fd8c710146101a257806378bd7935146101b757806383b5ff8b146102045780638456cb591461021957806385b861881461022e578063878eb368146102435780638a98a9cc1461025b5780638da5cb5b1461027057806396b5a755146102a1578063c55d0f56146102b9578063dd1b7a0f146102d1578063eac9d94c146102e6578063f2fde38b146102fb575b600080fd5b34801561010c57600080fd5b5061012d600435602435604435606435600160a060020a036084351661031c565b005b34801561013b57600080fd5b50610144610414565b604080519115158252519081900360200190f35b61012d60043561048f565b34801561016f57600080fd5b5061017b6004356104f9565b60408051918252519081900360200190f35b34801561019957600080fd5b5061014461050d565b3480156101ae57600080fd5b5061012d61051d565b3480156101c357600080fd5b506101cf60043561057a565b60408051600160a060020a03909616865260208601949094528484019290925260608401526080830152519081900360a00190f35b34801561021057600080fd5b5061017b610610565b34801561022557600080fd5b50610144610616565b34801561023a57600080fd5b50610144610696565b34801561024f57600080fd5b5061012d60043561069f565b34801561026757600080fd5b5061017b61070c565b34801561027c57600080fd5b50610285610712565b60408051600160a060020a039092168252519081900360200190f35b3480156102ad57600080fd5b5061012d600435610721565b3480156102c557600080fd5b5061017b600435610766565b3480156102dd57600080fd5b50610285610798565b3480156102f257600080fd5b5061017b6107a7565b34801561030757600080fd5b5061012d600160a060020a03600435166107db565b610324610d2e565b6fffffffffffffffffffffffffffffffff8516851461034257600080fd5b6fffffffffffffffffffffffffffffffff8416841461036057600080fd5b67ffffffffffffffff8316831461037657600080fd5b600154600160a060020a0316331461038d57600080fd5b610397828761082d565b60a06040519081016040528083600160a060020a03168152602001866fffffffffffffffffffffffffffffffff168152602001856fffffffffffffffffffffffffffffffff1681526020018467ffffffffffffffff1681526020014267ffffffffffffffff16815250905061040c86826108b5565b505050505050565b60008054600160a060020a0316331461042c57600080fd5b60005460a060020a900460ff16151561044457600080fd5b6000805474ff0000000000000000000000000000000000000000191681556040517f7805862f689e2f13df9f062ff482ad3ad112aca9e0847911ed832e158c525b339190a150600190565b600081815260036020526040812054600160a060020a0316906104b28334610a09565b90506104be3384610b2f565b600154600160a060020a03838116911614156104f45760058054829160069106600581106104e857fe5b01556005805460010190555b505050565b6006816005811061050657fe5b0154905081565b60005460a060020a900460ff1681565b60015460008054600160a060020a039283169216331480610546575033600160a060020a038316145b151561055157600080fd5b604051600160a060020a03831690303180156108fc02916000818181858888f150505050505050565b6000818152600360205260408120819081908190819061059981610b9d565b15156105a457600080fd5b80546001820154600290920154600160a060020a03909116986fffffffffffffffffffffffffffffffff8084169950700100000000000000000000000000000000909304909216965067ffffffffffffffff808216965068010000000000000000909104169350915050565b60025481565b60008054600160a060020a0316331461062e57600080fd5b60005460a060020a900460ff161561064557600080fd5b6000805474ff0000000000000000000000000000000000000000191660a060020a1781556040517f6985a02210a168e66602d3235cb6db0e70f92b3ba4d376a33c0f3d9434bff6259190a150600190565b60045460ff1681565b6000805460a060020a900460ff1615156106b857600080fd5b600054600160a060020a031633146106cf57600080fd5b5060008181526003602052604090206106e781610b9d565b15156106f257600080fd5b8054610708908390600160a060020a0316610bbe565b5050565b60055481565b600054600160a060020a031681565b60008181526003602052604081209061073982610b9d565b151561074457600080fd5b508054600160a060020a031633811461075c57600080fd5b6104f48382610bbe565b600081815260036020526040812061077d81610b9d565b151561078857600080fd5b61079181610c08565b9392505050565b600154600160a060020a031681565b600080805b60058110156107d157600681600581106107c257fe5b015491909101906001016107ac565b5060059004919050565b600054600160a060020a031633146107f257600080fd5b600160a060020a0381161561082a576000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0383161790555b50565b600154604080517f23b872dd000000000000000000000000000000000000000000000000000000008152600160a060020a03858116600483015230602483015260448201859052915191909216916323b872dd91606480830192600092919082900301818387803b1580156108a157600080fd5b505af115801561040c573d6000803e3d6000fd5b603c816060015167ffffffffffffffff16101515156108d357600080fd5b60008281526003602090815260409182902083518154600160a060020a0390911673ffffffffffffffffffffffffffffffffffffffff1990911617815581840151600182018054858701516fffffffffffffffffffffffffffffffff90811670010000000000000000000000000000000081029482166fffffffffffffffffffffffffffffffff19909316831790911693909317909155606080870151600290940180546080808a015167ffffffffffffffff90811668010000000000000000026fffffffffffffffff0000000000000000199190981667ffffffffffffffff1990931683171696909617909155865189815295860192909252848601929092529083015291517fa9c8dfcda5664a5a124c713e386da27de87432d5b668e79458501eb296389ba7929181900390910190a15050565b60008281526003602052604081208180808080610a2586610b9d565b1515610a3057600080fd5b610a3986610c08565b945084881015610a4857600080fd5b8554600160a060020a03169350610a5e89610c98565b6000851115610ab057610a7085610ce5565b6040519093508386039250600160a060020a0385169083156108fc029084906000818181858888f19350505050158015610aae573d6000803e3d6000fd5b505b5060405184880390339082156108fc029083906000818181858888f19350505050158015610ae2573d6000803e3d6000fd5b50604080518a815260208101879052338183015290517f4fcc30d90a842164dd58501ab874a101a3749c3d4747139cefe7c876f4ccebd29181900360600190a15092979650505050505050565b600154604080517fa9059cbb000000000000000000000000000000000000000000000000000000008152600160a060020a038581166004830152602482018590529151919092169163a9059cbb91604480830192600092919082900301818387803b1580156108a157600080fd5b6002015460006801000000000000000090910467ffffffffffffffff161190565b610bc782610c98565b610bd18183610b2f565b6040805183815290517f2809c7e17bf978fbc7194c0a694b638c4215e9140cacc6c38ca36010b45697df9181900360200190a15050565b6002810154600090819068010000000000000000900467ffffffffffffffff16421115610c4e5750600282015468010000000000000000900467ffffffffffffffff1642035b60018301546002840154610791916fffffffffffffffffffffffffffffffff80821692700100000000000000000000000000000000909204169067ffffffffffffffff1684610cf1565b6000908152600360205260408120805473ffffffffffffffffffffffffffffffffffffffff19168155600181019190915560020180546fffffffffffffffffffffffffffffffff19169055565b60025461271091020490565b6000808080858510610d0557869350610d23565b878703925085858402811515610d1757fe5b05915081880190508093505b505050949350505050565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152905600a165627a7a723058203c3d7d4039d9d9a82dd65c7bc046590e8fe3580af952a66fe24052959889bef50029" - code_TestNetErc721Cat_deploySiringClockAuction = "60806040526000805460a060020a60ff02191690556004805460ff1916600117905534801561002d57600080fd5b50604051604080610e1a83398101604052805160209091015160008054600160a060020a031916331781558290829061271082111561006b57600080fd5b506002819055604080517f01ffc9a70000000000000000000000000000000000000000000000000000000081527f9a20483d00000000000000000000000000000000000000000000000000000000600482015290518391600160a060020a038316916301ffc9a7916024808201926020929091908290030181600087803b1580156100f557600080fd5b505af1158015610109573d6000803e3d6000fd5b505050506040513d602081101561011f57600080fd5b5051151561012c57600080fd5b60018054600160a060020a03909216600160a060020a031990921691909117905550505050610cba806101606000396000f3006080604052600436106100da5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166327ebe40a81146100df5780633f4ba83a1461010e578063454a2ab3146101375780635c975abb146101425780635fd8c7101461015757806376190f8f1461016c57806378bd79351461018157806383b5ff8b146101ce5780638456cb59146101f5578063878eb3681461020a5780638da5cb5b1461022257806396b5a75514610253578063c55d0f561461026b578063dd1b7a0f14610283578063f2fde38b14610298575b600080fd5b3480156100eb57600080fd5b5061010c600435602435604435606435600160a060020a03608435166102b9565b005b34801561011a57600080fd5b506101236103b1565b604080519115158252519081900360200190f35b61010c60043561042c565b34801561014e57600080fd5b50610123610478565b34801561016357600080fd5b5061010c610488565b34801561017857600080fd5b506101236104e5565b34801561018d57600080fd5b506101996004356104ee565b60408051600160a060020a03909616865260208601949094528484019290925260608401526080830152519081900360a00190f35b3480156101da57600080fd5b506101e3610584565b60408051918252519081900360200190f35b34801561020157600080fd5b5061012361058a565b34801561021657600080fd5b5061010c60043561060a565b34801561022e57600080fd5b50610237610673565b60408051600160a060020a039092168252519081900360200190f35b34801561025f57600080fd5b5061010c600435610682565b34801561027757600080fd5b506101e36004356106cc565b34801561028f57600080fd5b506102376106fe565b3480156102a457600080fd5b5061010c600160a060020a036004351661070d565b6102c1610c60565b6fffffffffffffffffffffffffffffffff851685146102df57600080fd5b6fffffffffffffffffffffffffffffffff841684146102fd57600080fd5b67ffffffffffffffff8316831461031357600080fd5b600154600160a060020a0316331461032a57600080fd5b610334828761075f565b60a06040519081016040528083600160a060020a03168152602001866fffffffffffffffffffffffffffffffff168152602001856fffffffffffffffffffffffffffffffff1681526020018467ffffffffffffffff1681526020014267ffffffffffffffff1681525090506103a986826107e7565b505050505050565b60008054600160a060020a031633146103c957600080fd5b60005460a060020a900460ff1615156103e157600080fd5b6000805474ff0000000000000000000000000000000000000000191681556040517f7805862f689e2f13df9f062ff482ad3ad112aca9e0847911ed832e158c525b339190a150600190565b600154600090600160a060020a0316331461044657600080fd5b50600081815260036020526040902054600160a060020a0316610469823461093b565b506104748183610a61565b5050565b60005460a060020a900460ff1681565b60015460008054600160a060020a0392831692163314806104b1575033600160a060020a038316145b15156104bc57600080fd5b604051600160a060020a03831690303180156108fc02916000818181858888f150505050505050565b60045460ff1681565b6000818152600360205260408120819081908190819061050d81610acf565b151561051857600080fd5b80546001820154600290920154600160a060020a03909116986fffffffffffffffffffffffffffffffff8084169950700100000000000000000000000000000000909304909216965067ffffffffffffffff808216965068010000000000000000909104169350915050565b60025481565b60008054600160a060020a031633146105a257600080fd5b60005460a060020a900460ff16156105b957600080fd5b6000805474ff0000000000000000000000000000000000000000191660a060020a1781556040517f6985a02210a168e66602d3235cb6db0e70f92b3ba4d376a33c0f3d9434bff6259190a150600190565b6000805460a060020a900460ff16151561062357600080fd5b600054600160a060020a0316331461063a57600080fd5b50600081815260036020526040902061065281610acf565b151561065d57600080fd5b8054610474908390600160a060020a0316610af0565b600054600160a060020a031681565b60008181526003602052604081209061069a82610acf565b15156106a557600080fd5b508054600160a060020a03163381146106bd57600080fd5b6106c78382610af0565b505050565b60008181526003602052604081206106e381610acf565b15156106ee57600080fd5b6106f781610b3a565b9392505050565b600154600160a060020a031681565b600054600160a060020a0316331461072457600080fd5b600160a060020a0381161561075c576000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0383161790555b50565b600154604080517f23b872dd000000000000000000000000000000000000000000000000000000008152600160a060020a03858116600483015230602483015260448201859052915191909216916323b872dd91606480830192600092919082900301818387803b1580156107d357600080fd5b505af11580156103a9573d6000803e3d6000fd5b603c816060015167ffffffffffffffff161015151561080557600080fd5b60008281526003602090815260409182902083518154600160a060020a0390911673ffffffffffffffffffffffffffffffffffffffff1990911617815581840151600182018054858701516fffffffffffffffffffffffffffffffff90811670010000000000000000000000000000000081029482166fffffffffffffffffffffffffffffffff19909316831790911693909317909155606080870151600290940180546080808a015167ffffffffffffffff90811668010000000000000000026fffffffffffffffff0000000000000000199190981667ffffffffffffffff1990931683171696909617909155865189815295860192909252848601929092529083015291517fa9c8dfcda5664a5a124c713e386da27de87432d5b668e79458501eb296389ba7929181900390910190a15050565b6000828152600360205260408120818080808061095786610acf565b151561096257600080fd5b61096b86610b3a565b94508488101561097a57600080fd5b8554600160a060020a0316935061099089610bca565b60008511156109e2576109a285610c17565b6040519093508386039250600160a060020a0385169083156108fc029084906000818181858888f193505050501580156109e0573d6000803e3d6000fd5b505b5060405184880390339082156108fc029083906000818181858888f19350505050158015610a14573d6000803e3d6000fd5b50604080518a815260208101879052338183015290517f4fcc30d90a842164dd58501ab874a101a3749c3d4747139cefe7c876f4ccebd29181900360600190a15092979650505050505050565b600154604080517fa9059cbb000000000000000000000000000000000000000000000000000000008152600160a060020a038581166004830152602482018590529151919092169163a9059cbb91604480830192600092919082900301818387803b1580156107d357600080fd5b6002015460006801000000000000000090910467ffffffffffffffff161190565b610af982610bca565b610b038183610a61565b6040805183815290517f2809c7e17bf978fbc7194c0a694b638c4215e9140cacc6c38ca36010b45697df9181900360200190a15050565b6002810154600090819068010000000000000000900467ffffffffffffffff16421115610b805750600282015468010000000000000000900467ffffffffffffffff1642035b600183015460028401546106f7916fffffffffffffffffffffffffffffffff80821692700100000000000000000000000000000000909204169067ffffffffffffffff1684610c23565b6000908152600360205260408120805473ffffffffffffffffffffffffffffffffffffffff19168155600181019190915560020180546fffffffffffffffffffffffffffffffff19169055565b60025461271091020490565b6000808080858510610c3757869350610c55565b878703925085858402811515610c4957fe5b05915081880190508093505b505050949350505050565b6040805160a081018252600080825260208201819052918101829052606081018290526080810191909152905600a165627a7a723058208d1842c4569ecc7005642ae981f6c77b856b1d9a921f3792bdb4219144ae25e00029" - code_TestNetErc721Cat_deployGeneScienceInterface = "608060405234801561001057600080fd5b5060dc8061001f6000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630d9f5aed8114604d57806354c15b8214607a575b600080fd5b348015605857600080fd5b50606860043560243560443560a0565b60408051918252519081900360200190f35b348015608557600080fd5b50608c60ab565b604080519115158252519081900360200190f35b600292909101010490565b6001905600a165627a7a72305820d9550024d511527e5124d542daf0a0f3168b9bece6a238bcbccba8b61d3f0bdb0029" - code_TestNetFomo3D_deployErc721CryptoKitties = "60c0604052600660808190527f464f4d4f3344000000000000000000000000000000000000000000000000000060a0908152620000409160009190620000b3565b506040805180820190915260038082527f463344000000000000000000000000000000000000000000000000000000000060209092019182526200008791600191620000b3565b506305f5e1006002556000600855600b805460ff19169055348015620000ac57600080fd5b5062000158565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620000f657805160ff191683800117855562000126565b8280016001018555821562000126579182015b828111156200012657825182559160200191906001019062000109565b506200013492915062000138565b5090565b6200015591905b808211156200013457600081556001016200013f565b90565b61165980620001686000396000f3006080604052600436106101685763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166265318b811461017657806306fdde03146101a957806310d0ffdd1461023357806318160ddd1461024b578063226093731461026057806327defa1f14610278578063313ce567146102a1578063392efb52146102cc5780633ccfd60b146102e45780634b750334146102fb57806356d399e814610310578063688abbf7146103255780636b2f46321461033f57806370a08231146103545780638328b610146103755780638620410b1461038d57806389135ae9146103a25780638fea64bd146103bf578063949e8acd146103d457806395d89b41146103e9578063a8e04f34146103fe578063a9059cbb14610413578063b84c824614610437578063c47f002714610490578063e4849b32146104e9578063e9fad8ee14610501578063f088d54714610516578063fdb5a03e1461052a575b61017334600061053f565b50005b34801561018257600080fd5b50610197600160a060020a0360043516610b15565b60408051918252519081900360200190f35b3480156101b557600080fd5b506101be610b50565b6040805160208082528351818301528351919283929083019185019080838360005b838110156101f85781810151838201526020016101e0565b50505050905090810190601f1680156102255780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561023f57600080fd5b50610197600435610bde565b34801561025757600080fd5b50610197610c0e565b34801561026c57600080fd5b50610197600435610c15565b34801561028457600080fd5b5061028d610c4e565b604080519115158252519081900360200190f35b3480156102ad57600080fd5b506102b6610c57565b6040805160ff9092168252519081900360200190f35b3480156102d857600080fd5b5061028d600435610c5c565b3480156102f057600080fd5b506102f9610c71565b005b34801561030757600080fd5b50610197610d44565b34801561031c57600080fd5b50610197610d93565b34801561033157600080fd5b506101976004351515610d99565b34801561034b57600080fd5b50610197610ddc565b34801561036057600080fd5b50610197600160a060020a0360043516610de1565b34801561038157600080fd5b506102f9600435610dfc565b34801561039957600080fd5b50610197610e43565b3480156103ae57600080fd5b506102f96004356024351515610e87565b3480156103cb57600080fd5b506102f9610ee9565b3480156103e057600080fd5b50610197610eeb565b3480156103f557600080fd5b506101be610efe565b34801561040a57600080fd5b506102f9610f58565b34801561041f57600080fd5b5061028d600160a060020a0360043516602435610fa6565b34801561044357600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526102f99436949293602493928401919081908401838280828437509497506111609650505050505050565b34801561049c57600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526102f99436949293602493928401919081908401838280828437509497506111b99650505050505050565b3480156104f557600080fd5b506102f960043561120d565b34801561050d57600080fd5b506102f961135e565b610197600160a060020a036004351661138b565b34801561053657600080fd5b506102f9611397565b60008060008060008060008060008a6000339050600b60009054906101000a900460ff16801561058157506801158e460913d000008261057d610ddc565b0311155b1561088e57600160a060020a03811660009081526003602052604090205460ff16151560011480156105d65750600160a060020a038116600090815260076020526040902054670de0b6b3a764000090830111155b15156105e157600080fd5b600160a060020a038116600090815260076020526040902054610604908361144d565b600160a060020a03821660009081526007602052604090205533995061062b8d6005611463565b9850610638896003611463565b9750610644898961147a565b96506106508d8a61147a565b955061065b8661148c565b945068010000000000000000870293506000851180156106855750600854610683868261144d565b115b151561069057600080fd5b600160a060020a038c16158015906106ba575089600160a060020a03168c600160a060020a031614155b80156106e05750600254600160a060020a038d1660009081526004602052604090205410155b1561072657600160a060020a038c16600090815260056020526040902054610708908961144d565b600160a060020a038d16600090815260056020526040902055610741565b610730878961144d565b965068010000000000000000870293505b600060085411156107a5576107586008548661144d565b600881905568010000000000000000880281151561077257fe5b6009805492909104909101905560085468010000000000000000880281151561079757fe5b0485028403840393506107ab565b60088590555b600160a060020a038a166000908152600460205260409020546107ce908661144d565b600460008c600160a060020a0316600160a060020a031681526020019081526020016000208190555083856009540203925082600660008c600160a060020a0316600160a060020a03168152602001908152602001600020600082825401925050819055508b600160a060020a03168a600160a060020a03167f022c0d992e4d873a3748436d960d5140c1f9721cf73f7ca5ec679d3d9f4fe2d58f88604051808381526020018281526020019250505060405180910390a3849a50610b05565b600b805460ff191690553399506108a68d6005611463565b98506108b3896003611463565b97506108bf898961147a565b96506108cb8d8a61147a565b95506108d68661148c565b9450680100000000000000008702935060008511801561090057506008546108fe868261144d565b115b151561090b57600080fd5b600160a060020a038c1615801590610935575089600160a060020a03168c600160a060020a031614155b801561095b5750600254600160a060020a038d1660009081526004602052604090205410155b156109a157600160a060020a038c16600090815260056020526040902054610983908961144d565b600160a060020a038d166000908152600560205260409020556109bc565b6109ab878961144d565b965068010000000000000000870293505b60006008541115610a20576109d36008548661144d565b60088190556801000000000000000088028115156109ed57fe5b60098054929091049091019055600854680100000000000000008802811515610a1257fe5b048502840384039350610a26565b60088590555b600160a060020a038a16600090815260046020526040902054610a49908661144d565b600460008c600160a060020a0316600160a060020a031681526020019081526020016000208190555083856009540203925082600660008c600160a060020a0316600160a060020a03168152602001908152602001600020600082825401925050819055508b600160a060020a03168a600160a060020a03167f022c0d992e4d873a3748436d960d5140c1f9721cf73f7ca5ec679d3d9f4fe2d58f88604051808381526020018281526020019250505060405180910390a3849a505b5050505050505050505092915050565b600160a060020a0316600090815260066020908152604080832054600490925290912054600954680100000000000000009102919091030490565b6000805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610bd65780601f10610bab57610100808354040283529160200191610bd6565b820191906000526020600020905b815481529060010190602001808311610bb957829003601f168201915b505050505081565b6000808080610bee856005611463565b9250610bfa858461147a565b9150610c058261148c565b95945050505050565b6008545b90565b6000806000806008548511151515610c2c57600080fd5b610c3585611508565b9250610c42836005611463565b9150610c05838361147a565b600b5460ff1681565b600681565b600a6020526000908152604090205460ff1681565b6000806000610c806001610d99565b11610c8a57600080fd5b339150610c976000610d99565b600160a060020a038316600081815260066020908152604080832080546801000000000000000087020190556005909152808220805490839055905193019350909183156108fc0291849190818181858888f19350505050158015610d00573d6000803e3d6000fd5b50604080518281529051600160a060020a038416917fccad973dcd043c7d680389db4378bd6b9775db7124092e9e0422c9e46d7985dc919081900360200190a25050565b60008060008060085460001415610d625764d18c2e28009350610d8d565b610d6e620f4240611508565b9250610d7b836005611463565b9150610d87838361147a565b90508093505b50505090565b60025481565b60003382610daf57610daa81610b15565b610dd3565b600160a060020a038116600090815260056020526040902054610dd182610b15565b015b91505b50919050565b303190565b600160a060020a031660009081526004602052604090205490565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff161515610e3d57600080fd5b50600255565b60008060008060085460001415610e62576501001d1bf8009350610d8d565b610e6e620f4240611508565b9250610e7b836005611463565b9150610d87838361144d565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff161515610ec857600080fd5b506000918252600a6020526040909120805460ff1916911515919091179055565b565b600033610ef781610de1565b91505b5090565b60018054604080516020600284861615610100026000190190941693909304601f81018490048402820184019092528181529291830182828015610bd65780601f10610bab57610100808354040283529160200191610bd6565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff161515610f9957600080fd5b50600b805460ff19169055565b600080600080600080610fb7610eeb565b11610fc157600080fd5b600b5433945060ff16158015610fef5750600160a060020a0384166000908152600460205260409020548611155b1515610ffa57600080fd5b60006110066001610d99565b111561101457611014610c71565b61101f866005611463565b925061102b868461147a565b915061103683611508565b90506110446008548461147a565b600855600160a060020a03841660009081526004602052604090205461106a908761147a565b600160a060020a038086166000908152600460205260408082209390935590891681522054611099908361144d565b600160a060020a0388811660008181526004602090815260408083209590955560098054948a16835260069091528482208054948c0290940390935582549181529290922080549285029092019091555460085461110d919068010000000000000000840281151561110757fe5b0461144d565b600955604080518381529051600160a060020a03808a1692908716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9181900360200190a35060019695505050505050565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff1615156111a157600080fd5b81516111b490600190602085019061159f565b505050565b604080516c010000000000000000000000003390810282528251918290036014019091206000908152600a602052919091205460ff1615156111fa57600080fd5b81516111b490600090602085019061159f565b6000806000806000806000611220610eeb565b1161122a57600080fd5b3360008181526004602052604090205490965087111561124957600080fd5b86945061125585611508565b9350611262846005611463565b925061126e848461147a565b915061127c6008548661147a565b600855600160a060020a0386166000908152600460205260409020546112a2908661147a565b600160a060020a038716600090815260046020908152604080832093909355600954600690915291812080549288026801000000000000000086020192839003905560085491925010156113125761130e60095460085468010000000000000000860281151561110757fe5b6009555b60408051868152602081018490528151600160a060020a038916927fc4823739c5787d2ca17e404aa47d5569ae71dfb49cbf21b3f6152ed238a31139928290030190a250505050505050565b336000818152600460205260408120549081111561137f5761137f8161120d565b611387610c71565b5050565b6000610dd6348361053f565b6000806000806113a76001610d99565b116113b157600080fd5b6113bb6000610d99565b336000818152600660209081526040808320805468010000000000000000870201905560059091528120805490829055909201945092506113fd90849061053f565b905081600160a060020a03167fbe339fc14b041c2b0e0f3dd2cd325d0c3668b78378001e53160eab36153264588483604051808381526020018281526020019250505060405180910390a2505050565b60008282018381101561145c57fe5b9392505050565b600080828481151561147157fe5b04949350505050565b60008282111561148657fe5b50900390565b600854600090670de0b6b3a764000090829064174876e8006114f56114ef692a5a058fc295ed000000880269021e19e0c9bab24000006002860a02016c02863c1f5cdae42f95400000008502016ec097ce7bc90715b34b9f10000000000161156a565b8561147a565b8115156114fe57fe5b0403949350505050565b600854600090620f424083810191810190839061155764d18c2e280082850464174876e80002018702600283620f423f1982890a8b9003010464174876e8000281151561155157fe5b0461147a565b81151561156057fe5b0495945050505050565b80600260018201045b81811015610dd657809150600281828581151561158c57fe5b040181151561159757fe5b049050611573565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106115e057805160ff191683800117855561160d565b8280016001018555821561160d579182015b8281111561160d5782518255916020019190600101906115f2565b50610efa92610c129250905b80821115610efa57600081556001016116195600a165627a7a72305820bf757ace6c45263e75b0a8eb6c539065f0ca610f7bf4378df93a0eff2d0551060029" - code1_TestNetFomo3D_deployErc721CryptoKitties = "608060405234801561001057600080fd5b5061011a806100206000396000f300608060405260043610603f576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff168063f8a8fd6d146044575b600080fd5b348015604f57600080fd5b506056606c565b6040518082815260200191505060405180910390f35b6000600180141515607c57600080fd5b603c80141515608a57600080fd5b610e1080141515609957600080fd5b620151808014151560a957600080fd5b62093a808014151560b957600080fd5b6301e133808014151560ca57600080fd5b620f42408014151560da57600080fd5b60018014151560e857600080fd5b429050905600a165627a7a72305820e8f9994ec320bbc329299a1cec491445178da2a60b219fb25e91adb9c4e4aa930029" - code_TestNetFomo3D_tooLargeStorage = "60e0604090815260808190527f313233343536373831323334353637383132333435363738313233343536373860a081815260c091909152610044916001919061009e565b50604080516060810182528181527f6162636466657467616263646665746761626364666574676162636466657467602082018181529183015261008b916002919061009e565b5034801561009857600080fd5b50610139565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100df57805160ff191683800117855561010c565b8280016001018555821561010c579182015b8281111561010c5782518255916020019190600101906100f1565b5061011892915061011c565b5090565b61013691905b808211156101185760008155600101610122565b90565b6105bb806101486000396000f3006080604052600436106100615763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166386b714e28114610066578063c2985578146100f0578063e6a01b5a14610105578063f8ac93e81461011f575b600080fd5b34801561007257600080fd5b5061007b610134565b6040805160208082528351818301528351919283929083019185019080838360005b838110156100b557818101518382015260200161009d565b50505050905090810190601f1680156100e25780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156100fc57600080fd5b5061007b6101c2565b34801561011157600080fd5b5061011d6004356102cc565b005b34801561012b57600080fd5b5061011d6103e0565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156101ba5780601f1061018f576101008083540402835291602001916101ba565b820191906000526020600020905b81548152906001019060200180831161019d57829003601f168201915b505050505081565b60028054604080516020601f600019610100600187161502019094168590049384018190048102820181019092528281526060936102c6936102599383018282801561024f5780601f106102245761010080835404028352916020019161024f565b820191906000526020600020905b81548152906001019060200180831161023257829003601f168201915b50505050506103ff565b60018054604080516020601f6002600019610100878916150201909516949094049384018190048102820181019092528281526102ba939092909183018282801561024f5780601f106102245761010080835404028352916020019161024f565b9063ffffffff61042516565b90505b90565b60006102d66101c2565b80516102ea916000916020909101906104e0565b50600090505b818110156103dc576000805460408051602060026001851615610100026000190190941693909304601f81018490048402820184019092528181526103bf9361035d939192909183018282801561024f5780601f106102245761010080835404028352916020019161024f565b60008054604080516020601f600260001961010060018816150201909516949094049384018190048102820181019092528281526102ba939092909183018282801561024f5780601f106102245761010080835404028352916020019161024f565b80516103d3916000916020909101906104e0565b506001016102f0565b5050565b6040805160208101918290526000908190526103fc91816104e0565b50565b61040761055e565b50604080518082019091528151815260209182019181019190915290565b606080600083600001518560000151016040519080825280601f01601f191660200182016040528015610462578160200160208202803883390190505b50915060208201905061047e818660200151876000015161049c565b845160208501518551610494928401919061049c565b509392505050565b60005b602082106104c1578251845260209384019390920191601f199091019061049f565b50905182516020929092036101000a6000190180199091169116179052565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061052157805160ff191683800117855561054e565b8280016001018555821561054e579182015b8281111561054e578251825591602001919060010190610533565b5061055a929150610575565b5090565b604080518082019091526000808252602082015290565b6102c991905b8082111561055a576000815560010161057b5600a165627a7a723058207e0cfcb8e796037851028c428aca173ecd924a4572c51605ecebbf548fecdf3d0029" - code_TestStorageAndCpu_storageAndCpu = "6080604052600060045534801561001557600080fd5b506104c0806100256000396000f3006080604052600436106100a35763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416632656df4881146100a85780633755cd3c146100bf5780636f269385146100e95780637d965688146100fe578063a05b257714610116578063b0d6304d1461012e578063b648763914610162578063bbe1d75b146101ec578063f8a8fd6d14610201578063fe75faab14610216575b600080fd5b3480156100b457600080fd5b506100bd61022e565b005b3480156100cb57600080fd5b506100d7600435610230565b60408051918252519081900360200190f35b3480156100f557600080fd5b506100bd61024f565b34801561010a57600080fd5b506100d7600435610296565b34801561012257600080fd5b506100d76004356102b6565b34801561013a57600080fd5b506100d773ffffffffffffffffffffffffffffffffffffffff60043581169060243516610300565b34801561016e57600080fd5b5061017761031d565b6040805160208082528351818301528351919283929083019185019080838360005b838110156101b1578181015183820152602001610199565b50505050905090810190601f1680156101de5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b3480156101f857600080fd5b506100d76103ab565b34801561020d57600080fd5b506100bd6103b1565b34801561022257600080fd5b506100d76004356103c2565b565b600180548290811061023e57fe5b600091825260209091200154905081565b6040805180820190915260088082527f31323334353637380000000000000000000000000000000000000000000000006020909201918252610293916000916103f9565b50565b600080805b838110156102af576001918201910161029b565b5092915050565b600080805b838110156102af5760018054808201825560008290527fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf60182905591820191016102bb565b600360209081526000928352604080842090915290825290205481565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103a35780601f10610378576101008083540402835291602001916103a3565b820191906000526020600020905b81548152906001019060200180831161038657829003601f168201915b505050505081565b60025481565b60048054600101905561022e6103b1565b60006103cd826103d8565b600281905592915050565b60006103e6600283036103d8565b6103f2600184036103d8565b0192915050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061043a57805160ff1916838001178555610467565b82800160010185558215610467579182015b8281111561046757825182559160200191906001019061044c565b50610473929150610477565b5090565b61049191905b80821115610473576000815560010161047d565b905600a165627a7a72305820ca3a4850a926264dc27c0e3483830bac3385c61565c738281b05d747d20676670029" - code_WalletTestAccount013 = "608060405234801561001057600080fd5b5061045c806100206000396000f30060806040526004361061006d576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806304c58438146100725780634f2be91f1461009f578063812db772146100b657806393cd5755146100e3578063d1cd64e914610189575b600080fd5b34801561007e57600080fd5b5061009d600480360381019080803590602001909291905050506101a0565b005b3480156100ab57600080fd5b506100b4610230565b005b3480156100c257600080fd5b506100e1600480360381019080803590602001909291905050506102a2565b005b3480156100ef57600080fd5b5061010e600480360381019080803590602001909291905050506102c3565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561014e578082015181840152602081019050610133565b50505050905090810190601f16801561017b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561019557600080fd5b5061019e61037e565b005b6000600190505b8181101561022c5760008060018154018082558091505090600182039060005260206000200160006040805190810160405280600881526020017f31323334353637380000000000000000000000000000000000000000000000008152509091909150908051906020019061021d92919061038b565b505080806001019150506101a7565b5050565b60008060018154018082558091505090600182039060005260206000200160006040805190810160405280600881526020017f61626364656667680000000000000000000000000000000000000000000000008152509091909150908051906020019061029e92919061038b565b5050565b6000600190505b81811115156102bf5780806001019150506102a9565b5050565b6000818154811015156102d257fe5b906000526020600020016000915090508054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103765780601f1061034b57610100808354040283529160200191610376565b820191906000526020600020905b81548152906001019060200180831161035957829003601f168201915b505050505081565b6000808060010191505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106103cc57805160ff19168380011785556103fa565b828001600101855582156103fa579182015b828111156103f95782518255916020019190600101906103de565b5b509050610407919061040b565b5090565b61042d91905b80821115610429576000816000905550600101610411565b5090565b905600a165627a7a7230582087d9880a135295a17100f63b8941457f4369204d3ccc9ce4a1abf99820eb68480029" - code_ContractEventAndLog1 = "608060405234801561001057600080fd5b50610e6c806100206000396000f3006080604052600436106100fc576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630265ec371461010b5780630a98bcec146101155780630d16a1e31461013557806312d2c2091461013f57806340de00d314610149578063462da3081461017c57806360edcb5f1461018657806367392426146101905780636cb244f11461019a5780636e5f4528146101cd57806372f48b1a146101d7578063797d1255146101f75780638615960d14610232578063bd85753b14610249578063ce6db7c0146102f8578063d0a0eadc146103a7578063d228d484146103be578063d52aca67146103e9575b34801561010857600080fd5b50005b6101136103f3565b005b61013360048036038101908080359060200190929190505050610485565b005b61013d610535565b005b61014761057c565b005b34801561015557600080fd5b5061015e610669565b60405180826000191660001916815260200191505060405180910390f35b6101846106cc565b005b61018e610798565b005b61019861080a565b005b3480156101a657600080fd5b506101af610872565b60405180826000191660001916815260200191505060405180910390f35b6101d56108af565b005b6101f56004803603810190808035906020019092919050505061095b565b005b34801561020357600080fd5b506102306004803603810190808035151590602001909291908035151590602001909291905050506109e1565b005b34801561023e57600080fd5b50610247610a23565b005b34801561025557600080fd5b506102f6600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610aba565b005b34801561030457600080fd5b506103a5600480360381019080803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290803590602001908201803590602001908080601f0160208091040260200160405190810160405280939291908181526020018383808284378201915050505050509192919290505050610bbd565b005b3480156103b357600080fd5b506103bc610c9f565b005b3480156103ca57600080fd5b506103d3610d7c565b6040518082815260200191505060405180910390f35b6103f1610d9b565b005b60008030915034905034600102600019168273ffffffffffffffffffffffffffffffffffffffff16600102600019163373ffffffffffffffffffffffffffffffffffffffff16600102600019167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860010260405180826000191660001916815260200191505060405180910390a35050565b6000806000309250349150600090505b8381101561052f5734600102600019168373ffffffffffffffffffffffffffffffffffffffff16600102600019163373ffffffffffffffffffffffffffffffffffffffff16600102600019167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860010260405180826000191660001916815260200191505060405180910390a38080600101915050610495565b50505050565b600080309150349050808273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1660405160405180910390a35050565b600080309150349050808273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860405160405180910390a48173ffffffffffffffffffffffffffffffffffffffff16600102600019163373ffffffffffffffffffffffffffffffffffffffff166001026000191634600102600019167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860010260405180826000191660001916815260200191505060405180910390a35050565b600060405180807f7472616e7366657228616464726573732c616464726573732c75696e7432353681526020017f290000000000000000000000000000000000000000000000000000000000000081525060210190506040518091039020905090565b600080309150349050808273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1660405160405180910390a38173ffffffffffffffffffffffffffffffffffffffff16600102600019163373ffffffffffffffffffffffffffffffffffffffff166001026000191634600102600019167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860010260405180826000191660001916815260200191505060405180910390a35050565b6000803091503490508173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f233b34846284da6adf1006478380fa328232b0a6ede5041bfe21ea9be1b3b88a836040518082815260200191505060405180910390a35050565b600080309150349050808273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860405160405180910390a45050565b600060405180807f4465706f73697428616464726573732c686173683235362c75696e743235362981525060200190506040518091039020905090565b6000803091503490507f0c2fb0b24194d40c1d753915af9ba7185bd7a703e4374ca9fb376a4f7c91dcca338383604051808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001828152602001935050505060405180910390a15050565b6000806000309250349150600090505b838110156109db57818373ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860405160405180910390a4808060010191505061096b565b50505050565b8015157f37f1c240387a938c945ab44c1cff92ff6d224ce37ee4db1d770944201f6fcc2983604051808215151515815260200191505060405180910390a25050565b7f4e2428acf9e70e881e61b1dabc7589a9c3800a9737a6a67e29f70a1397925b2c600160c8610bb8619c40604051808560ff1681526020018467ffffffffffffffff168152602001836fffffffffffffffffffffffffffffffff168152602001827effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff16815260200194505050505060405180910390a1565b806040518082805190602001908083835b602083101515610af05780518252602082019150602081019050602083039250610acb565b6001836020036101000a03801982511681845116808217855250505050505090500191505060405180910390207fcb164b075277ecd24c68a6ff14fbdd71a2c6cc9cf7bec9797b8227471f740dfa836040518080602001828103825283818151815260200191508051906020019080838360005b83811015610b7f578082015181840152602081019050610b64565b50505050905090810190601f168015610bac5780820380516001836020036101000a031916815260200191505b509250505060405180910390a25050565b806040518082805190602001908083835b602083101515610bf35780518252602082019150602081019050602083039250610bce565b6001836020036101000a0380198251168184511680821785525050505050509050019150506040518091039020826040518080602001828103825283818151815260200191508051906020019080838360005b83811015610c61578082015181840152602081019050610c46565b50505050905090810190601f168015610c8e5780820380516001836020036101000a031916815260200191505b509250505060405180910390a15050565b7fb24eee86cea7aa22cfdcfaa01da5152afa042fd9a0a446ef038034c705bc25d57fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8307ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff4487ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd9da600604051808560000b81526020018460080b81526020018360100b815260200182601c0b815260200194505050505060405180910390a1565b60003073ffffffffffffffffffffffffffffffffffffffff1631905090565b600080309150349050807f39f02551491f3fe37d6822a5987d21ac6d6385c6dc38b97a29699a5bb45f038a3384604051808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019250505060405180910390a250505600a165627a7a723058206121fcbe7b56027d526e504c463f8f29064931be358774a6a065110af09d21b70029" - code_ContractEventAndLog2 = "608060405234801561001057600080fd5b50610369806100206000396000f300608060405260043610610057576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680634247b80e14610066578063d0e30db014610070578063d228d4841461007a575b34801561006357600080fd5b50005b61006e6100a5565b005b6100786102b6565b005b34801561008657600080fd5b5061008f61031e565b6040518082815260200191505060405180910390f35b6000806000630420042076010000000000000000000000000000000000000000000002925063042004206f01000000000000000000000000000000029150630420042060010290507f88c75e92614e379252c5b1847e9753f9668ebb5ebb9a148333bdf0458d3d9cdf838383604051808475ffffffffffffffffffffffffffffffffffffffffffff191675ffffffffffffffffffffffffffffffffffffffffffff19168152602001836effffffffffffffffffffffffffffff19166effffffffffffffffffffffffffffff191681526020018260001916600019168152602001935050505060405180910390a1828282604051808475ffffffffffffffffffffffffffffffffffffffffffff191675ffffffffffffffffffffffffffffffffffffffffffff19168152602001836effffffffffffffffffffffffffffff19166effffffffffffffffffffffffffffff191681526020018260001916600019168152602001935050505060405180910390a08060001916826effffffffffffffffffffffffffffff19168475ffffffffffffffffffffffffffffffffffffffffffff19167f47f711f8177f4e1a7a44e07049543e0b69ef4b740c817c404c3ef911623fa89160405160405180910390a48060001916826effffffffffffffffffffffffffffff19168475ffffffffffffffffffffffffffffffffffffffffffff191660405160405180910390a3505050565b600080309150349050808273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fbeabacc8ffedac16e9a60acdb2ca743d80c2ebb44977a93fa8e483c74d2b35a860405160405180910390a45050565b60003073ffffffffffffffffffffffffffffffffffffffff16319050905600a165627a7a72305820f5c3bb96350b175387f95b45f915f736ba0468b0880f65c542b8b55d261e72760029" - - code_OriginEnergyLimit001 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5061014e8061003a6000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663329000b58114610045575b600080fd5b34801561005157600080fd5b50d3801561005e57600080fd5b50d2801561006b57600080fd5b50610077600435610089565b60408051918252519081900360200190f35b604080516003808252608082019092526000916060919060208201838038833901905050905060018160008151811015156100c057fe5b602090810290910101528051600290829060019081106100dc57fe5b602090810290910101528051600390829060029081106100f857fe5b60209081029091010152805181908490811061011057fe5b906020019060200201519150509190505600a165627a7a7230582058dd457e2aeba46e78dd8b9c36b777d362763c05ec1ad62e0d79de51ff3dde790029" - code_OriginEnergyLimit004 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5061014e8061003a6000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663329000b58114610045575b600080fd5b34801561005157600080fd5b50d3801561005e57600080fd5b50d2801561006b57600080fd5b50610077600435610089565b60408051918252519081900360200190f35b604080516003808252608082019092526000916060919060208201838038833901905050905060018160008151811015156100c057fe5b602090810290910101528051600290829060019081106100dc57fe5b602090810290910101528051600390829060029081106100f857fe5b60209081029091010152805181908490811061011057fe5b906020019060200201519150509190505600a165627a7a723058206503efa46ed431a2604563d7764b4b9e6ca03238259cb133c878592fc43a4b670029" - - - code_ContractTrcToken001_transferTokenContract = "6080604052d3600055d2600155346002556101418061001f6000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305c24200811461005b5780633be9ece71461008157806371dc08ce146100aa575b600080fd5b6100636100b2565b60408051938452602084019290925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffffffffffffff600435166024356044356100c0565b005b61006361010d565b600054600154600254909192565b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5f9e7905ef98e66e60dd4b38e00b05de418da3154e7570029" - code_ContractTrcToken002_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken005_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken006_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken011_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken011_resultContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken012_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken014_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken014_resultContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken016_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken016_resultContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken017_recieveTokenContract = "60806040526000805560c5806100166000396000f30060806040526004361060485763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166362548c7b8114604a578063890eba68146050575b005b6048608c565b348015605b57600080fd5b50d38015606757600080fd5b50d28015607357600080fd5b50607a6093565b60408051918252519081900360200190f35b6001600055565b600054815600a165627a7a723058204c4f1bb8eca0c4f1678cc7cc1179e03d99da2a980e6792feebe4d55c89c022830029" - code_ContractTrcToken042_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken042_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken043_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken043_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken046_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken047_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code2_ContractTrcToken023_tokenTest = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a7230582006508824be321d3ad4594b1b2dae9099960f982a99b5e1121896fbbb115967780029" - code_ContractTrcToken023_tokenTest = "60806040526000805560b3806100166000396000f300608060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663890eba6881146045575b6001600055005b348015605057600080fd5b50d38015605c57600080fd5b50d28015606857600080fd5b50606f6081565b60408051918252519081900360200190f35b600054815600a165627a7a72305820fc51dbe84825144f5e50d2ab8c418a5b1bfe75a31b054528816f2311b2632d6d0029" - code_ContractTrcToken026_BTest = "6080604052610145806100136000396000f3006080604052600436106100275763ffffffff60e060020a600035041663cb35b7e28114610029575b005b61002773ffffffffffffffffffffffffffffffffffffffff600435811690602435166044356064358373ffffffffffffffffffffffffffffffffffffffff1660405180807f7472616e7328616464726573732c75696e743235362c747263546f6b656e2900815250601f019050604051809103902060e060020a90048484846040518463ffffffff1660e060020a028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200183815260200182815260200193505050506000604051808303816000875af150505050505050505600a165627a7a72305820f80979e10a32bf6d6995716d7c5b159944473c2db9ac4ca5e780cfcd620261260029" - code1_ContractTrcToken026_CTest = "608060405260d9806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634f53d8a881146040575b005b603e73ffffffffffffffffffffffffffffffffffffffff6004351660243560443560405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc029084908490600081818185878a8ad094505050505015801560a7573d6000803e3d6000fd5b505050505600a165627a7a723058203db4692a33e354b8bb6b6274f3c25ca36facafc80e996629c2b7c8e79ef40f2e0029" - code1_ContractTrcToken026_tokenTest = "6080604052610257806100136000396000f3006080604052600436106100325763ffffffff60e060020a6000350416636409a1c0811461003457806383efe58114610067575b005b61003273ffffffffffffffffffffffffffffffffffffffff6004358116906024358116906044351660643560843561009a565b61003273ffffffffffffffffffffffffffffffffffffffff60043581169060243581169060443516606435608435610163565b604080517f7472616e734328616464726573732c616464726573732c75696e743235362c7481527f7263546f6b656e290000000000000000000000000000000000000000000000006020820152815190819003602801812063ffffffff60e060020a91829004908116909102825273ffffffffffffffffffffffffffffffffffffffff8781166004840152868116602484015260448301869052606483018590529251928816929091608480820192600092909190829003018183875af1505050505050505050565b604080517f7472616e734328616464726573732c616464726573732c75696e743235362c7481527f7263546f6b656e290000000000000000000000000000000000000000000000006020820152815190819003602801812063ffffffff60e060020a91829004908116909102825273ffffffffffffffffffffffffffffffffffffffff87811660048401528681166024840152604483018690526064830185905292519288169290916084808201926000929091908290030181865af45050505050505050505600a165627a7a72305820554cb78d3d6082a8b93092e5edd2b66b83a47707eb8cbbfdbb06a0806fce72840029" - code_ContractTrcToken027_BTest = "6080604052610145806100136000396000f3006080604052600436106100275763ffffffff60e060020a600035041663cb35b7e28114610029575b005b61002773ffffffffffffffffffffffffffffffffffffffff600435811690602435166044356064358373ffffffffffffffffffffffffffffffffffffffff1660405180807f7472616e7328616464726573732c75696e743235362c747263546f6b656e2900815250601f019050604051809103902060e060020a90048484846040518463ffffffff1660e060020a028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200183815260200182815260200193505050506000604051808303816000875af150505050505050505600a165627a7a72305820f80979e10a32bf6d6995716d7c5b159944473c2db9ac4ca5e780cfcd620261260029" - code_ContractTrcToken027_CTest = "608060405260d9806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634f53d8a881146040575b005b603e73ffffffffffffffffffffffffffffffffffffffff6004351660243560443560405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc029084908490600081818185878a8ad094505050505015801560a7573d6000803e3d6000fd5b505050505600a165627a7a723058203db4692a33e354b8bb6b6274f3c25ca36facafc80e996629c2b7c8e79ef40f2e0029" - - code_ContractTrcToken027_tokenTest = "6080604052610257806100136000396000f3006080604052600436106100325763ffffffff60e060020a6000350416636409a1c0811461003457806383efe58114610067575b005b61003273ffffffffffffffffffffffffffffffffffffffff6004358116906024358116906044351660643560843561009a565b61003273ffffffffffffffffffffffffffffffffffffffff60043581169060243581169060443516606435608435610163565b604080517f7472616e734328616464726573732c616464726573732c75696e743235362c7481527f7263546f6b656e290000000000000000000000000000000000000000000000006020820152815190819003602801812063ffffffff60e060020a91829004908116909102825273ffffffffffffffffffffffffffffffffffffffff8781166004840152868116602484015260448301869052606483018590529251928816929091608480820192600092909190829003018183875af1505050505050505050565b604080517f7472616e734328616464726573732c616464726573732c75696e743235362c7481527f7263546f6b656e290000000000000000000000000000000000000000000000006020820152815190819003602801812063ffffffff60e060020a91829004908116909102825273ffffffffffffffffffffffffffffffffffffffff87811660048401528681166024840152604483018690526064830185905292519288169290916084808201926000929091908290030181865af45050505050505050505600a165627a7a72305820554cb78d3d6082a8b93092e5edd2b66b83a47707eb8cbbfdbb06a0806fce72840029" - code_ContractTrcToken028_tokenTest = "608060405260016000556102a5806100186000396000f3006080604052600436106100565763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630dbe671f811461005b578063baf462821461009c578063d46300fd146100a9575b600080fd5b34801561006757600080fd5b50d3801561007457600080fd5b50d2801561008157600080fd5b5061008a6100b1565b60408051918252519081900360200190f35b6100a76004356100b7565b005b61008a610182565b60005481565b60006100c1610188565b604051809103906000f0801580156100dd573d6000803e3d6000fd5b5090508073ffffffffffffffffffffffffffffffffffffffff1663205e3c9c836040518263ffffffff167c010000000000000000000000000000000000000000000000000000000002815260040180828152602001915050602060405180830381600087803b15801561014f57600080fd5b505af1158015610163573d6000803e3d6000fd5b505050506040513d602081101561017957600080fd5b50516000555050565b60005490565b60405160e28061019883390190560060806040526000805560cc806100166000396000f30060806040526004361060485763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663205e3c9c8114604a578063890eba68146065575b005b6053600435608f565b60408051918252519081900360200190f35b348015607057600080fd5b50d38015607c57600080fd5b50d28015608857600080fd5b506053609a565b506009600081905590565b600054815600a165627a7a7230582000d7b938c0aa356a26f89e8816d8cafa65acdc21fbfc77112e7b774cc35ec6fa0029a165627a7a723058204f7b7aa7d1a83605c6830eee3ee774b9a06722e6c70a9dce28a51064abe834160029" - code_ContractTrcToken054_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken055_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken060_transferTokenContract = "6080604052d3600055d2600155346002556101418061001f6000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305c24200811461005b5780633be9ece71461008157806371dc08ce146100aa575b600080fd5b6100636100b2565b60408051938452602084019290925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffffffffffffff600435166024356044356100c0565b005b61006361010d565b600054600154600254909192565b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5f9e7905ef98e66e60dd4b38e00b05de418da3154e7570029" - code_ContractTrcToken061_transferTokenContract = "6080604052d3600055d2600155346002556101418061001f6000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305c24200811461005b5780633be9ece71461008157806371dc08ce146100aa575b600080fd5b6100636100b2565b60408051938452602084019290925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffffffffffffff600435166024356044356100c0565b005b61006361010d565b600054600154600254909192565b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5f9e7905ef98e66e60dd4b38e00b05de418da3154e7570029" - code_ContractTrcToken062_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken062_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken063_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken063_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken064_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken064_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken066_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken066_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken067_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken067_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken068_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - - code_ContractTrcToken068_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken071_transferTokenContract = "608060405261022e806100136000396000f3006080604052600436106100775763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f68114610079578063544051aa14610093578063584d4262146100a757806371dc08ce146100cd5780639663d3f2146100ee578063a730416e14610102575b005b610077600160a060020a0360043516602435604435610119565b610077600160a060020a0360043516610159565b6100bb600160a060020a036004351661019c565b60408051918252519081900360200190f35b6100d56101ad565b6040805192835260208301919091528051918290030190f35b610077600160a060020a03600435166101b3565b6100bb600160a060020a03600435166024356101f1565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad0945050505050158015610153573d6000803e3d6000fd5b50505050565b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d0945050505050158015610198573d6000803e3d6000fd5b5050565b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090600190678000000000000001908381818185878a84d0945050505050158015610198573d6000803e3d6000fd5b600160a060020a039190911690d1905600a165627a7a72305820d37032d630dfb2b80dac39db09b9eabfc228e157e20131e49ccde99a2cc3e2710029" - code_ContractTrcToken071_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken073_transferTokenContract = "608060405260e5806100126000396000f300608060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663dfc0db988114606f575b34d2d37f70536dc19abf7e0862a7afc0755f548bfd5f0b40cbd9fc87fa19b2e50b454a5660405160405180910390a4005b6078600435607a565b005b604080513481529051d291d3913385d1917fe8e04df6a82498bd5fb1fe7f2168f525c54ee1003b3a56638c858e94fd9e4854919081900360200190a4505600a165627a7a72305820dca795a21bfc9451314c14306b0220175611298bdb59c8b2cfdb1120cb3fda390029" - code_ContractTrcToken074_transferTokenContract = "608060405260e5806100126000396000f300608060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663dfc0db988114606f575b34d2d37f70536dc19abf7e0862a7afc0755f548bfd5f0b40cbd9fc87fa19b2e50b454a5660405160405180910390a4005b6078600435607a565b005b604080513481529051d291d3913385d1917fe8e04df6a82498bd5fb1fe7f2168f525c54ee1003b3a56638c858e94fd9e4854919081900360200190a4505600a165627a7a72305820dca795a21bfc9451314c14306b0220175611298bdb59c8b2cfdb1120cb3fda390029" - code_ContractTrcToken075_transferTokenContract = "608060405261019c806100136000396000f3006080604052600436106100565763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416632ab5cf918114610087578063dfc0db9814610091578063f9a677791461009c575b34d2d37f70536dc19abf7e0862a7afc0755f548bfd5f0b40cbd9fc87fa19b2e50b454a5660405160405180910390a4005b61008f6100a4565b005b61008f6004356100eb565b61008f61012a565b604080513481529051d291d391336780000000000f425319d1917fe8e04df6a82498bd5fb1fe7f2168f525c54ee1003b3a56638c858e94fd9e4854919081900360200190a4565b604080513481529051d291d3913385d1917fe8e04df6a82498bd5fb1fe7f2168f525c54ee1003b3a56638c858e94fd9e4854919081900360200190a450565b604080513481529051d291d391336780000000000f4253d1917fe8e04df6a82498bd5fb1fe7f2168f525c54ee1003b3a56638c858e94fd9e4854919081900360200190a45600a165627a7a723058204eef0c9d8221d37dbe366e9af0815246c4f9239d3f22f27b9db0aa0a3e23aa580029" - code_ContractTrcToken0552_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken0553_transferTokenContract = "6080604052610118806100136000396000f30060806040526004361060485763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece78114604d57806371dc08ce146074575b600080fd5b607273ffffffffffffffffffffffffffffffffffffffff600435166024356044356098565b005b607a60e4565b60408051938452602084019290925282820152519081900360600190f35b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560de573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820b8d4f8ea5443a03d615ea5dfe7a7435498522f9c7abeb25583d953ee2d20be4a0029" - code_ContractTrcToken0612_transferTokenContract = "6080604052d3600055d2600155346002556101418061001f6000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305c24200811461005b5780633be9ece71461008157806371dc08ce146100aa575b600080fd5b6100636100b2565b60408051938452602084019290925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffffffffffffff600435166024356044356100c0565b005b61006361010d565b600054600154600254909192565b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5f9e7905ef98e66e60dd4b38e00b05de418da3154e7570029" - code_ContractTrcToken0613_transferTokenContract = "6080604052d3600055d2600155346002556101418061001f6000396000f3006080604052600436106100565763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166305c24200811461005b5780633be9ece71461008157806371dc08ce146100aa575b600080fd5b6100636100b2565b60408051938452602084019290925282820152519081900360600190f35b6100a873ffffffffffffffffffffffffffffffffffffffff600435166024356044356100c0565b005b61006361010d565b600054600154600254909192565b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad0945050505050158015610107573d6000803e3d6000fd5b50505050565bd3d2349091925600a165627a7a72305820a2fb39541e90eda9a2f5f9e7905ef98e66e60dd4b38e00b05de418da3154e7570029" - code_ContractTrcToken0672_transferTokenContract = "6080604052610343806100136000396000f3006080604052600436106100985763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663144401f6811461009a5780631ea31431146100b45780632c5c6641146100c8578063544051aa146100dc578063584d4262146100f057806371dc08ce1461011657806393bc91fd14610137578063a730416e1461014b578063acea104514610162575b005b610098600160a060020a0360043516602435604435610176565b610098600160a060020a03600435166101b6565b610098600160a060020a03600435166101f1565b610098600160a060020a0360043516610231565b610104600160a060020a0360043516610270565b60408051918252519081900360200190f35b61011e610281565b6040805192835260208301919091528051918290030190f35b610098600160a060020a0360043516610287565b610104600160a060020a03600435166024356102c7565b610098600160a060020a03600435166102d8565b604051600160a060020a0384169083156108fc029084908490600081818185878a8ad09450505050501580156101b0573d6000803e3d6000fd5b50505050565b604051600160a060020a038216906000906000199082908181818181878a82d09450505050501580156101ed573d6000803e3d6000fd5b5050565b604051600160a060020a0382169060009067800000000000000090620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b604051600160a060020a03821690600090600190680200000000000f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a0316620f4241d190565bd3d29091565b604051600160a060020a03821690600090677fffffffffffffff90620f4241908381818185878a84d09450505050501580156101ed573d6000803e3d6000fd5b600160a060020a039190911690d190565b604051600160a060020a038216906108fc90600090678000000000000001908281818185828a8ad09450505050501580156101ed573d6000803e3d6000fd00a165627a7a72305820716217ff39873b1f852cdc214cfb38a4c2337d18fbd1128b69b2866f7f24ae1c0029" - code_ContractTrcToken0672_recieveTokenContract = "608060405260658060116000396000f30060806040819052d38152d260a0523460c0527fd1ed7a3c020c4f5939654147940a147a8e4e638fa1e8f5664b5efbd1e1f3c4a690606090a10000a165627a7a72305820ea1e6d9606638e6c9e72dcdcc749561b826ec85713c003fae9d4700a2919040f0029" - code_ContractTrcToken029_tokenTest = "608060405261034f806100136000396000f30060806040526004361061004b5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630dbe671f8114610050578063c3e911d4146100a8575b600080fd5b34801561005c57600080fd5b50d3801561006957600080fd5b50d2801561007657600080fd5b5061007f6100b8565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b6100b66004356024356100d4565b005b60005473ffffffffffffffffffffffffffffffffffffffff1681565b60006100de6101de565b604051809103906000f0801580156100fa573d6000803e3d6000fd5b5090508073ffffffffffffffffffffffffffffffffffffffff1663071f65a883856040518363ffffffff167c01000000000000000000000000000000000000000000000000000000000281526004018083815260200182815260200192505050602060405180830381600087803b15801561017457600080fd5b505af1158015610188573d6000803e3d6000fd5b505050506040513d602081101561019e57600080fd5b50506000805473ffffffffffffffffffffffffffffffffffffffff191673ffffffffffffffffffffffffffffffffffffffff929092169190911790555050565b604051610135806101ef83390190560060806040526000805561011e806100176000396000f30060806040526004361060525763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663071f65a881146054578063890eba68146074578063f96339301460b0575b005b606060043560243560da565b604080519115158252519081900360200190f35b348015607f57600080fd5b50d38015608b57600080fd5b50d28015609757600080fd5b50609e60e6565b60408051918252519081900360200190f35b34801560bb57600080fd5b50d3801560c757600080fd5b50d2801560d357600080fd5b50609e60ec565b50506009600090815590565b60005481565b600054905600a165627a7a72305820a699d9eec788d2a222b703af447d9c2ddffb626fc07a57834af8e3f9bce64dc90029a165627a7a72305820626050611353c2f66f9b94e3935c21fd4dad7cc494b7459f3597451e1b6004de0029" - code_ContractTrcToken030_tokenTest = "608060405260a9806100126000396000f300608060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cbf0b0c081146043575b600080fd5b606273ffffffffffffffffffffffffffffffffffffffff600435166064565b005b8073ffffffffffffffffffffffffffffffffffffffff16ff00a165627a7a72305820ad0052aaf68fac3eec3da8d49432d1529ec4df4fa82c1dd2847c088f2575ddb10029" - code_ContractTrcToken031_tokenTest = "608060405260a9806100126000396000f300608060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663cbf0b0c081146043575b600080fd5b606273ffffffffffffffffffffffffffffffffffffffff600435166064565b005b8073ffffffffffffffffffffffffffffffffffffffff16ff00a165627a7a72305820ad0052aaf68fac3eec3da8d49432d1529ec4df4fa82c1dd2847c088f2575ddb10029" - code_ContractTrcToken034_tokenTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101638061003a6000396000f30060806040526004361061004b5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634957baa18114610050578063e308c52714610079575b600080fd5b61007773ffffffffffffffffffffffffffffffffffffffff600435166024356044356100a0565b005b61007773ffffffffffffffffffffffffffffffffffffffff600435166024356044356100ea565b60405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc029084908490600081818185878a8ad09450505050501580156100e7573d6000803e3d6000fd5b50fe5b60405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc029084908490600081818185878a8ad0945050505050158015610131573d6000803e3d6000fd5b50600080fd00a165627a7a723058204c2d6334ac3ea724949482094951c3b7d11fea1e87b58110d562ef47ddd45c7b0029" - code_ContractTrcToken035_tokenTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101638061003a6000396000f30060806040526004361061004b5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634957baa18114610050578063e308c52714610079575b600080fd5b61007773ffffffffffffffffffffffffffffffffffffffff600435166024356044356100a0565b005b61007773ffffffffffffffffffffffffffffffffffffffff600435166024356044356100ea565b60405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc029084908490600081818185878a8ad09450505050501580156100e7573d6000803e3d6000fd5b50fe5b60405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc029084908490600081818185878a8ad0945050505050158015610131573d6000803e3d6000fd5b50600080fd00a165627a7a723058204c2d6334ac3ea724949482094951c3b7d11fea1e87b58110d562ef47ddd45c7b0029" - code_ContractTrcToken036_transferTokenWithPureTest = "60806040526101db806100136000396000f3006080604052600436106100405763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416639d9e5a388114610042575b005b34801561004e57600080fd5b50d3801561005b57600080fd5b50d2801561006857600080fd5b5061004073ffffffffffffffffffffffffffffffffffffffff600435166024356040805134815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d2815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d3815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160405173ffffffffffffffffffffffffffffffffffffffff831690d280156108fc0291d390600081818185878a8ad0945050505050158015610167573d6000803e3d6000fd5b5060405173ffffffffffffffffffffffffffffffffffffffff8316903480156108fc02916000818181858888f193505050501580156101aa573d6000803e3d6000fd5b5050505600a165627a7a7230582052825d8daae4fb444ce76f049e019c2c66d7b29584058ee7cc88a389e22f41dc0029" - code_ContractTrcToken036_transferTokenWithViewTest = "60806040526101db806100136000396000f3006080604052600436106100405763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663abecd9838114610042575b005b34801561004e57600080fd5b50d3801561005b57600080fd5b50d2801561006857600080fd5b5061004073ffffffffffffffffffffffffffffffffffffffff600435166024356040805134815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d2815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d3815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160405173ffffffffffffffffffffffffffffffffffffffff831690d280156108fc0291d390600081818185878a8ad0945050505050158015610167573d6000803e3d6000fd5b5060405173ffffffffffffffffffffffffffffffffffffffff8316903480156108fc02916000818181858888f193505050501580156101aa573d6000803e3d6000fd5b5050505600a165627a7a7230582020ddb4a20df32d91af717609926b277d218ac25965d8003ff48adf57a0f10f950029" - code_ContractTrcToken036_transferTokenWithOutPayableTest = "60806040526101db806100136000396000f3006080604052600436106100405763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416632b38e5478114610042575b005b34801561004e57600080fd5b50d3801561005b57600080fd5b50d2801561006857600080fd5b5061004073ffffffffffffffffffffffffffffffffffffffff600435166024356040805134815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d2815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d3815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160405173ffffffffffffffffffffffffffffffffffffffff831690d280156108fc0291d390600081818185878a8ad0945050505050158015610167573d6000803e3d6000fd5b5060405173ffffffffffffffffffffffffffffffffffffffff8316903480156108fc02916000818181858888f193505050501580156101aa573d6000803e3d6000fd5b5050505600a165627a7a723058203c20218af63eda8b09394f27964892ee199fa89d93e03506f9a0390dc0b9605d0029" - code_ContractTrcToken037_receiveTrc10Test = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060ba806100396000396000f300608060405260043610603e5763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663ec17fded81146040575b005b348015604b57600080fd5b50d38015605757600080fd5b50d28015606357600080fd5b50603e6004356024356044353082d18314607c57600080fd5b3382d18114608957600080fd5b5050505600a165627a7a723058205da58c4884728798dd87f6219bad7230ff56c1859ca6402bcc3f1584ca0af8080029" - code_ContractTrcToken037_tokenTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101ff8061003a6000396000f3006080604052600436106100275763ffffffff60e060020a6000350416639d01174f811461002c575b600080fd5b61004d73ffffffffffffffffffffffffffffffffffffffff6004351661004f565b005b30d39081d19073ffffffffffffffffffffffffffffffffffffffff831690d1d2821461007a57600080fd5bd2821461008657600080fd5b60405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc02908490d390600081818185878a8ad09450505050501580156100cd573d6000803e3d6000fd5b5030d3d1156100db57600080fd5b80820173ffffffffffffffffffffffffffffffffffffffff8416d3d11461010157600080fd5b8273ffffffffffffffffffffffffffffffffffffffff1660405180807f636865636b54726331302875696e743235362c747263546f6b656e2c75696e7481526020017f32353629000000000000000000000000000000000000000000000000000000008152506024019050604051809103902060e060020a9004838301d360006040518463ffffffff1660e060020a028152600401808481526020018381526020018260ff16815260200193505050506000604051808303816000875af19250505015156101ce57600080fd5b5050505600a165627a7a72305820e91d5a5eda7d9da85983cf55171fa13b3dbf99ebe851321c02831b3f74d7bafc0029" - code_ContractTrcToken038_tokenTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101b78061003a6000396000f3006080604052600436106100275763ffffffff60e060020a6000350416639d01174f811461002c575b600080fd5b61004d73ffffffffffffffffffffffffffffffffffffffff6004351661004f565b005b30d39081d19073ffffffffffffffffffffffffffffffffffffffff831690d1d2821461007a57600080fd5bd2821461008657600080fd5b60405173ffffffffffffffffffffffffffffffffffffffff84169083156108fc02908490d390600081818185878a8ad09450505050501580156100cd573d6000803e3d6000fd5b508273ffffffffffffffffffffffffffffffffffffffff1660405180807f4173736572744572726f72282900000000000000000000000000000000000000815250600d019050604051809103902060e060020a90046040518163ffffffff1660e060020a0281526004016000604051808303816000875af192505050151561015457600080fd5b30d3d1821461016257600080fd5b73ffffffffffffffffffffffffffffffffffffffff8316d3d1811461018657600080fd5b5050505600a165627a7a72305820962d49fbc330584b84b59e537e7450a5ca38cccf106466907e402f8653ab1dee0029" - code_ContractTrcToken038_BTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506094806100396000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416631966216581146040575b005b348015604b57600080fd5b50d38015605757600080fd5b50d28015606357600080fd5b50603efe00a165627a7a723058200fc1cef003f4eb28c1edc4c7b62c1012237dd9db791e8dac7a9671319ac003440029" - code_ContractTrcToken039_ProxyTest = "60806040526101bc806100136000396000f30060806040526004361061004b5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633659cfe681146100965780635c60da1b146100e0575b60005473ffffffffffffffffffffffffffffffffffffffff1680151561007057600080fd5b6040513660008237600081368185600019f43d6000833e808015610092573d83f35b3d83fd5b3480156100a257600080fd5b50d380156100af57600080fd5b50d280156100bc57600080fd5b506100de73ffffffffffffffffffffffffffffffffffffffff60043516610138565b005b3480156100ec57600080fd5b50d380156100f957600080fd5b50d2801561010657600080fd5b5061010f610174565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b6000805473ffffffffffffffffffffffffffffffffffffffff191673ffffffffffffffffffffffffffffffffffffffff92909216919091179055565b60005473ffffffffffffffffffffffffffffffffffffffff16815600a165627a7a7230582047b47a8f57880f0c2c028e44406b1868bbee2151938629caad7b65668d6a8a140029" - code_ContractTrcToken039_ATest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060de806100396000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630455012181146043575b600080fd5b606860043573ffffffffffffffffffffffffffffffffffffffff60243516604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff83169084156108fc029085906000818181858888f1935050505015801560ac573d6000803e3d6000fd5b505050505600a165627a7a72305820542cde58d75afb60ec2226b95c592a973666b56931d8ea8d7ed0d0a6bd16e7ea0029" - code_ContractTrcToken039_BTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060e2806100396000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416630455012181146043575b600080fd5b606860043573ffffffffffffffffffffffffffffffffffffffff60243516604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff83169084156108fc029085908490600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a72305820cccc1489247eb5366214a034107ebfbea955aac5229e03907a82321a1a4484240029" - code_ContractTrcToken041_transferTokenContract = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a72305820d7ac1a3b49eeff286b7f2402b93047e60deb6dba47f4f889d921dbcb3bb81f8a0029" - code_ContractTrcToken048_transferTokenContract = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5061010f8061003a6000396000f30060806040526004361060485763ffffffff7c0100000000000000000000000000000000000000000000000000000000600035041663a94b16d08114604d578063c0063993146065575b600080fd5b6053606b565b60408051918252519081900360200190f35b605360a7565b6040805134815290516000917ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c744919081900360200190a1503490565b60408051d2815290516000917ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c744919081900360200190a150d2905600a165627a7a7230582016ef7f5bc613147860a1de990c4258eaa2ca12ceb1ab21cd9069f50d1db238020029" - code_ContractTrcToken049_transferTokenContract = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a72305820d7ac1a3b49eeff286b7f2402b93047e60deb6dba47f4f889d921dbcb3bb81f8a0029" - code_ContractTrcToken050_transferTokenContract = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a72305820d7ac1a3b49eeff286b7f2402b93047e60deb6dba47f4f889d921dbcb3bb81f8a0029" - code_ContractTrcToken051_transferTokenContract = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a72305820d7ac1a3b49eeff286b7f2402b93047e60deb6dba47f4f889d921dbcb3bb81f8a0029" - code_ContractTrcToken052_transferTokenContract = "608060405260e2806100126000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633be9ece781146043575b600080fd5b606873ffffffffffffffffffffffffffffffffffffffff60043516602435604435606a565b005b60405173ffffffffffffffffffffffffffffffffffffffff84169082156108fc029083908590600081818185878a8ad094505050505015801560b0573d6000803e3d6000fd5b505050505600a165627a7a72305820d7ac1a3b49eeff286b7f2402b93047e60deb6dba47f4f889d921dbcb3bb81f8a0029" - code_ContractTrcToken036_tokenTest = "60806040526101b4806100136000396000f3006080604052600436106100405763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416632849fa4f8114610042575b005b61004073ffffffffffffffffffffffffffffffffffffffff600435166024356040805134815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d2815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160408051d3815290517ff82c50f1848136e6c140b186ea0c768b7deda5efffe42c25e96336a90b26c7449181900360200190a160405173ffffffffffffffffffffffffffffffffffffffff831690d280156108fc0291d390600081818185878a8ad0945050505050158015610140573d6000803e3d6000fd5b5060405173ffffffffffffffffffffffffffffffffffffffff8316903480156108fc02916000818181858888f19350505050158015610183573d6000803e3d6000fd5b5050505600a165627a7a72305820ddc15bf8809c92f9c6b6175f2ce1245ef1d65e5fbeccc2bb2772980cedee1eee0029" - code_ContractTrcToken076_originTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506103698061003a6000396000f3006080604052600436106100825763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166317ca5481811461008757806360d10813146100ca57806367e404ce146100f95780638be988cd14610151578063938b5f3214610159578063e8da042414610188578063f8a8fd6d14610190575b600080fd5b34801561009357600080fd5b50d380156100a057600080fd5b50d280156100ad57600080fd5b506100b66101c1565b604080519115158252519081900360200190f35b3480156100d657600080fd5b50d380156100e357600080fd5b50d280156100f057600080fd5b506100b66101e3565b34801561010557600080fd5b50d3801561011257600080fd5b50d2801561011f57600080fd5b50610128610204565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b6100b6610220565b34801561016557600080fd5b50d3801561017257600080fd5b50d2801561017f57600080fd5b50610128610241565b6100b661025d565b34801561019c57600080fd5b50d380156101a957600080fd5b50d280156101b657600080fd5b506101bf61027f565b005b6001547501000000000000000000000000000000000000000000900460ff1681565b60015474010000000000000000000000000000000000000000900460ff1681565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b60015474010000000000000000000000000000000000000000900460ff1690565b60005473ffffffffffffffffffffffffffffffffffffffff1681565b6001547501000000000000000000000000000000000000000000900460ff1690565b600080543273ffffffffffffffffffffffffffffffffffffffff199182168117928390556001805475ff0000000000000000000000000000000000000000001993163390811774ff00000000000000000000000000000000000000001916921474010000000000000000000000000000000000000000029190911791821673ffffffffffffffffffffffffffffffffffffffff92831692909316919091147501000000000000000000000000000000000000000000029190911790555600a165627a7a72305820487fd902512ac719158b1ec219e9e6648b9f47f7f0396d24044f4dca1de4a3c60029" - code_ContractTrcToken077_AddressTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060b6806100396000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416636241c1d881146043575b600080fd5b348015604e57600080fd5b50d38015605a57600080fd5b50d28015606657600080fd5b50606d607f565b60408051918252519081900360200190f35b6040513090819052905600a165627a7a723058207faa3a33e3b875c23563f2fb8ee4506affcd21d818c8399a71dd76fa973f487d0029" - code_ContractTrcToken077_AddressTest1 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506092806100396000396000f300608060405260043610603e5763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416636241c1d881146043575b600080fd5b6049605b565b60408051918252519081900360200190f35b6040513090819052905600a165627a7a723058200245dccce3c678939aba5ad813f3fd8d551ef14f01409a8e36bc3dac301113c40029" - code_ContractTrcToken078_AddressTest1 = "6080604052610264806100136000396000f30060806040526004361061003d5763ffffffff60e060020a600035041663648efe8b811461003f578063b45f578b14610059578063d818452114610073575b005b61003d600160a060020a036004358116906024351661008d565b61003d600160a060020a036004358116906024351661011c565b61003d600160a060020a03600435811690602435166101a9565b81600160a060020a031660405180807f7472616e73666572546f286164647265737329000000000000000000000000008152506013019050604051809103902060e060020a9004826040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a031681526020019150506000604051808303816000875af2505050505050565b81600160a060020a031660405180807f7472616e73666572546f286164647265737329000000000000000000000000008152506013019050604051809103902060e060020a9004826040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a03168152602001915050600060405180830381865af4505050505050565b81600160a060020a031660405180807f7472616e73666572546f286164647265737329000000000000000000000000008152506013019050604051809103902060e060020a9004826040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a031681526020019150506000604051808303816000875af15050505050505600a165627a7a7230582068a85b5cb5a41f10a7ba8250baed5adf37129ff04399bccae69e483fc85448a90029" - code_ContractTrcToken078_AddressTest2 = "6080604052610166806100136000396000f3006080604052600436106100325763ffffffff60e060020a6000350416630223024e8114610034578063a03fa7e314610055575b005b61003273ffffffffffffffffffffffffffffffffffffffff60043516610076565b61003273ffffffffffffffffffffffffffffffffffffffff600435166100f7565b8073ffffffffffffffffffffffffffffffffffffffff16600560405180807f73657449282900000000000000000000000000000000000000000000000000008152506006019050604051809103902060e060020a9004906040518263ffffffff1660e060020a02815260040160006040518083038185885af1505050505050565b60405173ffffffffffffffffffffffffffffffffffffffff82169060009060059082818181858883f19350505050158015610136573d6000803e3d6000fd5b50505600a165627a7a72305820ede28ac9884104396c5d52bbf3f480cb637f61bc331c2dc561670e6d2700ad630029" - code_ContractTrcToken078_AddressTest3 = "6080604052610172806100136000396000f30060806040526004361061004b5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166367e404ce8114610087578063938b5f32146100df575b6040805132815233602082015281517fdaf0d4aa9a5679e832ac921da67b43572b4326ee2565442d3ed255b48cfb5161929181900390910190a1005b34801561009357600080fd5b50d380156100a057600080fd5b50d280156100ad57600080fd5b506100b661010e565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b3480156100eb57600080fd5b50d380156100f857600080fd5b50d2801561010557600080fd5b506100b661012a565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b60005473ffffffffffffffffffffffffffffffffffffffff16815600a165627a7a7230582084426e82a8fde9cefb0ae9f1561ce743354adada27d217c8614c28829eecbcda0029" - code_ContractTrcToken078_AddressTest4 = "6080604052610264806100136000396000f30060806040526004361061003d5763ffffffff60e060020a600035041663648efe8b811461003f578063b45f578b14610059578063d818452114610073575b005b61003d600160a060020a036004358116906024351661008d565b61003d600160a060020a036004358116906024351661011c565b61003d600160a060020a03600435811690602435166101a9565b81600160a060020a031660405180807f7472616e73666572546f286164647265737329000000000000000000000000008152506013019050604051809103902060e060020a9004826040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a031681526020019150506000604051808303816000875af2505050505050565b81600160a060020a031660405180807f7472616e73666572546f286164647265737329000000000000000000000000008152506013019050604051809103902060e060020a9004826040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a03168152602001915050600060405180830381865af4505050505050565b81600160a060020a031660405180807f7472616e73666572546f286164647265737329000000000000000000000000008152506013019050604051809103902060e060020a9004826040518263ffffffff1660e060020a0281526004018082600160a060020a0316600160a060020a031681526020019150506000604051808303816000875af15050505050505600a165627a7a7230582068a85b5cb5a41f10a7ba8250baed5adf37129ff04399bccae69e483fc85448a90029" - code_ContractTrcToken078_AddressTest5 = "6080604052610166806100136000396000f3006080604052600436106100325763ffffffff60e060020a6000350416630223024e8114610034578063a03fa7e314610055575b005b61003273ffffffffffffffffffffffffffffffffffffffff60043516610076565b61003273ffffffffffffffffffffffffffffffffffffffff600435166100f7565b8073ffffffffffffffffffffffffffffffffffffffff16600560405180807f73657449282900000000000000000000000000000000000000000000000000008152506006019050604051809103902060e060020a9004906040518263ffffffff1660e060020a02815260040160006040518083038185885af1505050505050565b60405173ffffffffffffffffffffffffffffffffffffffff82169060009060059082818181858883f19350505050158015610136573d6000803e3d6000fd5b50505600a165627a7a72305820ede28ac9884104396c5d52bbf3f480cb637f61bc331c2dc561670e6d2700ad630029" - code_ContractTrcToken078_AddressTest6 = "6080604052610172806100136000396000f30060806040526004361061004b5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166367e404ce8114610087578063938b5f32146100df575b6040805132815233602082015281517fdaf0d4aa9a5679e832ac921da67b43572b4326ee2565442d3ed255b48cfb5161929181900390910190a1005b34801561009357600080fd5b50d380156100a057600080fd5b50d280156100ad57600080fd5b506100b661010e565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b3480156100eb57600080fd5b50d380156100f857600080fd5b50d2801561010557600080fd5b506100b661012a565b60015473ffffffffffffffffffffffffffffffffffffffff1681565b60005473ffffffffffffffffffffffffffffffffffffffff16815600a165627a7a7230582084426e82a8fde9cefb0ae9f1561ce743354adada27d217c8614c28829eecbcda0029" - code_veryLarge = "60806040523480156200001157600080fd5b50d380156200001f57600080fd5b50d280156200002d57600080fd5b5061c2ec806200003e6000396000f3fe6080604052600436106200003c577c010000000000000000000000000000000000000000000000000000000060003504631a695230811462000041575b600080fd5b62000077600480360360208110156200005957600080fd5b503573ffffffffffffffffffffffffffffffffffffffff1662000079565b005b6040516000906200008a906200c1dc565b604051809103906000f080158015620000a7573d6000803e3d6000fd5b5050604051620000b7906200c1dc565b604051809103906000f080158015620000d4573d6000803e3d6000fd5b5050604051620000e4906200c1dc565b604051809103906000f08015801562000101573d6000803e3d6000fd5b505060405162000111906200c1dc565b604051809103906000f0801580156200012e573d6000803e3d6000fd5b50506040516200013e906200c1dc565b604051809103906000f0801580156200015b573d6000803e3d6000fd5b50506040516200016b906200c1dc565b604051809103906000f08015801562000188573d6000803e3d6000fd5b505060405162000198906200c1dc565b604051809103906000f080158015620001b5573d6000803e3d6000fd5b5050604051620001c5906200c1dc565b604051809103906000f080158015620001e2573d6000803e3d6000fd5b5050604051620001f2906200c1dc565b604051809103906000f0801580156200020f573d6000803e3d6000fd5b50506040516200021f906200c1dc565b604051809103906000f0801580156200023c573d6000803e3d6000fd5b50506040516200024c906200c1dc565b604051809103906000f08015801562000269573d6000803e3d6000fd5b505060405162000279906200c1dc565b604051809103906000f08015801562000296573d6000803e3d6000fd5b5050604051620002a6906200c1dc565b604051809103906000f080158015620002c3573d6000803e3d6000fd5b5050604051620002d3906200c1dc565b604051809103906000f080158015620002f0573d6000803e3d6000fd5b505060405162000300906200c1dc565b604051809103906000f0801580156200031d573d6000803e3d6000fd5b50506040516200032d906200c1dc565b604051809103906000f0801580156200034a573d6000803e3d6000fd5b50506040516200035a906200c1dc565b604051809103906000f08015801562000377573d6000803e3d6000fd5b505060405162000387906200c1dc565b604051809103906000f080158015620003a4573d6000803e3d6000fd5b5050604051620003b4906200c1dc565b604051809103906000f080158015620003d1573d6000803e3d6000fd5b5050604051620003e1906200c1dc565b604051809103906000f080158015620003fe573d6000803e3d6000fd5b50506040516200040e906200c1dc565b604051809103906000f0801580156200042b573d6000803e3d6000fd5b50506040516200043b906200c1dc565b604051809103906000f08015801562000458573d6000803e3d6000fd5b505060405162000468906200c1dc565b604051809103906000f08015801562000485573d6000803e3d6000fd5b505060405162000495906200c1dc565b604051809103906000f080158015620004b2573d6000803e3d6000fd5b5050604051620004c2906200c1dc565b604051809103906000f080158015620004df573d6000803e3d6000fd5b5050604051620004ef906200c1dc565b604051809103906000f0801580156200050c573d6000803e3d6000fd5b50506040516200051c906200c1dc565b604051809103906000f08015801562000539573d6000803e3d6000fd5b505060405162000549906200c1dc565b604051809103906000f08015801562000566573d6000803e3d6000fd5b505060405162000576906200c1dc565b604051809103906000f08015801562000593573d6000803e3d6000fd5b5050604051620005a3906200c1dc565b604051809103906000f080158015620005c0573d6000803e3d6000fd5b5050604051620005d0906200c1dc565b604051809103906000f080158015620005ed573d6000803e3d6000fd5b5050604051620005fd906200c1dc565b604051809103906000f0801580156200061a573d6000803e3d6000fd5b50506040516200062a906200c1dc565b604051809103906000f08015801562000647573d6000803e3d6000fd5b505060405162000657906200c1dc565b604051809103906000f08015801562000674573d6000803e3d6000fd5b505060405162000684906200c1dc565b604051809103906000f080158015620006a1573d6000803e3d6000fd5b5050604051620006b1906200c1dc565b604051809103906000f080158015620006ce573d6000803e3d6000fd5b5050604051620006de906200c1dc565b604051809103906000f080158015620006fb573d6000803e3d6000fd5b50506040516200070b906200c1dc565b604051809103906000f08015801562000728573d6000803e3d6000fd5b505060405162000738906200c1dc565b604051809103906000f08015801562000755573d6000803e3d6000fd5b505060405162000765906200c1dc565b604051809103906000f08015801562000782573d6000803e3d6000fd5b505060405162000792906200c1dc565b604051809103906000f080158015620007af573d6000803e3d6000fd5b5050604051620007bf906200c1dc565b604051809103906000f080158015620007dc573d6000803e3d6000fd5b5050604051620007ec906200c1dc565b604051809103906000f08015801562000809573d6000803e3d6000fd5b505060405162000819906200c1dc565b604051809103906000f08015801562000836573d6000803e3d6000fd5b505060405162000846906200c1dc565b604051809103906000f08015801562000863573d6000803e3d6000fd5b505060405162000873906200c1dc565b604051809103906000f08015801562000890573d6000803e3d6000fd5b5050604051620008a0906200c1dc565b604051809103906000f080158015620008bd573d6000803e3d6000fd5b5050604051620008cd906200c1dc565b604051809103906000f080158015620008ea573d6000803e3d6000fd5b5050604051620008fa906200c1dc565b604051809103906000f08015801562000917573d6000803e3d6000fd5b505060405162000927906200c1dc565b604051809103906000f08015801562000944573d6000803e3d6000fd5b505060405162000954906200c1dc565b604051809103906000f08015801562000971573d6000803e3d6000fd5b505060405162000981906200c1dc565b604051809103906000f0801580156200099e573d6000803e3d6000fd5b5050604051620009ae906200c1dc565b604051809103906000f080158015620009cb573d6000803e3d6000fd5b5050604051620009db906200c1dc565b604051809103906000f080158015620009f8573d6000803e3d6000fd5b505060405162000a08906200c1dc565b604051809103906000f08015801562000a25573d6000803e3d6000fd5b505060405162000a35906200c1dc565b604051809103906000f08015801562000a52573d6000803e3d6000fd5b505060405162000a62906200c1dc565b604051809103906000f08015801562000a7f573d6000803e3d6000fd5b505060405162000a8f906200c1dc565b604051809103906000f08015801562000aac573d6000803e3d6000fd5b505060405162000abc906200c1dc565b604051809103906000f08015801562000ad9573d6000803e3d6000fd5b505060405162000ae9906200c1dc565b604051809103906000f08015801562000b06573d6000803e3d6000fd5b505060405162000b16906200c1dc565b604051809103906000f08015801562000b33573d6000803e3d6000fd5b505060405162000b43906200c1dc565b604051809103906000f08015801562000b60573d6000803e3d6000fd5b505060405162000b70906200c1dc565b604051809103906000f08015801562000b8d573d6000803e3d6000fd5b505060405162000b9d906200c1dc565b604051809103906000f08015801562000bba573d6000803e3d6000fd5b505060405162000bca906200c1dc565b604051809103906000f08015801562000be7573d6000803e3d6000fd5b505060405162000bf7906200c1dc565b604051809103906000f08015801562000c14573d6000803e3d6000fd5b505060405162000c24906200c1dc565b604051809103906000f08015801562000c41573d6000803e3d6000fd5b505060405162000c51906200c1dc565b604051809103906000f08015801562000c6e573d6000803e3d6000fd5b505060405162000c7e906200c1dc565b604051809103906000f08015801562000c9b573d6000803e3d6000fd5b505060405162000cab906200c1dc565b604051809103906000f08015801562000cc8573d6000803e3d6000fd5b505060405162000cd8906200c1dc565b604051809103906000f08015801562000cf5573d6000803e3d6000fd5b505060405162000d05906200c1dc565b604051809103906000f08015801562000d22573d6000803e3d6000fd5b505060405162000d32906200c1dc565b604051809103906000f08015801562000d4f573d6000803e3d6000fd5b505060405162000d5f906200c1dc565b604051809103906000f08015801562000d7c573d6000803e3d6000fd5b505060405162000d8c906200c1dc565b604051809103906000f08015801562000da9573d6000803e3d6000fd5b505060405162000db9906200c1dc565b604051809103906000f08015801562000dd6573d6000803e3d6000fd5b505060405162000de6906200c1dc565b604051809103906000f08015801562000e03573d6000803e3d6000fd5b505060405162000e13906200c1dc565b604051809103906000f08015801562000e30573d6000803e3d6000fd5b505060405162000e40906200c1dc565b604051809103906000f08015801562000e5d573d6000803e3d6000fd5b505060405162000e6d906200c1dc565b604051809103906000f08015801562000e8a573d6000803e3d6000fd5b505060405162000e9a906200c1dc565b604051809103906000f08015801562000eb7573d6000803e3d6000fd5b505060405162000ec7906200c1dc565b604051809103906000f08015801562000ee4573d6000803e3d6000fd5b505060405162000ef4906200c1dc565b604051809103906000f08015801562000f11573d6000803e3d6000fd5b505060405162000f21906200c1dc565b604051809103906000f08015801562000f3e573d6000803e3d6000fd5b505060405162000f4e906200c1dc565b604051809103906000f08015801562000f6b573d6000803e3d6000fd5b505060405162000f7b906200c1dc565b604051809103906000f08015801562000f98573d6000803e3d6000fd5b505060405162000fa8906200c1dc565b604051809103906000f08015801562000fc5573d6000803e3d6000fd5b505060405162000fd5906200c1dc565b604051809103906000f08015801562000ff2573d6000803e3d6000fd5b505060405162001002906200c1dc565b604051809103906000f0801580156200101f573d6000803e3d6000fd5b50506040516200102f906200c1dc565b604051809103906000f0801580156200104c573d6000803e3d6000fd5b50506040516200105c906200c1dc565b604051809103906000f08015801562001079573d6000803e3d6000fd5b505060405162001089906200c1dc565b604051809103906000f080158015620010a6573d6000803e3d6000fd5b5050604051620010b6906200c1dc565b604051809103906000f080158015620010d3573d6000803e3d6000fd5b5050604051620010e3906200c1dc565b604051809103906000f08015801562001100573d6000803e3d6000fd5b505060405162001110906200c1dc565b604051809103906000f0801580156200112d573d6000803e3d6000fd5b50506040516200113d906200c1dc565b604051809103906000f0801580156200115a573d6000803e3d6000fd5b50506040516200116a906200c1dc565b604051809103906000f08015801562001187573d6000803e3d6000fd5b505060405162001197906200c1dc565b604051809103906000f080158015620011b4573d6000803e3d6000fd5b5050604051620011c4906200c1dc565b604051809103906000f080158015620011e1573d6000803e3d6000fd5b5050604051620011f1906200c1dc565b604051809103906000f0801580156200120e573d6000803e3d6000fd5b50506040516200121e906200c1dc565b604051809103906000f0801580156200123b573d6000803e3d6000fd5b50506040516200124b906200c1dc565b604051809103906000f08015801562001268573d6000803e3d6000fd5b505060405162001278906200c1dc565b604051809103906000f08015801562001295573d6000803e3d6000fd5b5050604051620012a5906200c1dc565b604051809103906000f080158015620012c2573d6000803e3d6000fd5b5050604051620012d2906200c1dc565b604051809103906000f080158015620012ef573d6000803e3d6000fd5b5050604051620012ff906200c1dc565b604051809103906000f0801580156200131c573d6000803e3d6000fd5b50506040516200132c906200c1dc565b604051809103906000f08015801562001349573d6000803e3d6000fd5b505060405162001359906200c1dc565b604051809103906000f08015801562001376573d6000803e3d6000fd5b505060405162001386906200c1dc565b604051809103906000f080158015620013a3573d6000803e3d6000fd5b5050604051620013b3906200c1dc565b604051809103906000f080158015620013d0573d6000803e3d6000fd5b5050604051620013e0906200c1dc565b604051809103906000f080158015620013fd573d6000803e3d6000fd5b50506040516200140d906200c1dc565b604051809103906000f0801580156200142a573d6000803e3d6000fd5b50506040516200143a906200c1dc565b604051809103906000f08015801562001457573d6000803e3d6000fd5b505060405162001467906200c1dc565b604051809103906000f08015801562001484573d6000803e3d6000fd5b505060405162001494906200c1dc565b604051809103906000f080158015620014b1573d6000803e3d6000fd5b5050604051620014c1906200c1dc565b604051809103906000f080158015620014de573d6000803e3d6000fd5b5050604051620014ee906200c1dc565b604051809103906000f0801580156200150b573d6000803e3d6000fd5b50506040516200151b906200c1dc565b604051809103906000f08015801562001538573d6000803e3d6000fd5b505060405162001548906200c1dc565b604051809103906000f08015801562001565573d6000803e3d6000fd5b505060405162001575906200c1dc565b604051809103906000f08015801562001592573d6000803e3d6000fd5b5050604051620015a2906200c1dc565b604051809103906000f080158015620015bf573d6000803e3d6000fd5b5050604051620015cf906200c1dc565b604051809103906000f080158015620015ec573d6000803e3d6000fd5b5050604051620015fc906200c1dc565b604051809103906000f08015801562001619573d6000803e3d6000fd5b505060405162001629906200c1dc565b604051809103906000f08015801562001646573d6000803e3d6000fd5b505060405162001656906200c1dc565b604051809103906000f08015801562001673573d6000803e3d6000fd5b505060405162001683906200c1dc565b604051809103906000f080158015620016a0573d6000803e3d6000fd5b5050604051620016b0906200c1dc565b604051809103906000f080158015620016cd573d6000803e3d6000fd5b5050604051620016dd906200c1dc565b604051809103906000f080158015620016fa573d6000803e3d6000fd5b50506040516200170a906200c1dc565b604051809103906000f08015801562001727573d6000803e3d6000fd5b505060405162001737906200c1dc565b604051809103906000f08015801562001754573d6000803e3d6000fd5b505060405162001764906200c1dc565b604051809103906000f08015801562001781573d6000803e3d6000fd5b505060405162001791906200c1dc565b604051809103906000f080158015620017ae573d6000803e3d6000fd5b5050604051620017be906200c1dc565b604051809103906000f080158015620017db573d6000803e3d6000fd5b5050604051620017eb906200c1dc565b604051809103906000f08015801562001808573d6000803e3d6000fd5b505060405162001818906200c1dc565b604051809103906000f08015801562001835573d6000803e3d6000fd5b505060405162001845906200c1dc565b604051809103906000f08015801562001862573d6000803e3d6000fd5b505060405162001872906200c1dc565b604051809103906000f0801580156200188f573d6000803e3d6000fd5b50506040516200189f906200c1dc565b604051809103906000f080158015620018bc573d6000803e3d6000fd5b5050604051620018cc906200c1dc565b604051809103906000f080158015620018e9573d6000803e3d6000fd5b5050604051620018f9906200c1dc565b604051809103906000f08015801562001916573d6000803e3d6000fd5b505060405162001926906200c1dc565b604051809103906000f08015801562001943573d6000803e3d6000fd5b505060405162001953906200c1dc565b604051809103906000f08015801562001970573d6000803e3d6000fd5b505060405162001980906200c1dc565b604051809103906000f0801580156200199d573d6000803e3d6000fd5b5050604051620019ad906200c1dc565b604051809103906000f080158015620019ca573d6000803e3d6000fd5b5050604051620019da906200c1dc565b604051809103906000f080158015620019f7573d6000803e3d6000fd5b505060405162001a07906200c1dc565b604051809103906000f08015801562001a24573d6000803e3d6000fd5b505060405162001a34906200c1dc565b604051809103906000f08015801562001a51573d6000803e3d6000fd5b505060405162001a61906200c1dc565b604051809103906000f08015801562001a7e573d6000803e3d6000fd5b505060405162001a8e906200c1dc565b604051809103906000f08015801562001aab573d6000803e3d6000fd5b505060405162001abb906200c1dc565b604051809103906000f08015801562001ad8573d6000803e3d6000fd5b505060405162001ae8906200c1dc565b604051809103906000f08015801562001b05573d6000803e3d6000fd5b505060405162001b15906200c1dc565b604051809103906000f08015801562001b32573d6000803e3d6000fd5b505060405162001b42906200c1dc565b604051809103906000f08015801562001b5f573d6000803e3d6000fd5b505060405162001b6f906200c1dc565b604051809103906000f08015801562001b8c573d6000803e3d6000fd5b505060405162001b9c906200c1dc565b604051809103906000f08015801562001bb9573d6000803e3d6000fd5b505060405162001bc9906200c1dc565b604051809103906000f08015801562001be6573d6000803e3d6000fd5b505060405162001bf6906200c1dc565b604051809103906000f08015801562001c13573d6000803e3d6000fd5b505060405162001c23906200c1dc565b604051809103906000f08015801562001c40573d6000803e3d6000fd5b505060405162001c50906200c1dc565b604051809103906000f08015801562001c6d573d6000803e3d6000fd5b505060405162001c7d906200c1dc565b604051809103906000f08015801562001c9a573d6000803e3d6000fd5b505060405162001caa906200c1dc565b604051809103906000f08015801562001cc7573d6000803e3d6000fd5b505060405162001cd7906200c1dc565b604051809103906000f08015801562001cf4573d6000803e3d6000fd5b505060405162001d04906200c1dc565b604051809103906000f08015801562001d21573d6000803e3d6000fd5b505060405162001d31906200c1dc565b604051809103906000f08015801562001d4e573d6000803e3d6000fd5b505060405162001d5e906200c1dc565b604051809103906000f08015801562001d7b573d6000803e3d6000fd5b505060405162001d8b906200c1dc565b604051809103906000f08015801562001da8573d6000803e3d6000fd5b505060405162001db8906200c1dc565b604051809103906000f08015801562001dd5573d6000803e3d6000fd5b505060405162001de5906200c1dc565b604051809103906000f08015801562001e02573d6000803e3d6000fd5b505060405162001e12906200c1dc565b604051809103906000f08015801562001e2f573d6000803e3d6000fd5b505060405162001e3f906200c1dc565b604051809103906000f08015801562001e5c573d6000803e3d6000fd5b505060405162001e6c906200c1dc565b604051809103906000f08015801562001e89573d6000803e3d6000fd5b505060405162001e99906200c1dc565b604051809103906000f08015801562001eb6573d6000803e3d6000fd5b505060405162001ec6906200c1dc565b604051809103906000f08015801562001ee3573d6000803e3d6000fd5b505060405162001ef3906200c1dc565b604051809103906000f08015801562001f10573d6000803e3d6000fd5b505060405162001f20906200c1dc565b604051809103906000f08015801562001f3d573d6000803e3d6000fd5b505060405162001f4d906200c1dc565b604051809103906000f08015801562001f6a573d6000803e3d6000fd5b505060405162001f7a906200c1dc565b604051809103906000f08015801562001f97573d6000803e3d6000fd5b505060405162001fa7906200c1dc565b604051809103906000f08015801562001fc4573d6000803e3d6000fd5b505060405162001fd4906200c1dc565b604051809103906000f08015801562001ff1573d6000803e3d6000fd5b505060405162002001906200c1dc565b604051809103906000f0801580156200201e573d6000803e3d6000fd5b50506040516200202e906200c1dc565b604051809103906000f0801580156200204b573d6000803e3d6000fd5b50506040516200205b906200c1dc565b604051809103906000f08015801562002078573d6000803e3d6000fd5b505060405162002088906200c1dc565b604051809103906000f080158015620020a5573d6000803e3d6000fd5b5050604051620020b5906200c1dc565b604051809103906000f080158015620020d2573d6000803e3d6000fd5b5050604051620020e2906200c1dc565b604051809103906000f080158015620020ff573d6000803e3d6000fd5b50506040516200210f906200c1dc565b604051809103906000f0801580156200212c573d6000803e3d6000fd5b50506040516200213c906200c1dc565b604051809103906000f08015801562002159573d6000803e3d6000fd5b505060405162002169906200c1dc565b604051809103906000f08015801562002186573d6000803e3d6000fd5b505060405162002196906200c1dc565b604051809103906000f080158015620021b3573d6000803e3d6000fd5b5050604051620021c3906200c1dc565b604051809103906000f080158015620021e0573d6000803e3d6000fd5b5050604051620021f0906200c1dc565b604051809103906000f0801580156200220d573d6000803e3d6000fd5b50506040516200221d906200c1dc565b604051809103906000f0801580156200223a573d6000803e3d6000fd5b50506040516200224a906200c1dc565b604051809103906000f08015801562002267573d6000803e3d6000fd5b505060405162002277906200c1dc565b604051809103906000f08015801562002294573d6000803e3d6000fd5b5050604051620022a4906200c1dc565b604051809103906000f080158015620022c1573d6000803e3d6000fd5b5050604051620022d1906200c1dc565b604051809103906000f080158015620022ee573d6000803e3d6000fd5b5050604051620022fe906200c1dc565b604051809103906000f0801580156200231b573d6000803e3d6000fd5b50506040516200232b906200c1dc565b604051809103906000f08015801562002348573d6000803e3d6000fd5b505060405162002358906200c1dc565b604051809103906000f08015801562002375573d6000803e3d6000fd5b505060405162002385906200c1dc565b604051809103906000f080158015620023a2573d6000803e3d6000fd5b5050604051620023b2906200c1dc565b604051809103906000f080158015620023cf573d6000803e3d6000fd5b5050604051620023df906200c1dc565b604051809103906000f080158015620023fc573d6000803e3d6000fd5b50506040516200240c906200c1dc565b604051809103906000f08015801562002429573d6000803e3d6000fd5b505060405162002439906200c1dc565b604051809103906000f08015801562002456573d6000803e3d6000fd5b505060405162002466906200c1dc565b604051809103906000f08015801562002483573d6000803e3d6000fd5b505060405162002493906200c1dc565b604051809103906000f080158015620024b0573d6000803e3d6000fd5b5050604051620024c0906200c1dc565b604051809103906000f080158015620024dd573d6000803e3d6000fd5b5050604051620024ed906200c1dc565b604051809103906000f0801580156200250a573d6000803e3d6000fd5b50506040516200251a906200c1dc565b604051809103906000f08015801562002537573d6000803e3d6000fd5b505060405162002547906200c1dc565b604051809103906000f08015801562002564573d6000803e3d6000fd5b505060405162002574906200c1dc565b604051809103906000f08015801562002591573d6000803e3d6000fd5b5050604051620025a1906200c1dc565b604051809103906000f080158015620025be573d6000803e3d6000fd5b5050604051620025ce906200c1dc565b604051809103906000f080158015620025eb573d6000803e3d6000fd5b5050604051620025fb906200c1dc565b604051809103906000f08015801562002618573d6000803e3d6000fd5b505060405162002628906200c1dc565b604051809103906000f08015801562002645573d6000803e3d6000fd5b505060405162002655906200c1dc565b604051809103906000f08015801562002672573d6000803e3d6000fd5b505060405162002682906200c1dc565b604051809103906000f0801580156200269f573d6000803e3d6000fd5b5050604051620026af906200c1dc565b604051809103906000f080158015620026cc573d6000803e3d6000fd5b5050604051620026dc906200c1dc565b604051809103906000f080158015620026f9573d6000803e3d6000fd5b505060405162002709906200c1dc565b604051809103906000f08015801562002726573d6000803e3d6000fd5b505060405162002736906200c1dc565b604051809103906000f08015801562002753573d6000803e3d6000fd5b505060405162002763906200c1dc565b604051809103906000f08015801562002780573d6000803e3d6000fd5b505060405162002790906200c1dc565b604051809103906000f080158015620027ad573d6000803e3d6000fd5b5050604051620027bd906200c1dc565b604051809103906000f080158015620027da573d6000803e3d6000fd5b5050604051620027ea906200c1dc565b604051809103906000f08015801562002807573d6000803e3d6000fd5b505060405162002817906200c1dc565b604051809103906000f08015801562002834573d6000803e3d6000fd5b505060405162002844906200c1dc565b604051809103906000f08015801562002861573d6000803e3d6000fd5b505060405162002871906200c1dc565b604051809103906000f0801580156200288e573d6000803e3d6000fd5b50506040516200289e906200c1dc565b604051809103906000f080158015620028bb573d6000803e3d6000fd5b5050604051620028cb906200c1dc565b604051809103906000f080158015620028e8573d6000803e3d6000fd5b5050604051620028f8906200c1dc565b604051809103906000f08015801562002915573d6000803e3d6000fd5b505060405162002925906200c1dc565b604051809103906000f08015801562002942573d6000803e3d6000fd5b505060405162002952906200c1dc565b604051809103906000f0801580156200296f573d6000803e3d6000fd5b50506040516200297f906200c1dc565b604051809103906000f0801580156200299c573d6000803e3d6000fd5b5050604051620029ac906200c1dc565b604051809103906000f080158015620029c9573d6000803e3d6000fd5b5050604051620029d9906200c1dc565b604051809103906000f080158015620029f6573d6000803e3d6000fd5b505060405162002a06906200c1dc565b604051809103906000f08015801562002a23573d6000803e3d6000fd5b505060405162002a33906200c1dc565b604051809103906000f08015801562002a50573d6000803e3d6000fd5b505060405162002a60906200c1dc565b604051809103906000f08015801562002a7d573d6000803e3d6000fd5b505060405162002a8d906200c1dc565b604051809103906000f08015801562002aaa573d6000803e3d6000fd5b505060405162002aba906200c1dc565b604051809103906000f08015801562002ad7573d6000803e3d6000fd5b505060405162002ae7906200c1dc565b604051809103906000f08015801562002b04573d6000803e3d6000fd5b505060405162002b14906200c1dc565b604051809103906000f08015801562002b31573d6000803e3d6000fd5b505060405162002b41906200c1dc565b604051809103906000f08015801562002b5e573d6000803e3d6000fd5b505060405162002b6e906200c1dc565b604051809103906000f08015801562002b8b573d6000803e3d6000fd5b505060405162002b9b906200c1dc565b604051809103906000f08015801562002bb8573d6000803e3d6000fd5b505060405162002bc8906200c1dc565b604051809103906000f08015801562002be5573d6000803e3d6000fd5b505060405162002bf5906200c1dc565b604051809103906000f08015801562002c12573d6000803e3d6000fd5b505060405162002c22906200c1dc565b604051809103906000f08015801562002c3f573d6000803e3d6000fd5b505060405162002c4f906200c1dc565b604051809103906000f08015801562002c6c573d6000803e3d6000fd5b505060405162002c7c906200c1dc565b604051809103906000f08015801562002c99573d6000803e3d6000fd5b505060405162002ca9906200c1dc565b604051809103906000f08015801562002cc6573d6000803e3d6000fd5b505060405162002cd6906200c1dc565b604051809103906000f08015801562002cf3573d6000803e3d6000fd5b505060405162002d03906200c1dc565b604051809103906000f08015801562002d20573d6000803e3d6000fd5b505060405162002d30906200c1dc565b604051809103906000f08015801562002d4d573d6000803e3d6000fd5b505060405162002d5d906200c1dc565b604051809103906000f08015801562002d7a573d6000803e3d6000fd5b505060405162002d8a906200c1dc565b604051809103906000f08015801562002da7573d6000803e3d6000fd5b505060405162002db7906200c1dc565b604051809103906000f08015801562002dd4573d6000803e3d6000fd5b505060405162002de4906200c1dc565b604051809103906000f08015801562002e01573d6000803e3d6000fd5b505060405162002e11906200c1dc565b604051809103906000f08015801562002e2e573d6000803e3d6000fd5b505060405162002e3e906200c1dc565b604051809103906000f08015801562002e5b573d6000803e3d6000fd5b505060405162002e6b906200c1dc565b604051809103906000f08015801562002e88573d6000803e3d6000fd5b505060405162002e98906200c1dc565b604051809103906000f08015801562002eb5573d6000803e3d6000fd5b505060405162002ec5906200c1dc565b604051809103906000f08015801562002ee2573d6000803e3d6000fd5b505060405162002ef2906200c1dc565b604051809103906000f08015801562002f0f573d6000803e3d6000fd5b505060405162002f1f906200c1dc565b604051809103906000f08015801562002f3c573d6000803e3d6000fd5b505060405162002f4c906200c1dc565b604051809103906000f08015801562002f69573d6000803e3d6000fd5b505060405162002f79906200c1dc565b604051809103906000f08015801562002f96573d6000803e3d6000fd5b505060405162002fa6906200c1dc565b604051809103906000f08015801562002fc3573d6000803e3d6000fd5b505060405162002fd3906200c1dc565b604051809103906000f08015801562002ff0573d6000803e3d6000fd5b505060405162003000906200c1dc565b604051809103906000f0801580156200301d573d6000803e3d6000fd5b50506040516200302d906200c1dc565b604051809103906000f0801580156200304a573d6000803e3d6000fd5b50506040516200305a906200c1dc565b604051809103906000f08015801562003077573d6000803e3d6000fd5b505060405162003087906200c1dc565b604051809103906000f080158015620030a4573d6000803e3d6000fd5b5050604051620030b4906200c1dc565b604051809103906000f080158015620030d1573d6000803e3d6000fd5b5050604051620030e1906200c1dc565b604051809103906000f080158015620030fe573d6000803e3d6000fd5b50506040516200310e906200c1dc565b604051809103906000f0801580156200312b573d6000803e3d6000fd5b50506040516200313b906200c1dc565b604051809103906000f08015801562003158573d6000803e3d6000fd5b505060405162003168906200c1dc565b604051809103906000f08015801562003185573d6000803e3d6000fd5b505060405162003195906200c1dc565b604051809103906000f080158015620031b2573d6000803e3d6000fd5b5050604051620031c2906200c1dc565b604051809103906000f080158015620031df573d6000803e3d6000fd5b5050604051620031ef906200c1dc565b604051809103906000f0801580156200320c573d6000803e3d6000fd5b50506040516200321c906200c1dc565b604051809103906000f08015801562003239573d6000803e3d6000fd5b505060405162003249906200c1dc565b604051809103906000f08015801562003266573d6000803e3d6000fd5b505060405162003276906200c1dc565b604051809103906000f08015801562003293573d6000803e3d6000fd5b5050604051620032a3906200c1dc565b604051809103906000f080158015620032c0573d6000803e3d6000fd5b5050604051620032d0906200c1dc565b604051809103906000f080158015620032ed573d6000803e3d6000fd5b5050604051620032fd906200c1dc565b604051809103906000f0801580156200331a573d6000803e3d6000fd5b50506040516200332a906200c1dc565b604051809103906000f08015801562003347573d6000803e3d6000fd5b505060405162003357906200c1dc565b604051809103906000f08015801562003374573d6000803e3d6000fd5b505060405162003384906200c1dc565b604051809103906000f080158015620033a1573d6000803e3d6000fd5b5050604051620033b1906200c1dc565b604051809103906000f080158015620033ce573d6000803e3d6000fd5b5050604051620033de906200c1dc565b604051809103906000f080158015620033fb573d6000803e3d6000fd5b50506040516200340b906200c1dc565b604051809103906000f08015801562003428573d6000803e3d6000fd5b505060405162003438906200c1dc565b604051809103906000f08015801562003455573d6000803e3d6000fd5b505060405162003465906200c1dc565b604051809103906000f08015801562003482573d6000803e3d6000fd5b505060405162003492906200c1dc565b604051809103906000f080158015620034af573d6000803e3d6000fd5b5050604051620034bf906200c1dc565b604051809103906000f080158015620034dc573d6000803e3d6000fd5b5050604051620034ec906200c1dc565b604051809103906000f08015801562003509573d6000803e3d6000fd5b505060405162003519906200c1dc565b604051809103906000f08015801562003536573d6000803e3d6000fd5b505060405162003546906200c1dc565b604051809103906000f08015801562003563573d6000803e3d6000fd5b505060405162003573906200c1dc565b604051809103906000f08015801562003590573d6000803e3d6000fd5b5050604051620035a0906200c1dc565b604051809103906000f080158015620035bd573d6000803e3d6000fd5b5050604051620035cd906200c1dc565b604051809103906000f080158015620035ea573d6000803e3d6000fd5b5050604051620035fa906200c1dc565b604051809103906000f08015801562003617573d6000803e3d6000fd5b505060405162003627906200c1dc565b604051809103906000f08015801562003644573d6000803e3d6000fd5b505060405162003654906200c1dc565b604051809103906000f08015801562003671573d6000803e3d6000fd5b505060405162003681906200c1dc565b604051809103906000f0801580156200369e573d6000803e3d6000fd5b5050604051620036ae906200c1dc565b604051809103906000f080158015620036cb573d6000803e3d6000fd5b5050604051620036db906200c1dc565b604051809103906000f080158015620036f8573d6000803e3d6000fd5b505060405162003708906200c1dc565b604051809103906000f08015801562003725573d6000803e3d6000fd5b505060405162003735906200c1dc565b604051809103906000f08015801562003752573d6000803e3d6000fd5b505060405162003762906200c1dc565b604051809103906000f0801580156200377f573d6000803e3d6000fd5b50506040516200378f906200c1dc565b604051809103906000f080158015620037ac573d6000803e3d6000fd5b5050604051620037bc906200c1dc565b604051809103906000f080158015620037d9573d6000803e3d6000fd5b5050604051620037e9906200c1dc565b604051809103906000f08015801562003806573d6000803e3d6000fd5b505060405162003816906200c1dc565b604051809103906000f08015801562003833573d6000803e3d6000fd5b505060405162003843906200c1dc565b604051809103906000f08015801562003860573d6000803e3d6000fd5b505060405162003870906200c1dc565b604051809103906000f0801580156200388d573d6000803e3d6000fd5b50506040516200389d906200c1dc565b604051809103906000f080158015620038ba573d6000803e3d6000fd5b5050604051620038ca906200c1dc565b604051809103906000f080158015620038e7573d6000803e3d6000fd5b5050604051620038f7906200c1dc565b604051809103906000f08015801562003914573d6000803e3d6000fd5b505060405162003924906200c1dc565b604051809103906000f08015801562003941573d6000803e3d6000fd5b505060405162003951906200c1dc565b604051809103906000f0801580156200396e573d6000803e3d6000fd5b50506040516200397e906200c1dc565b604051809103906000f0801580156200399b573d6000803e3d6000fd5b5050604051620039ab906200c1dc565b604051809103906000f080158015620039c8573d6000803e3d6000fd5b5050604051620039d8906200c1dc565b604051809103906000f080158015620039f5573d6000803e3d6000fd5b505060405162003a05906200c1dc565b604051809103906000f08015801562003a22573d6000803e3d6000fd5b505060405162003a32906200c1dc565b604051809103906000f08015801562003a4f573d6000803e3d6000fd5b505060405162003a5f906200c1dc565b604051809103906000f08015801562003a7c573d6000803e3d6000fd5b505060405162003a8c906200c1dc565b604051809103906000f08015801562003aa9573d6000803e3d6000fd5b505060405162003ab9906200c1dc565b604051809103906000f08015801562003ad6573d6000803e3d6000fd5b505060405162003ae6906200c1dc565b604051809103906000f08015801562003b03573d6000803e3d6000fd5b505060405162003b13906200c1dc565b604051809103906000f08015801562003b30573d6000803e3d6000fd5b505060405162003b40906200c1dc565b604051809103906000f08015801562003b5d573d6000803e3d6000fd5b505060405162003b6d906200c1dc565b604051809103906000f08015801562003b8a573d6000803e3d6000fd5b505060405162003b9a906200c1dc565b604051809103906000f08015801562003bb7573d6000803e3d6000fd5b505060405162003bc7906200c1dc565b604051809103906000f08015801562003be4573d6000803e3d6000fd5b505060405162003bf4906200c1dc565b604051809103906000f08015801562003c11573d6000803e3d6000fd5b505060405162003c21906200c1dc565b604051809103906000f08015801562003c3e573d6000803e3d6000fd5b505060405162003c4e906200c1dc565b604051809103906000f08015801562003c6b573d6000803e3d6000fd5b505060405162003c7b906200c1dc565b604051809103906000f08015801562003c98573d6000803e3d6000fd5b505060405162003ca8906200c1dc565b604051809103906000f08015801562003cc5573d6000803e3d6000fd5b505060405162003cd5906200c1dc565b604051809103906000f08015801562003cf2573d6000803e3d6000fd5b505060405162003d02906200c1dc565b604051809103906000f08015801562003d1f573d6000803e3d6000fd5b505060405162003d2f906200c1dc565b604051809103906000f08015801562003d4c573d6000803e3d6000fd5b505060405162003d5c906200c1dc565b604051809103906000f08015801562003d79573d6000803e3d6000fd5b505060405162003d89906200c1dc565b604051809103906000f08015801562003da6573d6000803e3d6000fd5b505060405162003db6906200c1dc565b604051809103906000f08015801562003dd3573d6000803e3d6000fd5b505060405162003de3906200c1dc565b604051809103906000f08015801562003e00573d6000803e3d6000fd5b505060405162003e10906200c1dc565b604051809103906000f08015801562003e2d573d6000803e3d6000fd5b505060405162003e3d906200c1dc565b604051809103906000f08015801562003e5a573d6000803e3d6000fd5b505060405162003e6a906200c1dc565b604051809103906000f08015801562003e87573d6000803e3d6000fd5b505060405162003e97906200c1dc565b604051809103906000f08015801562003eb4573d6000803e3d6000fd5b505060405162003ec4906200c1dc565b604051809103906000f08015801562003ee1573d6000803e3d6000fd5b505060405162003ef1906200c1dc565b604051809103906000f08015801562003f0e573d6000803e3d6000fd5b505060405162003f1e906200c1dc565b604051809103906000f08015801562003f3b573d6000803e3d6000fd5b505060405162003f4b906200c1dc565b604051809103906000f08015801562003f68573d6000803e3d6000fd5b505060405162003f78906200c1dc565b604051809103906000f08015801562003f95573d6000803e3d6000fd5b505060405162003fa5906200c1dc565b604051809103906000f08015801562003fc2573d6000803e3d6000fd5b505060405162003fd2906200c1dc565b604051809103906000f08015801562003fef573d6000803e3d6000fd5b505060405162003fff906200c1dc565b604051809103906000f0801580156200401c573d6000803e3d6000fd5b50506040516200402c906200c1dc565b604051809103906000f08015801562004049573d6000803e3d6000fd5b505060405162004059906200c1dc565b604051809103906000f08015801562004076573d6000803e3d6000fd5b505060405162004086906200c1dc565b604051809103906000f080158015620040a3573d6000803e3d6000fd5b5050604051620040b3906200c1dc565b604051809103906000f080158015620040d0573d6000803e3d6000fd5b5050604051620040e0906200c1dc565b604051809103906000f080158015620040fd573d6000803e3d6000fd5b50506040516200410d906200c1dc565b604051809103906000f0801580156200412a573d6000803e3d6000fd5b50506040516200413a906200c1dc565b604051809103906000f08015801562004157573d6000803e3d6000fd5b505060405162004167906200c1dc565b604051809103906000f08015801562004184573d6000803e3d6000fd5b505060405162004194906200c1dc565b604051809103906000f080158015620041b1573d6000803e3d6000fd5b5050604051620041c1906200c1dc565b604051809103906000f080158015620041de573d6000803e3d6000fd5b5050604051620041ee906200c1dc565b604051809103906000f0801580156200420b573d6000803e3d6000fd5b50506040516200421b906200c1dc565b604051809103906000f08015801562004238573d6000803e3d6000fd5b505060405162004248906200c1dc565b604051809103906000f08015801562004265573d6000803e3d6000fd5b505060405162004275906200c1dc565b604051809103906000f08015801562004292573d6000803e3d6000fd5b5050604051620042a2906200c1dc565b604051809103906000f080158015620042bf573d6000803e3d6000fd5b5050604051620042cf906200c1dc565b604051809103906000f080158015620042ec573d6000803e3d6000fd5b5050604051620042fc906200c1dc565b604051809103906000f08015801562004319573d6000803e3d6000fd5b505060405162004329906200c1dc565b604051809103906000f08015801562004346573d6000803e3d6000fd5b505060405162004356906200c1dc565b604051809103906000f08015801562004373573d6000803e3d6000fd5b505060405162004383906200c1dc565b604051809103906000f080158015620043a0573d6000803e3d6000fd5b5050604051620043b0906200c1dc565b604051809103906000f080158015620043cd573d6000803e3d6000fd5b5050604051620043dd906200c1dc565b604051809103906000f080158015620043fa573d6000803e3d6000fd5b50506040516200440a906200c1dc565b604051809103906000f08015801562004427573d6000803e3d6000fd5b505060405162004437906200c1dc565b604051809103906000f08015801562004454573d6000803e3d6000fd5b505060405162004464906200c1dc565b604051809103906000f08015801562004481573d6000803e3d6000fd5b505060405162004491906200c1dc565b604051809103906000f080158015620044ae573d6000803e3d6000fd5b5050604051620044be906200c1dc565b604051809103906000f080158015620044db573d6000803e3d6000fd5b5050604051620044eb906200c1dc565b604051809103906000f08015801562004508573d6000803e3d6000fd5b505060405162004518906200c1dc565b604051809103906000f08015801562004535573d6000803e3d6000fd5b505060405162004545906200c1dc565b604051809103906000f08015801562004562573d6000803e3d6000fd5b505060405162004572906200c1dc565b604051809103906000f0801580156200458f573d6000803e3d6000fd5b50506040516200459f906200c1dc565b604051809103906000f080158015620045bc573d6000803e3d6000fd5b5050604051620045cc906200c1dc565b604051809103906000f080158015620045e9573d6000803e3d6000fd5b5050604051620045f9906200c1dc565b604051809103906000f08015801562004616573d6000803e3d6000fd5b505060405162004626906200c1dc565b604051809103906000f08015801562004643573d6000803e3d6000fd5b505060405162004653906200c1dc565b604051809103906000f08015801562004670573d6000803e3d6000fd5b505060405162004680906200c1dc565b604051809103906000f0801580156200469d573d6000803e3d6000fd5b5050604051620046ad906200c1dc565b604051809103906000f080158015620046ca573d6000803e3d6000fd5b5050604051620046da906200c1dc565b604051809103906000f080158015620046f7573d6000803e3d6000fd5b505060405162004707906200c1dc565b604051809103906000f08015801562004724573d6000803e3d6000fd5b505060405162004734906200c1dc565b604051809103906000f08015801562004751573d6000803e3d6000fd5b505060405162004761906200c1dc565b604051809103906000f0801580156200477e573d6000803e3d6000fd5b50506040516200478e906200c1dc565b604051809103906000f080158015620047ab573d6000803e3d6000fd5b5050604051620047bb906200c1dc565b604051809103906000f080158015620047d8573d6000803e3d6000fd5b5050604051620047e8906200c1dc565b604051809103906000f08015801562004805573d6000803e3d6000fd5b505060405162004815906200c1dc565b604051809103906000f08015801562004832573d6000803e3d6000fd5b505060405162004842906200c1dc565b604051809103906000f0801580156200485f573d6000803e3d6000fd5b50506040516200486f906200c1dc565b604051809103906000f0801580156200488c573d6000803e3d6000fd5b50506040516200489c906200c1dc565b604051809103906000f080158015620048b9573d6000803e3d6000fd5b5050604051620048c9906200c1dc565b604051809103906000f080158015620048e6573d6000803e3d6000fd5b5050604051620048f6906200c1dc565b604051809103906000f08015801562004913573d6000803e3d6000fd5b505060405162004923906200c1dc565b604051809103906000f08015801562004940573d6000803e3d6000fd5b505060405162004950906200c1dc565b604051809103906000f0801580156200496d573d6000803e3d6000fd5b50506040516200497d906200c1dc565b604051809103906000f0801580156200499a573d6000803e3d6000fd5b5050604051620049aa906200c1dc565b604051809103906000f080158015620049c7573d6000803e3d6000fd5b5050604051620049d7906200c1dc565b604051809103906000f080158015620049f4573d6000803e3d6000fd5b505060405162004a04906200c1dc565b604051809103906000f08015801562004a21573d6000803e3d6000fd5b505060405162004a31906200c1dc565b604051809103906000f08015801562004a4e573d6000803e3d6000fd5b505060405162004a5e906200c1dc565b604051809103906000f08015801562004a7b573d6000803e3d6000fd5b505060405162004a8b906200c1dc565b604051809103906000f08015801562004aa8573d6000803e3d6000fd5b505060405162004ab8906200c1dc565b604051809103906000f08015801562004ad5573d6000803e3d6000fd5b505060405162004ae5906200c1dc565b604051809103906000f08015801562004b02573d6000803e3d6000fd5b505060405162004b12906200c1dc565b604051809103906000f08015801562004b2f573d6000803e3d6000fd5b505060405162004b3f906200c1dc565b604051809103906000f08015801562004b5c573d6000803e3d6000fd5b505060405162004b6c906200c1dc565b604051809103906000f08015801562004b89573d6000803e3d6000fd5b505060405162004b99906200c1dc565b604051809103906000f08015801562004bb6573d6000803e3d6000fd5b505060405162004bc6906200c1dc565b604051809103906000f08015801562004be3573d6000803e3d6000fd5b505060405162004bf3906200c1dc565b604051809103906000f08015801562004c10573d6000803e3d6000fd5b505060405162004c20906200c1dc565b604051809103906000f08015801562004c3d573d6000803e3d6000fd5b505060405162004c4d906200c1dc565b604051809103906000f08015801562004c6a573d6000803e3d6000fd5b505060405162004c7a906200c1dc565b604051809103906000f08015801562004c97573d6000803e3d6000fd5b505060405162004ca7906200c1dc565b604051809103906000f08015801562004cc4573d6000803e3d6000fd5b505060405162004cd4906200c1dc565b604051809103906000f08015801562004cf1573d6000803e3d6000fd5b505060405162004d01906200c1dc565b604051809103906000f08015801562004d1e573d6000803e3d6000fd5b505060405162004d2e906200c1dc565b604051809103906000f08015801562004d4b573d6000803e3d6000fd5b505060405162004d5b906200c1dc565b604051809103906000f08015801562004d78573d6000803e3d6000fd5b505060405162004d88906200c1dc565b604051809103906000f08015801562004da5573d6000803e3d6000fd5b505060405162004db5906200c1dc565b604051809103906000f08015801562004dd2573d6000803e3d6000fd5b505060405162004de2906200c1dc565b604051809103906000f08015801562004dff573d6000803e3d6000fd5b505060405162004e0f906200c1dc565b604051809103906000f08015801562004e2c573d6000803e3d6000fd5b505060405162004e3c906200c1dc565b604051809103906000f08015801562004e59573d6000803e3d6000fd5b505060405162004e69906200c1dc565b604051809103906000f08015801562004e86573d6000803e3d6000fd5b505060405162004e96906200c1dc565b604051809103906000f08015801562004eb3573d6000803e3d6000fd5b505060405162004ec3906200c1dc565b604051809103906000f08015801562004ee0573d6000803e3d6000fd5b505060405162004ef0906200c1dc565b604051809103906000f08015801562004f0d573d6000803e3d6000fd5b505060405162004f1d906200c1dc565b604051809103906000f08015801562004f3a573d6000803e3d6000fd5b505060405162004f4a906200c1dc565b604051809103906000f08015801562004f67573d6000803e3d6000fd5b505060405162004f77906200c1dc565b604051809103906000f08015801562004f94573d6000803e3d6000fd5b505060405162004fa4906200c1dc565b604051809103906000f08015801562004fc1573d6000803e3d6000fd5b505060405162004fd1906200c1dc565b604051809103906000f08015801562004fee573d6000803e3d6000fd5b505060405162004ffe906200c1dc565b604051809103906000f0801580156200501b573d6000803e3d6000fd5b50506040516200502b906200c1dc565b604051809103906000f08015801562005048573d6000803e3d6000fd5b505060405162005058906200c1dc565b604051809103906000f08015801562005075573d6000803e3d6000fd5b505060405162005085906200c1dc565b604051809103906000f080158015620050a2573d6000803e3d6000fd5b5050604051620050b2906200c1dc565b604051809103906000f080158015620050cf573d6000803e3d6000fd5b5050604051620050df906200c1dc565b604051809103906000f080158015620050fc573d6000803e3d6000fd5b50506040516200510c906200c1dc565b604051809103906000f08015801562005129573d6000803e3d6000fd5b505060405162005139906200c1dc565b604051809103906000f08015801562005156573d6000803e3d6000fd5b505060405162005166906200c1dc565b604051809103906000f08015801562005183573d6000803e3d6000fd5b505060405162005193906200c1dc565b604051809103906000f080158015620051b0573d6000803e3d6000fd5b5050604051620051c0906200c1dc565b604051809103906000f080158015620051dd573d6000803e3d6000fd5b5050604051620051ed906200c1dc565b604051809103906000f0801580156200520a573d6000803e3d6000fd5b50506040516200521a906200c1dc565b604051809103906000f08015801562005237573d6000803e3d6000fd5b505060405162005247906200c1dc565b604051809103906000f08015801562005264573d6000803e3d6000fd5b505060405162005274906200c1dc565b604051809103906000f08015801562005291573d6000803e3d6000fd5b5050604051620052a1906200c1dc565b604051809103906000f080158015620052be573d6000803e3d6000fd5b5050604051620052ce906200c1dc565b604051809103906000f080158015620052eb573d6000803e3d6000fd5b5050604051620052fb906200c1dc565b604051809103906000f08015801562005318573d6000803e3d6000fd5b505060405162005328906200c1dc565b604051809103906000f08015801562005345573d6000803e3d6000fd5b505060405162005355906200c1dc565b604051809103906000f08015801562005372573d6000803e3d6000fd5b505060405162005382906200c1dc565b604051809103906000f0801580156200539f573d6000803e3d6000fd5b5050604051620053af906200c1dc565b604051809103906000f080158015620053cc573d6000803e3d6000fd5b5050604051620053dc906200c1dc565b604051809103906000f080158015620053f9573d6000803e3d6000fd5b505060405162005409906200c1dc565b604051809103906000f08015801562005426573d6000803e3d6000fd5b505060405162005436906200c1dc565b604051809103906000f08015801562005453573d6000803e3d6000fd5b505060405162005463906200c1dc565b604051809103906000f08015801562005480573d6000803e3d6000fd5b505060405162005490906200c1dc565b604051809103906000f080158015620054ad573d6000803e3d6000fd5b5050604051620054bd906200c1dc565b604051809103906000f080158015620054da573d6000803e3d6000fd5b5050604051620054ea906200c1dc565b604051809103906000f08015801562005507573d6000803e3d6000fd5b505060405162005517906200c1dc565b604051809103906000f08015801562005534573d6000803e3d6000fd5b505060405162005544906200c1dc565b604051809103906000f08015801562005561573d6000803e3d6000fd5b505060405162005571906200c1dc565b604051809103906000f0801580156200558e573d6000803e3d6000fd5b50506040516200559e906200c1dc565b604051809103906000f080158015620055bb573d6000803e3d6000fd5b5050604051620055cb906200c1dc565b604051809103906000f080158015620055e8573d6000803e3d6000fd5b5050604051620055f8906200c1dc565b604051809103906000f08015801562005615573d6000803e3d6000fd5b505060405162005625906200c1dc565b604051809103906000f08015801562005642573d6000803e3d6000fd5b505060405162005652906200c1dc565b604051809103906000f0801580156200566f573d6000803e3d6000fd5b50506040516200567f906200c1dc565b604051809103906000f0801580156200569c573d6000803e3d6000fd5b5050604051620056ac906200c1dc565b604051809103906000f080158015620056c9573d6000803e3d6000fd5b5050604051620056d9906200c1dc565b604051809103906000f080158015620056f6573d6000803e3d6000fd5b505060405162005706906200c1dc565b604051809103906000f08015801562005723573d6000803e3d6000fd5b505060405162005733906200c1dc565b604051809103906000f08015801562005750573d6000803e3d6000fd5b505060405162005760906200c1dc565b604051809103906000f0801580156200577d573d6000803e3d6000fd5b50506040516200578d906200c1dc565b604051809103906000f080158015620057aa573d6000803e3d6000fd5b5050604051620057ba906200c1dc565b604051809103906000f080158015620057d7573d6000803e3d6000fd5b5050604051620057e7906200c1dc565b604051809103906000f08015801562005804573d6000803e3d6000fd5b505060405162005814906200c1dc565b604051809103906000f08015801562005831573d6000803e3d6000fd5b505060405162005841906200c1dc565b604051809103906000f0801580156200585e573d6000803e3d6000fd5b50506040516200586e906200c1dc565b604051809103906000f0801580156200588b573d6000803e3d6000fd5b50506040516200589b906200c1dc565b604051809103906000f080158015620058b8573d6000803e3d6000fd5b5050604051620058c8906200c1dc565b604051809103906000f080158015620058e5573d6000803e3d6000fd5b5050604051620058f5906200c1dc565b604051809103906000f08015801562005912573d6000803e3d6000fd5b505060405162005922906200c1dc565b604051809103906000f0801580156200593f573d6000803e3d6000fd5b50506040516200594f906200c1dc565b604051809103906000f0801580156200596c573d6000803e3d6000fd5b50506040516200597c906200c1dc565b604051809103906000f08015801562005999573d6000803e3d6000fd5b5050604051620059a9906200c1dc565b604051809103906000f080158015620059c6573d6000803e3d6000fd5b5050604051620059d6906200c1dc565b604051809103906000f080158015620059f3573d6000803e3d6000fd5b505060405162005a03906200c1dc565b604051809103906000f08015801562005a20573d6000803e3d6000fd5b505060405162005a30906200c1dc565b604051809103906000f08015801562005a4d573d6000803e3d6000fd5b505060405162005a5d906200c1dc565b604051809103906000f08015801562005a7a573d6000803e3d6000fd5b505060405162005a8a906200c1dc565b604051809103906000f08015801562005aa7573d6000803e3d6000fd5b505060405162005ab7906200c1dc565b604051809103906000f08015801562005ad4573d6000803e3d6000fd5b505060405162005ae4906200c1dc565b604051809103906000f08015801562005b01573d6000803e3d6000fd5b505060405162005b11906200c1dc565b604051809103906000f08015801562005b2e573d6000803e3d6000fd5b505060405162005b3e906200c1dc565b604051809103906000f08015801562005b5b573d6000803e3d6000fd5b505060405162005b6b906200c1dc565b604051809103906000f08015801562005b88573d6000803e3d6000fd5b505060405162005b98906200c1dc565b604051809103906000f08015801562005bb5573d6000803e3d6000fd5b505060405162005bc5906200c1dc565b604051809103906000f08015801562005be2573d6000803e3d6000fd5b505060405162005bf2906200c1dc565b604051809103906000f08015801562005c0f573d6000803e3d6000fd5b505060405162005c1f906200c1dc565b604051809103906000f08015801562005c3c573d6000803e3d6000fd5b505060405162005c4c906200c1dc565b604051809103906000f08015801562005c69573d6000803e3d6000fd5b505060405162005c79906200c1dc565b604051809103906000f08015801562005c96573d6000803e3d6000fd5b505060405162005ca6906200c1dc565b604051809103906000f08015801562005cc3573d6000803e3d6000fd5b505060405162005cd3906200c1dc565b604051809103906000f08015801562005cf0573d6000803e3d6000fd5b505060405162005d00906200c1dc565b604051809103906000f08015801562005d1d573d6000803e3d6000fd5b505060405162005d2d906200c1dc565b604051809103906000f08015801562005d4a573d6000803e3d6000fd5b505060405162005d5a906200c1dc565b604051809103906000f08015801562005d77573d6000803e3d6000fd5b505060405162005d87906200c1dc565b604051809103906000f08015801562005da4573d6000803e3d6000fd5b505060405162005db4906200c1dc565b604051809103906000f08015801562005dd1573d6000803e3d6000fd5b505060405162005de1906200c1dc565b604051809103906000f08015801562005dfe573d6000803e3d6000fd5b505060405162005e0e906200c1dc565b604051809103906000f08015801562005e2b573d6000803e3d6000fd5b505060405162005e3b906200c1dc565b604051809103906000f08015801562005e58573d6000803e3d6000fd5b505060405162005e68906200c1dc565b604051809103906000f08015801562005e85573d6000803e3d6000fd5b505060405162005e95906200c1dc565b604051809103906000f08015801562005eb2573d6000803e3d6000fd5b505060405162005ec2906200c1dc565b604051809103906000f08015801562005edf573d6000803e3d6000fd5b505060405162005eef906200c1dc565b604051809103906000f08015801562005f0c573d6000803e3d6000fd5b505060405162005f1c906200c1dc565b604051809103906000f08015801562005f39573d6000803e3d6000fd5b505060405162005f49906200c1dc565b604051809103906000f08015801562005f66573d6000803e3d6000fd5b505060405162005f76906200c1dc565b604051809103906000f08015801562005f93573d6000803e3d6000fd5b505060405162005fa3906200c1dc565b604051809103906000f08015801562005fc0573d6000803e3d6000fd5b505060405162005fd0906200c1dc565b604051809103906000f08015801562005fed573d6000803e3d6000fd5b505060405162005ffd906200c1dc565b604051809103906000f0801580156200601a573d6000803e3d6000fd5b50506040516200602a906200c1dc565b604051809103906000f08015801562006047573d6000803e3d6000fd5b505060405162006057906200c1dc565b604051809103906000f08015801562006074573d6000803e3d6000fd5b505060405162006084906200c1dc565b604051809103906000f080158015620060a1573d6000803e3d6000fd5b5050604051620060b1906200c1dc565b604051809103906000f080158015620060ce573d6000803e3d6000fd5b5050604051620060de906200c1dc565b604051809103906000f080158015620060fb573d6000803e3d6000fd5b50506040516200610b906200c1dc565b604051809103906000f08015801562006128573d6000803e3d6000fd5b505060405162006138906200c1dc565b604051809103906000f08015801562006155573d6000803e3d6000fd5b505060405162006165906200c1dc565b604051809103906000f08015801562006182573d6000803e3d6000fd5b505060405162006192906200c1dc565b604051809103906000f080158015620061af573d6000803e3d6000fd5b5050604051620061bf906200c1dc565b604051809103906000f080158015620061dc573d6000803e3d6000fd5b5050604051620061ec906200c1dc565b604051809103906000f08015801562006209573d6000803e3d6000fd5b505060405162006219906200c1dc565b604051809103906000f08015801562006236573d6000803e3d6000fd5b505060405162006246906200c1dc565b604051809103906000f08015801562006263573d6000803e3d6000fd5b505060405162006273906200c1dc565b604051809103906000f08015801562006290573d6000803e3d6000fd5b5050604051620062a0906200c1dc565b604051809103906000f080158015620062bd573d6000803e3d6000fd5b5050604051620062cd906200c1dc565b604051809103906000f080158015620062ea573d6000803e3d6000fd5b5050604051620062fa906200c1dc565b604051809103906000f08015801562006317573d6000803e3d6000fd5b505060405162006327906200c1dc565b604051809103906000f08015801562006344573d6000803e3d6000fd5b505060405162006354906200c1dc565b604051809103906000f08015801562006371573d6000803e3d6000fd5b505060405162006381906200c1dc565b604051809103906000f0801580156200639e573d6000803e3d6000fd5b5050604051620063ae906200c1dc565b604051809103906000f080158015620063cb573d6000803e3d6000fd5b5050604051620063db906200c1dc565b604051809103906000f080158015620063f8573d6000803e3d6000fd5b505060405162006408906200c1dc565b604051809103906000f08015801562006425573d6000803e3d6000fd5b505060405162006435906200c1dc565b604051809103906000f08015801562006452573d6000803e3d6000fd5b505060405162006462906200c1dc565b604051809103906000f0801580156200647f573d6000803e3d6000fd5b50506040516200648f906200c1dc565b604051809103906000f080158015620064ac573d6000803e3d6000fd5b5050604051620064bc906200c1dc565b604051809103906000f080158015620064d9573d6000803e3d6000fd5b5050604051620064e9906200c1dc565b604051809103906000f08015801562006506573d6000803e3d6000fd5b505060405162006516906200c1dc565b604051809103906000f08015801562006533573d6000803e3d6000fd5b505060405162006543906200c1dc565b604051809103906000f08015801562006560573d6000803e3d6000fd5b505060405162006570906200c1dc565b604051809103906000f0801580156200658d573d6000803e3d6000fd5b50506040516200659d906200c1dc565b604051809103906000f080158015620065ba573d6000803e3d6000fd5b5050604051620065ca906200c1dc565b604051809103906000f080158015620065e7573d6000803e3d6000fd5b5050604051620065f7906200c1dc565b604051809103906000f08015801562006614573d6000803e3d6000fd5b505060405162006624906200c1dc565b604051809103906000f08015801562006641573d6000803e3d6000fd5b505060405162006651906200c1dc565b604051809103906000f0801580156200666e573d6000803e3d6000fd5b50506040516200667e906200c1dc565b604051809103906000f0801580156200669b573d6000803e3d6000fd5b5050604051620066ab906200c1dc565b604051809103906000f080158015620066c8573d6000803e3d6000fd5b5050604051620066d8906200c1dc565b604051809103906000f080158015620066f5573d6000803e3d6000fd5b505060405162006705906200c1dc565b604051809103906000f08015801562006722573d6000803e3d6000fd5b505060405162006732906200c1dc565b604051809103906000f0801580156200674f573d6000803e3d6000fd5b50506040516200675f906200c1dc565b604051809103906000f0801580156200677c573d6000803e3d6000fd5b50506040516200678c906200c1dc565b604051809103906000f080158015620067a9573d6000803e3d6000fd5b5050604051620067b9906200c1dc565b604051809103906000f080158015620067d6573d6000803e3d6000fd5b5050604051620067e6906200c1dc565b604051809103906000f08015801562006803573d6000803e3d6000fd5b505060405162006813906200c1dc565b604051809103906000f08015801562006830573d6000803e3d6000fd5b505060405162006840906200c1dc565b604051809103906000f0801580156200685d573d6000803e3d6000fd5b50506040516200686d906200c1dc565b604051809103906000f0801580156200688a573d6000803e3d6000fd5b50506040516200689a906200c1dc565b604051809103906000f080158015620068b7573d6000803e3d6000fd5b5050604051620068c7906200c1dc565b604051809103906000f080158015620068e4573d6000803e3d6000fd5b5050604051620068f4906200c1dc565b604051809103906000f08015801562006911573d6000803e3d6000fd5b505060405162006921906200c1dc565b604051809103906000f0801580156200693e573d6000803e3d6000fd5b50506040516200694e906200c1dc565b604051809103906000f0801580156200696b573d6000803e3d6000fd5b50506040516200697b906200c1dc565b604051809103906000f08015801562006998573d6000803e3d6000fd5b5050604051620069a8906200c1dc565b604051809103906000f080158015620069c5573d6000803e3d6000fd5b5050604051620069d5906200c1dc565b604051809103906000f080158015620069f2573d6000803e3d6000fd5b505060405162006a02906200c1dc565b604051809103906000f08015801562006a1f573d6000803e3d6000fd5b505060405162006a2f906200c1dc565b604051809103906000f08015801562006a4c573d6000803e3d6000fd5b505060405162006a5c906200c1dc565b604051809103906000f08015801562006a79573d6000803e3d6000fd5b505060405162006a89906200c1dc565b604051809103906000f08015801562006aa6573d6000803e3d6000fd5b505060405162006ab6906200c1dc565b604051809103906000f08015801562006ad3573d6000803e3d6000fd5b505060405162006ae3906200c1dc565b604051809103906000f08015801562006b00573d6000803e3d6000fd5b505060405162006b10906200c1dc565b604051809103906000f08015801562006b2d573d6000803e3d6000fd5b505060405162006b3d906200c1dc565b604051809103906000f08015801562006b5a573d6000803e3d6000fd5b505060405162006b6a906200c1dc565b604051809103906000f08015801562006b87573d6000803e3d6000fd5b505060405162006b97906200c1dc565b604051809103906000f08015801562006bb4573d6000803e3d6000fd5b505060405162006bc4906200c1dc565b604051809103906000f08015801562006be1573d6000803e3d6000fd5b505060405162006bf1906200c1dc565b604051809103906000f08015801562006c0e573d6000803e3d6000fd5b505060405162006c1e906200c1dc565b604051809103906000f08015801562006c3b573d6000803e3d6000fd5b505060405162006c4b906200c1dc565b604051809103906000f08015801562006c68573d6000803e3d6000fd5b505060405162006c78906200c1dc565b604051809103906000f08015801562006c95573d6000803e3d6000fd5b505060405162006ca5906200c1dc565b604051809103906000f08015801562006cc2573d6000803e3d6000fd5b505060405162006cd2906200c1dc565b604051809103906000f08015801562006cef573d6000803e3d6000fd5b505060405162006cff906200c1dc565b604051809103906000f08015801562006d1c573d6000803e3d6000fd5b505060405162006d2c906200c1dc565b604051809103906000f08015801562006d49573d6000803e3d6000fd5b505060405162006d59906200c1dc565b604051809103906000f08015801562006d76573d6000803e3d6000fd5b505060405162006d86906200c1dc565b604051809103906000f08015801562006da3573d6000803e3d6000fd5b505060405162006db3906200c1dc565b604051809103906000f08015801562006dd0573d6000803e3d6000fd5b505060405162006de0906200c1dc565b604051809103906000f08015801562006dfd573d6000803e3d6000fd5b505060405162006e0d906200c1dc565b604051809103906000f08015801562006e2a573d6000803e3d6000fd5b505060405162006e3a906200c1dc565b604051809103906000f08015801562006e57573d6000803e3d6000fd5b505060405162006e67906200c1dc565b604051809103906000f08015801562006e84573d6000803e3d6000fd5b505060405162006e94906200c1dc565b604051809103906000f08015801562006eb1573d6000803e3d6000fd5b505060405162006ec1906200c1dc565b604051809103906000f08015801562006ede573d6000803e3d6000fd5b505060405162006eee906200c1dc565b604051809103906000f08015801562006f0b573d6000803e3d6000fd5b505060405162006f1b906200c1dc565b604051809103906000f08015801562006f38573d6000803e3d6000fd5b505060405162006f48906200c1dc565b604051809103906000f08015801562006f65573d6000803e3d6000fd5b505060405162006f75906200c1dc565b604051809103906000f08015801562006f92573d6000803e3d6000fd5b505060405162006fa2906200c1dc565b604051809103906000f08015801562006fbf573d6000803e3d6000fd5b505060405162006fcf906200c1dc565b604051809103906000f08015801562006fec573d6000803e3d6000fd5b505060405162006ffc906200c1dc565b604051809103906000f08015801562007019573d6000803e3d6000fd5b505060405162007029906200c1dc565b604051809103906000f08015801562007046573d6000803e3d6000fd5b505060405162007056906200c1dc565b604051809103906000f08015801562007073573d6000803e3d6000fd5b505060405162007083906200c1dc565b604051809103906000f080158015620070a0573d6000803e3d6000fd5b5050604051620070b0906200c1dc565b604051809103906000f080158015620070cd573d6000803e3d6000fd5b5050604051620070dd906200c1dc565b604051809103906000f080158015620070fa573d6000803e3d6000fd5b50506040516200710a906200c1dc565b604051809103906000f08015801562007127573d6000803e3d6000fd5b505060405162007137906200c1dc565b604051809103906000f08015801562007154573d6000803e3d6000fd5b505060405162007164906200c1dc565b604051809103906000f08015801562007181573d6000803e3d6000fd5b505060405162007191906200c1dc565b604051809103906000f080158015620071ae573d6000803e3d6000fd5b5050604051620071be906200c1dc565b604051809103906000f080158015620071db573d6000803e3d6000fd5b5050604051620071eb906200c1dc565b604051809103906000f08015801562007208573d6000803e3d6000fd5b505060405162007218906200c1dc565b604051809103906000f08015801562007235573d6000803e3d6000fd5b505060405162007245906200c1dc565b604051809103906000f08015801562007262573d6000803e3d6000fd5b505060405162007272906200c1dc565b604051809103906000f0801580156200728f573d6000803e3d6000fd5b50506040516200729f906200c1dc565b604051809103906000f080158015620072bc573d6000803e3d6000fd5b5050604051620072cc906200c1dc565b604051809103906000f080158015620072e9573d6000803e3d6000fd5b5050604051620072f9906200c1dc565b604051809103906000f08015801562007316573d6000803e3d6000fd5b505060405162007326906200c1dc565b604051809103906000f08015801562007343573d6000803e3d6000fd5b505060405162007353906200c1dc565b604051809103906000f08015801562007370573d6000803e3d6000fd5b505060405162007380906200c1dc565b604051809103906000f0801580156200739d573d6000803e3d6000fd5b5050604051620073ad906200c1dc565b604051809103906000f080158015620073ca573d6000803e3d6000fd5b5050604051620073da906200c1dc565b604051809103906000f080158015620073f7573d6000803e3d6000fd5b505060405162007407906200c1dc565b604051809103906000f08015801562007424573d6000803e3d6000fd5b505060405162007434906200c1dc565b604051809103906000f08015801562007451573d6000803e3d6000fd5b505060405162007461906200c1dc565b604051809103906000f0801580156200747e573d6000803e3d6000fd5b50506040516200748e906200c1dc565b604051809103906000f080158015620074ab573d6000803e3d6000fd5b5050604051620074bb906200c1dc565b604051809103906000f080158015620074d8573d6000803e3d6000fd5b5050604051620074e8906200c1dc565b604051809103906000f08015801562007505573d6000803e3d6000fd5b505060405162007515906200c1dc565b604051809103906000f08015801562007532573d6000803e3d6000fd5b505060405162007542906200c1dc565b604051809103906000f0801580156200755f573d6000803e3d6000fd5b50506040516200756f906200c1dc565b604051809103906000f0801580156200758c573d6000803e3d6000fd5b50506040516200759c906200c1dc565b604051809103906000f080158015620075b9573d6000803e3d6000fd5b5050604051620075c9906200c1dc565b604051809103906000f080158015620075e6573d6000803e3d6000fd5b5050604051620075f6906200c1dc565b604051809103906000f08015801562007613573d6000803e3d6000fd5b505060405162007623906200c1dc565b604051809103906000f08015801562007640573d6000803e3d6000fd5b505060405162007650906200c1dc565b604051809103906000f0801580156200766d573d6000803e3d6000fd5b50506040516200767d906200c1dc565b604051809103906000f0801580156200769a573d6000803e3d6000fd5b5050604051620076aa906200c1dc565b604051809103906000f080158015620076c7573d6000803e3d6000fd5b5050604051620076d7906200c1dc565b604051809103906000f080158015620076f4573d6000803e3d6000fd5b505060405162007704906200c1dc565b604051809103906000f08015801562007721573d6000803e3d6000fd5b505060405162007731906200c1dc565b604051809103906000f0801580156200774e573d6000803e3d6000fd5b50506040516200775e906200c1dc565b604051809103906000f0801580156200777b573d6000803e3d6000fd5b50506040516200778b906200c1dc565b604051809103906000f080158015620077a8573d6000803e3d6000fd5b5050604051620077b8906200c1dc565b604051809103906000f080158015620077d5573d6000803e3d6000fd5b5050604051620077e5906200c1dc565b604051809103906000f08015801562007802573d6000803e3d6000fd5b505060405162007812906200c1dc565b604051809103906000f0801580156200782f573d6000803e3d6000fd5b50506040516200783f906200c1dc565b604051809103906000f0801580156200785c573d6000803e3d6000fd5b50506040516200786c906200c1dc565b604051809103906000f08015801562007889573d6000803e3d6000fd5b505060405162007899906200c1dc565b604051809103906000f080158015620078b6573d6000803e3d6000fd5b5050604051620078c6906200c1dc565b604051809103906000f080158015620078e3573d6000803e3d6000fd5b5050604051620078f3906200c1dc565b604051809103906000f08015801562007910573d6000803e3d6000fd5b505060405162007920906200c1dc565b604051809103906000f0801580156200793d573d6000803e3d6000fd5b50506040516200794d906200c1dc565b604051809103906000f0801580156200796a573d6000803e3d6000fd5b50506040516200797a906200c1dc565b604051809103906000f08015801562007997573d6000803e3d6000fd5b5050604051620079a7906200c1dc565b604051809103906000f080158015620079c4573d6000803e3d6000fd5b5050604051620079d4906200c1dc565b604051809103906000f080158015620079f1573d6000803e3d6000fd5b505060405162007a01906200c1dc565b604051809103906000f08015801562007a1e573d6000803e3d6000fd5b505060405162007a2e906200c1dc565b604051809103906000f08015801562007a4b573d6000803e3d6000fd5b505060405162007a5b906200c1dc565b604051809103906000f08015801562007a78573d6000803e3d6000fd5b505060405162007a88906200c1dc565b604051809103906000f08015801562007aa5573d6000803e3d6000fd5b505060405162007ab5906200c1dc565b604051809103906000f08015801562007ad2573d6000803e3d6000fd5b505060405162007ae2906200c1dc565b604051809103906000f08015801562007aff573d6000803e3d6000fd5b505060405162007b0f906200c1dc565b604051809103906000f08015801562007b2c573d6000803e3d6000fd5b505060405162007b3c906200c1dc565b604051809103906000f08015801562007b59573d6000803e3d6000fd5b505060405162007b69906200c1dc565b604051809103906000f08015801562007b86573d6000803e3d6000fd5b505060405162007b96906200c1dc565b604051809103906000f08015801562007bb3573d6000803e3d6000fd5b505060405162007bc3906200c1dc565b604051809103906000f08015801562007be0573d6000803e3d6000fd5b505060405162007bf0906200c1dc565b604051809103906000f08015801562007c0d573d6000803e3d6000fd5b505060405162007c1d906200c1dc565b604051809103906000f08015801562007c3a573d6000803e3d6000fd5b505060405162007c4a906200c1dc565b604051809103906000f08015801562007c67573d6000803e3d6000fd5b505060405162007c77906200c1dc565b604051809103906000f08015801562007c94573d6000803e3d6000fd5b505060405162007ca4906200c1dc565b604051809103906000f08015801562007cc1573d6000803e3d6000fd5b505060405162007cd1906200c1dc565b604051809103906000f08015801562007cee573d6000803e3d6000fd5b505060405162007cfe906200c1dc565b604051809103906000f08015801562007d1b573d6000803e3d6000fd5b505060405162007d2b906200c1dc565b604051809103906000f08015801562007d48573d6000803e3d6000fd5b505060405162007d58906200c1dc565b604051809103906000f08015801562007d75573d6000803e3d6000fd5b505060405162007d85906200c1dc565b604051809103906000f08015801562007da2573d6000803e3d6000fd5b505060405162007db2906200c1dc565b604051809103906000f08015801562007dcf573d6000803e3d6000fd5b505060405162007ddf906200c1dc565b604051809103906000f08015801562007dfc573d6000803e3d6000fd5b505060405162007e0c906200c1dc565b604051809103906000f08015801562007e29573d6000803e3d6000fd5b505060405162007e39906200c1dc565b604051809103906000f08015801562007e56573d6000803e3d6000fd5b505060405162007e66906200c1dc565b604051809103906000f08015801562007e83573d6000803e3d6000fd5b505060405162007e93906200c1dc565b604051809103906000f08015801562007eb0573d6000803e3d6000fd5b505060405162007ec0906200c1dc565b604051809103906000f08015801562007edd573d6000803e3d6000fd5b505060405162007eed906200c1dc565b604051809103906000f08015801562007f0a573d6000803e3d6000fd5b505060405162007f1a906200c1dc565b604051809103906000f08015801562007f37573d6000803e3d6000fd5b505060405162007f47906200c1dc565b604051809103906000f08015801562007f64573d6000803e3d6000fd5b505060405162007f74906200c1dc565b604051809103906000f08015801562007f91573d6000803e3d6000fd5b505060405162007fa1906200c1dc565b604051809103906000f08015801562007fbe573d6000803e3d6000fd5b505060405162007fce906200c1dc565b604051809103906000f08015801562007feb573d6000803e3d6000fd5b505060405162007ffb906200c1dc565b604051809103906000f08015801562008018573d6000803e3d6000fd5b505060405162008028906200c1dc565b604051809103906000f08015801562008045573d6000803e3d6000fd5b505060405162008055906200c1dc565b604051809103906000f08015801562008072573d6000803e3d6000fd5b505060405162008082906200c1dc565b604051809103906000f0801580156200809f573d6000803e3d6000fd5b5050604051620080af906200c1dc565b604051809103906000f080158015620080cc573d6000803e3d6000fd5b5050604051620080dc906200c1dc565b604051809103906000f080158015620080f9573d6000803e3d6000fd5b505060405162008109906200c1dc565b604051809103906000f08015801562008126573d6000803e3d6000fd5b505060405162008136906200c1dc565b604051809103906000f08015801562008153573d6000803e3d6000fd5b505060405162008163906200c1dc565b604051809103906000f08015801562008180573d6000803e3d6000fd5b505060405162008190906200c1dc565b604051809103906000f080158015620081ad573d6000803e3d6000fd5b5050604051620081bd906200c1dc565b604051809103906000f080158015620081da573d6000803e3d6000fd5b5050604051620081ea906200c1dc565b604051809103906000f08015801562008207573d6000803e3d6000fd5b505060405162008217906200c1dc565b604051809103906000f08015801562008234573d6000803e3d6000fd5b505060405162008244906200c1dc565b604051809103906000f08015801562008261573d6000803e3d6000fd5b505060405162008271906200c1dc565b604051809103906000f0801580156200828e573d6000803e3d6000fd5b50506040516200829e906200c1dc565b604051809103906000f080158015620082bb573d6000803e3d6000fd5b5050604051620082cb906200c1dc565b604051809103906000f080158015620082e8573d6000803e3d6000fd5b5050604051620082f8906200c1dc565b604051809103906000f08015801562008315573d6000803e3d6000fd5b505060405162008325906200c1dc565b604051809103906000f08015801562008342573d6000803e3d6000fd5b505060405162008352906200c1dc565b604051809103906000f0801580156200836f573d6000803e3d6000fd5b50506040516200837f906200c1dc565b604051809103906000f0801580156200839c573d6000803e3d6000fd5b5050604051620083ac906200c1dc565b604051809103906000f080158015620083c9573d6000803e3d6000fd5b5050604051620083d9906200c1dc565b604051809103906000f080158015620083f6573d6000803e3d6000fd5b505060405162008406906200c1dc565b604051809103906000f08015801562008423573d6000803e3d6000fd5b505060405162008433906200c1dc565b604051809103906000f08015801562008450573d6000803e3d6000fd5b505060405162008460906200c1dc565b604051809103906000f0801580156200847d573d6000803e3d6000fd5b50506040516200848d906200c1dc565b604051809103906000f080158015620084aa573d6000803e3d6000fd5b5050604051620084ba906200c1dc565b604051809103906000f080158015620084d7573d6000803e3d6000fd5b5050604051620084e7906200c1dc565b604051809103906000f08015801562008504573d6000803e3d6000fd5b505060405162008514906200c1dc565b604051809103906000f08015801562008531573d6000803e3d6000fd5b505060405162008541906200c1dc565b604051809103906000f0801580156200855e573d6000803e3d6000fd5b50506040516200856e906200c1dc565b604051809103906000f0801580156200858b573d6000803e3d6000fd5b50506040516200859b906200c1dc565b604051809103906000f080158015620085b8573d6000803e3d6000fd5b5050604051620085c8906200c1dc565b604051809103906000f080158015620085e5573d6000803e3d6000fd5b5050604051620085f5906200c1dc565b604051809103906000f08015801562008612573d6000803e3d6000fd5b505060405162008622906200c1dc565b604051809103906000f0801580156200863f573d6000803e3d6000fd5b50506040516200864f906200c1dc565b604051809103906000f0801580156200866c573d6000803e3d6000fd5b50506040516200867c906200c1dc565b604051809103906000f08015801562008699573d6000803e3d6000fd5b5050604051620086a9906200c1dc565b604051809103906000f080158015620086c6573d6000803e3d6000fd5b5050604051620086d6906200c1dc565b604051809103906000f080158015620086f3573d6000803e3d6000fd5b505060405162008703906200c1dc565b604051809103906000f08015801562008720573d6000803e3d6000fd5b505060405162008730906200c1dc565b604051809103906000f0801580156200874d573d6000803e3d6000fd5b50506040516200875d906200c1dc565b604051809103906000f0801580156200877a573d6000803e3d6000fd5b50506040516200878a906200c1dc565b604051809103906000f080158015620087a7573d6000803e3d6000fd5b5050604051620087b7906200c1dc565b604051809103906000f080158015620087d4573d6000803e3d6000fd5b5050604051620087e4906200c1dc565b604051809103906000f08015801562008801573d6000803e3d6000fd5b505060405162008811906200c1dc565b604051809103906000f0801580156200882e573d6000803e3d6000fd5b50506040516200883e906200c1dc565b604051809103906000f0801580156200885b573d6000803e3d6000fd5b50506040516200886b906200c1dc565b604051809103906000f08015801562008888573d6000803e3d6000fd5b505060405162008898906200c1dc565b604051809103906000f080158015620088b5573d6000803e3d6000fd5b5050604051620088c5906200c1dc565b604051809103906000f080158015620088e2573d6000803e3d6000fd5b5050604051620088f2906200c1dc565b604051809103906000f0801580156200890f573d6000803e3d6000fd5b50506040516200891f906200c1dc565b604051809103906000f0801580156200893c573d6000803e3d6000fd5b50506040516200894c906200c1dc565b604051809103906000f08015801562008969573d6000803e3d6000fd5b505060405162008979906200c1dc565b604051809103906000f08015801562008996573d6000803e3d6000fd5b5050604051620089a6906200c1dc565b604051809103906000f080158015620089c3573d6000803e3d6000fd5b5050604051620089d3906200c1dc565b604051809103906000f080158015620089f0573d6000803e3d6000fd5b505060405162008a00906200c1dc565b604051809103906000f08015801562008a1d573d6000803e3d6000fd5b505060405162008a2d906200c1dc565b604051809103906000f08015801562008a4a573d6000803e3d6000fd5b505060405162008a5a906200c1dc565b604051809103906000f08015801562008a77573d6000803e3d6000fd5b505060405162008a87906200c1dc565b604051809103906000f08015801562008aa4573d6000803e3d6000fd5b505060405162008ab4906200c1dc565b604051809103906000f08015801562008ad1573d6000803e3d6000fd5b505060405162008ae1906200c1dc565b604051809103906000f08015801562008afe573d6000803e3d6000fd5b505060405162008b0e906200c1dc565b604051809103906000f08015801562008b2b573d6000803e3d6000fd5b505060405162008b3b906200c1dc565b604051809103906000f08015801562008b58573d6000803e3d6000fd5b505060405162008b68906200c1dc565b604051809103906000f08015801562008b85573d6000803e3d6000fd5b505060405162008b95906200c1dc565b604051809103906000f08015801562008bb2573d6000803e3d6000fd5b505060405162008bc2906200c1dc565b604051809103906000f08015801562008bdf573d6000803e3d6000fd5b505060405162008bef906200c1dc565b604051809103906000f08015801562008c0c573d6000803e3d6000fd5b505060405162008c1c906200c1dc565b604051809103906000f08015801562008c39573d6000803e3d6000fd5b505060405162008c49906200c1dc565b604051809103906000f08015801562008c66573d6000803e3d6000fd5b505060405162008c76906200c1dc565b604051809103906000f08015801562008c93573d6000803e3d6000fd5b505060405162008ca3906200c1dc565b604051809103906000f08015801562008cc0573d6000803e3d6000fd5b505060405162008cd0906200c1dc565b604051809103906000f08015801562008ced573d6000803e3d6000fd5b505060405162008cfd906200c1dc565b604051809103906000f08015801562008d1a573d6000803e3d6000fd5b505060405162008d2a906200c1dc565b604051809103906000f08015801562008d47573d6000803e3d6000fd5b505060405162008d57906200c1dc565b604051809103906000f08015801562008d74573d6000803e3d6000fd5b505060405162008d84906200c1dc565b604051809103906000f08015801562008da1573d6000803e3d6000fd5b505060405162008db1906200c1dc565b604051809103906000f08015801562008dce573d6000803e3d6000fd5b505060405162008dde906200c1dc565b604051809103906000f08015801562008dfb573d6000803e3d6000fd5b505060405162008e0b906200c1dc565b604051809103906000f08015801562008e28573d6000803e3d6000fd5b505060405162008e38906200c1dc565b604051809103906000f08015801562008e55573d6000803e3d6000fd5b505060405162008e65906200c1dc565b604051809103906000f08015801562008e82573d6000803e3d6000fd5b505060405162008e92906200c1dc565b604051809103906000f08015801562008eaf573d6000803e3d6000fd5b505060405162008ebf906200c1dc565b604051809103906000f08015801562008edc573d6000803e3d6000fd5b505060405162008eec906200c1dc565b604051809103906000f08015801562008f09573d6000803e3d6000fd5b505060405162008f19906200c1dc565b604051809103906000f08015801562008f36573d6000803e3d6000fd5b505060405162008f46906200c1dc565b604051809103906000f08015801562008f63573d6000803e3d6000fd5b505060405162008f73906200c1dc565b604051809103906000f08015801562008f90573d6000803e3d6000fd5b505060405162008fa0906200c1dc565b604051809103906000f08015801562008fbd573d6000803e3d6000fd5b505060405162008fcd906200c1dc565b604051809103906000f08015801562008fea573d6000803e3d6000fd5b505060405162008ffa906200c1dc565b604051809103906000f08015801562009017573d6000803e3d6000fd5b505060405162009027906200c1dc565b604051809103906000f08015801562009044573d6000803e3d6000fd5b505060405162009054906200c1dc565b604051809103906000f08015801562009071573d6000803e3d6000fd5b505060405162009081906200c1dc565b604051809103906000f0801580156200909e573d6000803e3d6000fd5b5050604051620090ae906200c1dc565b604051809103906000f080158015620090cb573d6000803e3d6000fd5b5050604051620090db906200c1dc565b604051809103906000f080158015620090f8573d6000803e3d6000fd5b505060405162009108906200c1dc565b604051809103906000f08015801562009125573d6000803e3d6000fd5b505060405162009135906200c1dc565b604051809103906000f08015801562009152573d6000803e3d6000fd5b505060405162009162906200c1dc565b604051809103906000f0801580156200917f573d6000803e3d6000fd5b50506040516200918f906200c1dc565b604051809103906000f080158015620091ac573d6000803e3d6000fd5b5050604051620091bc906200c1dc565b604051809103906000f080158015620091d9573d6000803e3d6000fd5b5050604051620091e9906200c1dc565b604051809103906000f08015801562009206573d6000803e3d6000fd5b505060405162009216906200c1dc565b604051809103906000f08015801562009233573d6000803e3d6000fd5b505060405162009243906200c1dc565b604051809103906000f08015801562009260573d6000803e3d6000fd5b505060405162009270906200c1dc565b604051809103906000f0801580156200928d573d6000803e3d6000fd5b50506040516200929d906200c1dc565b604051809103906000f080158015620092ba573d6000803e3d6000fd5b5050604051620092ca906200c1dc565b604051809103906000f080158015620092e7573d6000803e3d6000fd5b5050604051620092f7906200c1dc565b604051809103906000f08015801562009314573d6000803e3d6000fd5b505060405162009324906200c1dc565b604051809103906000f08015801562009341573d6000803e3d6000fd5b505060405162009351906200c1dc565b604051809103906000f0801580156200936e573d6000803e3d6000fd5b50506040516200937e906200c1dc565b604051809103906000f0801580156200939b573d6000803e3d6000fd5b5050604051620093ab906200c1dc565b604051809103906000f080158015620093c8573d6000803e3d6000fd5b5050604051620093d8906200c1dc565b604051809103906000f080158015620093f5573d6000803e3d6000fd5b505060405162009405906200c1dc565b604051809103906000f08015801562009422573d6000803e3d6000fd5b505060405162009432906200c1dc565b604051809103906000f0801580156200944f573d6000803e3d6000fd5b50506040516200945f906200c1dc565b604051809103906000f0801580156200947c573d6000803e3d6000fd5b50506040516200948c906200c1dc565b604051809103906000f080158015620094a9573d6000803e3d6000fd5b5050604051620094b9906200c1dc565b604051809103906000f080158015620094d6573d6000803e3d6000fd5b5050604051620094e6906200c1dc565b604051809103906000f08015801562009503573d6000803e3d6000fd5b505060405162009513906200c1dc565b604051809103906000f08015801562009530573d6000803e3d6000fd5b505060405162009540906200c1dc565b604051809103906000f0801580156200955d573d6000803e3d6000fd5b50506040516200956d906200c1dc565b604051809103906000f0801580156200958a573d6000803e3d6000fd5b50506040516200959a906200c1dc565b604051809103906000f080158015620095b7573d6000803e3d6000fd5b5050604051620095c7906200c1dc565b604051809103906000f080158015620095e4573d6000803e3d6000fd5b5050604051620095f4906200c1dc565b604051809103906000f08015801562009611573d6000803e3d6000fd5b505060405162009621906200c1dc565b604051809103906000f0801580156200963e573d6000803e3d6000fd5b50506040516200964e906200c1dc565b604051809103906000f0801580156200966b573d6000803e3d6000fd5b50506040516200967b906200c1dc565b604051809103906000f08015801562009698573d6000803e3d6000fd5b5050604051620096a8906200c1dc565b604051809103906000f080158015620096c5573d6000803e3d6000fd5b5050604051620096d5906200c1dc565b604051809103906000f080158015620096f2573d6000803e3d6000fd5b505060405162009702906200c1dc565b604051809103906000f0801580156200971f573d6000803e3d6000fd5b50506040516200972f906200c1dc565b604051809103906000f0801580156200974c573d6000803e3d6000fd5b50506040516200975c906200c1dc565b604051809103906000f08015801562009779573d6000803e3d6000fd5b505060405162009789906200c1dc565b604051809103906000f080158015620097a6573d6000803e3d6000fd5b5050604051620097b6906200c1dc565b604051809103906000f080158015620097d3573d6000803e3d6000fd5b5050604051620097e3906200c1dc565b604051809103906000f08015801562009800573d6000803e3d6000fd5b505060405162009810906200c1dc565b604051809103906000f0801580156200982d573d6000803e3d6000fd5b50506040516200983d906200c1dc565b604051809103906000f0801580156200985a573d6000803e3d6000fd5b50506040516200986a906200c1dc565b604051809103906000f08015801562009887573d6000803e3d6000fd5b505060405162009897906200c1dc565b604051809103906000f080158015620098b4573d6000803e3d6000fd5b5050604051620098c4906200c1dc565b604051809103906000f080158015620098e1573d6000803e3d6000fd5b5050604051620098f1906200c1dc565b604051809103906000f0801580156200990e573d6000803e3d6000fd5b50506040516200991e906200c1dc565b604051809103906000f0801580156200993b573d6000803e3d6000fd5b50506040516200994b906200c1dc565b604051809103906000f08015801562009968573d6000803e3d6000fd5b505060405162009978906200c1dc565b604051809103906000f08015801562009995573d6000803e3d6000fd5b5050604051620099a5906200c1dc565b604051809103906000f080158015620099c2573d6000803e3d6000fd5b5050604051620099d2906200c1dc565b604051809103906000f080158015620099ef573d6000803e3d6000fd5b5050604051620099ff906200c1dc565b604051809103906000f08015801562009a1c573d6000803e3d6000fd5b505060405162009a2c906200c1dc565b604051809103906000f08015801562009a49573d6000803e3d6000fd5b505060405162009a59906200c1dc565b604051809103906000f08015801562009a76573d6000803e3d6000fd5b505060405162009a86906200c1dc565b604051809103906000f08015801562009aa3573d6000803e3d6000fd5b505060405162009ab3906200c1dc565b604051809103906000f08015801562009ad0573d6000803e3d6000fd5b505060405162009ae0906200c1dc565b604051809103906000f08015801562009afd573d6000803e3d6000fd5b505060405162009b0d906200c1dc565b604051809103906000f08015801562009b2a573d6000803e3d6000fd5b505060405162009b3a906200c1dc565b604051809103906000f08015801562009b57573d6000803e3d6000fd5b505060405162009b67906200c1dc565b604051809103906000f08015801562009b84573d6000803e3d6000fd5b505060405162009b94906200c1dc565b604051809103906000f08015801562009bb1573d6000803e3d6000fd5b505060405162009bc1906200c1dc565b604051809103906000f08015801562009bde573d6000803e3d6000fd5b505060405162009bee906200c1dc565b604051809103906000f08015801562009c0b573d6000803e3d6000fd5b505060405162009c1b906200c1dc565b604051809103906000f08015801562009c38573d6000803e3d6000fd5b505060405162009c48906200c1dc565b604051809103906000f08015801562009c65573d6000803e3d6000fd5b505060405162009c75906200c1dc565b604051809103906000f08015801562009c92573d6000803e3d6000fd5b505060405162009ca2906200c1dc565b604051809103906000f08015801562009cbf573d6000803e3d6000fd5b505060405162009ccf906200c1dc565b604051809103906000f08015801562009cec573d6000803e3d6000fd5b505060405162009cfc906200c1dc565b604051809103906000f08015801562009d19573d6000803e3d6000fd5b505060405162009d29906200c1dc565b604051809103906000f08015801562009d46573d6000803e3d6000fd5b505060405162009d56906200c1dc565b604051809103906000f08015801562009d73573d6000803e3d6000fd5b505060405162009d83906200c1dc565b604051809103906000f08015801562009da0573d6000803e3d6000fd5b505060405162009db0906200c1dc565b604051809103906000f08015801562009dcd573d6000803e3d6000fd5b505060405162009ddd906200c1dc565b604051809103906000f08015801562009dfa573d6000803e3d6000fd5b505060405162009e0a906200c1dc565b604051809103906000f08015801562009e27573d6000803e3d6000fd5b505060405162009e37906200c1dc565b604051809103906000f08015801562009e54573d6000803e3d6000fd5b505060405162009e64906200c1dc565b604051809103906000f08015801562009e81573d6000803e3d6000fd5b505060405162009e91906200c1dc565b604051809103906000f08015801562009eae573d6000803e3d6000fd5b505060405162009ebe906200c1dc565b604051809103906000f08015801562009edb573d6000803e3d6000fd5b505060405162009eeb906200c1dc565b604051809103906000f08015801562009f08573d6000803e3d6000fd5b505060405162009f18906200c1dc565b604051809103906000f08015801562009f35573d6000803e3d6000fd5b505060405162009f45906200c1dc565b604051809103906000f08015801562009f62573d6000803e3d6000fd5b505060405162009f72906200c1dc565b604051809103906000f08015801562009f8f573d6000803e3d6000fd5b505060405162009f9f906200c1dc565b604051809103906000f08015801562009fbc573d6000803e3d6000fd5b505060405162009fcc906200c1dc565b604051809103906000f08015801562009fe9573d6000803e3d6000fd5b505060405162009ff9906200c1dc565b604051809103906000f0801580156200a016573d6000803e3d6000fd5b50506040516200a026906200c1dc565b604051809103906000f0801580156200a043573d6000803e3d6000fd5b50506040516200a053906200c1dc565b604051809103906000f0801580156200a070573d6000803e3d6000fd5b50506040516200a080906200c1dc565b604051809103906000f0801580156200a09d573d6000803e3d6000fd5b50506040516200a0ad906200c1dc565b604051809103906000f0801580156200a0ca573d6000803e3d6000fd5b50506040516200a0da906200c1dc565b604051809103906000f0801580156200a0f7573d6000803e3d6000fd5b50506040516200a107906200c1dc565b604051809103906000f0801580156200a124573d6000803e3d6000fd5b50506040516200a134906200c1dc565b604051809103906000f0801580156200a151573d6000803e3d6000fd5b50506040516200a161906200c1dc565b604051809103906000f0801580156200a17e573d6000803e3d6000fd5b50506040516200a18e906200c1dc565b604051809103906000f0801580156200a1ab573d6000803e3d6000fd5b50506040516200a1bb906200c1dc565b604051809103906000f0801580156200a1d8573d6000803e3d6000fd5b50506040516200a1e8906200c1dc565b604051809103906000f0801580156200a205573d6000803e3d6000fd5b50506040516200a215906200c1dc565b604051809103906000f0801580156200a232573d6000803e3d6000fd5b50506040516200a242906200c1dc565b604051809103906000f0801580156200a25f573d6000803e3d6000fd5b50506040516200a26f906200c1dc565b604051809103906000f0801580156200a28c573d6000803e3d6000fd5b50506040516200a29c906200c1dc565b604051809103906000f0801580156200a2b9573d6000803e3d6000fd5b50506040516200a2c9906200c1dc565b604051809103906000f0801580156200a2e6573d6000803e3d6000fd5b50506040516200a2f6906200c1dc565b604051809103906000f0801580156200a313573d6000803e3d6000fd5b50506040516200a323906200c1dc565b604051809103906000f0801580156200a340573d6000803e3d6000fd5b50506040516200a350906200c1dc565b604051809103906000f0801580156200a36d573d6000803e3d6000fd5b50506040516200a37d906200c1dc565b604051809103906000f0801580156200a39a573d6000803e3d6000fd5b50506040516200a3aa906200c1dc565b604051809103906000f0801580156200a3c7573d6000803e3d6000fd5b50506040516200a3d7906200c1dc565b604051809103906000f0801580156200a3f4573d6000803e3d6000fd5b50506040516200a404906200c1dc565b604051809103906000f0801580156200a421573d6000803e3d6000fd5b50506040516200a431906200c1dc565b604051809103906000f0801580156200a44e573d6000803e3d6000fd5b50506040516200a45e906200c1dc565b604051809103906000f0801580156200a47b573d6000803e3d6000fd5b50506040516200a48b906200c1dc565b604051809103906000f0801580156200a4a8573d6000803e3d6000fd5b50506040516200a4b8906200c1dc565b604051809103906000f0801580156200a4d5573d6000803e3d6000fd5b50506040516200a4e5906200c1dc565b604051809103906000f0801580156200a502573d6000803e3d6000fd5b50506040516200a512906200c1dc565b604051809103906000f0801580156200a52f573d6000803e3d6000fd5b50506040516200a53f906200c1dc565b604051809103906000f0801580156200a55c573d6000803e3d6000fd5b50506040516200a56c906200c1dc565b604051809103906000f0801580156200a589573d6000803e3d6000fd5b50506040516200a599906200c1dc565b604051809103906000f0801580156200a5b6573d6000803e3d6000fd5b50506040516200a5c6906200c1dc565b604051809103906000f0801580156200a5e3573d6000803e3d6000fd5b50506040516200a5f3906200c1dc565b604051809103906000f0801580156200a610573d6000803e3d6000fd5b50506040516200a620906200c1dc565b604051809103906000f0801580156200a63d573d6000803e3d6000fd5b50506040516200a64d906200c1dc565b604051809103906000f0801580156200a66a573d6000803e3d6000fd5b50506040516200a67a906200c1dc565b604051809103906000f0801580156200a697573d6000803e3d6000fd5b50506040516200a6a7906200c1dc565b604051809103906000f0801580156200a6c4573d6000803e3d6000fd5b50506040516200a6d4906200c1dc565b604051809103906000f0801580156200a6f1573d6000803e3d6000fd5b50506040516200a701906200c1dc565b604051809103906000f0801580156200a71e573d6000803e3d6000fd5b50506040516200a72e906200c1dc565b604051809103906000f0801580156200a74b573d6000803e3d6000fd5b50506040516200a75b906200c1dc565b604051809103906000f0801580156200a778573d6000803e3d6000fd5b50506040516200a788906200c1dc565b604051809103906000f0801580156200a7a5573d6000803e3d6000fd5b50506040516200a7b5906200c1dc565b604051809103906000f0801580156200a7d2573d6000803e3d6000fd5b50506040516200a7e2906200c1dc565b604051809103906000f0801580156200a7ff573d6000803e3d6000fd5b50506040516200a80f906200c1dc565b604051809103906000f0801580156200a82c573d6000803e3d6000fd5b50506040516200a83c906200c1dc565b604051809103906000f0801580156200a859573d6000803e3d6000fd5b50506040516200a869906200c1dc565b604051809103906000f0801580156200a886573d6000803e3d6000fd5b50506040516200a896906200c1dc565b604051809103906000f0801580156200a8b3573d6000803e3d6000fd5b50506040516200a8c3906200c1dc565b604051809103906000f0801580156200a8e0573d6000803e3d6000fd5b50506040516200a8f0906200c1dc565b604051809103906000f0801580156200a90d573d6000803e3d6000fd5b50506040516200a91d906200c1dc565b604051809103906000f0801580156200a93a573d6000803e3d6000fd5b50506040516200a94a906200c1dc565b604051809103906000f0801580156200a967573d6000803e3d6000fd5b50506040516200a977906200c1dc565b604051809103906000f0801580156200a994573d6000803e3d6000fd5b50506040516200a9a4906200c1dc565b604051809103906000f0801580156200a9c1573d6000803e3d6000fd5b50506040516200a9d1906200c1dc565b604051809103906000f0801580156200a9ee573d6000803e3d6000fd5b50506040516200a9fe906200c1dc565b604051809103906000f0801580156200aa1b573d6000803e3d6000fd5b50506040516200aa2b906200c1dc565b604051809103906000f0801580156200aa48573d6000803e3d6000fd5b50506040516200aa58906200c1dc565b604051809103906000f0801580156200aa75573d6000803e3d6000fd5b50506040516200aa85906200c1dc565b604051809103906000f0801580156200aaa2573d6000803e3d6000fd5b50506040516200aab2906200c1dc565b604051809103906000f0801580156200aacf573d6000803e3d6000fd5b50506040516200aadf906200c1dc565b604051809103906000f0801580156200aafc573d6000803e3d6000fd5b50506040516200ab0c906200c1dc565b604051809103906000f0801580156200ab29573d6000803e3d6000fd5b50506040516200ab39906200c1dc565b604051809103906000f0801580156200ab56573d6000803e3d6000fd5b50506040516200ab66906200c1dc565b604051809103906000f0801580156200ab83573d6000803e3d6000fd5b50506040516200ab93906200c1dc565b604051809103906000f0801580156200abb0573d6000803e3d6000fd5b50506040516200abc0906200c1dc565b604051809103906000f0801580156200abdd573d6000803e3d6000fd5b50506040516200abed906200c1dc565b604051809103906000f0801580156200ac0a573d6000803e3d6000fd5b50506040516200ac1a906200c1dc565b604051809103906000f0801580156200ac37573d6000803e3d6000fd5b50506040516200ac47906200c1dc565b604051809103906000f0801580156200ac64573d6000803e3d6000fd5b50506040516200ac74906200c1dc565b604051809103906000f0801580156200ac91573d6000803e3d6000fd5b50506040516200aca1906200c1dc565b604051809103906000f0801580156200acbe573d6000803e3d6000fd5b50506040516200acce906200c1dc565b604051809103906000f0801580156200aceb573d6000803e3d6000fd5b50506040516200acfb906200c1dc565b604051809103906000f0801580156200ad18573d6000803e3d6000fd5b50506040516200ad28906200c1dc565b604051809103906000f0801580156200ad45573d6000803e3d6000fd5b50506040516200ad55906200c1dc565b604051809103906000f0801580156200ad72573d6000803e3d6000fd5b50506040516200ad82906200c1dc565b604051809103906000f0801580156200ad9f573d6000803e3d6000fd5b50506040516200adaf906200c1dc565b604051809103906000f0801580156200adcc573d6000803e3d6000fd5b50506040516200addc906200c1dc565b604051809103906000f0801580156200adf9573d6000803e3d6000fd5b50506040516200ae09906200c1dc565b604051809103906000f0801580156200ae26573d6000803e3d6000fd5b50506040516200ae36906200c1dc565b604051809103906000f0801580156200ae53573d6000803e3d6000fd5b50506040516200ae63906200c1dc565b604051809103906000f0801580156200ae80573d6000803e3d6000fd5b50506040516200ae90906200c1dc565b604051809103906000f0801580156200aead573d6000803e3d6000fd5b50506040516200aebd906200c1dc565b604051809103906000f0801580156200aeda573d6000803e3d6000fd5b50506040516200aeea906200c1dc565b604051809103906000f0801580156200af07573d6000803e3d6000fd5b50506040516200af17906200c1dc565b604051809103906000f0801580156200af34573d6000803e3d6000fd5b50506040516200af44906200c1dc565b604051809103906000f0801580156200af61573d6000803e3d6000fd5b50506040516200af71906200c1dc565b604051809103906000f0801580156200af8e573d6000803e3d6000fd5b50506040516200af9e906200c1dc565b604051809103906000f0801580156200afbb573d6000803e3d6000fd5b50506040516200afcb906200c1dc565b604051809103906000f0801580156200afe8573d6000803e3d6000fd5b50506040516200aff8906200c1dc565b604051809103906000f0801580156200b015573d6000803e3d6000fd5b50506040516200b025906200c1dc565b604051809103906000f0801580156200b042573d6000803e3d6000fd5b50506040516200b052906200c1dc565b604051809103906000f0801580156200b06f573d6000803e3d6000fd5b50506040516200b07f906200c1dc565b604051809103906000f0801580156200b09c573d6000803e3d6000fd5b50506040516200b0ac906200c1dc565b604051809103906000f0801580156200b0c9573d6000803e3d6000fd5b50506040516200b0d9906200c1dc565b604051809103906000f0801580156200b0f6573d6000803e3d6000fd5b50506040516200b106906200c1dc565b604051809103906000f0801580156200b123573d6000803e3d6000fd5b50506040516200b133906200c1dc565b604051809103906000f0801580156200b150573d6000803e3d6000fd5b50506040516200b160906200c1dc565b604051809103906000f0801580156200b17d573d6000803e3d6000fd5b50506040516200b18d906200c1dc565b604051809103906000f0801580156200b1aa573d6000803e3d6000fd5b50506040516200b1ba906200c1dc565b604051809103906000f0801580156200b1d7573d6000803e3d6000fd5b50506040516200b1e7906200c1dc565b604051809103906000f0801580156200b204573d6000803e3d6000fd5b50506040516200b214906200c1dc565b604051809103906000f0801580156200b231573d6000803e3d6000fd5b50506040516200b241906200c1dc565b604051809103906000f0801580156200b25e573d6000803e3d6000fd5b50506040516200b26e906200c1dc565b604051809103906000f0801580156200b28b573d6000803e3d6000fd5b50506040516200b29b906200c1dc565b604051809103906000f0801580156200b2b8573d6000803e3d6000fd5b50506040516200b2c8906200c1dc565b604051809103906000f0801580156200b2e5573d6000803e3d6000fd5b50506040516200b2f5906200c1dc565b604051809103906000f0801580156200b312573d6000803e3d6000fd5b50506040516200b322906200c1dc565b604051809103906000f0801580156200b33f573d6000803e3d6000fd5b50506040516200b34f906200c1dc565b604051809103906000f0801580156200b36c573d6000803e3d6000fd5b50506040516200b37c906200c1dc565b604051809103906000f0801580156200b399573d6000803e3d6000fd5b50506040516200b3a9906200c1dc565b604051809103906000f0801580156200b3c6573d6000803e3d6000fd5b50506040516200b3d6906200c1dc565b604051809103906000f0801580156200b3f3573d6000803e3d6000fd5b50506040516200b403906200c1dc565b604051809103906000f0801580156200b420573d6000803e3d6000fd5b50506040516200b430906200c1dc565b604051809103906000f0801580156200b44d573d6000803e3d6000fd5b50506040516200b45d906200c1dc565b604051809103906000f0801580156200b47a573d6000803e3d6000fd5b50506040516200b48a906200c1dc565b604051809103906000f0801580156200b4a7573d6000803e3d6000fd5b50506040516200b4b7906200c1dc565b604051809103906000f0801580156200b4d4573d6000803e3d6000fd5b50506040516200b4e4906200c1dc565b604051809103906000f0801580156200b501573d6000803e3d6000fd5b50506040516200b511906200c1dc565b604051809103906000f0801580156200b52e573d6000803e3d6000fd5b50506040516200b53e906200c1dc565b604051809103906000f0801580156200b55b573d6000803e3d6000fd5b50506040516200b56b906200c1dc565b604051809103906000f0801580156200b588573d6000803e3d6000fd5b50506040516200b598906200c1dc565b604051809103906000f0801580156200b5b5573d6000803e3d6000fd5b50506040516200b5c5906200c1dc565b604051809103906000f0801580156200b5e2573d6000803e3d6000fd5b50506040516200b5f2906200c1dc565b604051809103906000f0801580156200b60f573d6000803e3d6000fd5b50506040516200b61f906200c1dc565b604051809103906000f0801580156200b63c573d6000803e3d6000fd5b50506040516200b64c906200c1dc565b604051809103906000f0801580156200b669573d6000803e3d6000fd5b50506040516200b679906200c1dc565b604051809103906000f0801580156200b696573d6000803e3d6000fd5b50506040516200b6a6906200c1dc565b604051809103906000f0801580156200b6c3573d6000803e3d6000fd5b50506040516200b6d3906200c1dc565b604051809103906000f0801580156200b6f0573d6000803e3d6000fd5b50506040516200b700906200c1dc565b604051809103906000f0801580156200b71d573d6000803e3d6000fd5b50506040516200b72d906200c1dc565b604051809103906000f0801580156200b74a573d6000803e3d6000fd5b50506040516200b75a906200c1dc565b604051809103906000f0801580156200b777573d6000803e3d6000fd5b50506040516200b787906200c1dc565b604051809103906000f0801580156200b7a4573d6000803e3d6000fd5b50506040516200b7b4906200c1dc565b604051809103906000f0801580156200b7d1573d6000803e3d6000fd5b50506040516200b7e1906200c1dc565b604051809103906000f0801580156200b7fe573d6000803e3d6000fd5b50506040516200b80e906200c1dc565b604051809103906000f0801580156200b82b573d6000803e3d6000fd5b50506040516200b83b906200c1dc565b604051809103906000f0801580156200b858573d6000803e3d6000fd5b50506040516200b868906200c1dc565b604051809103906000f0801580156200b885573d6000803e3d6000fd5b50506040516200b895906200c1dc565b604051809103906000f0801580156200b8b2573d6000803e3d6000fd5b50506040516200b8c2906200c1dc565b604051809103906000f0801580156200b8df573d6000803e3d6000fd5b50506040516200b8ef906200c1dc565b604051809103906000f0801580156200b90c573d6000803e3d6000fd5b50506040516200b91c906200c1dc565b604051809103906000f0801580156200b939573d6000803e3d6000fd5b50506040516200b949906200c1dc565b604051809103906000f0801580156200b966573d6000803e3d6000fd5b50506040516200b976906200c1dc565b604051809103906000f0801580156200b993573d6000803e3d6000fd5b50506040516200b9a3906200c1dc565b604051809103906000f0801580156200b9c0573d6000803e3d6000fd5b50506040516200b9d0906200c1dc565b604051809103906000f0801580156200b9ed573d6000803e3d6000fd5b50506040516200b9fd906200c1dc565b604051809103906000f0801580156200ba1a573d6000803e3d6000fd5b50506040516200ba2a906200c1dc565b604051809103906000f0801580156200ba47573d6000803e3d6000fd5b50506040516200ba57906200c1dc565b604051809103906000f0801580156200ba74573d6000803e3d6000fd5b50506040516200ba84906200c1dc565b604051809103906000f0801580156200baa1573d6000803e3d6000fd5b50506040516200bab1906200c1dc565b604051809103906000f0801580156200bace573d6000803e3d6000fd5b50506040516200bade906200c1dc565b604051809103906000f0801580156200bafb573d6000803e3d6000fd5b50506040516200bb0b906200c1dc565b604051809103906000f0801580156200bb28573d6000803e3d6000fd5b50506040516200bb38906200c1dc565b604051809103906000f0801580156200bb55573d6000803e3d6000fd5b50506040516200bb65906200c1dc565b604051809103906000f0801580156200bb82573d6000803e3d6000fd5b50506040516200bb92906200c1dc565b604051809103906000f0801580156200bbaf573d6000803e3d6000fd5b50506040516200bbbf906200c1dc565b604051809103906000f0801580156200bbdc573d6000803e3d6000fd5b50506040516200bbec906200c1dc565b604051809103906000f0801580156200bc09573d6000803e3d6000fd5b50506040516200bc19906200c1dc565b604051809103906000f0801580156200bc36573d6000803e3d6000fd5b50506040516200bc46906200c1dc565b604051809103906000f0801580156200bc63573d6000803e3d6000fd5b50506040516200bc73906200c1dc565b604051809103906000f0801580156200bc90573d6000803e3d6000fd5b50506040516200bca0906200c1dc565b604051809103906000f0801580156200bcbd573d6000803e3d6000fd5b50506040516200bccd906200c1dc565b604051809103906000f0801580156200bcea573d6000803e3d6000fd5b50506040516200bcfa906200c1dc565b604051809103906000f0801580156200bd17573d6000803e3d6000fd5b50506040516200bd27906200c1dc565b604051809103906000f0801580156200bd44573d6000803e3d6000fd5b50506040516200bd54906200c1dc565b604051809103906000f0801580156200bd71573d6000803e3d6000fd5b50506040516200bd81906200c1dc565b604051809103906000f0801580156200bd9e573d6000803e3d6000fd5b50506040516200bdae906200c1dc565b604051809103906000f0801580156200bdcb573d6000803e3d6000fd5b50506040516200bddb906200c1dc565b604051809103906000f0801580156200bdf8573d6000803e3d6000fd5b50506040516200be08906200c1dc565b604051809103906000f0801580156200be25573d6000803e3d6000fd5b50506040516200be35906200c1dc565b604051809103906000f0801580156200be52573d6000803e3d6000fd5b50506040516200be62906200c1dc565b604051809103906000f0801580156200be7f573d6000803e3d6000fd5b50506040516200be8f906200c1dc565b604051809103906000f0801580156200beac573d6000803e3d6000fd5b50506040516200bebc906200c1dc565b604051809103906000f0801580156200bed9573d6000803e3d6000fd5b50506040516200bee9906200c1dc565b604051809103906000f0801580156200bf06573d6000803e3d6000fd5b50506040516200bf16906200c1dc565b604051809103906000f0801580156200bf33573d6000803e3d6000fd5b50506040516200bf43906200c1dc565b604051809103906000f0801580156200bf60573d6000803e3d6000fd5b50506040516200bf70906200c1dc565b604051809103906000f0801580156200bf8d573d6000803e3d6000fd5b50506040516200bf9d906200c1dc565b604051809103906000f0801580156200bfba573d6000803e3d6000fd5b50506040516200bfca906200c1dc565b604051809103906000f0801580156200bfe7573d6000803e3d6000fd5b50506040516200bff7906200c1dc565b604051809103906000f0801580156200c014573d6000803e3d6000fd5b50506040516200c024906200c1dc565b604051809103906000f0801580156200c041573d6000803e3d6000fd5b50506040516200c051906200c1dc565b604051809103906000f0801580156200c06e573d6000803e3d6000fd5b50506040516200c07e906200c1dc565b604051809103906000f0801580156200c09b573d6000803e3d6000fd5b50506040516200c0ab906200c1dc565b604051809103906000f0801580156200c0c8573d6000803e3d6000fd5b50506040516200c0d8906200c1dc565b604051809103906000f0801580156200c0f5573d6000803e3d6000fd5b50506040516200c105906200c1dc565b604051809103906000f0801580156200c122573d6000803e3d6000fd5b50506040516200c132906200c1dc565b604051809103906000f0801580156200c14f573d6000803e3d6000fd5b50506040516200c15f906200c1dc565b604051809103906000f0801580156200c17c573d6000803e3d6000fd5b50506040516200c18c906200c1dc565b604051809103906000f0801580156200c1a9573d6000803e3d6000fd5b50506040516200c1b9906200c1dc565b604051809103906000f0801580156200c1d6573d6000803e3d6000fd5b50505050565b60d7806200c1ea8339019056fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50609e806100396000396000f3fe6080604052600436106038577c010000000000000000000000000000000000000000000000000000000060003504631a6952308114603d575b600080fd5b606d60048036036020811015605157600080fd5b503573ffffffffffffffffffffffffffffffffffffffff16606f565b005b5056fea165627a7a7230582083f7a0331a259c77978d4e827b5b676f9e07ff2fa04be79c314e25873f3b11040029a165627a7a7230582084782da67a2e82014f2871d2e67c7a7d13b0595d88286112fb82e4f6ea3cf8700029" - code_Scenario015_TRC20_TRON = "6060604052604060405190810160405280600681526020017f54726f6e697800000000000000000000000000000000000000000000000000008152506000908051906020019062000052929190620001b6565b50604060405190810160405280600381526020017f545258000000000000000000000000000000000000000000000000000000000081525060019080519060200190620000a1929190620001b6565b50600660025560006005556000600660006101000a81548160ff0219169083151502179055506000600660016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555034156200011257fe5b5b33600660016101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555067016345785d8a000060058190555067016345785d8a0000600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505b62000265565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f10620001f957805160ff19168380011785556200022a565b828001600101855582156200022a579182015b82811115620002295782518255916020019190600101906200020c565b5b5090506200023991906200023d565b5090565b6200026291905b808211156200025e57600081600090555060010162000244565b5090565b90565b61111480620002756000396000f300606060405236156100ce576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806306fdde03146100d057806307da68f514610169578063095ea7b31461017b57806318160ddd146101d257806323b872dd146101f8578063313ce5671461026e57806342966c681461029457806370a08231146102b457806375f12b21146102fe57806395d89b4114610328578063a9059cbb146103c1578063be9a655514610418578063c47f00271461042a578063dd62ed3e14610484575bfe5b34156100d857fe5b6100e06104ed565b604051808060200182810382528381815181526020019150805190602001908083836000831461012f575b80518252602083111561012f5760208201915060208101905060208303925061010b565b505050905090810190601f16801561015b5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561017157fe5b61017961058b565b005b341561018357fe5b6101b8600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610603565b604051808215151515815260200191505060405180910390f35b34156101da57fe5b6101e26107cb565b6040518082815260200191505060405180910390f35b341561020057fe5b610254600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff169060200190919080359060200190919050506107d1565b604051808215151515815260200191505060405180910390f35b341561027657fe5b61027e610b11565b6040518082815260200191505060405180910390f35b341561029c57fe5b6102b26004808035906020019091905050610b17565b005b34156102bc57fe5b6102e8600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091905050610c3f565b6040518082815260200191505060405180910390f35b341561030657fe5b61030e610c57565b604051808215151515815260200191505060405180910390f35b341561033057fe5b610338610c6a565b6040518080602001828103825283818151815260200191508051906020019080838360008314610387575b80518252602083111561038757602082019150602081019050602083039250610363565b505050905090810190601f1680156103b35780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156103c957fe5b6103fe600480803573ffffffffffffffffffffffffffffffffffffffff16906020019091908035906020019091905050610d08565b604051808215151515815260200191505060405180910390f35b341561042057fe5b610428610f31565b005b341561043257fe5b610482600480803590602001908201803590602001908080601f01602080910402602001604051908101604052809392919081815260200183838082843782019150505050505091905050610fa9565b005b341561048c57fe5b6104d7600480803573ffffffffffffffffffffffffffffffffffffffff1690602001909190803573ffffffffffffffffffffffffffffffffffffffff1690602001909190505061101e565b6040518082815260200191505060405180910390f35b60008054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156105835780601f1061055857610100808354040283529160200191610583565b820191906000526020600020905b81548152906001019060200180831161056657829003601f168201915b505050505081565b3373ffffffffffffffffffffffffffffffffffffffff16600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415156105e457fe5b6001600660006101000a81548160ff0219169083151502179055505b5b565b6000600660009054906101000a900460ff1615151561061e57fe5b3373ffffffffffffffffffffffffffffffffffffffff1660001415151561064157fe5b60008214806106cc57506000600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054145b15156106d85760006000fd5b81600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a3600190505b5b5b92915050565b60055481565b6000600660009054906101000a900460ff161515156107ec57fe5b3373ffffffffffffffffffffffffffffffffffffffff1660001415151561080f57fe5b81600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015151561085e5760006000fd5b600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205401101515156108ee5760006000fd5b81600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020541015151561097a5760006000fd5b81600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555081600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600460008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b5b5b9392505050565b60025481565b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610b665760006000fd5b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825403925050819055508060036000600073ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254019250508190555060003373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040518082815260200191505060405180910390a35b50565b60036020528060005260406000206000915090505481565b600660009054906101000a900460ff1681565b60018054600181600116156101000203166002900480601f016020809104026020016040519081016040528092919081815260200182805460018160011615610100020316600290048015610d005780601f10610cd557610100808354040283529160200191610d00565b820191906000526020600020905b815481529060010190602001808311610ce357829003601f168201915b505050505081565b6000600660009054906101000a900460ff16151515610d2357fe5b3373ffffffffffffffffffffffffffffffffffffffff16600014151515610d4657fe5b81600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205410151515610d955760006000fd5b600360008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482600360008673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020540110151515610e255760006000fd5b81600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828254039250508190555081600360008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600082825401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a3600190505b5b5b92915050565b3373ffffffffffffffffffffffffffffffffffffffff16600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515610f8a57fe5b6000600660006101000a81548160ff0219169083151502179055505b5b565b3373ffffffffffffffffffffffffffffffffffffffff16600660019054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151561100257fe5b8060009080519060200190611018929190611043565b505b5b50565b6004602052816000526040600020602052806000526040600020600091509150505481565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061108457805160ff19168380011785556110b2565b828001600101855582156110b2579182015b828111156110b1578251825591602001919060010190611096565b5b5090506110bf91906110c3565b5090565b6110e591905b808211156110e15760008160009055506001016110c9565b5090565b905600a165627a7a723058204858328431ff0a4e0db74ff432e5805ce4bcf91a1c59650a93bd7c1aec5e0fe10029" - code_MainGateway = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50604051602080611df8833981016040818152915160008054600160a060020a0319163317815560016004819055600160a060020a0383168083526003602090815292869020805460ff191690921790915583529251909283927f51b292b9f000ae271c781ab0e5f63c49de0000ab30e186d92a03bbaf3325a4a3929081900390910190a15050611d38806100c06000396000f3006080604052600436106101195763ffffffff60e060020a6000350416630aa33f758114610144578063190791da146101935780634b398e991461021c5780635821563e1461022457806361857b441461022c578063715018a61461026a5780637276575c146102995780637ecebe00146102d7578063898de999146103245780638d3e651d146103535780638da5cb5b146103dc57806394042b46146104275780639435455f14610459578063a165302a14610499578063a8ced426146104d7578063bc2de9b01461055d578063bcad917b14610598578063cb912b1e14610650578063cd9df8e1146106d3578063d3d5177b14610702578063e77256f814610743578063e7fc18f8146107c6578063f2fde38b14610801575b620f4240d311156101315761012c61083c565b610142565b6000341115610142576101426108b4565b005b34801561015057600080fd5b50d3801561015d57600080fd5b50d2801561016a57600080fd5b5061017f600160a060020a0360043516610906565b604080519115158252519081900360200190f35b34801561019f57600080fd5b50d380156101ac57600080fd5b50d280156101b957600080fd5b50604080516020601f60643560048181013592830184900484028501840190955281845261014294600160a060020a0381358116956024803590921695604435953695608494019181908401838280828437509497506109489650505050505050565b6101426108b4565b61014261083c565b34801561023857600080fd5b50d3801561024557600080fd5b50d2801561025257600080fd5b50610142600435600160a060020a0360243516610cb2565b34801561027657600080fd5b50d3801561028357600080fd5b50d2801561029057600080fd5b50610142610e35565b3480156102a557600080fd5b50d380156102b257600080fd5b50d280156102bf57600080fd5b50610142600435600160a060020a0360243516610ea1565b3480156102e357600080fd5b50d380156102f057600080fd5b50d280156102fd57600080fd5b50610312600160a060020a0360043516610ff6565b60408051918252519081900360200190f35b34801561033057600080fd5b50d3801561033d57600080fd5b50d2801561034a57600080fd5b50610312611008565b34801561035f57600080fd5b50d3801561036c57600080fd5b50d2801561037957600080fd5b50604080516020601f60643560048181013592830184900484028501840190955281845261014294600160a060020a03813581169560248035909216956044359536956084940191819084018382808284375094975061100e9650505050505050565b3480156103e857600080fd5b50d380156103f557600080fd5b50d2801561040257600080fd5b5061040b6112ed565b60408051600160a060020a039092168252519081900360200190f35b34801561043357600080fd5b50d3801561044057600080fd5b50d2801561044d57600080fd5b506103126004356112fc565b34801561046557600080fd5b50d3801561047257600080fd5b50d2801561047f57600080fd5b50610142600160a060020a0360043516602435151561130e565b3480156104a557600080fd5b50d380156104b257600080fd5b50d280156104bf57600080fd5b5061017f600435600160a060020a0360243516611350565b3480156104e357600080fd5b50d380156104f057600080fd5b50d280156104fd57600080fd5b50604080516020601f60643560048181013592830184900484028501840190955281845261014294600160a060020a0381351694602480359560443595369560849493019181908401838280828437509497506113789650505050505050565b34801561056957600080fd5b50d3801561057657600080fd5b50d2801561058357600080fd5b5061040b600160a060020a036004351661163a565b3480156105a457600080fd5b50d380156105b157600080fd5b50d280156105be57600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845261061b948235600160a060020a03169460248035953695946064949201919081908401838280828437509497506116559650505050505050565b604080517fffffffff000000000000000000000000000000000000000000000000000000009092168252519081900360200190f35b34801561065c57600080fd5b50d3801561066957600080fd5b50d2801561067657600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845261061b948235600160a060020a031694602480359536959460649492019190819084018382808284375094975061172c9650505050505050565b3480156106df57600080fd5b50d380156106ec57600080fd5b50d280156106f957600080fd5b50610312611803565b34801561070e57600080fd5b50d3801561071b57600080fd5b50d2801561072857600080fd5b50610142600160a060020a0360043581169060243516611809565b34801561074f57600080fd5b50d3801561075c57600080fd5b50d2801561076957600080fd5b50604080516020600460443581810135601f8101849004840285018401909552848452610142948235600160a060020a03169460248035953695946064949201919081908401838280828437509497506118589650505050505050565b3480156107d257600080fd5b50d380156107df57600080fd5b50d280156107ec57600080fd5b50610312600160a060020a0360043516611af6565b34801561080d57600080fd5b50d3801561081a57600080fd5b50d2801561082757600080fd5b50610142600160a060020a0360043516611b11565bd360009081526006602052604090205461085c90d263ffffffff611b3416565bd3600081815260066020908152604091829020939093558051338152d29381019390935282810191909152517f752bc43ba57e4a49162727f5fb5d6f7b0e017826011a02a0b3cddcd70c49b1459181900360600190a1565b6005546108c7903463ffffffff611b3416565b6005556040805133815234602082015281517f1bab02886c659969cbb004cc17dc19be19f193323a306e26c669bedb29c651f7929181900390910190a1565b60008054600160a060020a038381169116141561092557506001610943565b50600160a060020a03811660009081526003602052604090205460ff165b919050565b83828483606060008061095a33610906565b151561096557600080fd5b6040805160028082526060820183529091602083019080388339505050600160a060020a03881660009081526002602052604081205482519295509185919081106109ac57fe5b6020908102909101015282518690849060019081106109c757fe5b906020019060200201818152505084836040516020018083600160a060020a0316600160a060020a03166c01000000000000000000000000028152601401828051906020019060200280838360005b83811015610a2e578181015183820152602001610a16565b50505050905001925050506040516020818303038152906040526040518082805190602001908083835b60208310610a775780518252601f199092019160209182019101610a58565b5181516020939093036101000a600019018019909116921691909117905260405192018290039091209450610ab29250849150869050611b4a565b9050600160a060020a0380821690881614610b05576040805160e560020a62461bcd02815260206004820152601e6024820152600080516020611ced833981519152604482015290519081900360640190fd5b600160a060020a038a1660009081526008602090815260408083208c845290915290205460ff161515610b82576040805160e560020a62461bcd02815260206004820152601260248201527f446f6573206e6f74206f776e20746f6b656e0000000000000000000000000000604482015290519081900360640190fd5b89600160a060020a031663a9059cbb8c8b6040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050600060405180830381600087803b158015610be557600080fd5b505af1158015610bf9573d6000803e3d6000fd5b505050600160a060020a03808c1660009081526008602090815260408083208e845290915290819020805460ff1916905551908d1691507f591f2d33d85291e32c4067b5a497caf3ddb5b1830eba9909e66006ec3a0051b4906003908d908d9080845b60ff168152600160a060020a0390931660208401525060408083019190915251908190036060019150a2505050600160a060020a0390931660009081526002602052604090208054600101905550505050505050565b600160a060020a03818116600090815260016020526040902054161515610d11576040805160e560020a62461bcd0281526020600482015260136024820152600080516020611ccd833981519152604482015290519081900360640190fd5b604080517f23b872dd000000000000000000000000000000000000000000000000000000008152336004820152306024820152604481018490529051600160a060020a038316916323b872dd9160648083019260209291908290030181600087803b158015610d7f57600080fd5b505af1158015610d93573d6000803e3d6000fd5b505050506040513d6020811015610da957600080fd5b5050600160a060020a038116600090815260076020526040902054610dd4908363ffffffff611b3416565b600160a060020a03821660008181526007602090815260409182902093909355805133815292830185905282810191909152517fe669217c299ce4efdf9b6269aaa41cc844a89016bdb0badde25a2e2f469cc3409181900360600190a15050565b600054600160a060020a03163314610e4c57600080fd5b60008054604051600160a060020a03909116917ff8df31144d9c2f0f6b59d69b8b98abd5459d07f2742c4df920b25aae33c6482091a26000805473ffffffffffffffffffffffffffffffffffffffff19169055565b600160a060020a03818116600090815260016020526040902054161515610f00576040805160e560020a62461bcd0281526020600482015260136024820152600080516020611ccd833981519152604482015290519081900360640190fd5b604080517f23b872dd000000000000000000000000000000000000000000000000000000008152336004820152306024820152604481018490529051600160a060020a038316916323b872dd91606480830192600092919082900301818387803b158015610f6d57600080fd5b505af1158015610f81573d6000803e3d6000fd5b505050600160a060020a0382166000818152600860209081526040808320878452825291829020805460ff19166001179055815133815290810186905280820192909252517fdf4b094c64ac1ec490d3302edb22d396ed9c1f23b14d2c307e04858399cc393292509081900360600190a15050565b60026020526000908152604090205481565b60045481565b83828483606060008061102033610906565b151561102b57600080fd5b6040805160028082526060820183529091602083019080388339505050600160a060020a038816600090815260026020526040812054825192955091859190811061107257fe5b60209081029091010152825186908490600190811061108d57fe5b906020019060200201818152505084836040516020018083600160a060020a0316600160a060020a03166c01000000000000000000000000028152601401828051906020019060200280838360005b838110156110f45781810151838201526020016110dc565b50505050905001925050506040516020818303038152906040526040518082805190602001908083835b6020831061113d5780518252601f19909201916020918201910161111e565b5181516020939093036101000a6000190180199091169216919091179052604051920182900390912094506111789250849150869050611b4a565b9050600160a060020a03808216908816146111cb576040805160e560020a62461bcd02815260206004820152601e6024820152600080516020611ced833981519152604482015290519081900360640190fd5b600160a060020a038a166000908152600760205260409020546111f4908a63ffffffff611be116565b600560020160008c600160a060020a0316600160a060020a031681526020019081526020016000208190555089600160a060020a031663a9059cbb8c8b6040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050602060405180830381600087803b15801561128357600080fd5b505af1158015611297573d6000803e3d6000fd5b505050506040513d60208110156112ad57600080fd5b5050604051600160a060020a038c16907f591f2d33d85291e32c4067b5a497caf3ddb5b1830eba9909e66006ec3a0051b4906002908d908d908084610c5c565b600054600160a060020a031681565b60009081526006602052604090205490565b600054600160a060020a0316331461132557600080fd5b600160a060020a03919091166000908152600360205260409020805460ff1916911515919091179055565b600160a060020a03166000908152600860209081526040808320938352929052205460ff1690565b83828483606060008061138a33610906565b151561139557600080fd5b604080516003808252608082019092529060208201606080388339019050509250848360008151811015156113c657fe5b6020908102909101810191909152600160a060020a0388166000908152600290915260409020548351849060019081106113fc57fe5b60209081029091010152825186908490600290811061141757fe5b90602001906020020181815250508260405160200180828051906020019060200280838360005b8381101561145657818101518382015260200161143e565b505050509050019150506040516020818303038152906040526040518082805190602001908083835b6020831061149e5780518252601f19909201916020918201910161147f565b5181516020939093036101000a6000190180199091169216919091179052604051920182900390912094506114d99250849150869050611b4a565b9050600160a060020a038082169088161461152c576040805160e560020a62461bcd02815260206004820152601e6024820152600080516020611ced833981519152604482015290519081900360640190fd5b60008a81526006602052604090205461154b908a63ffffffff611be116565b60008b815260066020526040902055600160a060020a038b1689156108fc028a8c8015801561157957600080fd5b50806780000000000000001115801561159157600080fd5b5080620f4240101580156115a457600080fd5b50604051600081818185878a8ad09450505050501580156115c9573d6000803e3d6000fd5b506040805160018152602081018c90528082018b9052905133917f472adea2ebbd52a19b140bc25ddcbbe8d3317953a32da818924bab945e4709b1919081900360600190a2505050600160a060020a0390931660009081526002602052604090208054600101905550505050505050565b600160205260009081526040902054600160a060020a031681565b33600090815260016020526040812054600160a060020a031615156116b2576040805160e560020a62461bcd0281526020600482015260136024820152600080516020611ccd833981519152604482015290519081900360640190fd5b6116bb83611bf6565b60408051600160a060020a038616815260208101859052338183015290517fe669217c299ce4efdf9b6269aaa41cc844a89016bdb0badde25a2e2f469cc3409181900360600190a1507fbcad917b000000000000000000000000000000000000000000000000000000009392505050565b33600090815260016020526040812054600160a060020a03161515611789576040805160e560020a62461bcd0281526020600482015260136024820152600080516020611ccd833981519152604482015290519081900360640190fd5b61179283611c29565b60408051600160a060020a038616815260208101859052338183015290517fdf4b094c64ac1ec490d3302edb22d396ed9c1f23b14d2c307e04858399cc39329181900360600190a1507fcb912b1e000000000000000000000000000000000000000000000000000000009392505050565b60055490565b61181233610906565b151561181d57600080fd5b600160a060020a039182166000908152600160205260409020805473ffffffffffffffffffffffffffffffffffffffff191691909216179055565b82823083606060008061186a33610906565b151561187557600080fd5b6040805160028082526060820183529091602083019080388339505050600160a060020a03881660009081526002602052604081205482519295509185919081106118bc57fe5b6020908102909101015282518690849060019081106118d757fe5b906020019060200201818152505084836040516020018083600160a060020a0316600160a060020a03166c01000000000000000000000000028152601401828051906020019060200280838360005b8381101561193e578181015183820152602001611926565b50505050905001925050506040516020818303038152906040526040518082805190602001908083835b602083106119875780518252601f199092019160209182019101611968565b5181516020939093036101000a6000190180199091169216919091179052604051920182900390912094506119c29250849150869050611b4a565b9050600160a060020a0380821690881614611a15576040805160e560020a62461bcd02815260206004820152601e6024820152600080516020611ced833981519152604482015290519081900360640190fd5b600554611a28908a63ffffffff611be116565b600555604051600160a060020a038b16908a156108fc02908b906000818181858888f19350505050158015611a61573d6000803e3d6000fd5b5089600160a060020a03167f591f2d33d85291e32c4067b5a497caf3ddb5b1830eba9909e66006ec3a0051b46000808c60405180846003811115611aa157fe5b60ff168152600160a060020a0390931660208401525060408083019190915251908190036060019150a2505050600160a060020a03909316600090815260026020526040902080546001019055505050505050565b600160a060020a031660009081526007602052604090205490565b600054600160a060020a03163314611b2857600080fd5b611b3181611c4f565b50565b81810182811015611b4457600080fd5b92915050565b60208101516040820151604183015160009260ff90911691601b831015611b7257601b830192505b60408051600080825260208083018085528a905260ff8716838501526060830186905260808301859052925160019360a0808501949193601f19840193928390039091019190865af1158015611bcc573d6000803e3d6000fd5b5050604051601f190151979650505050505050565b600082821115611bf057600080fd5b50900390565b33600090815260076020526040902054611c16908263ffffffff611b3416565b3360009081526007602052604090205550565b33600090815260086020908152604080832093835292905220805460ff19166001179055565b600160a060020a0381161515611c6457600080fd5b60008054604051600160a060020a03808516939216917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e091a36000805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a039290921691909117905556004e6f7420616e20616c6c6f776520746f6b656e000000000000000000000000004d657373616765206e6f74207369676e65642062792061206761696e65720000a165627a7a723058205cb7d7406fcca2093208cdfb8fa6d9a1ce5e4ae6b526286910d1b63990e322030029" - code_SideGateway = "608060405260068054600160a060020a03199081166201000017909155600780549091166201000117905534801561003657600080fd5b50d3801561004357600080fd5b50d2801561005057600080fd5b50604051602080613c54833981016040908152905160048054600160a060020a03191633179055600160a060020a03166000908152600360205220805460ff19166001179055613baf806100a56000396000f300608060405260043610620001195763ffffffff60e060020a6000350416630a61c59f81146200011e5780630bb0482f14620001605780630f40ef09146200028e5780631f1767eb14620002dc57806331775cc6146200032e578063455042361462000377578063473c3bd714620003c257806355781fcf146200041e57806367bf590314620005175780637ce67366146200054b5780638da5cb5b14620005ce5780639435455f1462000602578063ab15bdf81462000647578063addd5099146200073b578063bcad917b146200077b578063cb912b1e1462000838578063db13a12b14620008c0578063ded8454a1462000900578063ede1a1e91462000940578063eff457d2146200098e578063fce16fec14620009d1575b600080fd5b3480156200012b57600080fd5b50d380156200013957600080fd5b50d280156200014757600080fd5b506200015e600160a060020a036004351662000a1a565b005b3480156200016d57600080fd5b50d380156200017b57600080fd5b50d280156200018957600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200021694369492936024939284019190819084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a99988101979196509182019450925082915084018382808284375094975062000ac29650505050505050565b6040805160208082528351818301528351919283929083019185019080838360005b838110156200025257818101518382015260200162000238565b50505050905090810190601f168015620002805780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b6040805160206004803580820135601f81018490048402850184019095528484526200015e94369492936024939284019190819084018382808284375094975062000bb49650505050505050565b348015620002e957600080fd5b50d38015620002f757600080fd5b50d280156200030557600080fd5b506200015e600160a060020a036004351660243560443560643560843560ff60a4351662000ca3565b3480156200033b57600080fd5b50d380156200034957600080fd5b50d280156200035757600080fd5b506200015e600160a060020a036004358116906024351660443562000e9c565b3480156200038457600080fd5b50d380156200039257600080fd5b50d28015620003a057600080fd5b50620003ae60043562001022565b604080519115158252519081900360200190f35b348015620003cf57600080fd5b50d38015620003dd57600080fd5b50d28015620003eb57600080fd5b5062000402600160a060020a036004351662001037565b60408051600160a060020a039092168252519081900360200190f35b3480156200042b57600080fd5b50d380156200043957600080fd5b50d280156200044757600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200040294369492936024939284019190819084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a99988101979196509182019450925082915084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a9998810197919650918201945092508291508401838280828437509497505050923560ff1693506200105292505050565b3480156200052457600080fd5b50d380156200053257600080fd5b50d280156200054057600080fd5b506200040262001344565b3480156200055857600080fd5b50d380156200056657600080fd5b50d280156200057457600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200040294369492936024939284019190819084018382808284375094975050509235600160a060020a031693506200135392505050565b348015620005db57600080fd5b50d38015620005e957600080fd5b50d28015620005f757600080fd5b5062000402620013da565b3480156200060f57600080fd5b50d380156200061d57600080fd5b50d280156200062b57600080fd5b506200015e600160a060020a03600435166024351515620013e9565b3480156200065457600080fd5b50d380156200066257600080fd5b50d280156200067057600080fd5b506040805160206004803580820135601f81018490048402850184019095528484526200040294369492936024939284019190819084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a99988101979196509182019450925082915084018382808284375050604080516020601f89358b018035918201839004830284018301909452808352979a9998810197919650918201945092508291508401838280828437509497506200142c9650505050505050565b3480156200074857600080fd5b50d380156200075657600080fd5b50d280156200076457600080fd5b50620003ae600160a060020a036004351662001712565b3480156200078857600080fd5b50d380156200079657600080fd5b50d28015620007a457600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845262000803948235600160a060020a0316946024803595369594606494920191908190840183828082843750949750620017279650505050505050565b604080517fffffffff000000000000000000000000000000000000000000000000000000009092168252519081900360200190f35b3480156200084557600080fd5b50d380156200085357600080fd5b50d280156200086157600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845262000803948235600160a060020a0316946024803595369594606494920191908190840183828082843750949750620019019650505050505050565b348015620008cd57600080fd5b50d38015620008db57600080fd5b50d28015620008e957600080fd5b5062000402600160a060020a036004351662001b01565b3480156200090d57600080fd5b50d380156200091b57600080fd5b50d280156200092957600080fd5b5062000216600160a060020a036004351662001b1c565b6040805160206004803580820135601f81018490048402850184019095528484526200015e94369492936024939284019190819084018382808284375094975062001b519650505050505050565b3480156200099b57600080fd5b50d38015620009a957600080fd5b50d28015620009b757600080fd5b506200015e600160a060020a036004351660243562001cf1565b348015620009de57600080fd5b50d38015620009ec57600080fd5b50d28015620009fa57600080fd5b506200015e600160a060020a036004358116906024351660443562001dbf565b600454600160a060020a0316331462000a3257600080fd5b600160a060020a038116151562000a93576040805160e560020a62461bcd02815260206004820152601e60248201527f5f73756e546f6b656e41646472657373203d3d20616464726573732830290000604482015290519081900360640190fd5b6005805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0392909216919091179055565b6060826041836040516020018084805190602001908083835b6020831062000afc5780518252601f19909201916020918201910162000adb565b6001836020036101000a0380198251168184511680821785525050505050509050018360ff167f010000000000000000000000000000000000000000000000000000000000000002815260010182805190602001908083835b6020831062000b765780518252601f19909201916020918201910162000b55565b6001836020036101000a0380198251168184511680821785525050505050509050019350505050604051602081830303815290604052905092915050565b6040516000903480156108fc029183818181858288f1935050505015801562000be1573d6000803e3d6000fd5b507f7a47a70a1221ce1b92f8d000c55e2c92c0255a381cf1be25c3ca697593ecc96a3334836040518084600160a060020a0316600160a060020a0316815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101562000c6357818101518382015260200162000c49565b50505050905090810190601f16801562000c915780820380516001836020036101000a031916815260200191505b5094505050505060405180910390a150565b3360009081526003602052604081205460ff16151562000cc257600080fd5b620f42408611801562000cd85750621e84808611155b151562000d55576040805160e560020a62461bcd02815260206004820152602360248201527f7472633130203c3d2031303030303030206f72207472633130203e203230303060448201527f3030300000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b5060008581526002602052604090205460ff1680151562000d8a576000868152600260205260409020805460ff191660011790555b60075460408051878152602081018990528082018790526060810186905260ff851660808201529051600160a060020a039092169160a0808301926000929190829003018183865af1505050600160a060020a0387166108fc86150286888015801562000df657600080fd5b50806780000000000000001115801562000e0f57600080fd5b5080620f42401015801562000e2357600080fd5b50604051600081818185878a8ad094505050505015801562000e49573d6000803e3d6000fd5b5060408051600160a060020a03891681526020810188905280820187905290517f4aac44dc080543b9fe45d9dfaad396001ee0ecdc07499d64e2e798bfffc42fde9181900360600190a150505050505050565b3360009081526003602052604081205460ff16151562000ebb57600080fd5b50600160a060020a038083166000908152602081905260409020541680151562000f54576040805160e560020a62461bcd028152602060048201526024808201527f746865206d61696e20636861696e2061646472657373206861736e2774206d6160448201527f7070656400000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b80600160a060020a03166340c10f1985846040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050600060405180830381600087803b15801562000fb857600080fd5b505af115801562000fcd573d6000803e3d6000fd5b505060408051600160a060020a0380861682528816602082015280820186905290517f48c104169bad147dfc9c0b2ac8fc83202a035d4d9632e24e839680be759772089350908190036060019150a150505050565b60026020526000908152604090205460ff1681565b600060208190529081526040902054600160a060020a031681565b600080600062001063873362001353565b600160a060020a038082166000908152602081905260409020549193501615620010fd576040805160e560020a62461bcd02815260206004820152602160248201527f746865206d61696e20636861696e206164647265737320686173206d6170706560448201527f6400000000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b600554600160a060020a03838116911614156200118a576040805160e560020a62461bcd02815260206004820152602360248201527f6d61696e436861696e41646472657373203d3d2073756e546f6b656e4164647260448201527f6573730000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b308686866200119862001f45565b600160a060020a038516815260ff82166060820152608060208083018281528651928401929092528551604084019160a08501919088019080838360005b83811015620011f0578181015183820152602001620011d6565b50505050905090810190601f1680156200121e5780820380516001836020036101000a031916815260200191505b50838103825285518152855160209182019187019080838360005b838110156200125357818101518382015260200162001239565b50505050905090810190601f168015620012815780820380516001836020036101000a031916815260200191505b509650505050505050604051809103906000f080158015620012a7573d6000803e3d6000fd5b50600160a060020a03808416600081815260208181526040808320805495871673ffffffffffffffffffffffffffffffffffffffff1996871681179091558084526001835292819020805490951684179094558351338152908101929092528183015290519192507fee201bea1b0aff77f5f792b979e4732ba6605c2203d0f92f9aa45625eff88222919081900360600190a19695505050505050565b600554600160a060020a031681565b6000606080620013638462001b1c565b915062001371858362000ac2565b9050806040518082805190602001908083835b60208310620013a55780518252601f19909201916020918201910162001384565b5181516020939093036101000a6000190180199091169216919091179052604051920182900390912098975050505050505050565b600454600160a060020a031681565b600454600160a060020a031633146200140157600080fd5b600160a060020a03919091166000908152600360205260409020805460ff1916911515919091179055565b60008060006200143d863362001353565b600160a060020a038082166000908152602081905260409020549193501615620014d7576040805160e560020a62461bcd02815260206004820152602160248201527f746865206d61696e20636861696e206164647265737320686173206d6170706560448201527f6400000000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b600554600160a060020a038381169116141562001564576040805160e560020a62461bcd02815260206004820152602360248201527f6d61696e436861696e41646472657373203d3d2073756e546f6b656e4164647260448201527f6573730000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b3085856200157162001f56565b600160a060020a0384168152606060208083018281528551928401929092528451604084019160808501919087019080838360005b83811015620015c0578181015183820152602001620015a6565b50505050905090810190601f168015620015ee5780820380516001836020036101000a031916815260200191505b50838103825284518152845160209182019186019080838360005b838110156200162357818101518382015260200162001609565b50505050905090810190601f168015620016515780820380516001836020036101000a031916815260200191505b5095505050505050604051809103906000f08015801562001676573d6000803e3d6000fd5b50600160a060020a03808416600081815260208181526040808320805495871673ffffffffffffffffffffffffffffffffffffffff1996871681179091558084526001835292819020805490951684179094558351338152908101929092528183015290519192507fa2399d6f422f35b470d7aff96f7b2d8ce1c07bc14d978c9fbad6083461c564a7919081900360600190a195945050505050565b60036020526000908152604090205460ff1681565b33600081815260016020526040812054909190600160a060020a03168015156200179b576040805160e560020a62461bcd02815260206004820152601e60248201527f6d61696e436861696e41646472657373203d3d20616464726573732830290000604482015290519081900360640190fd5b81600160a060020a03166342966c68866040518263ffffffff1660e060020a02815260040180828152602001915050600060405180830381600087803b158015620017e557600080fd5b505af1158015620017fa573d6000803e3d6000fd5b505050507fc7b54407df97321a6170a99eeb667db3dc95205c9a9b12a4f1673bac84066544868683876040518085600160a060020a0316600160a060020a0316815260200184815260200183600160a060020a0316600160a060020a0316815260200180602001828103825283818151815260200191508051906020019080838360005b83811015620018985781810151838201526020016200187e565b50505050905090810190601f168015620018c65780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1507fbcad917b0000000000000000000000000000000000000000000000000000000095945050505050565b33600081815260016020526040812054909190600160a060020a03168015156200199b576040805160e560020a62461bcd02815260206004820152602360248201527f74686520747263373231206d7573742068617665206265656e206465706f736960448201527f7465640000000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b81600160a060020a03166342966c68866040518263ffffffff1660e060020a02815260040180828152602001915050600060405180830381600087803b158015620019e557600080fd5b505af1158015620019fa573d6000803e3d6000fd5b505050507fa93bdc38faeb2081566bca9d2c041ba1545a11a459c67a8baf5c671a262e9b7c868683876040518085600160a060020a0316600160a060020a0316815260200184815260200183600160a060020a0316600160a060020a0316815260200180602001828103825283818151815260200191508051906020019080838360005b8381101562001a9857818101518382015260200162001a7e565b50505050905090810190601f16801562001ac65780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a1507fcb912b1e0000000000000000000000000000000000000000000000000000000095945050505050565b600160205260009081526040902054600160a060020a031681565b60408051600160a060020a03929092167414000000000000000000000000000000000000000018601483015260348201905290565bd360009081526002602052604090205460ff16151562001bbb576040805160e560020a62461bcd02815260206004820152601e60248201527f74726331304d61705b6d73672e746f6b656e69645d203d3d2066616c73650000604482015290519081900360640190fd5b6000d280156108fc0290d38015801562001bd457600080fd5b50806780000000000000001115801562001bed57600080fd5b5080620f42401015801562001c0157600080fd5b50604051600081818185878a8ad094505050505015801562001c27573d6000803e3d6000fd5b507f4cdc0dc16c2640bf1cbeebfe9055747d6c36b74120ed1d06440846a8150cc4c333d2d3846040518085600160a060020a0316600160a060020a0316815260200184815260200183815260200180602001828103825283818151815260200191508051906020019080838360005b8381101562001cb057818101518382015260200162001c96565b50505050905090810190601f16801562001cde5780820380516001836020036101000a031916815260200191505b509550505050505060405180910390a150565b3360009081526003602052604090205460ff16151562001d1057600080fd5b600654604080518381529051600160a060020a03909216916020808301926000929190829003018183865af15050604051600160a060020a038416915082156108fc029083906000818181858888f1935050505015801562001d76573d6000803e3d6000fd5b5060408051600160a060020a03841681526020810183905281517f0e3147459e9437f793e793b98df267ee885cfe4ad096b279287f03dcd0ca0497929181900390910190a15050565b3360009081526003602052604081205460ff16151562001dde57600080fd5b50600160a060020a038083166000908152602081905260409020541680151562001e77576040805160e560020a62461bcd028152602060048201526024808201527f746865206d61696e20636861696e2061646472657373206861736e2774206d6160448201527f7070656400000000000000000000000000000000000000000000000000000000606482015290519081900360840190fd5b80600160a060020a03166340c10f1985846040518363ffffffff1660e060020a0281526004018083600160a060020a0316600160a060020a0316815260200182815260200192505050600060405180830381600087803b15801562001edb57600080fd5b505af115801562001ef0573d6000803e3d6000fd5b505060408051600160a060020a0380861682528816602082015280820186905290517fb49dbda83c867b85d55c88d22a084e7db05c8a29e16d027af1b02105906d16bc9350908190036060019150a150505050565b604051610d7c8062001f6883390190565b604051610ea08062002ce4833901905600608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50604051610d7c380380610d7c833981016040908152815160208084015192840151606085015160038054600160a060020a031916600160a060020a0386161790559385018051939590949101929091610089916004918601906100bf565b50815161009d9060059060208501906100bf565b506006805460ff191660ff92909216919091179055505060006002555061015a565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061010057805160ff191683800117855561012d565b8280016001018555821561012d579182015b8281111561012d578251825591602001919060010190610112565b5061013992915061013d565b5090565b61015791905b808211156101395760008155600101610143565b90565b610c13806101696000396000f3006080604052600436106100da5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100df578063095ea7b314610183578063116191b6146101d557806318160ddd1461022057806323b872dd14610261578063313ce567146102a557806339509351146102ea57806340c10f191461032857806342966c681461036857806349e118931461039a57806370a082311461041257806395d89b411461044d578063a457c2d71461047c578063a9059cbb146104ba578063dd62ed3e146104f8575b600080fd5b3480156100eb57600080fd5b50d380156100f857600080fd5b50d2801561010557600080fd5b5061010e610539565b6040805160208082528351818301528351919283929083019185019080838360005b83811015610148578181015183820152602001610130565b50505050905090810190601f1680156101755780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561018f57600080fd5b50d3801561019c57600080fd5b50d280156101a957600080fd5b506101c1600160a060020a03600435166024356105c7565b604080519115158252519081900360200190f35b3480156101e157600080fd5b50d380156101ee57600080fd5b50d280156101fb57600080fd5b506102046105dd565b60408051600160a060020a039092168252519081900360200190f35b34801561022c57600080fd5b50d3801561023957600080fd5b50d2801561024657600080fd5b5061024f6105ec565b60408051918252519081900360200190f35b34801561026d57600080fd5b50d3801561027a57600080fd5b50d2801561028757600080fd5b506101c1600160a060020a03600435811690602435166044356105f2565b3480156102b157600080fd5b50d380156102be57600080fd5b50d280156102cb57600080fd5b506102d4610649565b6040805160ff9092168252519081900360200190f35b3480156102f657600080fd5b50d3801561030357600080fd5b50d2801561031057600080fd5b506101c1600160a060020a0360043516602435610652565b34801561033457600080fd5b50d3801561034157600080fd5b50d2801561034e57600080fd5b50610366600160a060020a036004351660243561068e565b005b34801561037457600080fd5b50d3801561038157600080fd5b50d2801561038e57600080fd5b5061036660043561074f565b3480156103a657600080fd5b50d380156103b357600080fd5b50d280156103c057600080fd5b5060408051602060046024803582810135601f810185900485028601850190965285855261036695833595369560449491939091019190819084018382808284375094975061075c9650505050505050565b34801561041e57600080fd5b50d3801561042b57600080fd5b50d2801561043857600080fd5b5061024f600160a060020a03600435166108d0565b34801561045957600080fd5b50d3801561046657600080fd5b50d2801561047357600080fd5b5061010e6108eb565b34801561048857600080fd5b50d3801561049557600080fd5b50d280156104a257600080fd5b506101c1600160a060020a0360043516602435610946565b3480156104c657600080fd5b50d380156104d357600080fd5b50d280156104e057600080fd5b506101c1600160a060020a0360043516602435610982565b34801561050457600080fd5b50d3801561051157600080fd5b50d2801561051e57600080fd5b5061024f600160a060020a036004358116906024351661098f565b6004805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105bf5780601f10610594576101008083540402835291602001916105bf565b820191906000526020600020905b8154815290600101906020018083116105a257829003601f168201915b505050505081565b60006105d43384846109ba565b50600192915050565b600354600160a060020a031681565b60025490565b60006105ff848484610a46565b600160a060020a03841660009081526001602090815260408083203380855292529091205461063f91869161063a908663ffffffff610b1316565b6109ba565b5060019392505050565b60065460ff1681565b336000818152600160209081526040808320600160a060020a038716845290915281205490916105d491859061063a908663ffffffff610b2816565b600354600160a060020a031633146106a557600080fd5b600160a060020a03821615156106ba57600080fd5b6002546106cd908263ffffffff610b2816565b600255600160a060020a0382166000908152602081905260409020546106f9908263ffffffff610b2816565b600160a060020a0383166000818152602081815260408083209490945583518581529351929391927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9281900390910190a35050565b6107593382610b3e565b50565b60035460009061077590600160a060020a031684610982565b506003546040517fbcad917b000000000000000000000000000000000000000000000000000000008152336004820181815260248301879052606060448401908152865160648501528651600160a060020a039095169463bcad917b94899389939092909160840190602085019080838360005b838110156108015781810151838201526020016107e9565b50505050905090810190601f16801561082e5780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561084f57600080fd5b505af1158015610863573d6000803e3d6000fd5b505050506040513d602081101561087957600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167fbcad917b00000000000000000000000000000000000000000000000000000000146108cb57600080fd5b505050565b600160a060020a031660009081526020819052604090205490565b6005805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105bf5780601f10610594576101008083540402835291602001916105bf565b336000818152600160209081526040808320600160a060020a038716845290915281205490916105d491859061063a908663ffffffff610b1316565b60006105d4338484610a46565b600160a060020a03918216600090815260016020908152604080832093909416825291909152205490565b600160a060020a03821615156109cf57600080fd5b600160a060020a03831615156109e457600080fd5b600160a060020a03808416600081815260016020908152604080832094871680845294825291829020859055815185815291517f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259281900390910190a3505050565b600160a060020a0382161515610a5b57600080fd5b600160a060020a038316600090815260208190526040902054610a84908263ffffffff610b1316565b600160a060020a038085166000908152602081905260408082209390935590841681522054610ab9908263ffffffff610b2816565b600160a060020a038084166000818152602081815260409182902094909455805185815290519193928716927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef92918290030190a3505050565b600082821115610b2257600080fd5b50900390565b81810182811015610b3857600080fd5b92915050565b600160a060020a0382161515610b5357600080fd5b600254610b66908263ffffffff610b1316565b600255600160a060020a038216600090815260208190526040902054610b92908263ffffffff610b1316565b600160a060020a038316600081815260208181526040808320949094558351858152935191937fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929081900390910190a350505600a165627a7a7230582030edf24eb27134d7c77898452315198f9886970c7fed0049b49cd05f121562db0029608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060405162000ea038038062000ea083398101604090815281516020808401519284015160048054600160a060020a031916600160a060020a038516179055928401805192949093019161008491600591908501906100a1565b5080516100989060069060208401906100a1565b5050505061013c565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100e257805160ff191683800117855561010f565b8280016001018555821561010f579182015b8281111561010f5782518255916020019190600101906100f4565b5061011b92915061011f565b5090565b61013991905b8082111561011b5760008155600101610125565b90565b610d54806200014c6000396000f3006080604052600436106100cf5763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100d4578063081812fc14610178578063095ea7b3146101c6578063116191b61461020657806323b872dd1461023557806340c10f191461027957806342966c68146102b757806349e11893146102e95780636352211e1461036157806370a082311461039357806395d89b41146103e0578063a22cb4651461040f578063a9059cbb1461044f578063e985e9c51461048d575b600080fd5b3480156100e057600080fd5b50d380156100ed57600080fd5b50d280156100fa57600080fd5b506101036104e2565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561013d578181015183820152602001610125565b50505050905090810190601f16801561016a5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561018457600080fd5b50d3801561019157600080fd5b50d2801561019e57600080fd5b506101aa600435610570565b60408051600160a060020a039092168252519081900360200190f35b3480156101d257600080fd5b50d380156101df57600080fd5b50d280156101ec57600080fd5b50610204600160a060020a03600435166024356105a2565b005b34801561021257600080fd5b50d3801561021f57600080fd5b50d2801561022c57600080fd5b506101aa610658565b34801561024157600080fd5b50d3801561024e57600080fd5b50d2801561025b57600080fd5b50610204600160a060020a0360043581169060243516604435610667565b34801561028557600080fd5b50d3801561029257600080fd5b50d2801561029f57600080fd5b50610204600160a060020a036004351660243561068c565b3480156102c357600080fd5b50d380156102d057600080fd5b50d280156102dd57600080fd5b50610204600435610763565b3480156102f557600080fd5b50d3801561030257600080fd5b50d2801561030f57600080fd5b5060408051602060046024803582810135601f81018590048502860185019096528585526102049583359536956044949193909101919081908401838280828437509497506107709650505050505050565b34801561036d57600080fd5b50d3801561037a57600080fd5b50d2801561038757600080fd5b506101aa6004356108e0565b34801561039f57600080fd5b50d380156103ac57600080fd5b50d280156103b957600080fd5b506103ce600160a060020a036004351661090a565b60408051918252519081900360200190f35b3480156103ec57600080fd5b50d380156103f957600080fd5b50d2801561040657600080fd5b5061010361093d565b34801561041b57600080fd5b50d3801561042857600080fd5b50d2801561043557600080fd5b50610204600160a060020a03600435166024351515610998565b34801561045b57600080fd5b50d3801561046857600080fd5b50d2801561047557600080fd5b50610204600160a060020a0360043516602435610a1c565b34801561049957600080fd5b50d380156104a657600080fd5b50d280156104b357600080fd5b506104ce600160a060020a0360043581169060243516610a2b565b604080519115158252519081900360200190f35b6005805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105685780601f1061053d57610100808354040283529160200191610568565b820191906000526020600020905b81548152906001019060200180831161054b57829003601f168201915b505050505081565b600061057b82610a59565b151561058657600080fd5b50600090815260016020526040902054600160a060020a031690565b60006105ad826108e0565b9050600160a060020a0383811690821614156105c857600080fd5b33600160a060020a03821614806105e457506105e48133610a2b565b15156105ef57600080fd5b600082815260016020526040808220805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a0387811691821790925591518593918516917f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591a4505050565b600454600160a060020a031681565b6106713382610a76565b151561067c57600080fd5b610687838383610ad5565b505050565b600454600160a060020a031633146106a357600080fd5b600160a060020a03821615156106b857600080fd5b6106c181610a59565b156106cb57600080fd5b600081815260208181526040808320805473ffffffffffffffffffffffffffffffffffffffff1916600160a060020a03871690811790915583526002909152902054610718906001610bf0565b600160a060020a0383166000818152600260205260408082209390935591518392907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908290a45050565b61076d3382610c00565b50565b60045460009061078990600160a060020a031684610a1c565b600480546040517fcb912b1e0000000000000000000000000000000000000000000000000000000081523392810183815260248201879052606060448301908152865160648401528651600160a060020a039094169463cb912b1e949093899389939092909160840190602085019080838360005b838110156108165781810151838201526020016107fe565b50505050905090810190601f1680156108435780820380516001836020036101000a031916815260200191505b50945050505050602060405180830381600087803b15801561086457600080fd5b505af1158015610878573d6000803e3d6000fd5b505050506040513d602081101561088e57600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167fcb912b1e000000000000000000000000000000000000000000000000000000001461068757600080fd5b600081815260208190526040812054600160a060020a031680151561090457600080fd5b92915050565b6000600160a060020a038216151561092157600080fd5b50600160a060020a031660009081526002602052604090205490565b6006805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156105685780601f1061053d57610100808354040283529160200191610568565b600160a060020a0382163314156109ae57600080fd5b336000818152600360209081526040808320600160a060020a03871680855290835292819020805460ff1916861515908117909155815190815290519293927f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31929181900390910190a35050565b610a27338383610ad5565b5050565b600160a060020a03918216600090815260036020908152604080832093909416825291909152205460ff1690565b600090815260208190526040902054600160a060020a0316151590565b600080610a82836108e0565b905080600160a060020a031684600160a060020a03161480610abd575083600160a060020a0316610ab284610570565b600160a060020a0316145b80610acd5750610acd8185610a2b565b949350505050565b82600160a060020a0316610ae8826108e0565b600160a060020a031614610afb57600080fd5b600160a060020a0382161515610b1057600080fd5b610b1981610ccb565b600160a060020a038316600090815260026020526040902054610b4390600163ffffffff610d1316565b600160a060020a038085166000908152600260205260408082209390935590841681522054610b7990600163ffffffff610bf016565b600160a060020a03808416600081815260026020908152604080832095909555858252819052838120805473ffffffffffffffffffffffffffffffffffffffff1916831790559251849391928716917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef91a4505050565b8181018281101561090457600080fd5b81600160a060020a0316610c13826108e0565b600160a060020a031614610c2657600080fd5b610c2f81610ccb565b600160a060020a038216600090815260026020526040902054610c5990600163ffffffff610d1316565b600160a060020a038316600081815260026020908152604080832094909455848252819052828120805473ffffffffffffffffffffffffffffffffffffffff191690559151839291907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908390a45050565b600081815260016020526040902054600160a060020a03161561076d576000908152600160205260409020805473ffffffffffffffffffffffffffffffffffffffff19169055565b600082821115610d2257600080fd5b509003905600a165627a7a72305820e95bf2b25cae43edb66a8c2c9a5784778a3163ec94f09ffb86ca32624f6a8b1b0029a165627a7a72305820642e8c16e0d0768025001430bcf8dea875428b07fc9214f0b1b37c74a5b34c660029" - code_shieldTrc20Token = "60806040526002805460ff1916600617905534801561001d57600080fd5b506040516109a53803806109a583398101604090815281516020808401518385015160025460ff16600a0a84026003819055336000908152600485529586205590850180519395909491019261007592850190610092565b508051610089906001906020840190610092565b5050505061012d565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106100d357805160ff1916838001178555610100565b82800160010185558215610100579182015b828111156101005782518255916020019190600101906100e5565b5061010c929150610110565b5090565b61012a91905b8082111561010c5760008155600101610116565b90565b6108698061013c6000396000f3006080604052600436106100b95763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100be578063095ea7b31461014857806318160ddd1461018057806323b872dd146101a7578063313ce567146101d157806342966c68146101fc57806370a082311461021457806379cc67901461023557806395d89b4114610259578063a9059cbb1461026e578063cae9ca5114610292578063dd62ed3e146102fb575b600080fd5b3480156100ca57600080fd5b506100d3610322565b6040805160208082528351818301528351919283929083019185019080838360005b8381101561010d5781810151838201526020016100f5565b50505050905090810190601f16801561013a5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561015457600080fd5b5061016c600160a060020a03600435166024356103b0565b604080519115158252519081900360200190f35b34801561018c57600080fd5b506101956103dd565b60408051918252519081900360200190f35b3480156101b357600080fd5b5061016c600160a060020a03600435811690602435166044356103e3565b3480156101dd57600080fd5b506101e6610453565b6040805160ff9092168252519081900360200190f35b34801561020857600080fd5b5061016c60043561045c565b34801561022057600080fd5b50610195600160a060020a03600435166104d4565b34801561024157600080fd5b5061016c600160a060020a03600435166024356104e6565b34801561026557600080fd5b506100d36105b7565b34801561027a57600080fd5b5061016c600160a060020a0360043516602435610611565b34801561029e57600080fd5b50604080516020600460443581810135601f810184900484028501840190955284845261016c948235600160a060020a03169460248035953695946064949201919081908401838280828437509497506106259650505050505050565b34801561030757600080fd5b50610195600160a060020a036004358116906024351661073e565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103a85780601f1061037d576101008083540402835291602001916103a8565b820191906000526020600020905b81548152906001019060200180831161038b57829003601f168201915b505050505081565b336000908152600560209081526040808320600160a060020a039590951683529390529190912055600190565b60035481565b600160a060020a038316600090815260056020908152604080832033845290915281205482111561041357600080fd5b600160a060020a038416600090815260056020908152604080832033845290915290208054839003905561044884848461075b565b506001949350505050565b60025460ff1681565b3360009081526004602052604081205482111561047857600080fd5b3360008181526004602090815260409182902080548690039055600380548690039055815185815291517fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca59281900390910190a2506001919050565b60046020526000908152604090205481565b600160a060020a03821660009081526004602052604081205482111561050b57600080fd5b600160a060020a038316600090815260056020908152604080832033845290915290205482111561053b57600080fd5b600160a060020a0383166000818152600460209081526040808320805487900390556005825280832033845282529182902080548690039055600380548690039055815185815291517fcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca59281900390910190a250600192915050565b60018054604080516020600284861615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156103a85780601f1061037d576101008083540402835291602001916103a8565b600061061e33848461075b565b9392505050565b60008361063281856103b0565b15610736576040517f8f4ffcb10000000000000000000000000000000000000000000000000000000081523360048201818152602483018790523060448401819052608060648501908152875160848601528751600160a060020a03871695638f4ffcb195948b94938b939192909160a490910190602085019080838360005b838110156106ca5781810151838201526020016106b2565b50505050905090810190601f1680156106f75780820380516001836020036101000a031916815260200191505b5095505050505050600060405180830381600087803b15801561071957600080fd5b505af115801561072d573d6000803e3d6000fd5b50505050600191505b509392505050565b600560209081526000928352604080842090915290825290205481565b600080600160a060020a038416151561077357600080fd5b600160a060020a03851660009081526004602052604090205483111561079857600080fd5b600160a060020a03841660009081526004602052604090205483810110156107bf57600080fd5b50600160a060020a0380841660008181526004602090815260408083208054958a1680855282852080548a81039091559486905281548901909155815188815291519390950194927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef929181900390910190a35060019493505050505600a165627a7a723058208600353fffbf658cb8b57929fba657c57e83d756e4101cf874b153cc6eb4bb1c0029" - code_shield = "6104806040527f010000000000000000000000000000000000000000000000000000000000000060809081527f817de36ab2d57feb077634bca77819c8e0bd298c04f6fed0e6a83cc1356ca15560a0527fffe9fc03f18b176c998806439ff0bb8ad193afdb27b2ccbc88856916dd804e3460c0527fd8283386ef2ef07ebdbb4383c12a739a953a4d6e0d6fb1139a4036d693bfbb6c60e0527fe110de65c907b9dea4ae0bd83a4b0a51bea175646a64c12b4c9f931b2cb31b49610100527f912d82b2c2bca231f71efcf61737fbf0a08befa0416215aeef53e8bb6d23390a610120527f8ac9cf9c391e3fd42891d27238a81a8a5c1d3a72b1bcbea8cf44a58ce7389613610140527fd6c639ac24b46bd19341c91b13fdcab31581ddaf7f1411336a271f3d0aa52813610160527f7b99abdc3730991cc9274727d7d82d28cb794edbc7034b4f0053ff7c4b680444610180527f43ff5457f13b926b61df552d4e402ee6dc1463f99a535f9a713439264d5b616b6101a0527fba49b659fbd0b7334211ea6a9d9df185c757e70aa81da562fb912b84f49bce726101c0527f4777c8776a3b1e69b73a62fa701fa4f7a6282d9aee2c7a6b82e7937d7081c23c6101e0527fec677114c27206f5debc1c1ed66f95e2b1885da5b7be3d736b1de98579473048610200527f1b77dac4d24fb7258c3c528704c59430b630718bec486421837021cf75dab651610220527fbd74b25aacb92378a871bf27d225cfc26baca344a1ea35fdd94510f3d157082c610240527fd6acdedf95f608e09fa53fb43dcd0990475726c5131210c9e5caeab97f0e642f610260527f1ea6675f9551eeb9dfaaa9247bc9858270d3d3a4c5afa7177a984d5ed1be2451610280527f6edb16d01907b759977d7650dad7e3ec049af1a3d875380b697c862c9ec5d51c6102a0527fcd1c8dbf6e3acc7a80439bc4962cf25b9dce7c896f3a5bd70803fc5a0e33cf006102c0527f6aca8448d8263e547d5ff2950e2ed3839e998d31cbc6ac9fd57bc6002b1592166102e0527f8d5fa43e5a10d11605ac7430ba1f5d81fb1b68d29a640405767749e841527673610300527f08eeab0c13abd6069e6310197bf80f9c1ea6de78fd19cbae24d4a520e6cf3023610320527f0769557bc682b1bf308646fd0b22e648e8b9e98f57e29f5af40f6edb833e2c49610340527f4c6937d78f42685f84b43ad3b7b00f81285662f85c6a68ef11d62ad1a3ee0850610360527ffee0e52802cb0c46b1eb4d376c62697f4759f6c8917fa352571202fd778fd712610380527f16d6252968971a83da8521d65382e61f0176646d771c91528e3276ee45383e4a6103a0527fd2e1642c9a462229289e5b0e3b7f9008e0301cbb93385ee0e21da2545073cb586103c0527fa5122c08ff9c161d9ca6fc462073396c7d7d38e8ee48cdb3bea7e2230134ed6a6103e0527f28e7b841dcbc47cceb69d7cb8d94245fb7cb2ba3a7a6bc18f13f945f7dbd6e2a610400527fe1f34b034d4a3cd28557e2907ebf990c918f64ecb50a94f01d6fda5ca5c7ef72610420527f12935f14b676509b81eb49ef25f39269ed72309238b4c145803544b646dca62d610440527fb2eed031d4d6a4f02a097f80b54cc1541d4163c6b6f5971f88b6e41d35c5381461046052620004b390602890602062000580565b50348015620004c157600080fd5b50d38015620004cf57600080fd5b50d28015620004dd57600080fd5b506040516200354738038062003547833981016040819052620005009162000615565b604d811062000546576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016200053d90620006b5565b60405180910390fd5b600a0a60005560488054336001600160a01b031991821617909155604980549091166001600160a01b039290921691909117905562000713565b8260208101928215620005b1579160200282015b82811115620005b157825182559160200191906001019062000594565b50620005bf929150620005c3565b5090565b620005e091905b80821115620005bf5760008155600101620005ca565b90565b8051620005f081620006ee565b620005fb81620006d0565b9392505050565b80516200060f8162000708565b92915050565b600080604083850312156200062957600080fd5b6000620006378585620005e3565b92505060206200064a8582860162000602565b9150509250929050565b600062000663602a83620006c7565b7f546865207363616c696e67466163746f724578706f6e656e74206973206f757481527f206f662072616e67652100000000000000000000000000000000000000000000602082015260400192915050565b602080825281016200060f8162000654565b90815260200190565b60006001600160a01b0382166200060f565b6001600160a81b031690565b620006f981620006e2565b81146200070557600080fd5b50565b620006f981620005e0565b612e2480620007236000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100c35760003560e01c80639110a55b1161008b5780639110a55b14610134578063ae6dead714610147578063cc1058751461015a578063d7b0fef11461016d578063e176507314610175578063ed3437f814610196576100c3565b80632997e86b146100c85780632a6bb45a146100f157806330e69fc314610104578063313529361461010c578063855d175e1461011f575b600080fd5b6100db6100d6366004611c30565b61019e565b6040516100e89190612a7d565b60405180910390f35b6100db6100ff366004611c30565b6101b0565b6100db6101c2565b6100db61011a366004611c30565b6101c8565b61013261012d366004611c6c565b6101da565b005b610132610142366004611a3d565b6105a9565b6100db610155366004611c30565b610bd4565b610132610168366004611b22565b610be6565b6100db61106c565b610188610183366004611c30565b611072565b6040516100e8929190612a8b565b6100db6111c5565b60036020526000908152604090205481565b60066020526000908152604090205481565b60015481565b60056020526000908152604090205481565b6049546040516323b872dd60e01b815233916000916001600160a01b03909116906323b872dd9061021390859030908b90600401612852565b602060405180830381600087803b15801561022d57600080fd5b505af1158015610241573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506102659190810190611c12565b90508061028d5760405162461bcd60e51b815260040161028490612ad8565b60405180910390fd5b8435600090815260066020526040902054156102bb5760405162461bcd60e51b815260040161028490612b58565b60006102c6876111cb565b905060006002308389886040516020016102e394939291906127fc565b60408051601f19818403018152908290526102fd91612846565b602060405180830381855afa15801561031a573d6000803e3d6000fd5b5050506040513d601f19601f8201168201806040525061033d9190810190611c4e565b90506060630100000188888585600760015460405161036196959493929190612a1d565b600060405180830381855afa15801561037e573d6000803e3d6000fd5b5050503d80600081146103ad576040519150601f19603f3d011682016040523d82523d6000602084013e6103b2565b606091505b5090506000816000815181106103c457fe5b602002602001015160001c9050806001146103f15760405162461bcd60e51b815260040161028490612b68565b60008260018151811061040057fe5b60209081029190910181015160015463ffffffff016000818152600590935260409092208c359055915081610435578a356007555b60015b826001018110156104aa576002600019830104915084816001018151811061045c57fe5b60200260200101516005600084815260200190815260200160002081905550828114156104a2576000828152600560205260409020546007846021811061049f57fe5b01555b600101610438565b508382600201815181106104ba57fe5b60209081029190910181015160028190556000818152600490925260408220558b906020020135600660008d81602090810291909101358252810191909152604001600090812091909155600180548082019091557fbe22cbc129fd01d04b02a7b3258b72e8c8ae5bfcf054d7f0359779be627a6b27918d9060200201358d600160200201358e600260200201358d60405161055a959493929190612bb8565b60405180910390a17f36bf5aa3964be01dbd95a0154a8930793fe68353bdc580871ffb2c911366bbc7888d60405161059392919061287a565b60405180910390a1505050505050505050505050565b600188108015906105bb575060028811155b6105d75760405162461bcd60e51b815260040161028490612b98565b8786146105f65760405162461bcd60e51b815260040161028490612b08565b60018410801590610608575060028411155b6106245760405162461bcd60e51b815260040161028490612b18565b8381146106435760405162461bcd60e51b815260040161028490612b38565b60005b8881101561070757600360008b8b8481811061065e57fe5b905061014002016000600a811061067157fe5b60200201358152602001908152602001600020546000801b146106a65760405162461bcd60e51b815260040161028490612ba8565b600460008b8b848181106106b657fe5b905061014002016001600a81106106c957fe5b60200201358152602001908152602001600020546000801b14156106ff5760405162461bcd60e51b815260040161028490612af8565b600101610646565b5060005b84811015610773576006600087878481811061072357fe5b9050610120020160006009811061073657fe5b60200201358152602001908152602001600020546000801b1461076b5760405162461bcd60e51b815260040161028490612ae8565b60010161070b565b5060006002308b8b898988886040516020016107959796959493929190612751565b60408051601f19818403018152908290526107af91612846565b602060405180830381855afa1580156107cc573d6000803e3d6000fd5b5050506040513d601f19601f820116820180604052506107ef9190810190611c4e565b9050606063010000028b8b8b8b8b8b8b896000600760015460405161081e9b9a999897969594939291906128bd565b600060405180830381855afa15801561083b573d6000803e3d6000fd5b5050503d806000811461086a576040519150601f19603f3d011682016040523d82523d6000602084013e61086f565b606091505b50905060008160008151811061088157fe5b602002602001015160001c9050806001146108ae5760405162461bcd60e51b815260040161028490612b68565b600160005b888110156109d95760008483806001019450815181106108cf57fe5b602090810291909101015160015490915063ffffffff018b8b848181106108f257fe5b9050610120020160006009811061090557fe5b60008381526005602090815260409091209102919091013590558161094c578b8b8481811061093057fe5b9050610120020160006009811061094357fe5b60200201356007555b60015b826001018110156109c4576002600019830104915086858060010196508151811061097657fe5b60200260200101516005600084815260200190815260200160002081905550828114156109bc57600082815260056020526040902054600784602181106109b957fe5b01555b60010161094f565b505060018054810181559190910190506108b3565b508281815181106109e657fe5b60209081029190910181015160028190556000818152600490925260408220555b8c811015610a8f5760008e8e83818110610a1d57fe5b905061014002016000600a8110610a3057fe5b602002013590508060036000838152602001908152602001600020819055507fd13faa8100906cf559aebacf9c16532cfc9708645c198c8f15798ee049dbcfc181604051610a7e9190612a7d565b60405180910390a150600101610a07565b5060005b88811015610bc457898982818110610aa757fe5b90506101200201600060098110610aba57fe5b6020020135600660008c8c85818110610acf57fe5b90506101200201600060098110610ae257fe5b60200201358152602001908152602001600020819055507f0f190e6ff1f0e1c1f4ec51aecdafdd02278c568898b57df5ca7dccba83a8181c818b8b905003600154038b8b84818110610b3057fe5b90506101200201600060098110610b4357fe5b60200201358c8c85818110610b5457fe5b90506101200201600160098110610b6757fe5b60200201358d8d86818110610b7857fe5b90506101200201600260098110610b8b57fe5b60200201358b8b87818110610b9c57fe5b90506102a00201604051610bb4959493929190612bb8565b60405180910390a1600101610a93565b5050505050505050505050505050565b60046020526000908152604090205481565b6000610bf1896111cb565b905060006002308d888888888e89604051602001610c16989796959493929190612795565b60408051601f1981840301815290829052610c3091612846565b602060405180830381855afa158015610c4d573d6000803e3d6000fd5b5050506040513d601f19601f82011682018060405250610c709190810190611c4e565b8c356000818152600360209081526040909120549293509091908e01359015610cab5760405162461bcd60e51b815260040161028490612ba8565b600081815260046020526040902054610cd65760405162461bcd60e51b815260040161028490612af8565b6001871115610cf75760405162461bcd60e51b815260040161028490612b28565b868514610d165760405162461bcd60e51b815260040161028490612b88565b86610d9d57600063010000038f8f878f88604051610d389594939291906129cc565b602060405180830381855afa158015610d55573d6000803e3d6000fd5b5050506040513d601f19601f82011682018060405250610d789190810190611c12565b905080610d975760405162461bcd60e51b815260040161028490612b68565b50610f21565b610f218e600a806020026040519081016040528092919082600a60200280828437600081840152601f19601f8201169050808301925050505050508e6002806020026040519081016040528092919082600260200280828437600081840152601f19601f820116905080830192505050505050868e6002806020026040519081016040528092919082600260200280828437600081840152601f19601f820116905080830192505050505050878d8d808060200260200160405190810160405280939291908181526020016000905b82821015610eae576040805161012081810190925290808402870190600990839083908082843760009201919091525050508152600190910190602001610e6c565b50505050508c8c808060200260200160405190810160405280939291908181526020016000905b82821015610f1757604080516102a081810190925290808402870190601590839083908082843760009201919091525050508152600190910190602001610ed5565b505050505061124e565b60008281526003602052604090819020839055517fd13faa8100906cf559aebacf9c16532cfc9708645c198c8f15798ee049dbcfc190610f62908490612a7d565b60405180910390a16000604960009054906101000a90046001600160a01b03166001600160a01b031663a9059cbb8c8f6040518363ffffffff1660e01b8152600401610faf92919061287a565b602060405180830381600087803b158015610fc957600080fd5b505af1158015610fdd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052506110019190810190611c12565b9050806110205760405162461bcd60e51b815260040161028490612b48565b7f1daf70c304f467a9efbc9ac1ca7bfe859a478aa6c4b88131b4dbb1547029b9728b8e8c60405161105393929190612895565b60405180910390a1505050505050505050505050505050565b60025481565b600061107c611842565b600154831061109d5760405162461bcd60e51b815260040161028490612b78565b63ffffffff83016110ac611842565b60006110b7866115ab565b905060006110c587836115fa565b905060005b60208163ffffffff1610156111b4578263ffffffff168163ffffffff16141561110d57818482601f0363ffffffff166020811061110357fe5b60200201526111a2565b600285066111415760056000600187038152602001908152602001600020548482601f0363ffffffff166020811061110357fe5b60018501600090815260056020526040902054156111715760018501600090815260056020526040902054611187565b60288163ffffffff166020811061118457fe5b01545b8482601f0363ffffffff166020811061119c57fe5b60200201525b600260001986010494506001016110ca565b505060025494509092505050915091565b60005481565b60008082116111ec5760405162461bcd60e51b815260040161028490612ac8565b60005461120090839063ffffffff61174c16565b1561121d5760405162461bcd60e51b815260040161028490612ab8565b6000805461123290849063ffffffff61179516565b9050677fffffffffffffff811061124857600080fd5b92915050565b60008260008151811061125d57fe5b602002602001015160006009811061127157fe5b6020020151905060066000828152602001908152602001600020546000801b146112ad5760405162461bcd60e51b815260040161028490612ae8565b604080516001808252818301909252606091816020015b6112cc611861565b8152602001906001900390816112c457905050905088816000815181106112ef57fe5b6020908102919091010152604080516001808252818301909252606091816020015b611319611880565b815260200190600190039081611311579050509050888160008151811061133c57fe5b6020026020010181905250606063010000028383888b8b8e600760015460405161136d98979695949392919061294e565b600060405180830381855afa15801561138a573d6000803e3d6000fd5b5050503d80600081146113b9576040519150601f19603f3d011682016040523d82523d6000602084013e6113be565b606091505b5090506000816000815181106113d057fe5b602002602001015160001c9050806001146113fd5760405162461bcd60e51b815260040161028490612b68565b60008260018151811061140c57fe5b60209081029190910181015160015463ffffffff016000818152600590935260409092208890559150816114405760078790555b60015b826001018110156114b5576002600019830104915084816001018151811061146757fe5b60200260200101516005600084815260200190815260200160002081905550828114156114ad57600082815260056020526040902054600784602181106114aa57fe5b01555b600101611443565b508382600201815181106114c557fe5b602090810291909101810151600281905560008181526004835260408082209290925589815260069092528120889055600180548082019091558a517f3814d251636df4a739162facca3862684b45af01ce54bcc56ea488fa6a69412d928a918d919061152e57fe5b602002602001015160016009811061154257fe5b60200201518c60008151811061155457fe5b602002602001015160026009811061156857fe5b60200201518c60008151811061157a57fe5b6020026020010151604051611593959493929190612bfb565b60405180910390a15050505050505050505050505050565b60015460009063ffffffff83019063fffffffe01825b60026000198301046002600019850104146115f25760026000198401049250600260001983010491506001016115c1565b949350505050565b60015463fffffffe0160008181526005602052604081205490918291829163ffffffff8088019290871661167b578183101561163c5794506112489350505050565b8183141561167b576002830661166b575050600019016000908152600560205260409020549250611248915050565b5050602854935061124892505050565b60005b8763ffffffff168163ffffffff16101561174057600283066116ba576000198301600090815260056020526040902054955090935083906116d5565b81955060288163ffffffff16602081106116d057fe5b015494505b63010000048187876040516116ec93929190612c3e565b602060405180830381855afa158015611709573d6000803e3d6000fd5b5050506040513d601f19601f8201168201806040525061172c9190810190611c4e565b91506002600019840104925060010161167e565b50979650505050505050565b600061178e83836040518060400160405280601881526020017f536166654d6174683a206d6f64756c6f206279207a65726f00000000000000008152506117d7565b9392505050565b600061178e83836040518060400160405280601a81526020017f536166654d6174683a206469766973696f6e206279207a65726f00000000000081525061180b565b600081836117f85760405162461bcd60e51b81526004016102849190612aa7565b5082848161180257fe5b06949350505050565b6000818361182c5760405162461bcd60e51b81526004016102849190612aa7565b50600083858161183857fe5b0495945050505050565b6040518061040001604052806020906020820280388339509192915050565b604051806101400160405280600a906020820280388339509192915050565b60405180604001604052806002906020820280388339509192915050565b80356118a981612d93565b61178e81612cbd565b60008083601f8401126118c457600080fd5b50813567ffffffffffffffff8111156118dc57600080fd5b602083019150836101408202830111156118f557600080fd5b9250929050565b60008083601f84011261190e57600080fd5b50813567ffffffffffffffff81111561192657600080fd5b602083019150836102a08202830111156118f557600080fd5b60008083601f84011261195157600080fd5b50813567ffffffffffffffff81111561196957600080fd5b6020830191508360408202830111156118f557600080fd5b60008083601f84011261199357600080fd5b50813567ffffffffffffffff8111156119ab57600080fd5b602083019150836101208202830111156118f557600080fd5b80610140810183101561124857600080fd5b806102a0810183101561124857600080fd5b806040810183101561124857600080fd5b806060810183101561124857600080fd5b80610120810183101561124857600080fd5b805161124881612daa565b803561124881612db3565b805161124881612db3565b600080600080600080600080600060c08a8c031215611a5b57600080fd5b893567ffffffffffffffff811115611a7257600080fd5b611a7e8c828d016118b2565b995099505060208a013567ffffffffffffffff811115611a9d57600080fd5b611aa98c828d0161193f565b975097505060408a013567ffffffffffffffff811115611ac857600080fd5b611ad48c828d01611981565b95509550506060611ae78c828d016119e8565b93505060a08a013567ffffffffffffffff811115611b0457600080fd5b611b108c828d016118fc565b92509250509295985092959850929598565b6000806000806000806000806000806102a08b8d031215611b4257600080fd5b6000611b4e8d8d6119c4565b9a5050610140611b608d828e016119e8565b995050610180611b728d828e01611a27565b9850506101a0611b848d828e016119e8565b9750506101e0611b968d828e0161189e565b965050610200611ba88d828e016119f9565b9550506102608b013567ffffffffffffffff811115611bc657600080fd5b611bd28d828e01611981565b94509450506102808b013567ffffffffffffffff811115611bf257600080fd5b611bfe8d828e016118fc565b92509250509295989b9194979a5092959850565b600060208284031215611c2457600080fd5b60006115f28484611a1c565b600060208284031215611c4257600080fd5b60006115f28484611a27565b600060208284031215611c6057600080fd5b60006115f28484611a32565b6000806000806104208587031215611c8357600080fd5b6000611c8f8787611a27565b9450506020611ca087828801611a0a565b935050610140611cb2878288016119e8565b925050610180611cc4878288016119d6565b91505092959194509250565b6000611cdc838361203e565b50506101400190565b6000611cdc838361204f565b6000611cfd83836120a3565b50506102a00190565b6000611d1283836120fc565b505060400190565b6000611d128383612154565b6000611d32838361224b565b50506101200190565b6000611d328383612258565b6000611d5383836122a4565b505060200190565b611d6481612cbd565b82525050565b611d64611d7682612cbd565b612d55565b6000611d878385612cab565b9350611d9282612c59565b8060005b85811015611dc857611da88284612cb9565b611db28882611cd0565b9750611dbd83612c8a565b925050600101611d96565b509495945050505050565b6000611ddf8385612cb4565b9350611dea82612c59565b8060005b85811015611dc857611e008284612cb9565b611e0a8882611cd0565b9750611e1583612c8a565b925050600101611dee565b6000611e2b82612c62565b611e358185612cab565b9350611e4083612c5c565b8060005b83811015611dc8578151611e588882611ce5565b9750611e6383612c5c565b925050600101611e44565b6000611e7a8385612cb4565b9350611e8582612c59565b8060005b85811015611dc857611e9b8284612cb9565b611ea58882611cf1565b9750611eb083612c91565b925050600101611e89565b6000611ec78385612cab565b9350611ed282612c59565b8060005b85811015611dc857611ee88284612cb9565b611ef28882611d06565b9750611efd83612c98565b925050600101611ed6565b6000611f1382612c62565b611f1d8185612cab565b9350611f2883612c5c565b8060005b83811015611dc8578151611f408882611d1a565b9750611f4b83612c5c565b925050600101611f2c565b6000611f628385612cab565b9350611f6d82612c59565b8060005b85811015611dc857611f838284612cb9565b611f8d8882611d26565b9750611f9883612c9e565b925050600101611f71565b6000611faf8385612cb4565b9350611fba82612c59565b8060005b85811015611dc857611fd08284612cb9565b611fda8882611d26565b9750611fe583612c9e565b925050600101611fbe565b6000611ffb82612c62565b6120058185612cab565b935061201083612c5c565b8060005b83811015611dc85781516120288882611d3b565b975061203383612c5c565b925050600101612014565b61204b6101408383612d06565b5050565b61205881612c66565b6120628184612cb4565b925061206d82612c59565b8060005b8381101561209b5781516120858782611d47565b965061209083612c5c565b925050600101612071565b505050505050565b61204b6102a08383612d06565b6120b981612c6c565b6120c38184612cb4565b92506120ce82612c59565b8060005b8381101561209b5781516120e68782611d47565b96506120f183612c5c565b9250506001016120d2565b61204b60408383612d06565b61211181612c72565b61211b8184612cb4565b925061212682612c59565b8060005b8381101561209b57815161213e8782611d47565b965061214983612c5c565b92505060010161212a565b61215d81612c72565b6121678184612cb4565b925061217282612c59565b8060005b8381101561209b57815161218a8782611d47565b965061219583612c5c565b925050600101612176565b6121a981612c78565b6121b38184612cb4565b92506121be82612c59565b8060005b8381101561209b5781516121d68782611d47565b96506121e183612c5c565b9250506001016121c2565b6121f581612c7e565b6121ff8184612cb4565b925061220a82612c59565b8060005b8381101561209b5761221f82612d71565b6122298782611d47565b965061223483612ca5565b92505060010161220e565b61204b60608383612d06565b61204b6101208383612d06565b61226181612c84565b61226b8184612cb4565b925061227682612c59565b8060005b8381101561209b57815161228e8782611d47565b965061229983612c5c565b92505060010161227a565b611d6481612c59565b60006122b882612c62565b6122c28185612cb4565b93506122d2818560208601612d12565b9290920192915050565b611d6481612cfb565b60006122f082612c62565b6122fa8185612cab565b935061230a818560208601612d12565b61231381612d7d565b9093019392505050565b600061232a603183612cab565b7f56616c7565206d75737420626520696e7465676572206d756c7469706c6573208152706f66207363616c696e67466163746f722160781b602082015260400192915050565b600061237d601783612cab565b7f56616c7565206d75737420626520706f73697469766521000000000000000000815260200192915050565b60006123b6601483612cab565b735472616e7366657246726f6d206661696c65642160601b815260200192915050565b60006123e6601983612cab565b7f4475706c6963617465206e6f7465436f6d6d69746d656e742100000000000000815260200192915050565b600061241f601683612cab565b7554686520616e63686f72206d7573742065786973742160501b815260200192915050565b6000612451603d83612cab565b7f496e707574206e756d626572206d75737420626520657175616c20746f20737081527f656e64417574686f726974795369676e6174757265206e756d62657221000000602082015260400192915050565b60006124b0601d83612cab565b7f4f7574707574206e756d626572206d7573742062652031206f72203221000000815260200192915050565b60006124e9601e83612cab565b7f4f7574707574206e756d6265722063616e6e6f74206578636565642031210000815260200192915050565b6000612522602883612cab565b7f4f7574707574206e756d626572206d75737420626520657175616c20746f2063815267206e756d6265722160c01b602082015260400192915050565b600061256c601083612cab565b6f5472616e73666572206661696c65642160801b815260200192915050565b6000612598601a83612cab565b7f4475706c6963617465206e6f7465436f6d6d69746d656e747321000000000000815260200192915050565b60006125d1603f83612cab565b7f5468652070726f6f6620616e64207369676e61747572652068617665206e6f7481527f206265656e2076657269666965642062792074686520636f6e74726163742100602082015260400192915050565b6000612630602a83612cab565b7f506f736974696f6e2073686f756c6420626520736d616c6c6572207468616e208152696c656166436f756e742160b01b602082015260400192915050565b600061267c602b83612cab565b7f4f7574707574206e756d626572206d75737420626520657175616c20746f206c81526a656e677468206f6620632160a81b602082015260400192915050565b60006126c9601c83612cab565b7f496e707574206e756d626572206d7573742062652031206f7220322100000000815260200192915050565b6000612702602083612cab565b7f546865206e6f74652068617320616c7265616479206265656e207370656e7421815260200192915050565b611d6481612ce5565b611d6481612cee565b611d6461274c82612cee565b612d66565b600061275d828a611d6a565b60148201915061276e82888a611dd3565b915061277b828688611fa3565b9150612788828486611e6e565b9998505050505050505050565b60006127a1828b611d6a565b6014820191506127b1828a61203e565b610140820191506127c382888a611fa3565b91506127d0828688611e6e565b91506127dc8285611d6a565b6014820191506127ec8284612740565b5060080198975050505050505050565b60006128088287611d6a565b6014820191506128188286612740565b600882019150612828828561224b565b6101208201915061283982846120a3565b506102a001949350505050565b600061178e82846122ad565b606081016128608286611d5b565b61286d6020830185611d5b565b6115f260408301846122a4565b604081016128888285611d5b565b61178e60208301846122a4565b60a081016128a38286611d5b565b6128b060208301856122a4565b6115f2604083018461223f565b61052080825281016128d0818d8f611d7b565b905081810360208301526128e5818b8d611ebb565b905081810360408301526128fa81898b611f56565b905061290960608301886120fc565b61291660a08301876122a4565b61292360c08301866122dc565b61293060e08301856121ec565b61293e6105008301846122a4565b9c9b505050505050505050505050565b6105208082528101612960818b611e20565b90508181036020830152612974818a611f08565b905081810360408301526129888189611ff0565b90506129976060830188612108565b6129a460a08301876122a4565b6129b160c0830186612737565b6129be60e08301856121ec565b6127886105008301846122a4565b61020081016129db828861203e565b6129e96101408301876120fc565b6129f7610180830186612737565b612a056101a08301856120fc565b612a136101e08301846122a4565b9695505050505050565b6105e08101612a2c828961224b565b612a3a6101208301886120fc565b612a48610160830187612737565b612a566101808301866122a4565b612a646101a08301856121ec565b612a726105c08301846122a4565b979650505050505050565b6020810161124882846122a4565b6104208101612a9a82856122a4565b61178e60208301846121a0565b6020808252810161178e81846122e5565b602080825281016112488161231d565b6020808252810161124881612370565b60208082528101611248816123a9565b60208082528101611248816123d9565b6020808252810161124881612412565b6020808252810161124881612444565b60208082528101611248816124a3565b60208082528101611248816124dc565b6020808252810161124881612515565b602080825281016112488161255f565b602080825281016112488161258b565b60208082528101611248816125c4565b6020808252810161124881612623565b602080825281016112488161266f565b60208082528101611248816126bc565b60208082528101611248816126f5565b6103208101612bc782886122a4565b612bd460208301876122a4565b612be160408301866122a4565b612bee60608301856122a4565b612a1360808301846120a3565b6103208101612c0a82886122a4565b612c1760208301876122a4565b612c2460408301866122a4565b612c3160608301856122a4565b612a1360808301846120b0565b60608101612c4c828661272e565b61286d60208301856122a4565b90565b60200190565b5190565b50600a90565b50601590565b50600290565b50602090565b50602190565b50600990565b6101400190565b6102a00190565b60400190565b6101200190565b60010190565b90815260200190565b919050565b5090565b600061124882612ccd565b151590565b6001600160a01b031690565b6001600160a81b031690565b63ffffffff1690565b67ffffffffffffffff1690565b600061124882612cee565b82818337506000910152565b60005b83811015612d2d578181015183820152602001612d15565b83811115612d3c576000848401525b50505050565b6000611248612d5083612c59565b612c59565b600061124882600061124882612d8d565b600061124882612d87565b60006112488254612d42565b601f01601f191690565b60c01b90565b60601b90565b612d9c81612cd9565b8114612da757600080fd5b50565b612d9c81612cc8565b612d9c81612c5956fea36474726f6e58207ef421e01e827fa1d2e384579b655503e18aef0f4bf9ff3e5176a254c97da9036c6578706572696d656e74616cf564736f6c637828302e352e31322d646576656c6f702e323032302e362e31352b636f6d6d69742e34323336323638380065" - code_getAddressChange = "608060405260e3806100126000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b5060043610604a5760003560e01c806358c6464814604f578063b4cef28d146071575b600080fd5b605560a6565b604080516001600160a01b039092168252519081900360200190f35b609460048036036020811015608557600080fd5b50356001600160a01b031660aa565b60408051918252519081900360200190f35b3090565b50479056fea26474726f6e58208f096542a0e814a7dd8434fd85def0ee9521b022f5cad9176f1c993e2615bdad64736f6c634300050f0031" - code_fallbackOldVersionTest = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101d98061003a6000396000f3fe60c0604052600860808190526766616c6c6261636b60c01b60a0908152610029916000919061010a565b506040805181815260008054600260001961010060018416150201909116049282018390527f1f0af026fd1015e37743a803fa8c7b92c09a6fc99890b1681a1e3c888427c25e9290918291369190819060208201906060830190869080156100d25780601f106100a7576101008083540402835291602001916100d2565b820191906000526020600020905b8154815290600101906020018083116100b557829003601f168201915b50508381038252848152602001858580828437600083820152604051601f909101601f191690920182900397509095505050505050a1005b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061014b57805160ff1916838001178555610178565b82800160010185558215610178579182015b8281111561017857825182559160200191906001019061015d565b50610184929150610188565b5090565b6101a291905b80821115610184576000815560010161018e565b9056fea26474726f6e5820e77b862582c00095aa34fd5c2839c0d8f209bdac194c0adeec660fa15a08fbe464736f6c634300050f0031" - code_fallbackOldVersionCall = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506101748061003a6000396000f3fe60806040526004361061001e5760003560e01c8063f55332ab14610023575b600080fd5b6100496004803603602081101561003957600080fd5b50356001600160a01b031661005d565b604080519115158252519081900360200190f35b60408051600481526024810182526020810180516001600160e01b031663f85396d760e01b1781529151815160009384936001600160a01b038716939092909182918083835b602083106100c25780518252601f1990920191602091820191016100a3565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114610124576040519150601f19603f3d011682016040523d82523d6000602084013e610129565b606091505b505090508061013757600080fd5b5060019291505056fea26474726f6e58203498e1c23a661ae640e44836405d25839850ec79748cabd2dab945fd13ee0c7c64736f6c634300050f0031" - code_arrayLength_0.5.15 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506102708061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100455760003560e01c8063cbcec91e1461004a575b600080fd5b6100526100a2565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561008e578181015183820152602001610076565b505050509050019250505060405180910390f35b60008054600181018255818052602081047f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e56301805460ff601f9093166101000a928302191690911790556060906003906100fc90826101e5565b50600080549061010f90600183016101e5565b5060008054906101239060001983016101e5565b5060008054906101379060001983016101e5565b50600080548061014357fe5b60008281526020808220600019909301818104909301805460ff601f86166101000a0219169055919092558154604080518284028101840190915281815292918301828280156101da57602002820191906000526020600020906000905b825461010083900a900460f81b6001600160f81b0319168152602060019283018181049485019490930390920291018084116101a15790505b505050505090505b90565b81548183558181111561021957601f016020900481601f01602090048360005260206000209182019101610219919061021e565b505050565b6101e291905b808211156102385760008155600101610224565b509056fea26474726f6e582030f1b13e292e442f2c4de67e0d5bb6f78dd7f44f99e5f2fa3952de6c9d94dd8b64736f6c634300050e0031" - code_override001 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060d8806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b506004361060545760003560e01c80630c55699c14605957806355241077146071578063a56dfe4a14608d575b600080fd5b605f6093565b60408051918252519081900360200190f35b608b60048036036020811015608557600080fd5b50356099565b005b605f609e565b60005481565b600155565b6001548156fea26474726f6e58204b9c06785956097a789fe5d4b75dbe9390a30c48c3080d3c14d8655cb84e11e564736f6c634300050f0031" - code_override002 = "6080604052600460005534801561001557600080fd5b50d3801561002257600080fd5b50d2801561002f57600080fd5b5061012b8061003f6000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b506004361060545760003560e01c80630c55699c1460595780635524107714607157806374d393f014608d575b600080fd5b605f60a7565b60408051918252519081900360200190f35b608b60048036036020811015608557600080fd5b503560ad565b005b608b6004803603602081101560a157600080fd5b503560f2565b60005481565b6006600054101560f2576040805162461bcd60e51b815260206004820152600b60248201526a3c1036bab9ba101f1e901b60a91b604482015290519081900360640190fd5b60005556fea26474726f6e5820d72f89553adaa33af6034260ea794957bdaebd8e26bccaac25c685c1bd1e8f2764736f6c634300050f0031" - code_override003 = "608060405260008054600160ff19918216811761ff0019169092556301efa6ad9091556301efa6ac19600255630166654f6003908155600480546001600160a01b03191673dcad3a6d3569df655070ded06cb7a1b2ccd1d3af1790557fb55a21aaee0ce8f1c8ffaa0dbd23105cb55a21aaee0ce8f1c8ffaa0dbd23105c6005556006805490921617905534801561009557600080fd5b50d380156100a257600080fd5b50d280156100af57600080fd5b506101c8806100bf6000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b50600436106100a25760003560e01c806398f42fe31161007557806398f42fe31461012d578063a223e05d14610135578063e5aa3d581461013d578063f8aab23814610145576100a2565b806375f12b21146100a757806383cdfab8146100c357806387cfa5bf146100dd578063938b5f3214610109575b600080fd5b6100af61014d565b604080519115158252519081900360200190f35b6100cb61015b565b60408051918252519081900360200190f35b6100e5610161565b604051808260038111156100f557fe5b60ff16815260200191505060405180910390f35b61011161016a565b604080516001600160a01b039092168252519081900360200190f35b6100e5610179565b6100cb610182565b6100cb610188565b6100cb61018e565b600054610100900460ff1681565b60025481565b60005460ff1681565b6004546001600160a01b031681565b60065460ff1681565b60035481565b60015481565b6005548156fea26474726f6e5820dacca6ecfb02875aede259b98aa35a6aba6aea8284a01f0c82fdeba6ffc8012d64736f6c634300050f0031" - code_virtual001 = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506103778061003a6000396000f3fe608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b506004361061007c5760003560e01c80630c55699c146100815780631e26fd331461009b57806355241077146100bc5780637fcaf666146100d9578063a56dfe4a14610149578063c5d7802e14610165575b600080fd5b6100896101e2565b60408051918252519081900360200190f35b6100ba600480360360208110156100b157600080fd5b503515156101e8565b005b6100ba600480360360208110156100d257600080fd5b50356101fb565b6100ba600480360360208110156100ef57600080fd5b81019060208101813564010000000081111561010a57600080fd5b82018360208201111561011c57600080fd5b8035906020019184600183028401116401000000008311171561013e57600080fd5b509092509050610200565b610151610211565b604080519115158252519081900360200190f35b61016d61021a565b6040805160208082528351818301528351919283929083019185019080838360005b838110156101a757818101518382015260200161018f565b50505050905090810190601f1680156101d45780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60015481565b6002805460ff1916911515919091179055565b600155565b61020c600083836102a8565b505050565b60025460ff1681565b6000805460408051602060026001851615610100026000190190941693909304601f810184900484028201840190925281815292918301828280156102a05780601f10610275576101008083540402835291602001916102a0565b820191906000526020600020905b81548152906001019060200180831161028357829003601f168201915b505050505081565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106102e95782800160ff19823516178555610316565b82800160010185558215610316579182015b828111156103165782358255916020019190600101906102fb565b50610322929150610326565b5090565b61034091905b80821115610322576000815560010161032c565b9056fea26474726f6e5820b48ac0b0a646831f6a4069f95888081a6e12cd0ffb453b66d879c3f04e3b71ec64736f6c634300050f0031" - code_slotAndOffset_06x = "608060405234801561001057600080fd5b50d3801561001d57600080fd5b50d2801561002a57600080fd5b5060ba806100396000396000f3fe6080604052348015600f57600080fd5b50d38015601b57600080fd5b50d28015602757600080fd5b5060043610604a5760003560e01c8063b1cb267b14604f578063d46300fd14606e575b600080fd5b60556074565b6040805192835260208301919091528051918290030190f35b6055607c565b600460009091565b60016000909156fea264697066735822122076bb65351c887d12efbc6982560551c4979591981777ea571d32f7f267f8888864736f6c634300060c0033" -} - - -abi = { - abi_Scenario015_TRC20_TRON = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"constant\":false,\"inputs\":[],\"name\":\"stop\",\"outputs\":[],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"constant\":false,\"inputs\":[{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"constant\":true,\"inputs\":[],\"name\":\"stopped\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":false,\"inputs\":[],\"name\":\"start\",\"outputs\":[],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":false,\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"name\":\"setName\",\"outputs\":[],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"nonpayable\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\",\"stateMutability\":\"view\"},{\"inputs\":[],\"payable\":false,\"type\":\"constructor\",\"stateMutability\":\"nonpayable\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]" - abi_AssertException_testdivideInt = "[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"int256\"},{\"name\":\"y\",\"type\":\"int256\"}],\"name\":\"divideIHaveArgsReturn\",\"outputs\":[{\"name\":\"z\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_AssertException_testfindArgsContractMinTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"i\",\"type\":\"uint256\"}],\"name\":\"findArgsByIndexTest\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_AssertException_testbyteMinContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"i\",\"type\":\"uint256\"}],\"name\":\"testBytesGet\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes1\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_AssertException_testenum = "[{\"constant\":true,\"inputs\":[],\"name\":\"getChoice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"choice\",\"type\":\"uint8\"}],\"name\":\"setGoStraight\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_AssertException_testmoveRight = "[{\"constant\":false,\"inputs\":[{\"name\":\"i\",\"type\":\"int256\"}],\"name\":\"binaryMoveR\",\"outputs\":[{\"name\":\"z\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_AssertException_testuninitializedContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"test2\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"test1\",\"outputs\":[{\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_AssertException_testTestAssertContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"testAssert\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testRequire\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testThrow\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testRevert\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - - abi_ContractGrammar001_testGrammar001 = "[{\"constant\":false,\"inputs\":[{\"name\":\"useB\",\"type\":\"bool\"},{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"select\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"b\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"a\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar001_testGrammar002 = "[{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"remove\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"contains\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"insert\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi1_ContractGrammar001_testGrammar002 = "[{\"constant\":false,\"inputs\":[{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"register\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar001_testGrammar003 = "[{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"remove\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"contains\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"insert\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi1_ContractGrammar001_testGrammar003 = "[{\"constant\":false,\"inputs\":[{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"register\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar001_testGrammar004 = "[{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"uint256[] storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"indexOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi1_ContractGrammar001_testGrammar004 = "[{\"constant\":false,\"inputs\":[{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"getData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"append\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_old\",\"type\":\"uint256\"},{\"name\":\"_new\",\"type\":\"uint256\"}],\"name\":\"replace\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"data\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_ContractGrammar001_testGrammar006 = "[{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"d4\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"d\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"d5\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"f\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"d6\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"d1\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"d2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - - abi_ContractGrammar002_testGrammar007 = "[{\"constant\":true,\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"name\":\"getDougName\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_age\",\"type\":\"uint256\"}],\"name\":\"getDougAge\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"contracts\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]" - abi1_ContractGrammar002_testGrammar007 = "[{\"constant\":false,\"inputs\":[{\"name\":\"_name\",\"type\":\"bytes32\"}],\"name\":\"uintOfName\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_doug\",\"type\":\"address\"}],\"name\":\"setDOUG\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_age\",\"type\":\"uint256\"}],\"name\":\"dougOfage\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"dogInterfaceAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"sender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"name\",\"type\":\"bytes32\"}],\"name\":\"FetchContract\",\"type\":\"event\"}]" - abi_ContractGrammar002_testGrammar008 = "[{\"constant\":false,\"inputs\":[],\"name\":\"utterance\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getContractName\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar002_testGrammar010 = "[{\"constant\":false,\"inputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"name\":\"setFeed\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"callFeed\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar002_testGrammar011 = "[{\"constant\":false,\"inputs\":[{\"name\":\"key\",\"type\":\"uint256\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"f\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"g\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar002_testGrammar012 = "[{\"constant\":false,\"inputs\":[],\"name\":\"info\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"bytes4\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractGrammar002_testGrammar013 = "[{\"constant\":false,\"inputs\":[],\"name\":\"kill\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"increment\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]" - - abi_ContractGrammar003_testGrammar014 = "[{\"constant\":false,\"inputs\":[{\"name\":\"bAddress\",\"type\":\"address\"},{\"name\":\"_number\",\"type\":\"uint256\"}],\"name\":\"delegatecallTest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"bAddress\",\"type\":\"address\"},{\"name\":\"_number\",\"type\":\"uint256\"}],\"name\":\"callTest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"senderForB\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getsenderForB\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"bAddress\",\"type\":\"address\"},{\"name\":\"_number\",\"type\":\"uint256\"}],\"name\":\"callcodeTest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"numberForB\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"bAddress\",\"type\":\"address\"}],\"name\":\"callAddTest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getnumberForB\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi1_ContractGrammar003_testGrammar014 = "[{\"constant\":true,\"inputs\":[],\"name\":\"addr11\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"addr2\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"addr1\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"add\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_number\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"senderForB\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getsenderForB\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"numberForB\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getnumberForB\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar003_testGrammar015 = "[{\"constant\":true,\"inputs\":[],\"name\":\"ExistFuncCalledTopic\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"para\",\"type\":\"uint256\"}],\"name\":\"existFunc\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"FallbackCalledTopic\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"callNonExistFunc\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"callExistFunc\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"data\",\"type\":\"bytes\"}],\"name\":\"FallbackCalled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"data\",\"type\":\"bytes\"},{\"indexed\":false,\"name\":\"para\",\"type\":\"uint256\"}],\"name\":\"ExistFuncCalled\",\"type\":\"event\"}]" - abi_ContractGrammar003_testGrammar016 = "[{\"constant\":false,\"inputs\":[],\"name\":\"readData\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi1_ContractGrammar003_testGrammar016 = "[{\"constant\":false,\"inputs\":[],\"name\":\"getData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"setData\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"g\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar003_testGrammar017 = "[{\"constant\":false,\"inputs\":[{\"name\":\"compaingnID\",\"type\":\"uint256\"}],\"name\":\"vote\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"comapingnId\",\"type\":\"uint256\"}],\"name\":\"check\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"beneficiary\",\"type\":\"address\"},{\"name\":\"goal\",\"type\":\"uint256\"}],\"name\":\"candidate\",\"outputs\":[{\"name\":\"compaingnID\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar003_testGrammar018 = "[{\"constant\":false,\"inputs\":[],\"name\":\"testKeccak256\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testMulmod\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testAddmod\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testSha256\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testRipemd160\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testSha3\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractGrammar003_testGrammar019 = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]" - abi_ContractGrammar003_testGrammar020 = "[{\"constant\":false,\"inputs\":[],\"name\":\"timetest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractScenario004_deployErc20TronToken = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"stop\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"stopped\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"start\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"name\":\"setName\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_addressFounder\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]" - abi_ContractScenario005_deployIcoContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"checkGoalReached\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"deadline\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"beneficiary\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"tokenReward\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"fundingGoal\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"amountRaised\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"price\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"safeWithdrawal\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"ifSuccessfulSendTo\",\"type\":\"address\"},{\"name\":\"fundingGoalInEthers\",\"type\":\"uint256\"},{\"name\":\"durationInMinutes\",\"type\":\"uint256\"},{\"name\":\"finneyCostOfEachToken\",\"type\":\"uint256\"},{\"name\":\"addressOfTokenUsedAsReward\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"recipient\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"totalAmountRaised\",\"type\":\"uint256\"}],\"name\":\"GoalReached\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"backer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"isContribution\",\"type\":\"bool\"}],\"name\":\"FundTransfer\",\"type\":\"event\"}]" - abi_ContractScenario006_deployFomo3D = "[{\"constant\":true,\"inputs\":[{\"name\":\"_customerAddress\",\"type\":\"address\"}],\"name\":\"dividendsOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_ethereumToSpend\",\"type\":\"uint256\"}],\"name\":\"calculateTokensReceived\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokensToSell\",\"type\":\"uint256\"}],\"name\":\"calculateEthereumReceived\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"onlyAmbassadors\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"administrators\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"sellPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"stakingRequirement\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_includeReferralBonus\",\"type\":\"bool\"}],\"name\":\"myDividends\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalEthereumBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_customerAddress\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_amountOfTokens\",\"type\":\"uint256\"}],\"name\":\"setStakingRequirement\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"buyPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_identifier\",\"type\":\"bytes32\"},{\"name\":\"_status\",\"type\":\"bool\"}],\"name\":\"setAdministrator\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"Hourglass\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"myTokens\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"disableInitialStage\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_toAddress\",\"type\":\"address\"},{\"name\":\"_amountOfTokens\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"name\":\"setSymbol\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"name\":\"setName\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_amountOfTokens\",\"type\":\"uint256\"}],\"name\":\"sell\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"exit\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_referredBy\",\"type\":\"address\"}],\"name\":\"buy\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"reinvest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"incomingEthereum\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"tokensMinted\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"referredBy\",\"type\":\"address\"}],\"name\":\"onTokenPurchase\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokensBurned\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"ethereumEarned\",\"type\":\"uint256\"}],\"name\":\"onTokenSell\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"ethereumReinvested\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"tokensMinted\",\"type\":\"uint256\"}],\"name\":\"onReinvestment\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"ethereumWithdrawn\",\"type\":\"uint256\"}],\"name\":\"onWithdraw\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokens\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]" - abi_ContractScenario007_deployErc721CardMigration = "[{\"constant\":true,\"inputs\":[{\"name\":\"_interfaceId\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"uint16\"}],\"name\":\"getProto\",\"outputs\":[{\"name\":\"exists\",\"type\":\"bool\"},{\"name\":\"god\",\"type\":\"uint8\"},{\"name\":\"season\",\"type\":\"uint8\"},{\"name\":\"cardType\",\"type\":\"uint8\"},{\"name\":\"rarity\",\"type\":\"uint8\"},{\"name\":\"mana\",\"type\":\"uint8\"},{\"name\":\"attack\",\"type\":\"uint8\"},{\"name\":\"health\",\"type\":\"uint8\"},{\"name\":\"tribe\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"ids\",\"type\":\"uint256[]\"}],\"name\":\"transferAllFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"governor\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"migrated\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"ids\",\"type\":\"uint256[]\"}],\"name\":\"burnAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"InterfaceId_ERC165\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"season\",\"type\":\"uint8\"}],\"name\":\"makePermanantlyTradable\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"externalID\",\"type\":\"uint16\"},{\"name\":\"god\",\"type\":\"uint8\"},{\"name\":\"rarity\",\"type\":\"uint8\"},{\"name\":\"mana\",\"type\":\"uint8\"},{\"name\":\"packable\",\"type\":\"bool\"}],\"name\":\"addSpell\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"common\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getActiveCards\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"migrate\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"mythic\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"exists\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenByIndex\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"index\",\"type\":\"uint16\"},{\"name\":\"god\",\"type\":\"uint8\"},{\"name\":\"cardType\",\"type\":\"uint8\"},{\"name\":\"mana\",\"type\":\"uint8\"},{\"name\":\"attack\",\"type\":\"uint8\"},{\"name\":\"health\",\"type\":\"uint8\"},{\"name\":\"tribe\",\"type\":\"uint8\"}],\"name\":\"replaceProto\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"burnCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"name\":\"seasonTradabilityLocked\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"uint16\"},{\"name\":\"limit\",\"type\":\"uint64\"}],\"name\":\"setLimit\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"ids\",\"type\":\"uint256[]\"}],\"name\":\"transferAll\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"name\":\"seasonTradable\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"proposed\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"owns\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"approved\",\"type\":\"address\"}],\"name\":\"addPack\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"purity\",\"type\":\"uint16\"}],\"name\":\"getShine\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"cards\",\"outputs\":[{\"name\":\"proto\",\"type\":\"uint16\"},{\"name\":\"purity\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"ids\",\"type\":\"uint256[]\"}],\"name\":\"migrateAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"getCard\",\"outputs\":[{\"name\":\"proto\",\"type\":\"uint16\"},{\"name\":\"purity\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"id\",\"type\":\"uint16\"}],\"name\":\"getLimit\",\"outputs\":[{\"name\":\"limit\",\"type\":\"uint64\"},{\"name\":\"set\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"name\":\"limits\",\"outputs\":[{\"name\":\"limit\",\"type\":\"uint64\"},{\"name\":\"exists\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"setApprovalForAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"NAME\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"rare\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"proto\",\"type\":\"uint16\"}],\"name\":\"isTradable\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"proposed\",\"type\":\"address\"},{\"name\":\"ids\",\"type\":\"uint256[]\"}],\"name\":\"ownsAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"tokenMetadataBaseURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"packs\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"safeTransferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"nextSeason\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"currentSeason\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_gov\",\"type\":\"address\"}],\"name\":\"setGovernor\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenURI\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"season\",\"type\":\"uint8\"}],\"name\":\"makeUntradable\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"rarity\",\"type\":\"uint8\"},{\"name\":\"random\",\"type\":\"uint16\"}],\"name\":\"getRandomCard\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"externalID\",\"type\":\"uint16\"},{\"name\":\"god\",\"type\":\"uint8\"},{\"name\":\"rarity\",\"type\":\"uint8\"},{\"name\":\"mana\",\"type\":\"uint8\"},{\"name\":\"attack\",\"type\":\"uint8\"},{\"name\":\"durability\",\"type\":\"uint8\"},{\"name\":\"packable\",\"type\":\"bool\"}],\"name\":\"addWeapon\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"externalID\",\"type\":\"uint16\"},{\"name\":\"god\",\"type\":\"uint8\"},{\"name\":\"rarity\",\"type\":\"uint8\"},{\"name\":\"mana\",\"type\":\"uint8\"},{\"name\":\"attack\",\"type\":\"uint8\"},{\"name\":\"health\",\"type\":\"uint8\"},{\"name\":\"cardType\",\"type\":\"uint8\"},{\"name\":\"tribe\",\"type\":\"uint8\"},{\"name\":\"packable\",\"type\":\"bool\"}],\"name\":\"addProto\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"protoCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"epic\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"externalID\",\"type\":\"uint16\"},{\"name\":\"god\",\"type\":\"uint8\"},{\"name\":\"rarity\",\"type\":\"uint8\"},{\"name\":\"mana\",\"type\":\"uint8\"},{\"name\":\"attack\",\"type\":\"uint8\"},{\"name\":\"health\",\"type\":\"uint8\"},{\"name\":\"tribe\",\"type\":\"uint8\"},{\"name\":\"packable\",\"type\":\"bool\"}],\"name\":\"addMinion\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"externalIDs\",\"type\":\"uint16[]\"},{\"name\":\"gods\",\"type\":\"uint8[]\"},{\"name\":\"rarities\",\"type\":\"uint8[]\"},{\"name\":\"manas\",\"type\":\"uint8[]\"},{\"name\":\"attacks\",\"type\":\"uint8[]\"},{\"name\":\"healths\",\"type\":\"uint8[]\"},{\"name\":\"cardTypes\",\"type\":\"uint8[]\"},{\"name\":\"tribes\",\"type\":\"uint8[]\"},{\"name\":\"packable\",\"type\":\"bool[]\"}],\"name\":\"addProtos\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getBurnCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_operator\",\"type\":\"address\"}],\"name\":\"isApprovedForAll\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"legendary\",\"outputs\":[{\"name\":\"\",\"type\":\"uint16\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"ids\",\"type\":\"uint256[]\"}],\"name\":\"approveAll\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"season\",\"type\":\"uint8\"}],\"name\":\"makeTradable\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"SYMBOL\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"owner\",\"type\":\"address\"},{\"name\":\"proto\",\"type\":\"uint16\"},{\"name\":\"purity\",\"type\":\"uint16\"}],\"name\":\"createCard\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"previous\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"id\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"proto\",\"type\":\"uint16\"},{\"indexed\":false,\"name\":\"purity\",\"type\":\"uint16\"},{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"}],\"name\":\"CardCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_operator\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_approved\",\"type\":\"bool\"}],\"name\":\"ApprovalForAll\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"id\",\"type\":\"uint16\"},{\"indexed\":false,\"name\":\"season\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"god\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"rarity\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"mana\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"attack\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"health\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"cardType\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"tribe\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"packable\",\"type\":\"bool\"}],\"name\":\"NewProtoCard\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Pause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Unpause\",\"type\":\"event\"}]" - abi_ContractScenario008_deployErc721CryptoKitties = "[{\"constant\":true,\"inputs\":[{\"name\":\"_interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cfoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_preferredTransport\",\"type\":\"string\"}],\"name\":\"tokenMetadata\",\"outputs\":[{\"name\":\"infoUrl\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"promoCreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ceoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_STARTING_PRICE\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSiringAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"pregnantKitties\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isPregnant\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_AUCTION_DURATION\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"siringAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setGeneScienceAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCEO\",\"type\":\"address\"}],\"name\":\"setCEO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCOO\",\"type\":\"address\"}],\"name\":\"setCOO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSaleAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"sireAllowedToAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"canBreedWith\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSiringAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"val\",\"type\":\"uint256\"}],\"name\":\"setAutoBirthFee\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"approveSiring\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCFO\",\"type\":\"address\"}],\"name\":\"setCFO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"},{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"createPromoKitty\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"secs\",\"type\":\"uint256\"}],\"name\":\"setSecondsPerBlock\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"newContractAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSaleAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"count\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_v2Address\",\"type\":\"address\"}],\"name\":\"setNewAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"secondsPerBlock\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"tokensOfOwner\",\"outputs\":[{\"name\":\"ownerTokens\",\"type\":\"uint256[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"giveBirth\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawAuctionBalances\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"cooldowns\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cooAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"autoBirthFee\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"erc721Metadata\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"}],\"name\":\"createGen0Auction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isReadyToBreed\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"PROMO_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_contractAddress\",\"type\":\"address\"}],\"name\":\"setMetadataAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"saleAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_id\",\"type\":\"uint256\"}],\"name\":\"getKitty\",\"outputs\":[{\"name\":\"isGestating\",\"type\":\"bool\"},{\"name\":\"isReady\",\"type\":\"bool\"},{\"name\":\"cooldownIndex\",\"type\":\"uint256\"},{\"name\":\"nextActionAt\",\"type\":\"uint256\"},{\"name\":\"siringWithId\",\"type\":\"uint256\"},{\"name\":\"birthTime\",\"type\":\"uint256\"},{\"name\":\"matronId\",\"type\":\"uint256\"},{\"name\":\"sireId\",\"type\":\"uint256\"},{\"name\":\"generation\",\"type\":\"uint256\"},{\"name\":\"genes\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_sireId\",\"type\":\"uint256\"},{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"bidOnSiringAuction\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"gen0CreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"geneScience\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"breedWithAuto\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"cooldownEndBlock\",\"type\":\"uint256\"}],\"name\":\"Pregnant\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"kittyId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"genes\",\"type\":\"uint256\"}],\"name\":\"Birth\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"newContract\",\"type\":\"address\"}],\"name\":\"ContractUpgrade\",\"type\":\"event\"}]" - abi_ContractScenario009_deployContainLibraryContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"remove\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"contains\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"self\",\"type\":\"Set.Data storage\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"insert\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractScenario010_deployContainLibraryContract = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"supply\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_index\",\"type\":\"uint256\"}],\"name\":\"tokenOfOwnerByIndex\",\"outputs\":[{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"tokenMetadata\",\"outputs\":[{\"name\":\"infoUrl\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"takeOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_approved\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]" - abi_ContractScenario012_deployTransactionCoin = "[{\"constant\":false,\"inputs\":[],\"name\":\"getBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"n\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"sendToAddress\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"user\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"nPlusOne\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositOneCoin\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"money\",\"type\":\"uint256\"}],\"name\":\"deposit\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"sendToAddress2\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getSenderBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractScenario013_deployTronTrxAndSunContract = "[{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]" - abi_ContractScenario013_triggerTronTrxAndSunContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"time\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractScenario014_testTripleTrigger = "[{\"constant\":false,\"inputs\":[{\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"send5SunToReceiver\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi1_ContractScenario014_testTripleTrigger = "[{\"constant\":false,\"inputs\":[{\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"triggerContract1ButRevert\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"triggerContract1\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"payContract\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_add\",\"type\":\"address\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi2_ContractScenario014_testTripleTrigger = "[{\"constant\":false,\"inputs\":[{\"name\":\"_receiver\",\"type\":\"address\"}],\"name\":\"triggerContract2\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"payContract\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_add\",\"type\":\"address\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_TronDice_tronDice = "[{\"constant\":false,\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_point\",\"type\":\"uint256\"}],\"name\":\"rollDice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deposit\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"ownerkill\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getPendingBalane\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_addr\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_point\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_random\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_P\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_O\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_W\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_B\",\"type\":\"uint256\"}],\"name\":\"UserWin\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_addr\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_point\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_random\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_B\",\"type\":\"uint256\"}],\"name\":\"UserLose\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_addr\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"Withdraw\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_balance\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_reward\",\"type\":\"uint256\"}],\"name\":\"RollDice\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"}]" - abi_TvmContract_deployErc721CryptoKitties = "[{\"constant\":true,\"inputs\":[{\"name\":\"_interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cfoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_preferredTransport\",\"type\":\"string\"}],\"name\":\"tokenMetadata\",\"outputs\":[{\"name\":\"infoUrl\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"promoCreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ceoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_STARTING_PRICE\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSiringAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"pregnantKitties\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isPregnant\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_AUCTION_DURATION\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"siringAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setGeneScienceAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCEO\",\"type\":\"address\"}],\"name\":\"setCEO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCOO\",\"type\":\"address\"}],\"name\":\"setCOO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSaleAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"sireAllowedToAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"canBreedWith\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSiringAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"val\",\"type\":\"uint256\"}],\"name\":\"setAutoBirthFee\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"approveSiring\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCFO\",\"type\":\"address\"}],\"name\":\"setCFO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"},{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"createPromoKitty\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"secs\",\"type\":\"uint256\"}],\"name\":\"setSecondsPerBlock\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"newContractAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSaleAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"count\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_v2Address\",\"type\":\"address\"}],\"name\":\"setNewAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"secondsPerBlock\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"tokensOfOwner\",\"outputs\":[{\"name\":\"ownerTokens\",\"type\":\"uint256[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"giveBirth\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawAuctionBalances\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"cooldowns\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cooAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"autoBirthFee\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"erc721Metadata\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"}],\"name\":\"createGen0Auction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isReadyToBreed\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"PROMO_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_contractAddress\",\"type\":\"address\"}],\"name\":\"setMetadataAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"saleAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_id\",\"type\":\"uint256\"}],\"name\":\"getKitty\",\"outputs\":[{\"name\":\"isGestating\",\"type\":\"bool\"},{\"name\":\"isReady\",\"type\":\"bool\"},{\"name\":\"cooldownIndex\",\"type\":\"uint256\"},{\"name\":\"nextActionAt\",\"type\":\"uint256\"},{\"name\":\"siringWithId\",\"type\":\"uint256\"},{\"name\":\"birthTime\",\"type\":\"uint256\"},{\"name\":\"matronId\",\"type\":\"uint256\"},{\"name\":\"sireId\",\"type\":\"uint256\"},{\"name\":\"generation\",\"type\":\"uint256\"},{\"name\":\"genes\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_sireId\",\"type\":\"uint256\"},{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"bidOnSiringAuction\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"gen0CreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"geneScience\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"breedWithAuto\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"cooldownEndBlock\",\"type\":\"uint256\"}],\"name\":\"Pregnant\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"kittyId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"genes\",\"type\":\"uint256\"}],\"name\":\"Birth\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"newContract\",\"type\":\"address\"}],\"name\":\"ContractUpgrade\",\"type\":\"event\"}]" - abi_ContractScenario011_deployErc721KittyCore = "[{\"constant\":true,\"inputs\":[{\"name\":\"_interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cfoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_preferredTransport\",\"type\":\"string\"}],\"name\":\"tokenMetadata\",\"outputs\":[{\"name\":\"infoUrl\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"promoCreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ceoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_STARTING_PRICE\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSiringAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"pregnantKitties\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isPregnant\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_AUCTION_DURATION\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"siringAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setGeneScienceAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCEO\",\"type\":\"address\"}],\"name\":\"setCEO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCOO\",\"type\":\"address\"}],\"name\":\"setCOO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSaleAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"sireAllowedToAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"canBreedWith\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSiringAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"val\",\"type\":\"uint256\"}],\"name\":\"setAutoBirthFee\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"approveSiring\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCFO\",\"type\":\"address\"}],\"name\":\"setCFO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"},{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"createPromoKitty\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"secs\",\"type\":\"uint256\"}],\"name\":\"setSecondsPerBlock\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"newContractAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSaleAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"count\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_v2Address\",\"type\":\"address\"}],\"name\":\"setNewAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"secondsPerBlock\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"tokensOfOwner\",\"outputs\":[{\"name\":\"ownerTokens\",\"type\":\"uint256[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"giveBirth\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawAuctionBalances\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"cooldowns\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cooAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"autoBirthFee\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"erc721Metadata\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"}],\"name\":\"createGen0Auction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isReadyToBreed\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"PROMO_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_contractAddress\",\"type\":\"address\"}],\"name\":\"setMetadataAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"saleAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_id\",\"type\":\"uint256\"}],\"name\":\"getKitty\",\"outputs\":[{\"name\":\"isGestating\",\"type\":\"bool\"},{\"name\":\"isReady\",\"type\":\"bool\"},{\"name\":\"cooldownIndex\",\"type\":\"uint256\"},{\"name\":\"nextActionAt\",\"type\":\"uint256\"},{\"name\":\"siringWithId\",\"type\":\"uint256\"},{\"name\":\"birthTime\",\"type\":\"uint256\"},{\"name\":\"matronId\",\"type\":\"uint256\"},{\"name\":\"sireId\",\"type\":\"uint256\"},{\"name\":\"generation\",\"type\":\"uint256\"},{\"name\":\"genes\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_sireId\",\"type\":\"uint256\"},{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"bidOnSiringAuction\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"gen0CreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"geneScience\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"breedWithAuto\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"cooldownEndBlock\",\"type\":\"uint256\"}],\"name\":\"Pregnant\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"kittyId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"genes\",\"type\":\"uint256\"}],\"name\":\"Birth\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"newContract\",\"type\":\"address\"}],\"name\":\"ContractUpgrade\",\"type\":\"event\"}]" - abi_ContractScenario011_deploySaleClockAuction = "[{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"},{\"name\":\"_seller\",\"type\":\"address\"}],\"name\":\"createAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"bid\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"lastGen0SalePrices\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getAuction\",\"outputs\":[{\"name\":\"seller\",\"type\":\"address\"},{\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"name\":\"duration\",\"type\":\"uint256\"},{\"name\":\"startedAt\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ownerCut\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isSaleClockAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuctionWhenPaused\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"gen0SaleCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getCurrentPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"nonFungibleContract\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"averageGen0SalePrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_nftAddr\",\"type\":\"address\"},{\"name\":\"_cut\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"duration\",\"type\":\"uint256\"}],\"name\":\"AuctionCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"winner\",\"type\":\"address\"}],\"name\":\"AuctionSuccessful\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"AuctionCancelled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Pause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Unpause\",\"type\":\"event\"}]" - abi_ContractScenario011_deploySiringClockAuction = "[{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"},{\"name\":\"_seller\",\"type\":\"address\"}],\"name\":\"createAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"bid\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isSiringClockAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getAuction\",\"outputs\":[{\"name\":\"seller\",\"type\":\"address\"},{\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"name\":\"duration\",\"type\":\"uint256\"},{\"name\":\"startedAt\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ownerCut\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuctionWhenPaused\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getCurrentPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"nonFungibleContract\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_nftAddr\",\"type\":\"address\"},{\"name\":\"_cut\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"duration\",\"type\":\"uint256\"}],\"name\":\"AuctionCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"winner\",\"type\":\"address\"}],\"name\":\"AuctionSuccessful\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"AuctionCancelled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Pause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Unpause\",\"type\":\"event\"}]" - abi_ContractScenario011_deployGeneScienceInterface = "[{\"constant\":true,\"inputs\":[{\"name\":\"genes1\",\"type\":\"uint256\"},{\"name\":\"genes2\",\"type\":\"uint256\"},{\"name\":\"targetBlock\",\"type\":\"uint256\"}],\"name\":\"mixGenes\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isGeneScience\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"}]" - abi_WalletTestAccount012_storageAndCpu = "[{\"constant\":false,\"inputs\":[{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"add2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"add\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"fori2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"args\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"fori\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]" - abi_TestExceptionCodeAndAbi_testExceptionCodeAndAbi = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply1\",\"outputs\":[{\"name\":\"_totalSupply1\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"_decimals\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"MAX_UINT256\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_data\",\"type\":\"bytes\"},{\"name\":\"_custom_fallback\",\"type\":\"string\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"_data\",\"type\":\"bytes\"}],\"name\":\"Transfer\",\"type\":\"event\"}]" - abi_TestExceptionCodeAndAbi_testtimeout = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"iarray\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"testUseCpu\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"testUseStorage\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"m\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"calculatedFibNumber\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"test\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"n\",\"type\":\"uint256\"}],\"name\":\"setFibonacci\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_TestMapBigLongAndNumbers_deployErc721KittyCore = "[{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"bytes\"},{\"name\":\"addr3\",\"type\":\"address\"}],\"name\":\"update3\",\"outputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balances1\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balances\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balances3\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"testUseCpu\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"s\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"addr2\",\"type\":\"address\"},{\"name\":\"times\",\"type\":\"uint256\"}],\"name\":\"update1\",\"outputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"string\"},{\"name\":\"addr3\",\"type\":\"address\"}],\"name\":\"update2\",\"outputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"addr1\",\"type\":\"address\"}],\"name\":\"update\",\"outputs\":[{\"name\":\"addr\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_TestNetErc721Cat_deployErc721KittyCore = "[{\"constant\":true,\"inputs\":[{\"name\":\"_interfaceID\",\"type\":\"bytes4\"}],\"name\":\"supportsInterface\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cfoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_preferredTransport\",\"type\":\"string\"}],\"name\":\"tokenMetadata\",\"outputs\":[{\"name\":\"infoUrl\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"promoCreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ceoAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_STARTING_PRICE\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSiringAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"pregnantKitties\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isPregnant\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_AUCTION_DURATION\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"siringAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setGeneScienceAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCEO\",\"type\":\"address\"}],\"name\":\"setCEO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCOO\",\"type\":\"address\"}],\"name\":\"setCOO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSaleAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"sireAllowedToAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"canBreedWith\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToApproved\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"}],\"name\":\"createSiringAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"val\",\"type\":\"uint256\"}],\"name\":\"setAutoBirthFee\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_addr\",\"type\":\"address\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"approveSiring\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newCFO\",\"type\":\"address\"}],\"name\":\"setCFO\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"},{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"createPromoKitty\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"secs\",\"type\":\"uint256\"}],\"name\":\"setSecondsPerBlock\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"ownerOf\",\"outputs\":[{\"name\":\"owner\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"GEN0_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"newContractAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"setSaleAuctionAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"count\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_v2Address\",\"type\":\"address\"}],\"name\":\"setNewAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"secondsPerBlock\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"tokensOfOwner\",\"outputs\":[{\"name\":\"ownerTokens\",\"type\":\"uint256[]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"giveBirth\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawAuctionBalances\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"cooldowns\",\"outputs\":[{\"name\":\"\",\"type\":\"uint32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"kittyIndexToOwner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"cooAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"autoBirthFee\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"erc721Metadata\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_genes\",\"type\":\"uint256\"}],\"name\":\"createGen0Auction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_kittyId\",\"type\":\"uint256\"}],\"name\":\"isReadyToBreed\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"PROMO_CREATION_LIMIT\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_contractAddress\",\"type\":\"address\"}],\"name\":\"setMetadataAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"saleAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_id\",\"type\":\"uint256\"}],\"name\":\"getKitty\",\"outputs\":[{\"name\":\"isGestating\",\"type\":\"bool\"},{\"name\":\"isReady\",\"type\":\"bool\"},{\"name\":\"cooldownIndex\",\"type\":\"uint256\"},{\"name\":\"nextActionAt\",\"type\":\"uint256\"},{\"name\":\"siringWithId\",\"type\":\"uint256\"},{\"name\":\"birthTime\",\"type\":\"uint256\"},{\"name\":\"matronId\",\"type\":\"uint256\"},{\"name\":\"sireId\",\"type\":\"uint256\"},{\"name\":\"generation\",\"type\":\"uint256\"},{\"name\":\"genes\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_sireId\",\"type\":\"uint256\"},{\"name\":\"_matronId\",\"type\":\"uint256\"}],\"name\":\"bidOnSiringAuction\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"gen0CreatedCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"geneScience\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_matronId\",\"type\":\"uint256\"},{\"name\":\"_sireId\",\"type\":\"uint256\"}],\"name\":\"breedWithAuto\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"cooldownEndBlock\",\"type\":\"uint256\"}],\"name\":\"Pregnant\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"approved\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"kittyId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"matronId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"sireId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"genes\",\"type\":\"uint256\"}],\"name\":\"Birth\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"newContract\",\"type\":\"address\"}],\"name\":\"ContractUpgrade\",\"type\":\"event\"}]" - abi_TestNetErc721Cat_deploySaleClockAuction = "[{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"},{\"name\":\"_seller\",\"type\":\"address\"}],\"name\":\"createAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"bid\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"lastGen0SalePrices\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getAuction\",\"outputs\":[{\"name\":\"seller\",\"type\":\"address\"},{\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"name\":\"duration\",\"type\":\"uint256\"},{\"name\":\"startedAt\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ownerCut\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isSaleClockAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuctionWhenPaused\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"gen0SaleCount\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getCurrentPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"nonFungibleContract\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"averageGen0SalePrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_nftAddr\",\"type\":\"address\"},{\"name\":\"_cut\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"duration\",\"type\":\"uint256\"}],\"name\":\"AuctionCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"winner\",\"type\":\"address\"}],\"name\":\"AuctionSuccessful\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"AuctionCancelled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Pause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Unpause\",\"type\":\"event\"}]" - abi_TestNetErc721Cat_deploySiringClockAuction = "[{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"},{\"name\":\"_startingPrice\",\"type\":\"uint256\"},{\"name\":\"_endingPrice\",\"type\":\"uint256\"},{\"name\":\"_duration\",\"type\":\"uint256\"},{\"name\":\"_seller\",\"type\":\"address\"}],\"name\":\"createAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"unpause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"bid\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"paused\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdrawBalance\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isSiringClockAuction\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getAuction\",\"outputs\":[{\"name\":\"seller\",\"type\":\"address\"},{\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"name\":\"duration\",\"type\":\"uint256\"},{\"name\":\"startedAt\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ownerCut\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"pause\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuctionWhenPaused\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"cancelAuction\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokenId\",\"type\":\"uint256\"}],\"name\":\"getCurrentPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"nonFungibleContract\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_nftAddr\",\"type\":\"address\"},{\"name\":\"_cut\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"startingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"endingPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"duration\",\"type\":\"uint256\"}],\"name\":\"AuctionCreated\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"totalPrice\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"winner\",\"type\":\"address\"}],\"name\":\"AuctionSuccessful\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"AuctionCancelled\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Pause\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[],\"name\":\"Unpause\",\"type\":\"event\"}]" - abi_TestNetErc721Cat_deployGeneScienceInterface = "[{\"constant\":true,\"inputs\":[{\"name\":\"genes1\",\"type\":\"uint256\"},{\"name\":\"genes2\",\"type\":\"uint256\"},{\"name\":\"targetBlock\",\"type\":\"uint256\"}],\"name\":\"mixGenes\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"isGeneScience\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"}]" - abi_TestNetFomo3D_deployErc721CryptoKitties = "[{\"constant\":true,\"inputs\":[{\"name\":\"_customerAddress\",\"type\":\"address\"}],\"name\":\"dividendsOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_ethereumToSpend\",\"type\":\"uint256\"}],\"name\":\"calculateTokensReceived\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_tokensToSell\",\"type\":\"uint256\"}],\"name\":\"calculateEthereumReceived\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"onlyAmbassadors\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"administrators\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"withdraw\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"sellPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"stakingRequirement\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_includeReferralBonus\",\"type\":\"bool\"}],\"name\":\"myDividends\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalEthereumBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_customerAddress\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_amountOfTokens\",\"type\":\"uint256\"}],\"name\":\"setStakingRequirement\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"buyPrice\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_identifier\",\"type\":\"bytes32\"},{\"name\":\"_status\",\"type\":\"bool\"}],\"name\":\"setAdministrator\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"Hourglass\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"myTokens\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"disableInitialStage\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_toAddress\",\"type\":\"address\"},{\"name\":\"_amountOfTokens\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_symbol\",\"type\":\"string\"}],\"name\":\"setSymbol\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_name\",\"type\":\"string\"}],\"name\":\"setName\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_amountOfTokens\",\"type\":\"uint256\"}],\"name\":\"sell\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"exit\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_referredBy\",\"type\":\"address\"}],\"name\":\"buy\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"reinvest\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"incomingEthereum\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"tokensMinted\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"referredBy\",\"type\":\"address\"}],\"name\":\"onTokenPurchase\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokensBurned\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"ethereumEarned\",\"type\":\"uint256\"}],\"name\":\"onTokenSell\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"ethereumReinvested\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"tokensMinted\",\"type\":\"uint256\"}],\"name\":\"onReinvestment\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"customerAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"ethereumWithdrawn\",\"type\":\"uint256\"}],\"name\":\"onWithdraw\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokens\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"}]" - abi1_TestNetFomo3D_deployErc721CryptoKitties = "[{\"constant\":false,\"inputs\":[],\"name\":\"test\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_TestNetFomo3D_tooLargeStorage = "[{\"constant\":true,\"inputs\":[],\"name\":\"s\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"foo\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"times\",\"type\":\"uint256\"}],\"name\":\"slice\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"refresh\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_TestStorageAndCpu_storageAndCpu = "[{\"constant\":false,\"inputs\":[],\"name\":\"oneCpu\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"iarray\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"storage8Char\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"testUseCpu\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"testUseStorage\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"m\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"iarray1\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"calculatedFibNumber\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"test\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"n\",\"type\":\"uint256\"}],\"name\":\"setFibonacci\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_WalletTestAccount013 = "[{\"constant\":false,\"inputs\":[{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"add2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"add\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"index\",\"type\":\"uint256\"}],\"name\":\"fori2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"args\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"fori\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}] " - abi_ContractEventAndLog1 = "[{\"constant\":false,\"inputs\":[],\"name\":\"depositForLog\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"depositForLogCycle\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForAnonymousNoLog\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForEventAndLog\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getTransactionKeccak256\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForAnonymousHasLog\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForEventTwoIndex\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForEvent\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getDepositKeccak256\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForEventNoIndex\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"a\",\"type\":\"uint256\"}],\"name\":\"depositForEventCycle\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"yes\",\"type\":\"bool\"},{\"name\":\"no\",\"type\":\"bool\"}],\"name\":\"triggerBoolEvent\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"triggerUintEvent\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"age\",\"type\":\"string\"}],\"name\":\"triggerStringEvent\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"age\",\"type\":\"string\"}],\"name\":\"triggerStringEventAnonymous\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"triggerintEvent\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getBanlance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositForEventOneIndex\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"value1\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"value2\",\"type\":\"uint64\"},{\"indexed\":false,\"name\":\"value3\",\"type\":\"uint128\"},{\"indexed\":false,\"name\":\"value4\",\"type\":\"uint248\"}],\"name\":\"uintErgodic\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"value1\",\"type\":\"int8\"},{\"indexed\":false,\"name\":\"value2\",\"type\":\"int72\"},{\"indexed\":false,\"name\":\"value3\",\"type\":\"int136\"},{\"indexed\":false,\"name\":\"value4\",\"type\":\"int232\"}],\"name\":\"intErgodic\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"name\",\"type\":\"string\"},{\"indexed\":true,\"name\":\"age\",\"type\":\"string\"}],\"name\":\"stringEvent\",\"type\":\"event\"},{\"anonymous\":true,\"inputs\":[{\"indexed\":false,\"name\":\"name\",\"type\":\"string\"},{\"indexed\":true,\"name\":\"age\",\"type\":\"string\"}],\"name\":\"stringEventAnonymous\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"yes\",\"type\":\"bool\"},{\"indexed\":true,\"name\":\"no\",\"type\":\"bool\"}],\"name\":\"boolEvent\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferNoIndex\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferOneIndex\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferTwoIndex\",\"type\":\"event\"},{\"anonymous\":true,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transferAnonymous\",\"type\":\"event\"}]" - abi_ContractEventAndLog2 = "[{\"constant\":false,\"inputs\":[],\"name\":\"triggerEventBytes\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"deposit\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getBanlance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"value10\",\"type\":\"bytes10\"},{\"indexed\":false,\"name\":\"value17\",\"type\":\"bytes17\"},{\"indexed\":false,\"name\":\"value32\",\"type\":\"bytes32\"}],\"name\":\"eventBytes\",\"type\":\"event\"},{\"anonymous\":true,\"inputs\":[{\"indexed\":false,\"name\":\"value10\",\"type\":\"bytes10\"},{\"indexed\":false,\"name\":\"value17\",\"type\":\"bytes17\"},{\"indexed\":false,\"name\":\"value32\",\"type\":\"bytes32\"}],\"name\":\"triggerBytesAnonymous\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"value10\",\"type\":\"bytes10\"},{\"indexed\":true,\"name\":\"value17\",\"type\":\"bytes17\"},{\"indexed\":true,\"name\":\"value32\",\"type\":\"bytes32\"}],\"name\":\"eventBytesIndex\",\"type\":\"event\"},{\"anonymous\":true,\"inputs\":[{\"indexed\":true,\"name\":\"value10\",\"type\":\"bytes10\"},{\"indexed\":true,\"name\":\"value17\",\"type\":\"bytes17\"},{\"indexed\":true,\"name\":\"value32\",\"type\":\"bytes32\"}],\"name\":\"triggerBytesAnonymousIndex\",\"type\":\"event\"}]" - - abi_OriginEnergyLimit001 = "[{\"constant\":false,\"inputs\":[{\"name\":\"i\",\"type\":\"uint256\"}],\"name\":\"findArgsByIndexTest\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_OriginEnergyLimit004 = "[{\"constant\":false,\"inputs\":[{\"name\":\"i\",\"type\":\"uint256\"}],\"name\":\"findArgsByIndexTest\",\"outputs\":[{\"name\":\"z\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - - abi_ContractTrcToken001_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"getResultInCon\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]\n" - abi_ContractTrcToken002_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken005_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken006_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken011_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken011_resultContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken012_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken014_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken014_resultContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken016_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken016_resultContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken017_recieveTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"setFlag\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"flag\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken042_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken042_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken043_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken043_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken046_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken047_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi2_ContractTrcToken023_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken023_tokenTest = "[{\"constant\":true,\"inputs\":[],\"name\":\"flag\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken026_BTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"callCAddress\",\"type\":\"address\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transC\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi1_ContractTrcToken026_CTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"trans\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi1_ContractTrcToken026_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"callBAddress\",\"type\":\"address\"},{\"name\":\"callCAddress\",\"type\":\"address\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"testInCall\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"callBddress\",\"type\":\"address\"},{\"name\":\"callAddressC\",\"type\":\"address\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"testIndelegateCall\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken027_BTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"callCAddress\",\"type\":\"address\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transC\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken027_CTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"trans\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken027_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"callBAddress\",\"type\":\"address\"},{\"name\":\"callCAddress\",\"type\":\"address\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"testIndelegateCall\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"callBddress\",\"type\":\"address\"},{\"name\":\"callAddressC\",\"type\":\"address\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"testIndelegateCall\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken028_tokenTest = "[{\"constant\":true,\"inputs\":[],\"name\":\"a\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"tokenBalanceWithSameName\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getA\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken054_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken055_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken060_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"getResultInCon\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]\n" - abi_ContractTrcToken061_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"getResultInCon\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]\n" - abi_ContractTrcToken062_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken062_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken063_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken063_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken064_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken064_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken066_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken066_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken067_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken067_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken068_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken068_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken071_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestIDOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken071_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken073_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getToken\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"logFallback\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"logGetToken\",\"type\":\"event\"}]" - abi_ContractTrcToken074_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getToken\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"logFallback\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"logGetToken\",\"type\":\"event\"}]" - abi_ContractTrcToken075_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"getTokenLongMin\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getToken\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getTokenLongMax\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"logFallback\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":true,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"logGetToken\",\"type\":\"event\"}]" - abi_ContractTrcToken0552_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken0553_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken0612_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"getResultInCon\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]\n" - abi_ContractTrcToken0613_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"getResultInCon\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]\n" - abi_ContractTrcToken0672_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"transferTokenTest\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueOverBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueRandomIdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"accountAddress\",\"type\":\"address\"}],\"name\":\"getTokenBalanceTest\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"msgTokenValueAndTokenIdTest\",\"outputs\":[{\"name\":\"\",\"type\":\"trcToken\"},{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValueMaxLong\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"}],\"name\":\"getTokenBalnce\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTokenTestValue0IdBigInteger\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken0672_recieveTokenContract = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - - abi_ContractTrcToken029_tokenTest = "[{\"constant\":true,\"inputs\":[],\"name\":\"a\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"transferTokenWithSameName\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken030_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"kill\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken031_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"kill\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken034_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"failTransferTokenError\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"failTransferTokenRevert\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken035_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"failTransferTokenError\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"failTransferTokenRevert\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken036_transferTokenWithPureTest = "[{\"constant\":true,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"}],\"name\":\"transferTokenWithConstant\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - - abi_ContractTrcToken036_transferTokenWithViewTest = "[{\"constant\":true,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"}],\"name\":\"transferTokenWithView\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken036_transferTokenWithOutPayableTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"}],\"name\":\"transferTokenWithOutPayable\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken037_receiveTrc10Test = "[{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"tid\",\"type\":\"trcToken\"},{\"name\":\"meamount\",\"type\":\"uint256\"}],\"name\":\"checkTrc10\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - - abi_ContractTrcToken037_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"rec\",\"type\":\"address\"}],\"name\":\"receive\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken038_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"rec\",\"type\":\"address\"}],\"name\":\"receive\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken038_BTest = "[{\"constant\":false,\"inputs\":[],\"name\":\"AssertError\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - - abi_ContractTrcToken039_ProxyTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"upgradeTo\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"implementation\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - - abi_ContractTrcToken039_ATest = "[{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"trans\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken039_BTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"}],\"name\":\"trans\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken041_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken048_transferTokenContract = "[{\"constant\":false,\"inputs\":[],\"name\":\"testMsgValue\",\"outputs\":[{\"name\":\"value\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"testMsgTokenValue\",\"outputs\":[{\"name\":\"value\",\"type\":\"uint256\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - - abi_ContractTrcToken050_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - - abi_ContractTrcToken051_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - - - abi_ContractTrcToken052_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken036_tokenTest = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"tokenValue\",\"type\":\"uint256\"}],\"name\":\"transferTokenWithPure\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_ContractTrcToken049_transferTokenContract = "[{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"},{\"name\":\"id\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TransferTokenTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_ContractTrcToken076_originTest = "[{\"constant\":true,\"inputs\":[],\"name\":\"result2\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"result1\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"sender\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getResult1\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"origin\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"getResult2\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"test\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_ContractTrcToken077_AddressTest = "[{\"constant\":true,\"inputs\":[],\"name\":\"addressTest\",\"outputs\":[{\"name\":\"addressValue\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_ContractTrcToken077_AddressTest1 = "[{\"constant\":false,\"inputs\":[],\"name\":\"addressTest\",\"outputs\":[{\"name\":\"addressValue\",\"type\":\"bytes32\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_ContractTrcToken078_AddressTest1 = "[{\"constant\":false,\"inputs\":[{\"name\":\"called_address\",\"type\":\"address\"},{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"sendToB3\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"called_address\",\"type\":\"address\"},{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"sendToB\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"called_address\",\"type\":\"address\"},{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"sendToB2\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken078_AddressTest2 = "[{\"constant\":false,\"inputs\":[{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"setIinC\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken078_AddressTest3 = "[{\"constant\":true,\"inputs\":[],\"name\":\"sender\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"origin\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"\",\"type\":\"address\"}],\"name\":\"log\",\"type\":\"event\"}]" - - abi_ContractTrcToken078_AddressTest4 = "[{\"constant\":false,\"inputs\":[{\"name\":\"called_address\",\"type\":\"address\"},{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"sendToB3\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"called_address\",\"type\":\"address\"},{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"sendToB\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"called_address\",\"type\":\"address\"},{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"sendToB2\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - - abi_ContractTrcToken078_AddressTest5 = "[{\"constant\":false,\"inputs\":[{\"name\":\"c\",\"type\":\"address\"}],\"name\":\"setIinC\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"toAddress\",\"type\":\"address\"}],\"name\":\"transferTo\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_ContractTrcToken078_AddressTest6 = "[{\"constant\":true,\"inputs\":[],\"name\":\"sender\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"origin\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"\",\"type\":\"address\"}],\"name\":\"log\",\"type\":\"event\"}]" - abi_veryLarge = "[{\"constant\":false,\"inputs\":[],\"name\":\"getBalance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"Address\",\"type\":\"address\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"num\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"}]" - abi_MainGateway = "[{\"constant\":true,\"inputs\":[{\"name\":\"_address\",\"type\":\"address\"}],\"name\":\"checkOracle\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"contractAddress\",\"type\":\"address\"},{\"name\":\"uid\",\"type\":\"uint256\"},{\"name\":\"sig\",\"type\":\"bytes\"}],\"name\":\"withdrawTRC721\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositTRX\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"depositTRC10\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"contractAddress\",\"type\":\"address\"}],\"name\":\"depositTRC20\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[],\"name\":\"renounceOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"uid\",\"type\":\"uint256\"},{\"name\":\"contractAddress\",\"type\":\"address\"}],\"name\":\"depositTRC721\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"nonces\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"numOracles\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"contractAddress\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"sig\",\"type\":\"bytes\"}],\"name\":\"withdrawTRC20\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"getTRC10\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_oracle\",\"type\":\"address\"},{\"name\":\"isOracle\",\"type\":\"bool\"}],\"name\":\"modifyOracle\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"uid\",\"type\":\"uint256\"},{\"name\":\"contractAddress\",\"type\":\"address\"}],\"name\":\"getNFT\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"trcToken\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"sig\",\"type\":\"bytes\"}],\"name\":\"withdrawTRC10\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowes\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onTRC20Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_uid\",\"type\":\"uint256\"},{\"name\":\"\",\"type\":\"bytes\"}],\"name\":\"onTRC721Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"getTRX\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"mainChainToken\",\"type\":\"address\"},{\"name\":\"sideChainToken\",\"type\":\"address\"}],\"name\":\"migrationToken\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"amount\",\"type\":\"uint256\"},{\"name\":\"sig\",\"type\":\"bytes\"}],\"name\":\"withdrawTRX\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"contractAddress\",\"type\":\"address\"}],\"name\":\"getTRC20\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_newOwner\",\"type\":\"address\"}],\"name\":\"transferOwnership\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_oracle\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"TRXReceived\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"TRC10Received\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"amount\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"contractAddress\",\"type\":\"address\"}],\"name\":\"TRC20Received\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"uid\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"contractAddress\",\"type\":\"address\"}],\"name\":\"TRC721Received\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"kind\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"contractAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"TokenWithdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"owner\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"kind\",\"type\":\"uint8\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"trcToken\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Token10Withdrawn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"oracle\",\"type\":\"address\"}],\"name\":\"NewOracles\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"}],\"name\":\"OwnershipRenounced\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"previousOwner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"newOwner\",\"type\":\"address\"}],\"name\":\"OwnershipTransferred\",\"type\":\"event\"}]" - abi_SideGateway = "[{\"constant\":false,\"inputs\":[{\"name\":\"_sunTokenAddress\",\"type\":\"address\"}],\"name\":\"setSunTokenAddress\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"b1\",\"type\":\"bytes\"},{\"name\":\"b2\",\"type\":\"bytes\"}],\"name\":\"concatBytes\",\"outputs\":[{\"name\":\"r\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"withdrawTRX\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"trc10\",\"type\":\"uint256\"},{\"name\":\"value\",\"type\":\"uint256\"},{\"name\":\"name\",\"type\":\"bytes32\"},{\"name\":\"symbol\",\"type\":\"bytes32\"},{\"name\":\"decimals\",\"type\":\"uint8\"}],\"name\":\"depositTRC10\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"depositTRC20\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"trc10Map\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"mainToSideContractMap\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txId\",\"type\":\"bytes\"},{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"symbol\",\"type\":\"string\"},{\"name\":\"decimals\",\"type\":\"uint8\"}],\"name\":\"deployDAppTRC20AndMapping\",\"outputs\":[{\"name\":\"r\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"sunTokenAddress\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"txId\",\"type\":\"bytes\"},{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"calcContractAddress\",\"outputs\":[{\"name\":\"r\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_oracle\",\"type\":\"address\"},{\"name\":\"isOracle\",\"type\":\"bool\"}],\"name\":\"modifyOracle\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txId\",\"type\":\"bytes\"},{\"name\":\"name\",\"type\":\"string\"},{\"name\":\"symbol\",\"type\":\"string\"}],\"name\":\"deployDAppTRC721AndMapping\",\"outputs\":[{\"name\":\"r\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"oracles\",\"outputs\":[{\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"},{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"onTRC20Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"from\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"},{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"onTRC721Received\",\"outputs\":[{\"name\":\"\",\"type\":\"bytes4\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"sideToMainContractMap\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"a\",\"type\":\"address\"}],\"name\":\"addressToBytes\",\"outputs\":[{\"name\":\"b\",\"type\":\"bytes\"}],\"payable\":false,\"stateMutability\":\"pure\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"withdrawTRC10\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"depositTRX\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"to\",\"type\":\"address\"},{\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"depositTRC721\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"_oracle\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"developer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"}],\"name\":\"DeployDAppTRC20AndMapping\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"developer\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"}],\"name\":\"DeployDAppTRC721AndMapping\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"trc10\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositTRC10\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositTRC20\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"sideChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"}],\"name\":\"DepositTRC721\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"DepositTRX\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"trc10\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRC10\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRC20\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"tokenId\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"mainChainAddress\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRC721\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"name\":\"txData\",\"type\":\"bytes\"}],\"name\":\"WithdrawTRX\",\"type\":\"event\"}]" - abi_shieldTrc20Token = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"burn\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"burnFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_extraData\",\"type\":\"bytes\"}],\"name\":\"approveAndCall\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"address\"},{\"name\":\"\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialSupply\",\"type\":\"uint256\"},{\"name\":\"tokenName\",\"type\":\"string\"},{\"name\":\"tokenSymbol\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"Burn\",\"type\":\"event\"}]" - abi_shield = "[{\"inputs\":[{\"internalType\":\"address\",\"name\":\"trc20ContractAddress\",\"type\":\"address\"},{\"internalType\":\"uint256\",\"name\":\"scalingFactorExponent\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cm\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cv\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"epk\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"BurnNewLeaf\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cm\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cv\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"epk\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"MintNewLeaf\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"nf\",\"type\":\"bytes32\"}],\"name\":\"NoteSpent\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"to\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32[3]\",\"name\":\"ciphertext\",\"type\":\"bytes32[3]\"}],\"name\":\"TokenBurn\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"address\",\"name\":\"from\",\"type\":\"address\"},{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"name\":\"TokenMint\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cm\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"cv\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32\",\"name\":\"epk\",\"type\":\"bytes32\"},{\"indexed\":false,\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"TransferNewLeaf\",\"type\":\"event\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32[10]\",\"name\":\"input\",\"type\":\"bytes32[10]\"},{\"internalType\":\"bytes32[2]\",\"name\":\"spendAuthoritySignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"uint256\",\"name\":\"rawValue\",\"type\":\"uint256\"},{\"internalType\":\"bytes32[2]\",\"name\":\"bindingSignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"address\",\"name\":\"payTo\",\"type\":\"address\"},{\"internalType\":\"bytes32[3]\",\"name\":\"burnCipher\",\"type\":\"bytes32[3]\"},{\"internalType\":\"bytes32[9][]\",\"name\":\"output\",\"type\":\"bytes32[9][]\"},{\"internalType\":\"bytes32[21][]\",\"name\":\"c\",\"type\":\"bytes32[21][]\"}],\"name\":\"burn\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"position\",\"type\":\"uint256\"}],\"name\":\"getPath\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32[32]\",\"name\":\"\",\"type\":\"bytes32[32]\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"latestRoot\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"leafCount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"rawValue\",\"type\":\"uint256\"},{\"internalType\":\"bytes32[9]\",\"name\":\"output\",\"type\":\"bytes32[9]\"},{\"internalType\":\"bytes32[2]\",\"name\":\"bindingSignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"bytes32[21]\",\"name\":\"c\",\"type\":\"bytes32[21]\"}],\"name\":\"mint\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"noteCommitment\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"nullifiers\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"name\":\"roots\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"scalingFactor\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"bytes32[10][]\",\"name\":\"input\",\"type\":\"bytes32[10][]\"},{\"internalType\":\"bytes32[2][]\",\"name\":\"spendAuthoritySignature\",\"type\":\"bytes32[2][]\"},{\"internalType\":\"bytes32[9][]\",\"name\":\"output\",\"type\":\"bytes32[9][]\"},{\"internalType\":\"bytes32[2]\",\"name\":\"bindingSignature\",\"type\":\"bytes32[2]\"},{\"internalType\":\"bytes32[21][]\",\"name\":\"c\",\"type\":\"bytes32[21][]\"}],\"name\":\"transfer\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"tree\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_getAddressChange = "[{\"inputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"constructor\"},{\"constant\":true,\"inputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"name\":\"getamount\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"testaddress1\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_fallbackOldVersionTest = "[{\"anonymous\":false,\"inputs\":[{\"indexed\":false,\"internalType\":\"string\",\"name\":\"data\",\"type\":\"string\"},{\"indexed\":false,\"internalType\":\"bytes\",\"name\":\"msg\",\"type\":\"bytes\"}],\"name\":\"FallbackCall\",\"type\":\"event\"},{\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"fallback\"}]" - abi_fallbackOldversionCall = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"contract Test0\",\"name\":\"test\",\"type\":\"address\"}],\"name\":\"call\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"}]" - abi_arrayLenth_0.5.15 = "[{\"constant\":false,\"inputs\":[],\"name\":\"ChangeSize\",\"outputs\":[{\"internalType\":\"bytes1[]\",\"name\":\"\",\"type\":\"bytes1[]\"}],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" - abi_override001 = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_y\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"x\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"y\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_override002 = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_x\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_x\",\"type\":\"uint256\"}],\"name\":\"setValue2\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"x\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_override003 = "[{\"constant\":true,\"inputs\":[],\"name\":\"b32\",\"outputs\":[{\"internalType\":\"bytes32\",\"name\":\"\",\"type\":\"bytes32\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"choice\",\"outputs\":[{\"internalType\":\"enum Base.ActionChoices\",\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"choice2\",\"outputs\":[{\"internalType\":\"enum Base.ActionChoices\",\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"i2\",\"outputs\":[{\"internalType\":\"int256\",\"name\":\"\",\"type\":\"int256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"origin\",\"outputs\":[{\"internalType\":\"address\",\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"stopped\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"ui\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_virtual001 = "[{\"constant\":false,\"inputs\":[{\"internalType\":\"bool\",\"name\":\"_y\",\"type\":\"bool\"}],\"name\":\"setBool\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"string\",\"name\":\"_z\",\"type\":\"string\"}],\"name\":\"setString\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"internalType\":\"uint256\",\"name\":\"_x\",\"type\":\"uint256\"}],\"name\":\"setValue\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"x\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"y\",\"outputs\":[{\"internalType\":\"bool\",\"name\":\"\",\"type\":\"bool\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"z\",\"outputs\":[{\"internalType\":\"string\",\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"}]" - abi_slotAndOffset_06x = "[{\"inputs\":[],\"name\":\"getA\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"name\":\"getE\",\"outputs\":[{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"},{\"internalType\":\"uint256\",\"name\":\"\",\"type\":\"uint256\"}],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]" -} \ No newline at end of file diff --git a/framework/src/test/resources/testng.xml b/framework/src/test/resources/testng.xml deleted file mode 100644 index 6856338d3b8..00000000000 --- a/framework/src/test/resources/testng.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000000..031a8cddc89 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,2 @@ +org.gradle.parallel=true +org.gradle.jvmargs=-Xms1g diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml new file mode 100644 index 00000000000..b3c879f6b40 --- /dev/null +++ b/gradle/verification-metadata.xml @@ -0,0 +1,2531 @@ + + + + true + false + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 28861d273a5..5c2d1cf016b 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 1b00285c540..3994438e229 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,5 @@ -#Thu Aug 01 15:17:43 CST 2019 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip diff --git a/gradlew b/gradlew index cccdd3d517f..83f2acfdc31 100755 --- a/gradlew +++ b/gradlew @@ -1,5 +1,21 @@ #!/usr/bin/env sh +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + ############################################################################## ## ## Gradle start up script for UN*X @@ -28,7 +44,7 @@ APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS="" +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" @@ -109,8 +125,8 @@ if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi -# For Cygwin, switch paths to Windows format before running java -if $cygwin ; then +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` diff --git a/gradlew.bat b/gradlew.bat index e95643d6a2c..24467a141f7 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -1,3 +1,19 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS= +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome diff --git a/plugins/README.md b/plugins/README.md new file mode 100644 index 00000000000..0db6f2e6143 --- /dev/null +++ b/plugins/README.md @@ -0,0 +1,147 @@ +# Toolkit Manual + +This package contains a set of tools for TRON, the followings are the documentation for each tool. + +## DB Archive + +DB archive provides the ability to reformat the manifest according to the current `database`, parameters are compatible with the previous `ArchiveManifest`. + +### Available parameters: + +- `-b | --batch-size`: Specify the batch manifest size, default: 80000. +- `-d | --database-directory`: Specify the database directory to be processed, default: output-directory/database. +- `-m | --manifest-size`: Specify the minimum required manifest file size, unit: M, default: 0. +- `-h | --help`: Provide the help info. + +### Examples: + +```shell script +# full command + java -jar Toolkit.jar db archive [-h] [-b=] [-d=] [-m=] +# examples + java -jar Toolkit.jar db archive #1. use default settings + java -jar Toolkit.jar db archive -d /tmp/db/database #2. specify the database directory as /tmp/db/database + java -jar Toolkit.jar db archive -b 64000 #3. specify the batch size to 64000 when optimizing manifest + java -jar Toolkit.jar db archive -m 128 #4. specify optimization only when Manifest exceeds 128M +``` + + +## DB Convert + +DB convert provides a helper which can convert LevelDB data to RocksDB data, parameters are compatible with previous `DBConvert`. + +### Available parameters: + +- ``: Input path for leveldb, default: output-directory/database. +- ``: Output path for rocksdb, default: output-directory-dst/database. +- `--safe`: In safe mode, read data from leveldb then put into rocksdb, it's a very time-consuming procedure. If not, just change engine.properties from leveldb to rocksdb, rocksdb + is compatible with leveldb for the current version. This may not be the case in the future, default: false. +- `-h | --help`: Provide the help info. + +### Examples: + +```shell script +# full command + java -jar Toolkit.jar db convert [-h] [--safe] +# examples + java -jar Toolkit.jar db convert output-directory/database /tmp/database +``` + +## DB Copy + +DB copy provides a helper which can copy LevelDB or RocksDB data quickly on the same file systems by creating hard links. + +### Available parameters: + +- ``: Source path for database. Default: output-directory/database +- ``: Output path for database. Default: output-directory-cp/database +- `-h | --help`: provide the help info + +### Examples: + +```shell script +# full command + java -jar Toolkit.jar db cp [-h] +# examples + java -jar Toolkit.jar db cp output-directory/database /tmp/databse +``` + +## DB Lite + +DB lite provides lite database, parameters are compatible with previous `LiteFullNodeTool`. + +### Available parameters: + +- `-o | --operate`: [split,merge], default: split. +- `-t | --type`: Only used with operate=split: [snapshot,history], default: snapshot. +- `-fn | --fn-data-path`: The database path to be split or merged. +- `-ds | --dataset-path`: When operation is `split`,`dataset-path` is the path that store the `snapshot` or `history`, when + operation is `split`, `dataset-path` is the `history` data path. +- `-h | --help`: Provide the help info. + +### Examples: + +```shell script +# full command + java -jar Toolkit.jar db lite [-h] -ds= -fn= [-o=] [-t=] +# examples + #split and get a snapshot dataset + java -jar Toolkit.jar db lite -o split -t snapshot --fn-data-path output-directory/database --dataset-path /tmp + #split and get a history dataset + java -jar Toolkit.jar db lite -o split -t history --fn-data-path output-directory/database --dataset-path /tmp + #merge history dataset and snapshot dataset + java -jar Toolkit.jar db lite -o merge --fn-data-path /tmp/snapshot --dataset-path /tmp/history +``` + +## DB Move + +DB move provides a helper to move some dbs to a pre-set new path. For example move `block`, `transactionRetStore` or `transactionHistoryStore` to HDD for reducing storage expenses. + +### Available parameters: + +- `-c | --config`: config file. Default: config.conf. +- `-d | --database-directory`: database directory path. Default: output-directory. +- `-h | --help`: provide the help info + +### Examples: + +Take the example of moving `block` and `trans`. + + +Set path for `block` and `trans`. + +```conf +storage { + ...... + properties = [ + { + name = "block", + path = "/data1/tron", + }, + { + name = "trans", + path = "/data1/tron", + } + ] + ...... +} +``` +Execute move command. +```shell script +# full command + java -jar Toolkit.jar db mv [-h] [-c=] [-d=] +# examples + java -jar Toolkit.jar db mv -c main_net_config.conf -d /data/tron/output-directory +``` + +## DB Root + +DB root provides a helper which can compute merkle root for tiny db. + +NOTE: large db may GC overhead limit exceeded. + +### Available parameters: + +- ``: Source path for database. Default: output-directory/database +- `--db`: db name. +- `-h | --help`: provide the help info diff --git a/plugins/build.gradle b/plugins/build.gradle index 494694dee59..01afaa01708 100644 --- a/plugins/build.gradle +++ b/plugins/build.gradle @@ -5,9 +5,6 @@ plugins { apply plugin: 'application' apply plugin: 'checkstyle' -jacoco { - toolVersion = "0.8.4" -} def versions = [ checkstyle: '8.7', ] @@ -25,16 +22,17 @@ configurations.getByName('checkstyleConfig') { dependencies { //local libraries - compile fileTree(dir: 'libs', include: '*.jar') - testCompile group: 'junit', name: 'junit', version: '4.12' - testCompile group: 'org.mockito', name: 'mockito-core', version: '2.13.0' - testCompile group: 'org.hamcrest', name: 'hamcrest-junit', version: '1.0.0.1' - testCompile group: 'org.testng', name: 'testng', version: '6.14.3' - // https://mvnrepository.com/artifact/com.beust/jcommander - compile group: 'com.beust', name: 'jcommander', version: '1.78' - - compile 'com.github.halibobo1205.leveldb-java:leveldb:v0.12.5' - compile 'com.github.halibobo1205.leveldb-java:leveldb-api:v0.12.5' + implementation fileTree(dir: 'libs', include: '*.jar') + testImplementation project(":framework") + testImplementation project(":framework").sourceSets.test.output + implementation group: 'info.picocli', name: 'picocli', version: '4.6.3' + implementation group: 'com.typesafe', name: 'config', version: '1.3.2' + implementation group: 'me.tongfei', name: 'progressbar', version: '0.9.3' + implementation group: 'org.bouncycastle', name: 'bcprov-jdk15on', version: '1.69' + implementation group: 'org.rocksdb', name: 'rocksdbjni', version: '5.15.10' + implementation 'io.github.tronprotocol:leveldbjni-all:1.18.2' + implementation 'io.github.tronprotocol:leveldb:1.18.2' + implementation project(":protocol") } check.dependsOn 'lint' @@ -73,8 +71,9 @@ test { testLogging { exceptionFormat = 'full' } + maxParallelForks = Runtime.runtime.availableProcessors().intdiv(2) ?: 1 jacoco { - destinationFile = file("$buildDir/jacoco/jacocoTest.exec") + destinationFile = file("../framework/build/jacoco/jacocoTest1.exec") classDumpDir = file("$buildDir/jacoco/classpathdumps") } } @@ -85,7 +84,7 @@ jacocoTestReport { csv.enabled false html.destination file("${buildDir}/jacocoHtml") } - executionData.from = 'build/jacoco/jacocoTest.exec' + getExecutionData().setFrom(fileTree('../framework/build/jacoco').include("**.exec")) } def binaryRelease(taskName, jarName, mainClass) { @@ -95,13 +94,18 @@ def binaryRelease(taskName, jarName, mainClass) { from(sourceSets.main.output) { include "/**" } - + dependsOn project(':protocol').jar // explicit_dependency from { - configurations.compile.collect { + configurations.runtimeClasspath.collect { // https://docs.gradle.org/current/userguide/upgrading_version_6.html#changes_6.3 it.isDirectory() ? it : zipTree(it) } } + // exclude these files for bouncycastle + exclude "META-INF/*.SF" + exclude "META-INF/*.DSA" + exclude "META-INF/*.RSA" + manifest { attributes "Main-Class": "${mainClass}" } @@ -113,7 +117,7 @@ def createScript(project, mainClass, name) { outputDir = new File(project.buildDir, 'scripts') mainClassName = mainClass applicationName = name - classpath = project.tasks[JavaPlugin.JAR_TASK_NAME].outputs.files + project.configurations.runtime + classpath = project.tasks[JavaPlugin.JAR_TASK_NAME].outputs.files + project.configurations.runtimeClasspath } project.tasks[name].dependsOn(project.jar) project.applicationDistribution.with { @@ -127,11 +131,21 @@ applicationDistribution.from("../gradle/java-tron.vmoptions") { into "bin" } createScript(project, 'org.tron.plugins.ArchiveManifest', 'ArchiveManifest') +createScript(project, 'org.tron.plugins.Toolkit', 'Toolkit') def releaseBinary = hasProperty('binaryRelease') ? getProperty('binaryRelease') : 'true' +def skipArchive = hasProperty('skipArchive') ? true : false +def skipAll = hasProperty('skipAll') ? true : false if (releaseBinary == 'true') { artifacts { - archives(binaryRelease('buildArchiveManifestJar', 'ArchiveManifest', 'org.tron.plugins.ArchiveManifest')) + archives(binaryRelease('buildToolkitJar', 'Toolkit', 'org.tron.plugins.Toolkit')) + } + if (!skipAll) { + if (!skipArchive) { + artifacts { + archives(binaryRelease('buildArchiveManifestJar', 'ArchiveManifest', 'org.tron.plugins.ArchiveManifest')) + } + } } } diff --git a/plugins/src/main/java/org/tron/plugins/ArchiveManifest.java b/plugins/src/main/java/org/tron/plugins/ArchiveManifest.java index caf2cc0dac6..4d54df6d299 100644 --- a/plugins/src/main/java/org/tron/plugins/ArchiveManifest.java +++ b/plugins/src/main/java/org/tron/plugins/ArchiveManifest.java @@ -3,8 +3,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.iq80.leveldb.impl.Iq80DBFactory.factory; -import com.beust.jcommander.JCommander; -import com.beust.jcommander.Parameter; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; @@ -37,6 +35,8 @@ import org.iq80.leveldb.DB; import org.iq80.leveldb.Options; import org.iq80.leveldb.impl.Filename; +import picocli.CommandLine; +import picocli.CommandLine.Option; @Slf4j(topic = "archive") /* @@ -82,7 +82,6 @@ public static org.iq80.leveldb.Options newDefaultLevelDbOptions() { dbOptions.maxOpenFiles(1000); dbOptions.maxBatchSize(64_000); dbOptions.maxManifestSize(128); - dbOptions.fast(false); return dbOptions; } @@ -95,12 +94,10 @@ public static void main(String[] args) { public static int run(String[] args) { Args parameters = new Args(); - JCommander jc = JCommander.newBuilder() - .addObject(parameters) - .build(); - jc.parse(args); + CommandLine commandLine = new CommandLine(parameters); + commandLine.parseArgs(args); if (parameters.help) { - jc.usage(); + commandLine.usage(System.out); return 0; } @@ -110,6 +107,11 @@ public static int run(String[] args) { return 404; } + if (!dbDirectory.isDirectory()) { + logger.info("{} is not directory.", parameters.databaseDirectory); + return 405; + } + List files = Arrays.stream(Objects.requireNonNull(dbDirectory.listFiles())) .filter(File::isDirectory).collect( Collectors.toList()); @@ -194,14 +196,14 @@ public boolean doArchive() throws IOException { logger.info("File {},does not exist, ignored.", srcDbPath.toString()); return true; } - if (!checkEngine()) { - logger.info("Db {},not leveldb, ignored.", this.name); - return true; - } if (!checkManifest(levelDbFile.toString())) { logger.info("Db {},no need, ignored.", levelDbFile.toString()); return true; } + if (!checkEngine()) { + logger.info("Db {},not leveldb, ignored.", this.name); + return true; + } open(); logger.info("Db {} archive use {} ms.", this.name, (System.currentTimeMillis() - startTime)); return true; @@ -247,19 +249,23 @@ public static boolean writeProperty(String file, String key, String value) { } public static class Args { - @Parameter - private List parameters = new ArrayList<>(); - @Parameter(names = {"-d", "--database-directory"}, description = "java-tron database directory") - private String databaseDirectory = "output-directory/database"; + @Option(names = {"-d", "--database-directory"}, + defaultValue = "output-directory/database", + description = "java-tron database directory. Default: ${DEFAULT-VALUE}") + private String databaseDirectory; - @Parameter(names = {"-b", "--batch-size" }, description = "deal manifest batch size") - private int maxBatchSize = 80_000; + @Option(names = {"-b", "--batch-size" }, + defaultValue = "80000", + description = "deal manifest batch size. Default: ${DEFAULT-VALUE}") + private int maxBatchSize; - @Parameter(names = {"-m", "--manifest-size" }, description = "manifest min size(M) to archive") - private int maxManifestSize = 0; + @Option(names = {"-m", "--manifest-size" }, + defaultValue = "0", + description = "manifest min size(M) to archive. Default: ${DEFAULT-VALUE}") + private int maxManifestSize; - @Parameter(names = {"-h", "--help"}, help = true) + @Option(names = {"-h", "--help"}, help = true) private boolean help; } } \ No newline at end of file diff --git a/plugins/src/main/java/org/tron/plugins/Db.java b/plugins/src/main/java/org/tron/plugins/Db.java new file mode 100644 index 00000000000..84654dca934 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/Db.java @@ -0,0 +1,20 @@ +package org.tron.plugins; + +import picocli.CommandLine; + +@CommandLine.Command(name = "db", + mixinStandardHelpOptions = true, + version = "db command 1.0", + description = "An rich command set that provides high-level operations for dbs.", + subcommands = {CommandLine.HelpCommand.class, + DbMove.class, + DbArchive.class, + DbConvert.class, + DbLite.class, + DbCopy.class, + DbRoot.class + }, + commandListHeading = "%nCommands:%n%nThe most commonly used db commands are:%n" +) +public class Db { +} diff --git a/plugins/src/main/java/org/tron/plugins/DbArchive.java b/plugins/src/main/java/org/tron/plugins/DbArchive.java new file mode 100644 index 00000000000..e3032731ede --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/DbArchive.java @@ -0,0 +1,198 @@ +package org.tron.plugins; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.iq80.leveldb.impl.Iq80DBFactory.factory; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import me.tongfei.progressbar.ProgressBar; +import org.iq80.leveldb.CompressionType; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.Options; +import org.iq80.leveldb.impl.Filename; +import org.tron.plugins.utils.FileUtils; +import picocli.CommandLine; +import picocli.CommandLine.Option; + +@Slf4j(topic = "archive") +@CommandLine.Command(name = "archive", description = "A helper to rewrite leveldb manifest.") +public class DbArchive implements Callable { + + @CommandLine.Spec + CommandLine.Model.CommandSpec spec; + + @Option(names = {"-d", "--database-directory"}, + defaultValue = "output-directory/database", + description = "java-tron database directory. Default: ${DEFAULT-VALUE}") + private String databaseDirectory; + + @Option(names = {"-b", "--batch-size"}, + defaultValue = "80000", + description = "deal manifest batch size. Default: ${DEFAULT-VALUE}") + private int maxBatchSize; + + @Option(names = {"-m", "--manifest-size"}, + defaultValue = "0", + description = "manifest min size(M) to archive. Default: ${DEFAULT-VALUE}") + private int maxManifestSize; + + @Option(names = {"-h", "--help"}) + private boolean help; + + + @Override + public Integer call() throws Exception { + if (help) { + spec.commandLine().usage(System.out); + return 0; + } + + File dbDirectory = new File(databaseDirectory); + if (!dbDirectory.exists()) { + spec.commandLine().getErr().format("Directory %s does not exist.", + databaseDirectory).println(); + logger.info("Directory {} does not exist.", databaseDirectory); + return 404; + } + + if (!dbDirectory.isDirectory()) { + spec.commandLine().getErr().format(" %s is not directory.", + databaseDirectory).println(); + logger.info("{} is not directory.", databaseDirectory); + return 405; + } + + List files = Arrays.stream(Objects.requireNonNull(dbDirectory.listFiles())) + .filter(File::isDirectory).collect( + Collectors.toList()); + + if (files.isEmpty()) { + spec.commandLine().getErr().format("Directory %s does not contain any database.", + databaseDirectory).println(); + logger.info("Directory {} does not contain any database.", databaseDirectory); + return 0; + } + final long time = System.currentTimeMillis(); + List services = new ArrayList<>(); + files.forEach(f -> services.add(new ArchiveManifest(databaseDirectory, f.getName(), + maxManifestSize, maxBatchSize))); + ProgressBar.wrap(services.stream(), "archive task").parallel().forEach(Archive::doArchive); + spec.commandLine().getOut().println("archive db done."); + + logger.info("DatabaseDirectory:{}, maxManifestSize:{}, maxBatchSize:{}," + + "database reopen use {} seconds total.", + databaseDirectory, maxManifestSize, maxBatchSize, + (System.currentTimeMillis() - time) / 1000); + + return 0; + } + + + interface Archive { + + default void doArchive() { + + } + } + + static class ArchiveManifest implements Archive { + + private static final String KEY_ENGINE = "ENGINE"; + private static final String LEVELDB = "LEVELDB"; + + private final Path srcDbPath; + private final String name; + private final Options options; + private final long startTime; + + public ArchiveManifest(String src, String name, int maxManifestSize, int maxBatchSize) { + this.name = name; + this.srcDbPath = Paths.get(src, name); + this.startTime = System.currentTimeMillis(); + this.options = newDefaultLevelDbOptions(); + this.options.maxManifestSize(maxManifestSize); + this.options.maxBatchSize(maxBatchSize); + } + + public static Options newDefaultLevelDbOptions() { + Options dbOptions = new Options(); + dbOptions.createIfMissing(true); + dbOptions.paranoidChecks(true); + dbOptions.verifyChecksums(true); + dbOptions.compressionType(CompressionType.SNAPPY); + dbOptions.blockSize(4 * 1024); + dbOptions.writeBufferSize(10 * 1024 * 1024); + dbOptions.cacheSize(10 * 1024 * 1024L); + dbOptions.maxOpenFiles(1000); + dbOptions.maxBatchSize(64_000); + dbOptions.maxManifestSize(128); + return dbOptions; + } + + public void open() throws IOException { + DB database = factory.open(this.srcDbPath.toFile(), this.options); + database.close(); + } + + public boolean checkManifest(String dir) throws IOException { + // Read "CURRENT" file, which contains a pointer to the current manifest file + File currentFile = new File(dir, Filename.currentFileName()); + if (!currentFile.exists()) { + return false; + } + String currentName = com.google.common.io.Files.asCharSource(currentFile, UTF_8).read(); + if (currentName.isEmpty() || currentName.charAt(currentName.length() - 1) != '\n') { + return false; + } + currentName = currentName.substring(0, currentName.length() - 1); + File current = new File(dir, currentName); + if (!current.isFile()) { + return false; + } + long maxSize = options.maxManifestSize(); + if (maxSize < 0) { + return false; + } + logger.info("CurrentName {}/{},size {} kb.", dir, currentName, current.length() / 1024); + if ("market_pair_price_to_order".equalsIgnoreCase(this.name)) { + logger.info("Db {} ignored.", this.name); + return false; + } + return current.length() >= maxSize * 1024 * 1024; + } + + @Override + public void doArchive() { + File levelDbFile = srcDbPath.toFile(); + if (!levelDbFile.exists()) { + logger.info("File {},does not exist, ignored.", srcDbPath); + return; + } + try { + if (checkManifest(levelDbFile.toString())) { + if (!FileUtils.isLevelDBEngine(srcDbPath)) { + logger.info("Db {},not leveldb, ignored.", this.name); + return; + } + open(); + logger.info("Db {} archive use {} ms.", this.name, + (System.currentTimeMillis() - startTime)); + } else { + logger.info("Db {},no need, ignored.", levelDbFile); + } + } catch (Exception e) { + throw new RuntimeException("Db " + this.name + " archive failed.", e); + } + } + } + +} \ No newline at end of file diff --git a/plugins/src/main/java/org/tron/plugins/DbConvert.java b/plugins/src/main/java/org/tron/plugins/DbConvert.java new file mode 100644 index 00000000000..a75b235bbcf --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/DbConvert.java @@ -0,0 +1,360 @@ +package org.tron.plugins; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import me.tongfei.progressbar.ProgressBar; +import org.fusesource.leveldbjni.JniDBFactory; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.DBIterator; +import org.rocksdb.RocksDB; +import org.rocksdb.RocksDBException; +import org.rocksdb.RocksIterator; +import org.rocksdb.Status; +import org.tron.plugins.utils.DBUtils; +import org.tron.plugins.utils.FileUtils; +import picocli.CommandLine; + + +@Slf4j(topic = "convert") +@CommandLine.Command(name = "convert", + description = "Covert leveldb to rocksdb.", + exitCodeListHeading = "Exit Codes:%n", + exitCodeList = { + "0:Successful", + "n:Internal error: exception occurred,please check toolkit.log"}) +public class DbConvert implements Callable { + + static { + RocksDB.loadLibrary(); + } + + private static final int BATCH = 256; + + @CommandLine.Spec + CommandLine.Model.CommandSpec spec; + @CommandLine.Parameters(index = "0", defaultValue = "output-directory/database", + description = " Input path for leveldb. Default: ${DEFAULT-VALUE}") + private File src; + @CommandLine.Parameters(index = "1", defaultValue = "output-directory-dst/database", + description = "Output path for rocksdb. Default: ${DEFAULT-VALUE}") + private File dest; + + @CommandLine.Option(names = {"--safe"}, + description = "In safe mode, read data from leveldb then put rocksdb." + + "If not, just change engine.properties from leveldb to rocksdb," + + "rocksdb is compatible with leveldb for current version." + + "This may not be the case in the future." + + "Default: ${DEFAULT-VALUE}") + private boolean safe; + + @CommandLine.Option(names = {"-h", "--help"}) + private boolean help; + + + @Override + public Integer call() throws Exception { + if (help) { + spec.commandLine().usage(System.out); + return 0; + } + if (!src.exists()) { + logger.info(" {} does not exist.", src); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(String.format("%s does not exist.", src))); + return 404; + } + List files = Arrays.stream(Objects.requireNonNull(src.listFiles())) + .filter(File::isDirectory) + .filter(e -> !DBUtils.CHECKPOINT_DB_V2.equals(e.getName())) + .collect(Collectors.toList()); + + // add checkpoint v2 convert + File cpV2Dir = new File(Paths.get(src.toString(), DBUtils.CHECKPOINT_DB_V2).toString()); + List cpList = new ArrayList<>(); + if (cpV2Dir.exists()) { + cpList = Arrays.stream(Objects.requireNonNull(cpV2Dir.listFiles())) + .filter(File::isDirectory) + .collect(Collectors.toList()); + } + + if (files.isEmpty()) { + logger.info("{} does not contain any database.", src); + spec.commandLine().getOut().format("%s does not contain any database.", src).println(); + return 0; + } + final long time = System.currentTimeMillis(); + List services = new ArrayList<>(); + files.forEach(f -> services.add( + new DbConverter(src.getPath(), dest.getPath(), f.getName(), safe))); + cpList.forEach(f -> services.add( + new DbConverter( + Paths.get(src.getPath(), DBUtils.CHECKPOINT_DB_V2).toString(), + Paths.get(dest.getPath(), DBUtils.CHECKPOINT_DB_V2).toString(), + f.getName(), safe))); + List fails = ProgressBar.wrap(services.stream(), "convert task").parallel().map( + dbConverter -> { + try { + return dbConverter.doConvert() ? null : dbConverter.name(); + } catch (Exception e) { + logger.error("{}", e); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(e.getMessage())); + return dbConverter.name(); + } + }).filter(Objects::nonNull).collect(Collectors.toList()); + long during = (System.currentTimeMillis() - time) / 1000; + spec.commandLine().getOut().format("convert db done, fails: %s, take %d s.", + fails, during).println(); + logger.info("database convert use {} seconds total, fails: {}.", during, fails); + return fails.size(); + } + + interface Converter { + + boolean doConvert() throws Exception; + + String name(); + } + + static class DbConverter implements Converter { + private final String srcDir; + private final String dstDir; + private final String dbName; + private final Path srcDbPath; + private final Path dstDbPath; + + private long srcDbKeyCount = 0L; + private long dstDbKeyCount = 0L; + private long srcDbKeySum = 0L; + private long dstDbKeySum = 0L; + private long srcDbValueSum = 0L; + private long dstDbValueSum = 0L; + + private boolean safe; + + public DbConverter(String srcDir, String dstDir, String name, boolean safe) { + this.srcDir = srcDir; + this.dstDir = dstDir; + this.dbName = name; + this.srcDbPath = Paths.get(this.srcDir, name); + this.dstDbPath = Paths.get(this.dstDir, name); + this.safe = safe; + } + + @Override + public boolean doConvert() throws Exception { + + if (checkDone(this.dstDbPath.toString())) { + logger.info(" {} is done, skip it.", this.dbName); + return true; + } + + File levelDbFile = srcDbPath.toFile(); + if (!levelDbFile.exists()) { + logger.info(" {} does not exist.", srcDbPath); + return true; + } + if (!FileUtils.isLevelDBEngine(srcDbPath)) { + logger.info("Db {},not leveldb, ignored.", this.dbName); + return true; + } + long startTime = System.currentTimeMillis(); + if (this.dstDbPath.toFile().exists()) { + logger.info(" {} begin to clear exist database directory", this.dbName); + FileUtils.deleteDir(this.dstDbPath.toFile()); + logger.info(" {} clear exist database directory done.", this.dbName); + } + + FileUtils.createDirIfNotExists(dstDir); + + logger.info("Convert database {} start", this.dbName); + if (safe) { + convertLevelToRocks(); + compact(); + } else { + FileUtils.copyDir(Paths.get(srcDir), Paths.get(dstDir), dbName); + } + boolean result = check() && createEngine(dstDbPath.toString()); + long etime = System.currentTimeMillis(); + + if (result) { + if (safe) { + logger.info("Convert database {} successful end with {} key-value {} minutes", + this.dbName, this.srcDbKeyCount, (etime - startTime) / 1000.0 / 60); + } else { + logger.info("Convert database {} successful end {} minutes", + this.dbName, (etime - startTime) / 1000.0 / 60); + } + + } else { + logger.info("Convert database {} failure", this.dbName); + if (this.dstDbPath.toFile().exists()) { + logger.info(" {} begin to clear exist database directory", this.dbName); + FileUtils.deleteDir(this.dstDbPath.toFile()); + logger.info(" {} clear exist database directory done.", this.dbName); + } + } + return result; + } + + @Override + public String name() { + return dbName; + } + + private void batchInsert(RocksDB rocks, List keys, List values) + throws Exception { + try (org.rocksdb.WriteBatch batch = new org.rocksdb.WriteBatch()) { + for (int i = 0; i < keys.size(); i++) { + byte[] k = keys.get(i); + byte[] v = values.get(i); + batch.put(k, v); + } + write(rocks, batch); + } + keys.clear(); + values.clear(); + } + + /** + * https://github.com/facebook/rocksdb/issues/6625. + * + * @param rocks db + * @param batch write batch + * @throws Exception RocksDBException + */ + private void write(RocksDB rocks, org.rocksdb.WriteBatch batch) throws Exception { + try { + rocks.write(new org.rocksdb.WriteOptions(), batch); + } catch (RocksDBException e) { + // retry + if (maybeRetry(e)) { + TimeUnit.MILLISECONDS.sleep(1); + write(rocks, batch); + } else { + throw e; + } + } + } + + private boolean maybeRetry(RocksDBException e) { + boolean retry = false; + if (e.getStatus() != null) { + retry = e.getStatus().getCode() == Status.Code.TryAgain + || e.getStatus().getCode() == Status.Code.Busy + || e.getStatus().getCode() == Status.Code.Incomplete; + } + return retry || (e.getMessage() != null && ("Write stall".equalsIgnoreCase(e.getMessage()) + || ("Incomplete").equalsIgnoreCase(e.getMessage()))); + } + + /** + * https://github.com/facebook/rocksdb/wiki/RocksDB-FAQ . + * What's the fastest way to load data into RocksDB? + * + * @return if ok + */ + public void convertLevelToRocks() throws Exception { + List keys = new ArrayList<>(BATCH); + List values = new ArrayList<>(BATCH); + JniDBFactory.pushMemoryPool(1024 * 1024); + try ( + DB level = DBUtils.newLevelDb(srcDbPath); + RocksDB rocks = DBUtils.newRocksDbForBulkLoad(dstDbPath); + DBIterator levelIterator = level.iterator( + new org.iq80.leveldb.ReadOptions().fillCache(false))) { + + levelIterator.seekToFirst(); + + while (levelIterator.hasNext()) { + Map.Entry entry = levelIterator.next(); + byte[] key = entry.getKey(); + byte[] value = entry.getValue(); + srcDbKeyCount++; + srcDbKeySum = byteArrayToIntWithOne(srcDbKeySum, key); + srcDbValueSum = byteArrayToIntWithOne(srcDbValueSum, value); + keys.add(key); + values.add(value); + if (keys.size() >= BATCH) { + batchInsert(rocks, keys, values); + } + } + // clear + if (!keys.isEmpty()) { + batchInsert(rocks, keys, values); + } + } finally { + JniDBFactory.popMemoryPool(); + } + } + + private void compact() throws RocksDBException { + if (DBUtils.MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(this.dbName)) { + return; + } + try (RocksDB rocks = DBUtils.newRocksDb(this.dstDbPath)) { + logger.info("compact database {} start", this.dbName); + rocks.compactRange(); + logger.info("compact database {} end", this.dbName); + } + } + + private boolean check() throws RocksDBException { + if (!safe) { + return true; + } + try ( + RocksDB rocks = DBUtils.newRocksDbReadOnly(this.dstDbPath); + org.rocksdb.ReadOptions r = new org.rocksdb.ReadOptions().setFillCache(false); + RocksIterator rocksIterator = rocks.newIterator(r)) { + + // check + logger.info("check database {} start", this.dbName); + for (rocksIterator.seekToFirst(); rocksIterator.isValid(); rocksIterator.next()) { + byte[] key = rocksIterator.key(); + byte[] value = rocksIterator.value(); + dstDbKeyCount++; + dstDbKeySum = byteArrayToIntWithOne(dstDbKeySum, key); + dstDbValueSum = byteArrayToIntWithOne(dstDbValueSum, value); + } + logger.info("Check database {} end,dstDbKeyCount {}, dstDbKeySum {}, dstDbValueSum {}," + + "srcDbKeyCount {}, srcDbKeySum {}, srcDbValueSum {}", + dbName, dstDbKeyCount, dstDbKeySum, dstDbValueSum, + srcDbKeyCount, srcDbKeySum, srcDbValueSum); + return dstDbKeyCount == srcDbKeyCount && dstDbKeySum == srcDbKeySum + && dstDbValueSum == srcDbValueSum; + } + } + } + + private static boolean createEngine(String dir) { + String enginePath = dir + File.separator + DBUtils.FILE_ENGINE; + if (!FileUtils.createFileIfNotExists(enginePath)) { + return false; + } + return FileUtils.writeProperty(enginePath, DBUtils.KEY_ENGINE, DBUtils.ROCKSDB); + } + + private static boolean checkDone(String dir) { + String enginePath = dir + File.separator + DBUtils.FILE_ENGINE; + return FileUtils.isExists(enginePath); + } + + private static long byteArrayToIntWithOne(long sum, byte[] b) { + for (byte oneByte : b) { + sum += oneByte; + } + return sum; + } + +} diff --git a/plugins/src/main/java/org/tron/plugins/DbCopy.java b/plugins/src/main/java/org/tron/plugins/DbCopy.java new file mode 100644 index 00000000000..7558d764cd4 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/DbCopy.java @@ -0,0 +1,160 @@ +package org.tron.plugins; + +import java.io.File; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import me.tongfei.progressbar.ProgressBar; +import org.tron.plugins.utils.DBUtils; +import org.tron.plugins.utils.FileUtils; +import picocli.CommandLine; + + +@Slf4j(topic = "copy") +@CommandLine.Command(name = "cp", aliases = "copy", + description = "Quick copy leveldb or rocksdb data.", + exitCodeListHeading = "Exit Codes:%n", + exitCodeList = { + "0:Successful", + "n:Internal error: exception occurred,please check toolkit.log"}) +public class DbCopy implements Callable { + + + @CommandLine.Spec + CommandLine.Model.CommandSpec spec; + @CommandLine.Parameters(index = "0", defaultValue = "output-directory/database", + description = "Input path. Default: ${DEFAULT-VALUE}") + private File src; + @CommandLine.Parameters(index = "1", defaultValue = "output-directory-cp/database", + description = "Output path. Default: ${DEFAULT-VALUE}") + private File dest; + + @CommandLine.Option(names = {"-h", "--help"}) + private boolean help; + + + @Override + public Integer call() throws Exception { + if (help) { + spec.commandLine().usage(System.out); + return 0; + } + if (dest.exists()) { + logger.info(" {} exist, please delete it first.", dest); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(String.format("%s exist, please delete it first.", dest))); + return 402; + } + if (!src.exists()) { + logger.info(" {} does not exist.", src); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(String.format("%s does not exist.", src))); + return 404; + } + + if (!src.isDirectory()) { + logger.info(" {} is not a directory.", src); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(String.format("%s is not a directory.", src))); + return 403; + } + + List files = Arrays.stream(Objects.requireNonNull(src.listFiles())) + .filter(File::isDirectory) + .filter(e -> !DBUtils.CHECKPOINT_DB_V2.equals(e.getName())) + .collect(Collectors.toList()); + + // add checkpoint v2 convert + File cpV2Dir = new File(Paths.get(src.toString(), DBUtils.CHECKPOINT_DB_V2).toString()); + List cpList = new ArrayList<>(); + if (cpV2Dir.exists()) { + cpList = Arrays.stream(Objects.requireNonNull(cpV2Dir.listFiles())) + .filter(File::isDirectory) + .collect(Collectors.toList()); + } + + if (files.isEmpty()) { + logger.info("{} does not contain any database.", src); + spec.commandLine().getOut().format("%s does not contain any database.", src).println(); + return 0; + } + final long time = System.currentTimeMillis(); + List services = new ArrayList<>(); + files.forEach(f -> services.add( + new DbCopier(src.getPath(), dest.getPath(), f.getName()))); + cpList.forEach(f -> services.add( + new DbCopier( + Paths.get(src.getPath(), DBUtils.CHECKPOINT_DB_V2).toString(), + Paths.get(dest.getPath(), DBUtils.CHECKPOINT_DB_V2).toString(), + f.getName()))); + List fails = ProgressBar.wrap(services.stream(), "copy task").parallel().map( + dbCopier -> { + try { + return dbCopier.doCopy() ? null : dbCopier.name(); + } catch (Exception e) { + logger.error("{}", e); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(e.getMessage())); + return dbCopier.name(); + } + }).filter(Objects::nonNull).collect(Collectors.toList()); + // copy info.properties if lite need + Arrays.stream(Objects.requireNonNull(src.listFiles())) + .filter(File::isFile).forEach(f -> FileUtils.copy(Paths.get(src.toString(), f.getName()), + Paths.get(dest.toString(), f.getName()))); + long during = (System.currentTimeMillis() - time) / 1000; + spec.commandLine().getOut().format("copy db done, fails: %s, take %d s.", + fails, during).println(); + logger.info("database copy use {} seconds total, fails: {}.", during, fails); + return fails.size(); + } + + interface Copier { + + boolean doCopy(); + + String name(); + } + + static class DbCopier implements Copier { + private final String srcDir; + private final String dstDir; + private final String dbName; + private final Path srcDbPath; + private final Path dstDbPath; + + public DbCopier(String srcDir, String dstDir, String name) { + this.srcDir = srcDir; + this.dstDir = dstDir; + this.dbName = name; + this.srcDbPath = Paths.get(this.srcDir, name); + this.dstDbPath = Paths.get(this.dstDir, name); + } + + @Override + public boolean doCopy() { + File srcDb = srcDbPath.toFile(); + if (!srcDb.exists()) { + logger.info(" {} does not exist.", srcDb); + return true; + } + FileUtils.createDirIfNotExists(dstDir); + logger.info("Copy database {} start", this.dbName); + FileUtils.copyDir(Paths.get(srcDir), Paths.get(dstDir), dbName); + logger.info("Copy database {} end", this.dbName); + return true; + } + + @Override + public String name() { + return dbName; + } + } + +} diff --git a/plugins/src/main/java/org/tron/plugins/DbLite.java b/plugins/src/main/java/org/tron/plugins/DbLite.java new file mode 100644 index 00000000000..732d4913021 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/DbLite.java @@ -0,0 +1,725 @@ +package org.tron.plugins; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.primitives.Bytes; +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import java.util.stream.LongStream; +import lombok.extern.slf4j.Slf4j; +import me.tongfei.progressbar.ProgressBar; +import org.rocksdb.RocksDBException; +import org.tron.plugins.utils.ByteArray; +import org.tron.plugins.utils.DBUtils; +import org.tron.plugins.utils.FileUtils; +import org.tron.plugins.utils.db.DBInterface; +import org.tron.plugins.utils.db.DBIterator; +import org.tron.plugins.utils.db.DbTool; +import org.tron.protos.Protocol; +import picocli.CommandLine; + +@Slf4j(topic = "lite") +@CommandLine.Command(name = "lite", + description = "Split lite data for java-tron.", + exitCodeListHeading = "Exit Codes:%n", + exitCodeList = { + "0:Successful", + "1:Internal error: exception occurred,please check toolkit.log"}) +public class DbLite implements Callable { + + private static final long START_TIME = System.currentTimeMillis() / 1000; + + private static long RECENT_BLKS = 65536; + + private static final String SNAPSHOT_DIR_NAME = "snapshot"; + private static final String HISTORY_DIR_NAME = "history"; + private static final String INFO_FILE_NAME = "info.properties"; + private static final String BACKUP_DIR_PREFIX = ".bak_"; + private static final String CHECKPOINT_DB = "tmp"; + private static final String BLOCK_DB_NAME = "block"; + private static final String BLOCK_INDEX_DB_NAME = "block-index"; + private static final String TRANS_DB_NAME = "trans"; + private static final String TRANSACTION_RET_DB_NAME = "transactionRetStore"; + private static final String TRANSACTION_HISTORY_DB_NAME = "transactionHistoryStore"; + private static final String PROPERTIES_DB_NAME = "properties"; + private static final String TRANS_CACHE_DB_NAME = "trans-cache"; + + private static final List archiveDbs = Arrays.asList( + BLOCK_DB_NAME, + BLOCK_INDEX_DB_NAME, + TRANS_DB_NAME, + TRANSACTION_RET_DB_NAME, + TRANSACTION_HISTORY_DB_NAME); + + enum Operate { split, merge } + + enum Type { snapshot, history } + + @CommandLine.Spec + CommandLine.Model.CommandSpec spec; + + @CommandLine.Option( + names = {"--operate", "-o"}, + defaultValue = "split", + description = "operate: [ ${COMPLETION-CANDIDATES} ]. Default: ${DEFAULT-VALUE}", + order = 1) + private Operate operate; + + @CommandLine.Option( + names = {"--type", "-t"}, + defaultValue = "snapshot", + description = "only used with operate=split: [ ${COMPLETION-CANDIDATES} ]." + + " Default: ${DEFAULT-VALUE}", + order = 2) + private Type type; + + @CommandLine.Option( + names = {"--fn-data-path", "-fn"}, + required = true, + description = "the database path to be split or merged.", + order = 3) + private String fnDataPath; + + @CommandLine.Option( + names = {"--dataset-path", "-ds"}, + required = true, + description = "when operation is `split`," + + "`dataset-path` is the path that store the `snapshot` or `history`," + + "when operation is `split`," + + "`dataset-path` is the `history` data path.", + order = 4) + private String datasetPath; + + @CommandLine.Option( + names = {"--help", "-h"}, + order = 5) + private boolean help; + + + @Override + public Integer call() { + if (help) { + spec.commandLine().usage(System.out); + return 0; + } + try { + switch (this.operate) { + case split: + if (Type.snapshot == this.type) { + generateSnapshot(fnDataPath, datasetPath); + } else if (Type.history == type) { + generateHistory(fnDataPath, datasetPath); + } + break; + case merge: + completeHistoryData(datasetPath, fnDataPath); + break; + default: + } + return 0; + } catch (Exception e) { + logger.error("{}", e); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(e.getMessage())); + spec.commandLine().usage(System.out); + return 1; + } finally { + DbTool.close(); + } + } + + /** + * Create the snapshot dataset. + * + * @param sourceDir the original fullnode database dir, + * same with {storage.db.directory} in conf file. + * @param snapshotDir the path that stores the snapshot dataset + */ + public void generateSnapshot(String sourceDir, String snapshotDir) { + logger.info("Start create snapshot."); + spec.commandLine().getOut().println("Start create snapshot."); + long start = System.currentTimeMillis(); + snapshotDir = Paths.get(snapshotDir, SNAPSHOT_DIR_NAME).toString(); + try { + hasEnoughBlock(sourceDir); + List snapshotDbs = getSnapshotDbs(sourceDir); + split(sourceDir, snapshotDir, snapshotDbs); + mergeCheckpoint2Snapshot(sourceDir, snapshotDir); + // write genesisBlock , latest recent blocks and trans + fillSnapshotBlockAndTransDb(sourceDir, snapshotDir); + // save min block to info + generateInfoProperties(Paths.get(snapshotDir, INFO_FILE_NAME).toString(), + getSecondBlock(snapshotDir)); + } catch (IOException | RocksDBException e) { + logger.error("Create snapshot failed, {}.", e.getMessage()); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .stackTraceText(e)); + return; + } + long during = (System.currentTimeMillis() - start) / 1000; + logger.info("Create snapshot finished, take {} s.", during); + spec.commandLine().getOut().format("Create snapshot finished, take %d s.", during).println(); + } + + /** + * Create the history dataset. + * + * @param sourceDir the original fullnode database dir, + * same with {storage.db.directory} in conf file. + * @param historyDir the path that stores the history dataset + */ + public void generateHistory(String sourceDir, String historyDir) { + logger.info("Start create history."); + spec.commandLine().getOut().println("Start create history."); + long start = System.currentTimeMillis(); + historyDir = Paths.get(historyDir, HISTORY_DIR_NAME).toString(); + try { + if (isLite(sourceDir)) { + throw new IllegalStateException( + String.format("Unavailable sourceDir: %s is not fullNode data.", sourceDir)); + } + hasEnoughBlock(sourceDir); + split(sourceDir, historyDir, archiveDbs); + mergeCheckpoint2History(sourceDir, historyDir); + // save max block to info + generateInfoProperties(Paths.get(historyDir, INFO_FILE_NAME).toString(), + getLatestBlockHeaderNum(sourceDir)); + } catch (IOException | RocksDBException e) { + logger.error("Create history failed, {}.", e.getMessage()); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .stackTraceText(e)); + return; + } + long during = (System.currentTimeMillis() - start) / 1000; + logger.info("Create history finished, take {} s.", during); + spec.commandLine().getOut().format("Create history finished, take %d s.", during).println(); + } + + /** + * Merge the history dataset into database. + * + * @param historyDir the path that stores the history dataset + * + * @param liteDir lite fullnode database path + */ + public void completeHistoryData(String historyDir, String liteDir) { + logger.info("Start merge history to lite node."); + spec.commandLine().getOut().println("Start merge history to lite node."); + long start = System.currentTimeMillis(); + try { + // check historyDir is from lite data + if (isLite(historyDir)) { + throw new IllegalStateException( + String.format("Unavailable history: %s is not generated by fullNode data.", + historyDir)); + } + // 1. check block number and genesis block are compatible, + // and return the block numbers of snapshot and history + BlockNumInfo blockNumInfo = checkAndGetBlockNumInfo(historyDir, liteDir); + // 2. move archive dbs to bak + backupArchiveDbs(liteDir); + // 3. copy history data to liteDir + copyHistory2Database(historyDir, liteDir); + // 4. delete the extra block data in history data + trimExtraHistory(liteDir, blockNumInfo); + // 5. merge bak to database + mergeBak2Database(liteDir, blockNumInfo); + // 6. delete bak dir + deleteBackupArchiveDbs(liteDir); + // 7. delete snapshot flag + deleteSnapshotFlag(liteDir); + } catch (IOException | RocksDBException e) { + logger.error("Merge history data to database failed, {}.", e.getMessage()); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .stackTraceText(e)); + return; + } + long during = (System.currentTimeMillis() - start) / 1000; + logger.info("Merge history finished, take {} s.", during); + spec.commandLine().getOut().format("Merge history finished, take %d s.", during).println(); + } + + private List getSnapshotDbs(String sourceDir) { + List snapshotDbs = Lists.newArrayList(); + File basePath = new File(sourceDir); + Arrays.stream(Objects.requireNonNull(basePath.listFiles())) + .filter(File::isDirectory) + .filter(dir -> !archiveDbs.contains(dir.getName())) + .forEach(dir -> snapshotDbs.add(dir.getName())); + return snapshotDbs; + } + + private void mergeCheckpoint2Snapshot(String sourceDir, String historyDir) { + List snapshotDbs = getSnapshotDbs(sourceDir); + mergeCheckpoint(sourceDir, historyDir, snapshotDbs); + } + + private void mergeCheckpoint2History(String sourceDir, String destDir) { + mergeCheckpoint(sourceDir, destDir, archiveDbs); + } + + private void split(String sourceDir, String destDir, List dbs) throws IOException { + logger.info("Begin to split the dbs."); + spec.commandLine().getOut().println("Begin to split the dbs."); + if (!new File(sourceDir).isDirectory()) { + throw new RuntimeException(String.format("sourceDir: %s must be a directory ", sourceDir)); + } + File destPath = new File(destDir); + if (new File(destDir).exists()) { + throw new RuntimeException(String.format( + "destDir: %s is already exist, please remove it first", destDir)); + } + if (!destPath.mkdirs()) { + throw new RuntimeException(String.format("destDir: %s create failed, please check", destDir)); + } + FileUtils.copyDatabases(Paths.get(sourceDir), Paths.get(destDir), dbs); + } + + private void mergeCheckpoint(String sourceDir, String destDir, List destDbs) { + logger.info("Begin to merge checkpoint to dataset."); + spec.commandLine().getOut().println("Begin to merge checkpoint to dataset."); + try { + List cpList = getCheckpointV2List(sourceDir); + if (cpList.size() > 0) { + for (String cp : cpList) { + DBInterface checkpointDb = DbTool.getDB( + sourceDir + "/" + DBUtils.CHECKPOINT_DB_V2, cp); + recover(checkpointDb, destDir, destDbs); + } + } else if (Paths.get(sourceDir, CHECKPOINT_DB).toFile().exists()) { + DBInterface tmpDb = DbTool.getDB(sourceDir, CHECKPOINT_DB); + recover(tmpDb, destDir, destDbs); + } + } catch (IOException | RocksDBException e) { + throw new RuntimeException(e); + } + } + + private void recover(DBInterface db, String destDir, List destDbs) + throws IOException, RocksDBException { + try (DBIterator iterator = db.iterator()) { + for (iterator.seekToFirst(); iterator.hasNext(); iterator.next()) { + byte[] key = iterator.getKey(); + byte[] value = iterator.getValue(); + String dbName = DBUtils.simpleDecode(key); + // skip trans-cache db + if (TRANS_CACHE_DB_NAME.equalsIgnoreCase(dbName)) { + continue; + } + byte[] realKey = Arrays.copyOfRange(key, dbName.getBytes().length + 4, key.length); + byte[] realValue = + value.length == 1 ? null : Arrays.copyOfRange(value, 1, value.length); + if (destDbs != null && destDbs.contains(dbName)) { + DBInterface destDb = DbTool.getDB(destDir, dbName); + if (realValue != null) { + destDb.put(realKey, realValue); + } else { + byte op = value[0]; + if (DBUtils.Operator.DELETE.getValue() == op) { + destDb.delete(realKey); + } else { + destDb.put(realKey, new byte[0]); + } + } + } + } + } + } + + private void generateInfoProperties(String propertyfile, long num) + throws IOException, RocksDBException { + logger.info("Create {} for dataset.", INFO_FILE_NAME); + spec.commandLine().getOut().format("Create %s for dataset.", INFO_FILE_NAME).println(); + if (!FileUtils.createFileIfNotExists(propertyfile)) { + throw new RuntimeException("Create properties file failed."); + } + if (!FileUtils.writeProperty(propertyfile, DBUtils.SPLIT_BLOCK_NUM, Long.toString(num))) { + throw new RuntimeException("Write properties file failed."); + } + } + + private long getLatestBlockHeaderNum(String databaseDir) throws IOException, RocksDBException { + // query latest_block_header_number from checkpoint first + final String latestBlockHeaderNumber = "latest_block_header_number"; + DBInterface checkpointDb = getCheckpointDb(databaseDir); + Long blockNumber = getLatestBlockHeaderNumFromCP(checkpointDb, + latestBlockHeaderNumber.getBytes()); + if (blockNumber != null) { + return blockNumber; + } + // query from propertiesDb if checkpoint not contains latest_block_header_number + DBInterface propertiesDb = DbTool.getDB(databaseDir, PROPERTIES_DB_NAME); + return Optional.ofNullable(propertiesDb.get(ByteArray.fromString(latestBlockHeaderNumber))) + .map(ByteArray::toLong) + .orElseThrow( + () -> new IllegalArgumentException("not found latest block header number")); + } + + private Long getLatestBlockHeaderNumFromCP(DBInterface db, byte[] key) { + byte[] value = db.get(Bytes.concat(simpleEncode(PROPERTIES_DB_NAME), key)); + if (value != null && value.length > 1) { + return ByteArray.toLong(Arrays.copyOfRange(value, 1, value.length)); + } + return null; + } + + /** + * recent blocks, trans and genesis block. + */ + private void fillSnapshotBlockAndTransDb(String sourceDir, String snapshotDir) + throws IOException, RocksDBException { + logger.info("Begin to fill {} block, genesis block and trans to snapshot.", RECENT_BLKS); + spec.commandLine().getOut().format( + "Begin to fill %d block, genesis block and trans to snapshot.", RECENT_BLKS).println(); + DBInterface sourceBlockIndexDb = DbTool.getDB(sourceDir, BLOCK_INDEX_DB_NAME); + DBInterface sourceBlockDb = DbTool.getDB(sourceDir, BLOCK_DB_NAME); + // init snapshot db ,keep engine same as source + DBInterface destBlockDb = DbTool.getDB(sourceDir, snapshotDir, BLOCK_DB_NAME); + DBInterface destBlockIndexDb = DbTool.getDB(sourceDir, snapshotDir, BLOCK_INDEX_DB_NAME); + DBInterface destTransDb = DbTool.getDB(sourceDir, snapshotDir, TRANS_DB_NAME); + // put genesis block and block-index into snapshot + long genesisBlockNum = 0L; + byte[] genesisBlockID = sourceBlockIndexDb.get(ByteArray.fromLong(genesisBlockNum)); + destBlockIndexDb.put(ByteArray.fromLong(genesisBlockNum), genesisBlockID); + destBlockDb.put(genesisBlockID, sourceBlockDb.get(genesisBlockID)); + + long latestBlockNum = getLatestBlockHeaderNum(sourceDir); + long startIndex = latestBlockNum - RECENT_BLKS + 1; + // put the recent blocks and trans in snapshot + ProgressBar.wrap(LongStream.rangeClosed(startIndex, latestBlockNum), "fillBlockAndTrans") + .forEach(blockNum -> { + try { + byte[] blockId = getDataFromSourceDB(sourceDir, BLOCK_INDEX_DB_NAME, + Longs.toByteArray(blockNum)); + byte[] block = getDataFromSourceDB(sourceDir, BLOCK_DB_NAME, blockId); + // put block + destBlockDb.put(blockId, block); + // put block index + destBlockIndexDb.put(ByteArray.fromLong(blockNum), blockId); + // put trans + long finalBlockNum = blockNum; + Protocol.Block.parseFrom(block).getTransactionsList().stream().map( + tc -> DBUtils.getTransactionId(tc).getBytes()) + .map(bytes -> Maps.immutableEntry(bytes, Longs.toByteArray(finalBlockNum))) + .forEach(e -> destTransDb.put(e.getKey(), e.getValue())); + } catch (IOException | RocksDBException e) { + throw new RuntimeException(e.getMessage()); + } + }); + // copy engine.properties for block、block-index、trans from source if exist + copyEngineIfExist(sourceDir, snapshotDir, BLOCK_DB_NAME, BLOCK_INDEX_DB_NAME, TRANS_DB_NAME); + } + + private void copyEngineIfExist(String source, String dest, String... dbNames) { + for (String dbName : dbNames) { + Path ori = Paths.get(source, dbName, DBUtils.FILE_ENGINE); + if (ori.toFile().exists()) { + FileUtils.copy(ori, Paths.get(dest, dbName, DBUtils.FILE_ENGINE)); + } + } + } + + private byte[] getGenesisBlockHash(String parentDir) throws IOException, RocksDBException { + long genesisBlockNum = 0L; + DBInterface blockIndexDb = DbTool.getDB(parentDir, BLOCK_INDEX_DB_NAME); + byte[] result = blockIndexDb.get(ByteArray.fromLong(genesisBlockNum)); + // when merge history, block-index db will be moved to bak dir and replaced by history + // so should close this db and reopen it. + DbTool.closeDB(parentDir, BLOCK_INDEX_DB_NAME); + return result; + } + + private static byte[] simpleEncode(String s) { + byte[] bytes = s.getBytes(); + byte[] length = Ints.toByteArray(bytes.length); + byte[] r = new byte[4 + bytes.length]; + System.arraycopy(length, 0, r, 0, 4); + System.arraycopy(bytes, 0, r, 4, bytes.length); + return r; + } + + private BlockNumInfo checkAndGetBlockNumInfo(String historyDir, String liteDir) + throws IOException, RocksDBException { + logger.info("Check the compatibility of this history."); + spec.commandLine().getOut().println("Check the compatibility of this history."); + String snapshotInfo = Paths.get(liteDir, INFO_FILE_NAME).toString(); + String historyInfo = Paths.get(historyDir, INFO_FILE_NAME).toString(); + if (!FileUtils.isExists(snapshotInfo)) { + throw new FileNotFoundException( + "Snapshot property file is not found. maybe this is a complete fullnode?"); + } + if (!FileUtils.isExists(historyInfo)) { + throw new FileNotFoundException("history property file is not found."); + } + // min block for snapshot + long snapshotMinNum = getSecondBlock(liteDir); + // max block for snapshot + long snapshotMaxNum = getLatestBlockHeaderNum(liteDir); + // max block for history + long historyMaxNum = Long.parseLong(FileUtils.readProperty(historyInfo, DBUtils + .SPLIT_BLOCK_NUM)); + if (historyMaxNum < snapshotMinNum) { + throw new RuntimeException( + String.format( + "History max block is lower than snapshot min number, history: %d, snapshot: %d", + historyMaxNum, snapshotMinNum)); + } + // check genesis block is equal + if (!Arrays.equals(getGenesisBlockHash(liteDir), getGenesisBlockHash(historyDir))) { + throw new RuntimeException(String.format( + "Genesis block hash is not equal, history: %s, database: %s", + Arrays.toString(getGenesisBlockHash(historyDir)), + Arrays.toString(getGenesisBlockHash(liteDir)))); + } + return new BlockNumInfo(snapshotMinNum, historyMaxNum, snapshotMaxNum); + } + + private void backupArchiveDbs(String databaseDir) throws IOException { + Path bakDir = Paths.get(databaseDir, BACKUP_DIR_PREFIX + START_TIME); + logger.info("Backup the archive dbs to {}.", bakDir); + spec.commandLine().getOut().format("Backup the archive dbs to %s.", bakDir).println(); + if (!FileUtils.createDirIfNotExists(bakDir.toString())) { + throw new RuntimeException(String.format("create bak dir %s failed", bakDir)); + } + FileUtils.copyDatabases(Paths.get(databaseDir), bakDir, archiveDbs); + archiveDbs.forEach(db -> FileUtils.deleteDir(new File(databaseDir, db))); + } + + private void copyHistory2Database(String historyDir, String databaseDir) throws IOException { + logger.info("Begin to copy history to database."); + spec.commandLine().getOut().println("Begin to copy history to database."); + FileUtils.copyDatabases(Paths.get(historyDir), Paths.get(databaseDir), archiveDbs); + } + + private void trimExtraHistory(String liteDir, BlockNumInfo blockNumInfo) + throws IOException, RocksDBException { + long start = blockNumInfo.getSnapshotMaxNum() + 1; + long end = blockNumInfo.getHistoryMaxNum(); + if (start > end) { + logger.info("Ignore trimming the history data, from {} to {}.", start, end); + spec.commandLine().getOut() + .format("Ignore trimming the history data, from %d to %d.", start, end).println(); + return; + } + logger.info("Begin to trim the history data, from {} to {}.", start, end); + spec.commandLine().getOut() + .format("Begin to trim the history data, from %d to %d.", start, end).println(); + DBInterface blockIndexDb = DbTool.getDB(liteDir, BLOCK_INDEX_DB_NAME); + DBInterface blockDb = DbTool.getDB(liteDir, BLOCK_DB_NAME); + DBInterface transDb = DbTool.getDB(liteDir, TRANS_DB_NAME); + DBInterface tranRetDb = DbTool.getDB(liteDir, TRANSACTION_RET_DB_NAME); + + + ProgressBar.wrap(LongStream.rangeClosed(start, end) + .boxed() + .sorted((a, b) -> Long.compare(b, a)), "trimHistory").forEach(n -> { + try { + byte[] blockIdHash = blockIndexDb.get(ByteArray.fromLong(n)); + Protocol.Block block = Protocol.Block.parseFrom(blockDb.get(blockIdHash)); + // delete transactions + for (Protocol.Transaction e : block.getTransactionsList()) { + transDb.delete(DBUtils.getTransactionId(e).getBytes()); + } + // delete transaction result + tranRetDb.delete(ByteArray.fromLong(n)); + // delete block + blockDb.delete(blockIdHash); + // delete block index + blockIndexDb.delete(ByteArray.fromLong(n)); + } catch (IOException e) { + throw new RuntimeException(e); + } + }); + } + + private void mergeBak2Database(String liteDir, BlockNumInfo blockNumInfo) throws + IOException, RocksDBException { + long start = blockNumInfo.getHistoryMaxNum() + 1; + long end = blockNumInfo.getSnapshotMaxNum(); + + if (start > end) { + logger.info("Ignore merging the bak data, start {} end {}.", start, end); + spec.commandLine().getOut() + .format("Ignore merging the bak data, start %d end %d.", start, end).println(); + return; + } + + + Path bakDir = Paths.get(liteDir, BACKUP_DIR_PREFIX + START_TIME); + logger.info("Begin to merge {} to database, start {} end {}.", bakDir, start, end); + spec.commandLine().getOut() + .format("Begin to merge %s to database, start %d end %d.", bakDir, start, end).println(); + byte[] head = ByteArray.fromLong(start); + // use seek to skip + archiveDbs.stream().parallel().forEach(dbName -> { + try { + DBInterface bakDb = DbTool.getDB(bakDir.toString(), dbName); + DBInterface destDb = DbTool.getDB(liteDir, dbName); + try (DBIterator iterator = bakDb.iterator()) { + if (TRANS_DB_NAME.equals(dbName) || TRANSACTION_HISTORY_DB_NAME.equals(dbName)) { + iterator.seekToFirst(); + } else { + iterator.seek(head); + } + iterator.forEachRemaining(e -> destDb.put(e.getKey(), e.getValue())); + } + } catch (IOException | RocksDBException e) { + throw new RuntimeException(e); + } + }); + } + + private byte[] getDataFromSourceDB(String sourceDir, String dbName, byte[] key) + throws IOException, RocksDBException { + DBInterface sourceDb = DbTool.getDB(sourceDir, dbName); + DBInterface checkpointDb = getCheckpointDb(sourceDir); + // get data from tmp first. + byte[] valueFromTmp = checkpointDb.get(Bytes.concat(simpleEncode(dbName), key)); + byte[] value; + if (isEmptyBytes(valueFromTmp)) { + value = sourceDb.get(key); + } else { + value = valueFromTmp.length == 1 + ? null : Arrays.copyOfRange(valueFromTmp, 1, valueFromTmp.length); + } + if (isEmptyBytes(value)) { + throw new RuntimeException(String.format("data not found in store, dbName: %s, key: %s", + dbName, Arrays.toString(key))); + } + return value; + } + + /** + * return true if byte array is null or length is 0. + * + * @param b bytes + * @return true or false + */ + private static boolean isEmptyBytes(byte[] b) { + if (b != null) { + return b.length == 0; + } + return true; + } + + private void deleteSnapshotFlag(String databaseDir) throws IOException, RocksDBException { + logger.info("Delete the info file from {}.", databaseDir); + spec.commandLine().getOut().format("Delete the info file from %s.", databaseDir).println(); + Files.delete(Paths.get(databaseDir, INFO_FILE_NAME)); + } + + private void deleteBackupArchiveDbs(String liteDir) throws IOException, RocksDBException { + + Path bakDir = Paths.get(liteDir, BACKUP_DIR_PREFIX + START_TIME); + logger.info("Begin to delete bak dir {}.", bakDir); + spec.commandLine().getOut().format("Begin to delete bak dir %s.", bakDir).println(); + if (FileUtils.deleteDir(bakDir.toFile())) { + logger.info("End to delete bak dir {}.", bakDir); + spec.commandLine().getOut().format("End to delete bak dir %s.", bakDir).println(); + } else { + logger.info("Fail to delete bak dir {}, please remove manually.", bakDir); + spec.commandLine().getOut().format("Fail to delete bak dir %s, please remove manually.", + bakDir).println(); + } + } + + private void hasEnoughBlock(String sourceDir) throws RocksDBException, IOException { + // check latest + long latest = getLatestBlockHeaderNum(sourceDir); + // check second ,skip 0; + long second = getSecondBlock(sourceDir); + if (latest - second + 1 < RECENT_BLKS) { + throw new NoSuchElementException( + String.format("At least %d blocks in block store, actual latestBlock:%d, firstBlock:%d.", + RECENT_BLKS, latest, second)); + } + } + + private boolean isLite(String databaseDir) throws RocksDBException, IOException { + return getSecondBlock(databaseDir) > 1; + } + + private long getSecondBlock(String databaseDir) throws RocksDBException, IOException { + long num = 0; + DBInterface sourceBlockIndexDb = DbTool.getDB(databaseDir, BLOCK_INDEX_DB_NAME); + DBIterator iterator = sourceBlockIndexDb.iterator(); + iterator.seek(ByteArray.fromLong(1)); + if (iterator.hasNext()) { + num = Longs.fromByteArray(iterator.getKey()); + } + return num; + } + + private DBInterface getCheckpointDb(String sourceDir) throws IOException, RocksDBException { + List cpList = getCheckpointV2List(sourceDir); + DBInterface checkpointDb; + if (cpList.size() > 0) { + String latestCp = cpList.get(cpList.size() - 1); + checkpointDb = DbTool.getDB( + sourceDir + "/" + DBUtils.CHECKPOINT_DB_V2, latestCp); + } else { + checkpointDb = DbTool.getDB(sourceDir, CHECKPOINT_DB); + } + return checkpointDb; + } + + @VisibleForTesting + public static void setRecentBlks(long recentBlks) { + RECENT_BLKS = recentBlks; + } + + @VisibleForTesting + public static void reSetRecentBlks() { + RECENT_BLKS = 65536; + } + + private List getCheckpointV2List(String sourceDir) { + File file = new File(Paths.get(sourceDir, DBUtils.CHECKPOINT_DB_V2).toString()); + if (file.exists() && file.isDirectory() && file.list() != null) { + return Arrays.stream(Objects.requireNonNull(file.list())).sorted() + .collect(Collectors.toList()); + } + return Lists.newArrayList(); + } + + static class BlockNumInfo { + private final long snapshotMinNum; + private final long snapshotMaxNum; + private final long historyMaxNum; + + public BlockNumInfo(long snapshotMinNum, long historyMaxNum, long snapshotMaxNum) { + this.snapshotMinNum = snapshotMinNum; + this.historyMaxNum = historyMaxNum; + this.snapshotMaxNum = snapshotMaxNum; + } + + public long getSnapshotMinNum() { + return snapshotMinNum; + } + + public long getHistoryMaxNum() { + return historyMaxNum; + } + + public long getSnapshotMaxNum() { + return snapshotMaxNum; + } + } +} + + + diff --git a/plugins/src/main/java/org/tron/plugins/DbMove.java b/plugins/src/main/java/org/tron/plugins/DbMove.java new file mode 100644 index 00000000000..a5619d2d7ed --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/DbMove.java @@ -0,0 +1,245 @@ +package org.tron.plugins; + +import com.typesafe.config.Config; +import com.typesafe.config.ConfigFactory; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import me.tongfei.progressbar.ProgressBar; +import org.tron.plugins.utils.FileUtils; +import picocli.CommandLine; +import picocli.CommandLine.Command; + +@Slf4j(topic = "move") +@Command(name = "mv", aliases = "move", + description = "Move db to pre-set new path . For example HDD,reduce storage expenses.") +public class DbMove implements Callable { + + private static final String PROPERTIES_CONFIG_KEY = "storage.properties"; + private static final String DB_DIRECTORY_CONFIG_KEY = "storage.db.directory"; + private static final String DEFAULT_DB_DIRECTORY = "database"; + private static final String NAME_CONFIG_KEY = "name"; + private static final String PATH_CONFIG_KEY = "path"; + private static final String NOT_FIND = "There is no database to be moved, exist."; + + @CommandLine.Spec + CommandLine.Model.CommandSpec spec; + + @CommandLine.Option(names = {"-d", "--database-directory"}, + defaultValue = "output-directory", + converter = PathConverter.class, + description = "database directory path. Default: ${DEFAULT-VALUE}") + static Path database; + + @CommandLine.Option(names = {"-c", "--config"}, + defaultValue = "config.conf", + converter = ConfigConverter.class, + description = " config file. Default: ${DEFAULT-VALUE}") + Config config; + + @CommandLine.Option(names = {"-h", "--help"}) + static boolean help; + + @Override + public Integer call() throws Exception { + if (help) { + spec.commandLine().usage(System.out); + help = false; + return 0; + } + + if (config.hasPath(PROPERTIES_CONFIG_KEY)) { + List dbs = config.getConfigList(PROPERTIES_CONFIG_KEY); + if (dbs.isEmpty()) { + printNotExist(); + return 0; + } + String dbPath = config.hasPath(DB_DIRECTORY_CONFIG_KEY) + ? config.getString(DB_DIRECTORY_CONFIG_KEY) : DEFAULT_DB_DIRECTORY; + + dbs = dbs.stream() + .filter(c -> c.hasPath(NAME_CONFIG_KEY) && c.hasPath(PATH_CONFIG_KEY)) + .collect(Collectors.toList()); + + if (dbs.isEmpty()) { + printNotExist(); + return 0; + } + List toBeMove = dbs.stream() + .map(c -> { + try { + return new Property(c.getString(NAME_CONFIG_KEY), + Paths.get(database.toString(), dbPath, c.getString(NAME_CONFIG_KEY)), + Paths.get(c.getString(PATH_CONFIG_KEY), dbPath, c.getString(NAME_CONFIG_KEY))); + } catch (IOException e) { + spec.commandLine().getErr().println(e); + } + return null; + }).filter(Objects::nonNull) + .filter(p -> !p.destination.equals(p.original)).collect(Collectors.toList()); + + if (toBeMove.isEmpty()) { + printNotExist(); + return 0; + } + toBeMove = toBeMove.stream() + .filter(property -> { + if (property.destination.toFile().exists()) { + spec.commandLine().getOut().println(String.format("%s already exist,skip.", + property.destination)); + return false; + } else { + return true; + } + }).collect(Collectors.toList()); + + if (toBeMove.isEmpty()) { + printNotExist(); + return 0; + } + ProgressBar.wrap(toBeMove.stream(), "mv task").forEach(this::run); + spec.commandLine().getOut().println("move db done."); + + } else { + printNotExist(); + return 0; + } + return 0; + } + + private void run(Property p) { + if (p.destination.toFile().mkdirs()) { + ProgressBar.wrap(Arrays.stream(Objects.requireNonNull(p.original.toFile().listFiles())) + .filter(File::isFile).map(File::getName).parallel(), p.name).forEach(file -> { + Path original = Paths.get(p.original.toString(), file); + Path destination = Paths.get(p.destination.toString(), file); + try { + Files.copy(original, destination, + StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + spec.commandLine().getErr().println(e); + } + }); + try { + if (FileUtils.deleteDir(p.original.toFile())) { + Files.createSymbolicLink(p.original, p.destination); + } + } catch (IOException | UnsupportedOperationException x) { + spec.commandLine().getErr().println(x); + } + } else { + spec.commandLine().getErr().println(String.format("%s create failed.", p.destination)); + } + } + + private void printNotExist() { + spec.commandLine().getErr().println(NOT_FIND); + } + + + static class Property { + + private final String name; + private final Path original; + final Path destination; + + public Property(String name, Path original, Path destination) throws IOException { + this.name = name; + this.original = original.toFile().getCanonicalFile().toPath(); + if (!this.original.toFile().exists()) { + throw new IOException(this.original + " not exist!"); + } + if (this.original.toFile().isFile()) { + throw new IOException(this.original + " is a file!"); + } + if (FileUtils.isSymbolicLink(original.toFile())) { + throw new IOException(original + " is symbolicLink!"); + } + this.destination = destination.toFile().getCanonicalFile().toPath(); + if (this.destination.toFile().exists()) { + throw new IOException(this.destination + " already exist!"); + } + if (this.destination.equals(this.original)) { + throw new IOException("destination and original can not be same:[" + this.original + "]!"); + } + } + } + + static class ConfigConverter implements CommandLine.ITypeConverter { + private final Exception notFind = + new IllegalArgumentException("There is no database to be moved,please check."); + + ConfigConverter() { + } + + public Config convert(String value) throws Exception { + if (help) { + return null; + } + File file = Paths.get(value).toFile(); + if (file.exists() && file.isFile()) { + Config config = ConfigFactory.parseFile(Paths.get(value).toFile()); + if (config.hasPath(PROPERTIES_CONFIG_KEY)) { + List dbs = config.getConfigList(PROPERTIES_CONFIG_KEY); + if (dbs.isEmpty()) { + throw notFind; + } + String dbPath = config.hasPath(DB_DIRECTORY_CONFIG_KEY) + ? config.getString(DB_DIRECTORY_CONFIG_KEY) : DEFAULT_DB_DIRECTORY; + + dbs = dbs.stream() + .filter(c -> c.hasPath(NAME_CONFIG_KEY) && c.hasPath(PATH_CONFIG_KEY)) + .collect(Collectors.toList()); + + if (dbs.isEmpty()) { + throw notFind; + } + Set toBeMove = new HashSet<>(); + for (Config c : dbs) { + if (!toBeMove.add(new Property(c.getString(NAME_CONFIG_KEY), + Paths.get(database.toString(), dbPath, c.getString(NAME_CONFIG_KEY)), + Paths.get(c.getString(PATH_CONFIG_KEY), dbPath, + c.getString(NAME_CONFIG_KEY))).name)) { + throw new IllegalArgumentException( + "DB config has duplicate key:[" + c.getString(NAME_CONFIG_KEY) + + "],please check! "); + } + } + } else { + throw notFind; + } + return config; + } else { + throw new IOException("DB config [" + value + "] not exist!"); + } + } + } + + static class PathConverter implements CommandLine.ITypeConverter { + PathConverter() { + } + + public Path convert(String value) throws IOException { + if (help) { + return null; + } + File file = Paths.get(value).toFile(); + if (file.exists() && file.isDirectory()) { + return file.toPath(); + } else { + throw new IOException("DB path [" + value + "] not exist!"); + } + } + } +} diff --git a/plugins/src/main/java/org/tron/plugins/DbRoot.java b/plugins/src/main/java/org/tron/plugins/DbRoot.java new file mode 100644 index 00000000000..7c33219e180 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/DbRoot.java @@ -0,0 +1,121 @@ +package org.tron.plugins; + +import com.google.common.collect.Streams; +import com.google.common.primitives.Bytes; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.stream.Collectors; +import lombok.extern.slf4j.Slf4j; +import me.tongfei.progressbar.ProgressBar; +import org.rocksdb.RocksDBException; +import org.tron.plugins.utils.MerkleRoot; +import org.tron.plugins.utils.Sha256Hash; +import org.tron.plugins.utils.db.DBInterface; +import org.tron.plugins.utils.db.DBIterator; +import org.tron.plugins.utils.db.DbTool; +import picocli.CommandLine; + +@Slf4j(topic = "db-root") +@CommandLine.Command(name = "root", + description = "compute merkle root for tiny db. NOTE: large db may GC overhead limit exceeded.", + exitCodeListHeading = "Exit Codes:%n", + exitCodeList = { + "0:Successful", + "n:query failed,please check toolkit.log"}) +public class DbRoot implements Callable { + + @CommandLine.Spec + CommandLine.Model.CommandSpec spec; + @CommandLine.Parameters(index = "0", defaultValue = "output-directory/database", + description = "Input path. Default: ${DEFAULT-VALUE}") + private Path db; + + @CommandLine.Option(names = { "--db"}, + description = "db name for show root") + private List dbs; + + @CommandLine.Option(names = {"-h", "--help"}, help = true, description = "display a help message") + private boolean help; + + + @Override + public Integer call() throws Exception { + if (help) { + spec.commandLine().usage(System.out); + return 0; + } + if (!db.toFile().exists()) { + logger.info(" {} does not exist.", db); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(String.format("%s does not exist.", db))); + return 404; + } + + // remove not exit + if (dbs != null) { + dbs.removeIf(s -> !Paths.get(db.toString(), s).toFile().exists()); + } + + if (dbs == null || dbs.isEmpty()) { + logger.info("Specify at least one exit database: --db dbName."); + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText("Specify at least one exit database: --db dbName.")); + return 404; + } + List task = ProgressBar.wrap(dbs.stream(), "root task").parallel() + .map(this::calcMerkleRoot).collect(Collectors.toList()); + task.forEach(this::printInfo); + int code = (int) task.stream().filter(r -> r.code == 1).count(); + if (code > 0) { + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText("There are some errors, please check toolkit.log for detail.")); + } + spec.commandLine().getOut().println("root task done."); + return code; + } + + private Ret calcMerkleRoot(String name) { + Ret info = new Ret(); + try (DBInterface database = DbTool.getDB(this.db, name)) { + DBIterator iterator = database.iterator(); + iterator.seekToFirst(); + ArrayList ids = Streams.stream(iterator) + .map(this::getHash) + .collect(Collectors.toCollection(ArrayList::new)); + Sha256Hash root = MerkleRoot.root(ids); + logger.info("db: {},root: {}", database.getName(), root); + info.code = 0; + info.msg = String.format("db: %s,root: %s", database.getName(), root); + } catch (RocksDBException | IOException e) { + logger.error("calc db {} fail", name, e); + info.code = 1; + info.msg = String.format("db: %s,fail: %s", + name, e.getMessage()); + } + return info; + } + + private Sha256Hash getHash(Map.Entry entry) { + return Sha256Hash.of(true, + Bytes.concat(entry.getKey(), entry.getValue())); + } + + private void printInfo(Ret ret) { + if (ret.code == 0) { + spec.commandLine().getOut().println(ret.msg); + } else { + spec.commandLine().getErr().println(spec.commandLine().getColorScheme() + .errorText(ret.msg)); + } + } + + private static class Ret { + private int code; + private String msg; + } +} diff --git a/plugins/src/main/java/org/tron/plugins/Toolkit.java b/plugins/src/main/java/org/tron/plugins/Toolkit.java new file mode 100644 index 00000000000..3b9972de1c5 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/Toolkit.java @@ -0,0 +1,24 @@ +package org.tron.plugins; + +import java.util.concurrent.Callable; +import picocli.CommandLine; + +@CommandLine.Command(subcommands = { CommandLine.HelpCommand.class, Db.class}) +public class Toolkit implements Callable { + + + public static void main(String[] args) { + CommandLine cli = new CommandLine(new Toolkit()); + if (args == null || args.length == 0) { + cli.usage(System.out); + } else { + int exitCode = cli.execute(args); + System.exit(exitCode); + } + } + + @Override + public Integer call() throws Exception { + return 0; + } +} diff --git a/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForLevelDB.java b/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForLevelDB.java new file mode 100644 index 00000000000..0879f770e1f --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForLevelDB.java @@ -0,0 +1,28 @@ +package org.tron.plugins.comparator; + +import org.iq80.leveldb.DBComparator; +import org.tron.plugins.utils.MarketUtils; + +public class MarketOrderPriceComparatorForLevelDB implements DBComparator { + + @Override + public String name() { + return "MarketOrderPriceComparator"; + } + + @Override + public byte[] findShortestSeparator(byte[] start, byte[] limit) { + return new byte[0]; + } + + @Override + public byte[] findShortSuccessor(byte[] key) { + return new byte[0]; + } + + @Override + public int compare(byte[] o1, byte[] o2) { + return MarketUtils.comparePriceKey(o1, o2); + } + +} \ No newline at end of file diff --git a/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForRockDB.java b/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForRockDB.java new file mode 100644 index 00000000000..cd718bdd2d7 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/comparator/MarketOrderPriceComparatorForRockDB.java @@ -0,0 +1,38 @@ +package org.tron.plugins.comparator; + +import org.rocksdb.ComparatorOptions; +import org.rocksdb.DirectSlice; +import org.rocksdb.util.DirectBytewiseComparator; +import org.tron.plugins.utils.MarketUtils; + +public class MarketOrderPriceComparatorForRockDB extends DirectBytewiseComparator { + + public MarketOrderPriceComparatorForRockDB(final ComparatorOptions copt) { + super(copt); + } + + @Override + public String name() { + return "MarketOrderPriceComparator"; + } + + @Override + public int compare(final DirectSlice a, final DirectSlice b) { + return MarketUtils.comparePriceKey(convertDataToBytes(a), convertDataToBytes(b)); + } + + /** + * DirectSlice.data().array will throw UnsupportedOperationException. + * */ + public byte[] convertDataToBytes(DirectSlice directSlice) { + int capacity = directSlice.data().capacity(); + byte[] bytes = new byte[capacity]; + + for (int i = 0; i < capacity; i++) { + bytes[i] = directSlice.get(i); + } + + return bytes; + } + +} \ No newline at end of file diff --git a/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java b/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java new file mode 100644 index 00000000000..2922d110b7c --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/ByteArray.java @@ -0,0 +1,101 @@ +package org.tron.plugins.utils; + +import com.google.common.primitives.Ints; +import com.google.common.primitives.Longs; +import java.math.BigInteger; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.bouncycastle.util.encoders.Hex; + +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; + + /** + * 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); + } + + /** + * get long data from bytes data. + */ + public static long toLong(byte[] b) { + return ArrayUtils.isEmpty(b) ? 0 : new BigInteger(1, b).longValue(); + } + + public static byte[] fromInt(int val) { + return Ints.toByteArray(val); + } + + /** + * get int data from bytes data. + */ + public static int toInt(byte[] b) { + return ArrayUtils.isEmpty(b) ? 0 : new BigInteger(1, b).intValue(); + } + + public static int compareUnsigned(byte[] a, byte[] b) { + if (a == b) { + return 0; + } + if (a == null) { + return -1; + } + if (b == null) { + return 1; + } + int minLen = StrictMath.min(a.length, b.length); + for (int i = 0; i < minLen; ++i) { + int aVal = a[i] & 0xFF; + int bVal = b[i] & 0xFF; + if (aVal < bVal) { + return -1; + } + if (aVal > bVal) { + return 1; + } + } + if (a.length < b.length) { + return -1; + } + if (a.length > b.length) { + return 1; + } + return 0; + } + + 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); + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/CryptoUitls.java b/plugins/src/main/java/org/tron/plugins/utils/CryptoUitls.java new file mode 100644 index 00000000000..6d3e4ccb548 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/CryptoUitls.java @@ -0,0 +1,6 @@ +package org.tron.plugins.utils; + +public class CryptoUitls { + + public static final String ECKey_ENGINE = "ECKey"; +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java b/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java new file mode 100644 index 00000000000..f8559d5dba8 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/DBUtils.java @@ -0,0 +1,154 @@ +package org.tron.plugins.utils; + +import static org.fusesource.leveldbjni.JniDBFactory.factory; + +import com.google.common.primitives.Ints; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.util.Arrays; +import lombok.Getter; +import org.iq80.leveldb.CompressionType; +import org.iq80.leveldb.DB; +import org.rocksdb.BlockBasedTableConfig; +import org.rocksdb.BloomFilter; +import org.rocksdb.ComparatorOptions; +import org.rocksdb.Options; +import org.rocksdb.RocksDB; +import org.rocksdb.RocksDBException; +import org.tron.plugins.comparator.MarketOrderPriceComparatorForLevelDB; +import org.tron.plugins.comparator.MarketOrderPriceComparatorForRockDB; +import org.tron.protos.Protocol; + +public class DBUtils { + + + public enum Operator { + CREATE((byte) 0), + MODIFY((byte) 1), + DELETE((byte) 2), + PUT((byte) 3); + + @Getter + private byte value; + + Operator(byte value) { + this.value = value; + } + + static Operator valueOf(byte b) { + switch (b) { + case 0: + return Operator.CREATE; + case 1: + return Operator.MODIFY; + case 2: + return Operator.DELETE; + case 3: + return Operator.PUT; + default: + return null; + } + } + } + + public static final String SPLIT_BLOCK_NUM = "split_block_num"; + public static final String MARKET_PAIR_PRICE_TO_ORDER = "market_pair_price_to_order"; + public static final String CHECKPOINT_DB_V2 = "checkpoint"; + public static final String TMP = "tmp"; + + public static final int NODE_TYPE_LIGHT_NODE = 1; + + public static final String KEY_ENGINE = "ENGINE"; + public static final String FILE_ENGINE = "engine.properties"; + public static final String LEVELDB = "LEVELDB"; + public static final String ROCKSDB = "ROCKSDB"; + + public static DB newLevelDb(Path db) throws IOException { + File file = db.toFile(); + org.iq80.leveldb.Options dbOptions = newDefaultLevelDbOptions(); + if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(file.getName())) { + dbOptions.comparator(new MarketOrderPriceComparatorForLevelDB()); + } + return factory.open(file, dbOptions); + } + + public static org.iq80.leveldb.Options newDefaultLevelDbOptions() { + org.iq80.leveldb.Options dbOptions = new org.iq80.leveldb.Options(); + dbOptions.createIfMissing(true); + dbOptions.paranoidChecks(true); + dbOptions.verifyChecksums(true); + dbOptions.compressionType(CompressionType.SNAPPY); + dbOptions.blockSize(4 * 1024); + dbOptions.writeBufferSize(10 * 1024 * 1024); + dbOptions.cacheSize(10 * 1024 * 1024L); + dbOptions.maxOpenFiles(1000); + return dbOptions; + } + + private static Options newDefaultRocksDbOptions(boolean forBulkLoad) { + Options options = new Options(); + options.setCreateIfMissing(true); + options.setIncreaseParallelism(1); + options.setNumLevels(7); + options.setMaxOpenFiles(5000); + options.setTargetFileSizeBase(64 * 1024 * 1024); + options.setTargetFileSizeMultiplier(1); + options.setMaxBytesForLevelBase(512 * 1024 * 1024); + options.setMaxBackgroundCompactions(StrictMath.max( + 1, Runtime.getRuntime().availableProcessors())); + options.setLevel0FileNumCompactionTrigger(4); + options.setLevelCompactionDynamicLevelBytes(true); + final BlockBasedTableConfig tableCfg; + options.setTableFormatConfig(tableCfg = new BlockBasedTableConfig()); + tableCfg.setBlockSize(64 * 1024); + tableCfg.setBlockCacheSize(32 * 1024 * 1024); + tableCfg.setCacheIndexAndFilterBlocks(true); + tableCfg.setPinL0FilterAndIndexBlocksInCache(true); + tableCfg.setFilter(new BloomFilter(10, false)); + if (forBulkLoad) { + options.prepareForBulkLoad(); + } + return options; + } + + public static RocksDB newRocksDb(Path db) throws RocksDBException { + try (Options options = newDefaultRocksDbOptions(false)) { + if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(db.getFileName().toString())) { + options.setComparator(new MarketOrderPriceComparatorForRockDB(new ComparatorOptions())); + } + return RocksDB.open(options, db.toString()); + } + } + + public static RocksDB newRocksDbForBulkLoad(Path db) throws RocksDBException { + try (Options options = newDefaultRocksDbOptions(true)) { + if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(db.getFileName().toString())) { + options.setComparator(new MarketOrderPriceComparatorForRockDB(new ComparatorOptions())); + } + return RocksDB.open(options, db.toString()); + } + } + + + public static RocksDB newRocksDbReadOnly(Path db) throws RocksDBException { + try (Options options = newDefaultRocksDbOptions(false)) { + if (MARKET_PAIR_PRICE_TO_ORDER.equalsIgnoreCase(db.getFileName().toString())) { + options.setComparator(new MarketOrderPriceComparatorForRockDB(new ComparatorOptions())); + } + return RocksDB.openReadOnly(options, db.toString()); + } + } + + public static String simpleDecode(byte[] bytes) { + byte[] lengthBytes = Arrays.copyOf(bytes, 4); + int length = Ints.fromByteArray(lengthBytes); + byte[] value = Arrays.copyOfRange(bytes, 4, 4 + length); + return new String(value); + } + + public static Sha256Hash getTransactionId(Protocol.Transaction transaction) { + return Sha256Hash.of(true, + transaction.getRawData().toByteArray()); + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/FileUtils.java b/plugins/src/main/java/org/tron/plugins/utils/FileUtils.java new file mode 100644 index 00000000000..b07b4469dc3 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/FileUtils.java @@ -0,0 +1,189 @@ +package org.tron.plugins.utils; + +import java.io.BufferedInputStream; +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.FileSystemException; +import java.nio.file.FileVisitOption; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.util.List; +import java.util.Properties; +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class FileUtils { + + public static boolean isLevelDBEngine(Path path) { + String dir = path.toString(); + String enginePath = dir + File.separator + "engine.properties"; + if (!new File(enginePath).exists() + && !writeProperty(enginePath, DBUtils.KEY_ENGINE, DBUtils.LEVELDB)) { + return false; + } + String engine = readProperty(enginePath, DBUtils.KEY_ENGINE); + return DBUtils.LEVELDB.equals(engine); + } + + public static String readProperty(String file, String key) { + try (FileInputStream fileInputStream = new FileInputStream(file); + InputStream inputStream = new BufferedInputStream(fileInputStream)) { + Properties prop = new Properties(); + prop.load(inputStream); + return new String(prop.getProperty(key, "").getBytes(StandardCharsets.ISO_8859_1), + StandardCharsets.UTF_8); + } catch (Exception e) { + logger.error("readProperty", e); + return ""; + } + } + + public static boolean writeProperty(String file, String key, String value) { + try (OutputStream o = new FileOutputStream(file); + FileInputStream f = new FileInputStream(file); + BufferedWriter w = new BufferedWriter(new OutputStreamWriter(o, StandardCharsets.UTF_8)); + BufferedReader r = new BufferedReader(new InputStreamReader(f, StandardCharsets.UTF_8)) + ) { + Properties properties = new Properties(); + properties.load(r); + properties.setProperty(key, value); + properties.store(w, "Generated by the application. PLEASE DO NOT EDIT! "); + } catch (Exception e) { + logger.warn("writeProperty", e); + return false; + } + return true; + } + + + /** + * delete directory. + */ + public static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + for (int i = 0; i < children.length; i++) { + boolean success = deleteDir(new File(dir, children[i])); + if (!success) { + return false; + } + } + } + return dir.delete(); + } + + public static boolean createFileIfNotExists(String filepath) { + File file = new File(filepath); + if (!file.exists()) { + try { + file.createNewFile(); + } catch (Exception e) { + return false; + } + } + return true; + } + + public static boolean createDirIfNotExists(String dirPath) { + File dir = new File(dirPath); + if (!dir.exists()) { + return dir.mkdirs(); + } + return true; + } + + public static boolean isExists(String path) { + File file = new File(path); + return file.exists(); + } + + public static boolean isSymbolicLink(File file) throws IOException { + if (file == null) { + throw new NullPointerException("File must not be null"); + } + + File canon; + if (file.getParent() == null) { + canon = file; + } else { + File canonDir = file.getParentFile().getCanonicalFile(); + canon = new File(canonDir, file.getName()); + } + return !canon.getCanonicalFile().equals(canon.getAbsoluteFile()); + } + + /** + * Copy src to dest, if dest is a directory and already exists, throw Exception. + * + *

Note: This method is not rigorous, because all the dirs that its FileName + * is contained in List(subDirs) will be filtered, this may result in unpredictable result. + * just used in LiteFullNodeTool. + * + * @param src Path or File + * @param dest Path or File + * @param subDirs only the subDirs in {@code src} will be copied + * @throws IOException IOException + */ + public static void copyDatabases(Path src, Path dest, List subDirs) + throws IOException { + // create subdirs, as using parallel() to run, so should create dirs first. + subDirs.forEach(dir -> { + if (isExists(Paths.get(src.toString(), dir).toString())) { + try { + Files.walk(Paths.get(src.toString(), dir), FileVisitOption.FOLLOW_LINKS) + .forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } catch (IOException e) { + logger.error("copy database failed, src: {}, dest: {}, error: {}", + Paths.get(src.toString(), dir), Paths.get(dest.toString(), dir), e.getMessage()); + throw new RuntimeException(e); + } + } + }); + } + + public static void copyDir(Path src, Path dest, String dir) { + if (isExists(Paths.get(src.toString(), dir).toString())) { + try { + if (createDirIfNotExists(Paths.get(dest.toString(), dir).toString())) { + Files.walk(Paths.get(src.toString(), dir), FileVisitOption.FOLLOW_LINKS) + .forEach(source -> copy(source, dest.resolve(src.relativize(source)))); + } else { + throw new IOException(String.format("dest %s create fail ", + Paths.get(dest.toString(), dir))); + } + } catch (IOException e) { + logger.error("copy dir failed, src: {}, dest: {}, error: {}", + Paths.get(src.toString(), dir), Paths.get(dest.toString(), dir), e.getMessage()); + throw new RuntimeException(e); + } + } + } + + public static void copy(Path source, Path dest) { + try { + // create hard link when file is .sst + if (source.toString().endsWith(".sst")) { + try { + java.nio.file.Files.createLink(dest, source); + } catch (FileSystemException e) { + java.nio.file.Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); + } + } else { + java.nio.file.Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); + } + } catch (Exception e) { + throw new RuntimeException(e.getMessage(), e); + } + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java b/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java new file mode 100644 index 00000000000..dbd578a59a3 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/MarketUtils.java @@ -0,0 +1,148 @@ +package org.tron.plugins.utils; + +import java.math.BigInteger; +import org.tron.plugins.utils.ByteArray; + +public class MarketUtils { + + public static final int TOKEN_ID_LENGTH = ByteArray + .fromString(Long.toString(Long.MAX_VALUE)).length; // 19 + + + + /** + * In order to avoid the difference between the data of same key stored and fetched by hashMap and + * levelDB, when creating the price key, we will find the GCD (Greatest Common Divisor) of + * sellTokenQuantity and buyTokenQuantity. + */ + public static byte[] createPairPriceKey(byte[] sellTokenId, byte[] buyTokenId, + long sellTokenQuantity, long buyTokenQuantity) { + + byte[] sellTokenQuantityBytes; + byte[] buyTokenQuantityBytes; + + // cal the GCD + long gcd = findGCD(sellTokenQuantity, buyTokenQuantity); + if (gcd == 0) { + sellTokenQuantityBytes = ByteArray.fromLong(sellTokenQuantity); + buyTokenQuantityBytes = ByteArray.fromLong(buyTokenQuantity); + } else { + sellTokenQuantityBytes = ByteArray.fromLong(sellTokenQuantity / gcd); + buyTokenQuantityBytes = ByteArray.fromLong(buyTokenQuantity / gcd); + } + + return doCreatePairPriceKey(sellTokenId, buyTokenId, + sellTokenQuantityBytes, buyTokenQuantityBytes); + } + + public static long findGCD(long number1, long number2) { + if (number1 == 0 || number2 == 0) { + return 0; + } + return calGCD(number1, number2); + } + + private static long calGCD(long number1, long number2) { + if (number2 == 0) { + return number1; + } + return calGCD(number2, number1 % number2); + } + + + private static byte[] doCreatePairPriceKey(byte[] sellTokenId, byte[] buyTokenId, + byte[] sellTokenQuantity, byte[] buyTokenQuantity) { + byte[] result = new byte[TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + + sellTokenQuantity.length + buyTokenQuantity.length]; + + System.arraycopy(sellTokenId, 0, result, 0, sellTokenId.length); + System.arraycopy(buyTokenId, 0, result, TOKEN_ID_LENGTH, buyTokenId.length); + System.arraycopy(sellTokenQuantity, 0, result, + TOKEN_ID_LENGTH + TOKEN_ID_LENGTH, + sellTokenQuantity.length); + System.arraycopy(buyTokenQuantity, 0, result, + TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + buyTokenQuantity.length, + buyTokenQuantity.length); + + return result; + } + + + public static int comparePriceKey(byte[] o1, byte[] o2) { + //compare pair + byte[] pair1 = new byte[TOKEN_ID_LENGTH * 2]; + byte[] pair2 = new byte[TOKEN_ID_LENGTH * 2]; + + System.arraycopy(o1, 0, pair1, 0, TOKEN_ID_LENGTH * 2); + System.arraycopy(o2, 0, pair2, 0, TOKEN_ID_LENGTH * 2); + + int pairResult = ByteArray.compareUnsigned(pair1, pair2); + if (pairResult != 0) { + return pairResult; + } + + //compare price + byte[] getSellTokenQuantity1 = new byte[8]; + byte[] getBuyTokenQuantity1 = new byte[8]; + + byte[] getSellTokenQuantity2 = new byte[8]; + byte[] getBuyTokenQuantity2 = new byte[8]; + + int longByteNum = 8; + + System.arraycopy(o1, TOKEN_ID_LENGTH + TOKEN_ID_LENGTH, + getSellTokenQuantity1, 0, longByteNum); + System.arraycopy(o1, TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + longByteNum, + getBuyTokenQuantity1, 0, longByteNum); + + System.arraycopy(o2, TOKEN_ID_LENGTH + TOKEN_ID_LENGTH, + getSellTokenQuantity2, 0, longByteNum); + System.arraycopy(o2, TOKEN_ID_LENGTH + TOKEN_ID_LENGTH + longByteNum, + getBuyTokenQuantity2, 0, longByteNum); + + long sellTokenQuantity1 = ByteArray.toLong(getSellTokenQuantity1); + long buyTokenQuantity1 = ByteArray.toLong(getBuyTokenQuantity1); + long sellTokenQuantity2 = ByteArray.toLong(getSellTokenQuantity2); + long buyTokenQuantity2 = ByteArray.toLong(getBuyTokenQuantity2); + + if ((sellTokenQuantity1 == 0 || buyTokenQuantity1 == 0) + && (sellTokenQuantity2 == 0 || buyTokenQuantity2 == 0)) { + return 0; + } + + if (sellTokenQuantity1 == 0 || buyTokenQuantity1 == 0) { + return -1; + } + + if (sellTokenQuantity2 == 0 || buyTokenQuantity2 == 0) { + return 1; + } + + return comparePrice(sellTokenQuantity1, buyTokenQuantity1, + sellTokenQuantity2, buyTokenQuantity2); + + } + + /** + * Note: the params should be the same token pair, or you should change the order. + * All the quantity should be bigger than 0. + * */ + public static int comparePrice(long price1SellQuantity, long price1BuyQuantity, + long price2SellQuantity, long price2BuyQuantity) { + try { + return Long.compare(StrictMath.multiplyExact(price1BuyQuantity, price2SellQuantity), + StrictMath.multiplyExact(price2BuyQuantity, price1SellQuantity)); + + } catch (ArithmeticException ex) { + // do nothing here, because we will use BigInteger to compute again + } + + BigInteger price1BuyQuantityBI = BigInteger.valueOf(price1BuyQuantity); + BigInteger price1SellQuantityBI = BigInteger.valueOf(price1SellQuantity); + BigInteger price2BuyQuantityBI = BigInteger.valueOf(price2BuyQuantity); + BigInteger price2SellQuantityBI = BigInteger.valueOf(price2SellQuantity); + + return price1BuyQuantityBI.multiply(price2SellQuantityBI) + .compareTo(price2BuyQuantityBI.multiply(price1SellQuantityBI)); + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java b/plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java new file mode 100644 index 00000000000..055f5dcdee0 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/MerkleRoot.java @@ -0,0 +1,68 @@ +package org.tron.plugins.utils; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import lombok.Getter; + +public class MerkleRoot { + + private MerkleRoot() { + + } + + public static Sha256Hash root(List hashList) { + List leaves = createLeaves(hashList); + while (leaves.size() > 1) { + leaves = createParentLeaves(leaves); + } + return leaves.isEmpty() ? Sha256Hash.ZERO_HASH : leaves.get(0).hash; + } + + private static List createParentLeaves(List leaves) { + int step = 2; + int len = leaves.size(); + return IntStream.iterate(0, i -> i + step) + .limit(len) + .filter(i -> i < len) + .mapToObj(i -> { + Leaf right = i + 1 < len ? leaves.get(i + 1) : null; + return createLeaf(leaves.get(i), right); + }).collect(Collectors.toList()); + } + + private static List createLeaves(List hashList) { + int step = 2; + int len = hashList.size(); + return IntStream.iterate(0, i -> i + step) + .limit(len) + .filter(i -> i < len) + .mapToObj(i -> { + Leaf right = i + 1 < len ? createLeaf(hashList.get(i + 1)) : null; + return createLeaf(createLeaf(hashList.get(i)), right); + }).collect(Collectors.toList()); + } + + private static Leaf createLeaf(Leaf left, Leaf right) { + Leaf leaf = new Leaf(); + leaf.hash = right == null ? left.hash : computeHash(left.hash, right.hash); + return leaf; + } + + private static Leaf createLeaf(Sha256Hash hash) { + Leaf leaf = new Leaf(); + leaf.hash = hash; + return leaf; + } + + private static Sha256Hash computeHash(Sha256Hash leftHash, Sha256Hash rightHash) { + return Sha256Hash.of(true, + leftHash.getByteString().concat(rightHash.getByteString()).toByteArray()); + } + + @Getter + private static class Leaf { + + private Sha256Hash hash; + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/Sha256Hash.java b/plugins/src/main/java/org/tron/plugins/utils/Sha256Hash.java new file mode 100644 index 00000000000..67e6e64ea79 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/Sha256Hash.java @@ -0,0 +1,210 @@ +package org.tron.plugins.utils; + +/* + * Copyright 2011 Google Inc. + * Copyright 2014 Andreas Schildbach + * + * 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. + */ + +import static com.google.common.base.Preconditions.checkArgument; + +import com.google.common.io.ByteStreams; +import com.google.common.primitives.Ints; +import com.google.protobuf.ByteString; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.Serializable; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import org.bouncycastle.crypto.digests.SM3Digest; + + +/** + * A Sha256Hash just wraps a byte[] so that equals and hashcode work correctly, allowing it to be + * used as keys in a map. It also checks that the length is correct and provides a bit more type + * safety. + */ +public class Sha256Hash implements Serializable, Comparable { + + public static final int LENGTH = 32; // bytes + public static final Sha256Hash ZERO_HASH = wrap(new byte[LENGTH]); + private final byte[] bytes; + + /** + * Use {@link #wrap(byte[])} instead. + */ + @Deprecated + public Sha256Hash(byte[] rawHashBytes) { + checkArgument(rawHashBytes.length == LENGTH); + this.bytes = rawHashBytes; + } + + /** + * Creates a new instance that wraps the given hash value. + * + * @param rawHashBytes the raw hash bytes to wrap + * @return a new instance + * @throws IllegalArgumentException if the given array length is not exactly 32 + */ + @SuppressWarnings("deprecation") // the constructor will be made private in the future + public static Sha256Hash wrap(byte[] rawHashBytes) { + return new Sha256Hash(rawHashBytes); + } + + + /** + * Creates a new instance containing the calculated (one-time) hash of the given bytes. + * + * @param contents the bytes on which the hash value is calculated + * @return a new instance containing the calculated (one-time) hash + */ + public static Sha256Hash of(boolean isSha256, byte[] contents) { + return wrap(hash(isSha256, contents)); + } + + /** + * Creates a new instance containing the calculated (one-time) hash of the given file's contents. + * The file contents are read fully into memory, so this method should only be used with small + * files. + * + * @param file the file on which the hash value is calculated + * @return a new instance containing the calculated (one-time) hash + * @throws IOException if an error occurs while reading the file + */ + public static Sha256Hash of(boolean isSha256, File file) throws IOException { + + try (FileInputStream in = new FileInputStream(file)) { + return of(isSha256, ByteStreams.toByteArray(in)); + } + } + + + /** + * Returns a new SHA-256 MessageDigest instance. This is a convenience method which wraps the + * checked exception that can never occur with a RuntimeException. + * + * @return a new SHA-256 MessageDigest instance + */ + public static MessageDigest newDigest() { + try { + return MessageDigest.getInstance("SHA-256"); + } catch (NoSuchAlgorithmException e) { + throw new RuntimeException(e); // Can't happen. + } + } + + /** + * Returns a new SM3 MessageDigest instance. This is a convenience method which wraps the checked + * exception that can never occur with a RuntimeException. + * + * @return a new SM3 MessageDigest instance + */ + public static SM3Digest newSM3Digest() { + return new SM3Digest(); + } + + /** + * Calculates the SHA-256 hash of the given bytes. + * + * @param input the bytes to hash + * @return the hash (in big-endian order) + */ + public static byte[] hash(boolean isSha256, byte[] input) { + return hash(isSha256, input, 0, input.length); + } + + /** + * Calculates the SHA-256 hash of the given byte range. + * + * @param input the array containing the bytes to hash + * @param offset the offset within the array of the bytes to hash + * @param length the number of bytes to hash + * @return the hash (in big-endian order) + */ + public static byte[] hash(boolean isSha256, byte[] input, int offset, int length) { + if (isSha256) { + MessageDigest digest = newDigest(); + digest.update(input, offset, length); + return digest.digest(); + } else { + SM3Digest digest = newSM3Digest(); + digest.update(input, offset, length); + byte[] eHash = new byte[digest.getDigestSize()]; + digest.doFinal(eHash, 0); + return eHash; + } + + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof Sha256Hash)) { + return false; + } + return Arrays.equals(bytes, ((Sha256Hash) o).bytes); + } + + @Override + public String toString() { + return ByteArray.toHexString(bytes); + } + + /** + * Returns the last four bytes of the wrapped hash. This should be unique enough to be a suitable + * hash code even for blocks, where the goal is to try and get the first bytes to be zeros (i.e. + * the value as a big integer lower than the target value). + */ + @Override + public int hashCode() { + // Use the last 4 bytes, not the first 4 which are often zeros in Bitcoin. + return Ints + .fromBytes(bytes[LENGTH - 4], bytes[LENGTH - 3], bytes[LENGTH - 2], bytes[LENGTH - 1]); + } + + /** + * Returns the internal byte array, without defensively copying. Therefore do NOT modify the + * returned array. + */ + public byte[] getBytes() { + return bytes; + } + + /** + * For pb return ByteString. + */ + public ByteString getByteString() { + return ByteString.copyFrom(bytes); + } + + + @Override + public int compareTo(final Sha256Hash other) { + for (int i = LENGTH - 1; i >= 0; i--) { + final int thisByte = this.bytes[i] & 0xff; + final int otherByte = other.bytes[i] & 0xff; + if (thisByte > otherByte) { + return 1; + } + if (thisByte < otherByte) { + return -1; + } + } + return 0; + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/DBInterface.java b/plugins/src/main/java/org/tron/plugins/utils/db/DBInterface.java new file mode 100644 index 00000000000..513e021c83c --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/db/DBInterface.java @@ -0,0 +1,23 @@ +package org.tron.plugins.utils.db; + +import java.io.Closeable; +import java.io.IOException; + + +public interface DBInterface extends Closeable { + + byte[] get(byte[] key); + + void put(byte[] key, byte[] value); + + void delete(byte[] key); + + DBIterator iterator(); + + long size(); + + void close() throws IOException; + + String getName(); + +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/DBIterator.java b/plugins/src/main/java/org/tron/plugins/utils/db/DBIterator.java new file mode 100644 index 00000000000..b5cbd705331 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/db/DBIterator.java @@ -0,0 +1,59 @@ +package org.tron.plugins.utils.db; + +import java.io.Closeable; +import java.util.Iterator; +import java.util.Map; + +public interface DBIterator extends Iterator>, Closeable { + + /** + * An iterator is either positioned at a key/value pair, or + * not valid. This method returns true iff the iterator is valid. + * + * @return an iterator is either positioned at a key/value pair + */ + boolean valid(); + + /** + * Position at the first key in the source that is at or past target. + * The iterator is valid() after this call iff the source contains + * an entry that comes at or past target. + * + * @param key target + */ + void seek(byte[] key); + + /** + * Position at the first key in the source. The iterator is valid() + * after this call iff the source is not empty. + */ + void seekToFirst(); + + /** + * Position at the last key in the source. The iterator is + * valid() after this call iff the source is not empty. + */ + void seekToLast(); + + boolean hasNext(); + + /** + * The underlying storage for + * the returned slice is valid only until the next modification of + * the iterator. + * REQUIRES: valid() + * + * @return the key for the current entry + */ + byte[] getKey(); + + /** + * The underlying storage for + * the returned slice is valid only until the next modification of + * the iterator. + * REQUIRES: valid() + * + * @return the value for the current entry + */ + byte[] getValue(); +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/DbTool.java b/plugins/src/main/java/org/tron/plugins/utils/db/DbTool.java new file mode 100644 index 00000000000..429025e8f8b --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/db/DbTool.java @@ -0,0 +1,187 @@ +package org.tron.plugins.utils.db; + +import com.google.common.collect.Maps; +import java.io.File; +import java.io.IOException; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Iterator; +import java.util.Map; +import lombok.extern.slf4j.Slf4j; +import org.rocksdb.RocksDBException; +import org.tron.plugins.utils.DBUtils; +import org.tron.plugins.utils.FileUtils; + + +@Slf4j(topic = "tool") +public class DbTool { + + private static final String KEY_ENGINE = "ENGINE"; + private static final String ENGINE_FILE = "engine.properties"; + private static final String FILE_SEPARATOR = File.separator; + private static final String ROCKSDB = "ROCKSDB"; + + private static final Map dbMap = Maps.newConcurrentMap(); + + public enum DbType { + LevelDB, + RocksDB + } + + /** + * Get the DB object according to the specified path, + * create db object when not exists, otherwise get it from the dbMap. + * + * @param sourceDir the parent path of db + * @param dbName db dir name + * + * @return db object + * + * @throws IOException leveldb error + * @throws RocksDBException rocksdb error + */ + public static DBInterface getDB(String sourceDir, String dbName) + throws IOException, RocksDBException { + DbType type = getDbType(sourceDir, dbName); + return getDB(sourceDir, dbName, type); + } + + /** + * Get the DB object according to the specified path, keep engine same with source. + * + * @param sourceDir read engine + * @param destDir to be open parent path + * @param dbName database name + * + * @return db object + * + * @throws IOException leveldb error + * @throws RocksDBException rocksdb error + */ + public static DBInterface getDB(String sourceDir, String destDir, String dbName) + throws IOException, RocksDBException { + DbType type = getDbType(sourceDir, dbName); + return getDB(destDir, dbName, type); + } + + /** + * Get the DB object according to the specified path and engine. + * + * @param sourceDir to be open parent path + * @param dbName database name + * @param type engine + * @return db object + * @throws IOException leveldb error + * @throws RocksDBException rocksdb error + */ + public static DBInterface getDB(String sourceDir, String dbName, DbType type) + throws IOException, RocksDBException { + Path path = Paths.get(sourceDir, dbName); + if (dbMap.containsKey(path.toString())) { + return dbMap.get(path.toString()); + } + DBInterface db; + switch (type) { + case LevelDB: + db = openLevelDb(path, dbName); + dbMap.put(path.toString(), db); + break; + case RocksDB: + db = openRocksDb(path, dbName); + dbMap.put(path.toString(), db); + break; + default: + throw new IllegalStateException("Unexpected value: " + type); + } + return db; + } + + /** + * Get the DB object according to the specified path, + * not managed by dbMap. + * + * @param sourceDir the parent path of db + * @param dbName db dir name + * + * @return db object + * + * @throws IOException leveldb error + * @throws RocksDBException rocksdb error + */ + public static DBInterface getDB(Path sourceDir, String dbName) + throws IOException, RocksDBException { + Path path = Paths.get(sourceDir.toString(), dbName); + DbType type = getDbType(sourceDir.toString(), dbName); + switch (type) { + case LevelDB: + return openLevelDb(path, dbName); + case RocksDB: + return openRocksDb(path, dbName); + default: + throw new IllegalStateException("Unexpected value: " + type); + } + } + + /** + * Close db. + * + * @param sourceDir db parentPath + * @param dbName db dirname + * + * @throws IOException IOException + */ + public static void closeDB(String sourceDir, String dbName) + throws IOException { + Path path = Paths.get(sourceDir, dbName); + DBInterface db = dbMap.get(path.toString()); + if (db != null) { + try { + dbMap.remove(path.toString()); + db.close(); + } catch (IOException e) { + logger.error("close db {} error: {}", path, e); + throw e; + } + } + } + + /** + * Close all dbs. + */ + public static void close() { + Iterator> iterator = dbMap.entrySet().iterator(); + while (iterator.hasNext()) { + Map.Entry next = iterator.next(); + try { + next.getValue().close(); + } catch (IOException e) { + logger.error("close db failed, db: {}", next.getKey(), e); + } + iterator.remove(); + } + } + + private static DbType getDbType(String sourceDir, String dbName) { + String engineFile = String.format("%s%s%s%s%s", sourceDir, FILE_SEPARATOR, + dbName, FILE_SEPARATOR, ENGINE_FILE); + if (!new File(engineFile).exists()) { + return DbType.LevelDB; + } + String engine = FileUtils.readProperty(engineFile, KEY_ENGINE); + if (engine.equalsIgnoreCase(ROCKSDB)) { + return DbType.RocksDB; + } else { + return DbType.LevelDB; + } + } + + private static LevelDBImpl openLevelDb(Path db, String name) throws IOException { + return new LevelDBImpl(DBUtils.newLevelDb(db), name); + } + + private static RocksDBImpl openRocksDb(Path db, String name) throws RocksDBException { + return new RocksDBImpl(DBUtils.newRocksDb(db), name); + } + + +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBImpl.java b/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBImpl.java new file mode 100644 index 00000000000..511f4dfd5b4 --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBImpl.java @@ -0,0 +1,51 @@ +package org.tron.plugins.utils.db; + +import com.google.common.collect.Streams; +import java.io.IOException; +import lombok.Getter; +import org.iq80.leveldb.DB; +import org.iq80.leveldb.ReadOptions; + + +public class LevelDBImpl implements DBInterface { + + private DB leveldb; + + @Getter + private final String name; + + public LevelDBImpl(DB leveldb, String name) { + this.leveldb = leveldb; + this.name = name; + } + + @Override + public byte[] get(byte[] key) { + return leveldb.get(key); + } + + @Override + public void put(byte[] key, byte[] value) { + leveldb.put(key, value); + } + + @Override + public void delete(byte[] key) { + leveldb.delete(key); + } + + @Override + public DBIterator iterator() { + return new LevelDBIterator(leveldb.iterator(new ReadOptions().fillCache(false))); + } + + @Override + public long size() { + return Streams.stream(leveldb.iterator()).count(); + } + + @Override + public void close() throws IOException { + leveldb.close(); + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBIterator.java b/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBIterator.java new file mode 100644 index 00000000000..b5f0028dd6f --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/db/LevelDBIterator.java @@ -0,0 +1,58 @@ +package org.tron.plugins.utils.db; + +import java.io.IOException; +import java.util.Map; + +public class LevelDBIterator implements DBIterator { + + private final org.iq80.leveldb.DBIterator iterator; + + public LevelDBIterator(org.iq80.leveldb.DBIterator iterator) { + this.iterator = iterator; + } + + @Override + public boolean valid() { + return iterator.hasNext(); + } + + @Override + public void seek(byte[] key) { + iterator.seek(key); + } + + @Override + public void seekToFirst() { + iterator.seekToFirst(); + } + + @Override + public void seekToLast() { + iterator.seekToLast(); + } + + @Override + public boolean hasNext() { + return iterator.hasNext(); + } + + @Override + public byte[] getKey() { + return iterator.peekNext().getKey(); + } + + @Override + public byte[] getValue() { + return iterator.peekNext().getValue(); + } + + @Override + public Map.Entry next() { + return iterator.next(); + } + + @Override + public void close() throws IOException { + iterator.close(); + } +} diff --git a/plugins/src/main/java/org/tron/plugins/utils/db/RockDBIterator.java b/plugins/src/main/java/org/tron/plugins/utils/db/RockDBIterator.java new file mode 100644 index 00000000000..d3e17d9173f --- /dev/null +++ b/plugins/src/main/java/org/tron/plugins/utils/db/RockDBIterator.java @@ -0,0 +1,77 @@ +package org.tron.plugins.utils.db; + +import java.io.IOException; +import java.util.Map; +import org.rocksdb.RocksIterator; + +public class RockDBIterator implements DBIterator { + + private final RocksIterator iterator; + + public RockDBIterator(RocksIterator iterator) { + this.iterator = iterator; + } + + @Override + public boolean valid() { + return iterator.isValid(); + } + + @Override + public void seek(byte[] key) { + iterator.seek(key); + } + + @Override + public void seekToFirst() { + iterator.seekToFirst(); + } + + @Override + public void seekToLast() { + iterator.seekToLast(); + } + + @Override + public boolean hasNext() { + return iterator.isValid(); + } + + @Override + public byte[] getKey() { + return iterator.key(); + } + + @Override + public byte[] getValue() { + return iterator.value(); + } + + @Override + public Map.Entry next() { + byte[] key = iterator.key(); + byte[] value = iterator.value(); + iterator.next(); + return new Map.Entry() { + @Override + public byte[] getKey() { + return key; + } + + @Override + public byte[] getValue() { + return value; + } + + @Override + public byte[] setValue(byte[] value) { + throw new UnsupportedOperationException(); + } + }; + } + + @Override + public void close() throws IOException { + iterator.close(); + } +} diff --git a/framework/src/main/java/org/tron/tool/litefullnode/db/RocksDBImpl.java b/plugins/src/main/java/org/tron/plugins/utils/db/RocksDBImpl.java similarity index 78% rename from framework/src/main/java/org/tron/tool/litefullnode/db/RocksDBImpl.java rename to plugins/src/main/java/org/tron/plugins/utils/db/RocksDBImpl.java index d6dfc55f1bb..50957bbe61b 100644 --- a/framework/src/main/java/org/tron/tool/litefullnode/db/RocksDBImpl.java +++ b/plugins/src/main/java/org/tron/plugins/utils/db/RocksDBImpl.java @@ -1,18 +1,20 @@ -package org.tron.tool.litefullnode.db; +package org.tron.plugins.utils.db; -import com.google.common.collect.Streams; import java.io.IOException; +import lombok.Getter; import org.rocksdb.RocksDBException; import org.rocksdb.RocksIterator; -import org.tron.tool.litefullnode.iterator.DBIterator; -import org.tron.tool.litefullnode.iterator.RockDBIterator; public class RocksDBImpl implements DBInterface { private org.rocksdb.RocksDB rocksDB; - public RocksDBImpl(org.rocksdb.RocksDB rocksDB) { + @Getter + private final String name; + + public RocksDBImpl(org.rocksdb.RocksDB rocksDB, String name) { this.rocksDB = rocksDB; + this.name = name; } @Override @@ -45,7 +47,8 @@ public void delete(byte[] key) { @Override public DBIterator iterator() { - return new RockDBIterator(rocksDB.newIterator()); + return new RockDBIterator(rocksDB.newIterator( + new org.rocksdb.ReadOptions().setFillCache(false))); } @Override diff --git a/plugins/src/main/resources/logback.xml b/plugins/src/main/resources/logback.xml index 5e632f0d424..6c415042e38 100644 --- a/plugins/src/main/resources/logback.xml +++ b/plugins/src/main/resources/logback.xml @@ -16,11 +16,11 @@ - ./logs/archive.log + ./logs/toolkit.log - ./logs/archive-%d{yyyy-MM-dd}.%i.log.gz + ./logs/toolkit-%d{yyyy-MM-dd}.%i.log.gz 500MB 10 @@ -49,6 +49,9 @@ + + + diff --git a/plugins/src/test/java/org/tron/plugins/DbArchiveTest.java b/plugins/src/test/java/org/tron/plugins/DbArchiveTest.java new file mode 100644 index 00000000000..10bed418764 --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbArchiveTest.java @@ -0,0 +1,135 @@ +package org.tron.plugins; + +import static org.iq80.leveldb.impl.Iq80DBFactory.factory; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.Properties; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import picocli.CommandLine; + +@Slf4j +public class DbArchiveTest { + + private static final String OUTPUT_DIRECTORY = "output-directory/database/dbArchive"; + + private static final String ENGINE = "ENGINE"; + private static final String LEVELDB = "LEVELDB"; + private static final String ROCKSDB = "ROCKSDB"; + private static final String ACCOUNT = "account"; + private static final String ACCOUNT_ROCKSDB = "account-rocksdb"; + private static final String MARKET = "market_pair_price_to_order"; + private static final String ENGINE_FILE = "engine.properties"; + + @BeforeClass + public static void init() throws IOException { + File file = new File(OUTPUT_DIRECTORY,ACCOUNT); + factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close(); + writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,LEVELDB); + + file = new File(OUTPUT_DIRECTORY,MARKET); + factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close(); + writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,LEVELDB); + + file = new File(OUTPUT_DIRECTORY,ACCOUNT_ROCKSDB); + factory.open(file,ArchiveManifest.newDefaultLevelDbOptions()).close(); + writeProperty(file.toString() + File.separator + ENGINE_FILE,ENGINE,ROCKSDB); + + } + + @AfterClass + public static void destroy() { + deleteDir(new File(OUTPUT_DIRECTORY)); + } + + @Test + public void testRun() { + String[] args = new String[] {"db", "archive", "-d", OUTPUT_DIRECTORY }; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testHelp() { + String[] args = new String[] {"db", "archive", "-h"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testMaxManifest() { + String[] args = new String[] {"db", "archive", "-d", OUTPUT_DIRECTORY, "-m", "128"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testNotExist() { + String[] args = new String[] {"db", "archive", "-d", + OUTPUT_DIRECTORY + File.separator + UUID.randomUUID()}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(404, cli.execute(args)); + } + + @Test + public void testEmpty() { + File file = new File(OUTPUT_DIRECTORY + File.separator + UUID.randomUUID()); + file.mkdirs(); + file.deleteOnExit(); + String[] args = new String[] {"db", "archive", "-d", file.toString()}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + private static void writeProperty(String filename, String key, String value) throws IOException { + File file = new File(filename); + if (!file.exists()) { + file.createNewFile(); + } + + try (FileInputStream fis = new FileInputStream(file); + OutputStream out = new FileOutputStream(file); + BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out, + StandardCharsets.UTF_8))) { + BufferedReader bf = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8)); + Properties properties = new Properties(); + properties.load(bf); + properties.setProperty(key, value); + properties.store(bw, "Generated by the application. PLEASE DO NOT EDIT! "); + } catch (Exception e) { + logger.warn("{}", e); + } + } + + /** + * delete directory. + */ + private static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + assert children != null; + for (String child : children) { + boolean success = deleteDir(new File(dir, child)); + if (!success) { + logger.warn("can't delete dir:" + dir); + return false; + } + } + } + return dir.delete(); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbConvertTest.java b/plugins/src/test/java/org/tron/plugins/DbConvertTest.java new file mode 100644 index 00000000000..150e47c9f65 --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbConvertTest.java @@ -0,0 +1,46 @@ +package org.tron.plugins; + +import java.io.IOException; +import java.util.UUID; +import org.junit.Assert; +import org.junit.Test; +import picocli.CommandLine; + +public class DbConvertTest extends DbTest { + + @Test + public void testRun() throws IOException { + String[] args = new String[] { "db", "convert", INPUT_DIRECTORY, + temporaryFolder.newFolder().toString() }; + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testRunWithSafe() throws IOException { + String[] args = new String[] { "db", "convert", INPUT_DIRECTORY, + temporaryFolder.newFolder().toString(),"--safe" }; + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testHelp() { + String[] args = new String[] {"db", "convert", "-h"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testNotExist() { + String[] args = new String[] {"db", "convert", UUID.randomUUID().toString(), + UUID.randomUUID().toString()}; + Assert.assertEquals(404, cli.execute(args)); + } + + @Test + public void testEmpty() throws IOException { + String[] args = new String[] {"db", "convert", temporaryFolder.newFolder().toString(), + temporaryFolder.newFolder().toString()}; + Assert.assertEquals(0, cli.execute(args)); + } + +} diff --git a/plugins/src/test/java/org/tron/plugins/DbCopyTest.java b/plugins/src/test/java/org/tron/plugins/DbCopyTest.java new file mode 100644 index 00000000000..9e488a592aa --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbCopyTest.java @@ -0,0 +1,53 @@ +package org.tron.plugins; + +import java.io.IOException; +import java.util.UUID; +import org.junit.Assert; +import org.junit.Test; +import picocli.CommandLine; + +public class DbCopyTest extends DbTest { + + @Test + public void testRun() { + String[] args = new String[] { "db", "cp", INPUT_DIRECTORY, + genarateTmpDir()}; + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testHelp() { + String[] args = new String[] {"db", "cp", "-h"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testNotExist() { + String[] args = new String[] {"db", "cp", UUID.randomUUID().toString(), + UUID.randomUUID().toString()}; + Assert.assertEquals(404, cli.execute(args)); + } + + @Test + public void testEmpty() throws IOException { + String[] args = new String[] {"db", "cp", temporaryFolder.newFolder().toString(), + genarateTmpDir()}; + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testDestIsExist() throws IOException { + String[] args = new String[] {"db", "cp", temporaryFolder.newFile().toString(), + temporaryFolder.newFolder().toString()}; + Assert.assertEquals(402, cli.execute(args)); + } + + @Test + public void testSrcIsFile() throws IOException { + String[] args = new String[] {"db", "cp", temporaryFolder.newFile().toString(), + genarateTmpDir()}; + Assert.assertEquals(403, cli.execute(args)); + } + +} diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbTest.java b/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbTest.java new file mode 100644 index 00000000000..792f93ad197 --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbTest.java @@ -0,0 +1,13 @@ +package org.tron.plugins; + +import java.io.IOException; +import org.junit.Test; + + +public class DbLiteLevelDbTest extends DbLiteTest { + + @Test + public void testToolsWithLevelDB() throws InterruptedException, IOException { + testTools("LEVELDB", 1); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbV2Test.java b/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbV2Test.java new file mode 100644 index 00000000000..ae48e1d66e9 --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbLiteLevelDbV2Test.java @@ -0,0 +1,12 @@ +package org.tron.plugins; + +import java.io.IOException; +import org.junit.Test; + +public class DbLiteLevelDbV2Test extends DbLiteTest { + + @Test + public void testToolsWithLevelDBV2() throws InterruptedException, IOException { + testTools("LEVELDB", 2); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteRocksDbTest.java b/plugins/src/test/java/org/tron/plugins/DbLiteRocksDbTest.java new file mode 100644 index 00000000000..e6910b1103a --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbLiteRocksDbTest.java @@ -0,0 +1,12 @@ +package org.tron.plugins; + +import java.io.IOException; +import org.junit.Test; + +public class DbLiteRocksDbTest extends DbLiteTest { + + @Test + public void testToolsWithRocksDB() throws InterruptedException, IOException { + testTools("ROCKSDB", 1); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbLiteTest.java b/plugins/src/test/java/org/tron/plugins/DbLiteTest.java new file mode 100644 index 00000000000..b4c66c9820f --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbLiteTest.java @@ -0,0 +1,175 @@ +package org.tron.plugins; + +import static org.tron.common.utils.PublicMethod.getRandomPrivateKey; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.concurrent.TimeUnit; +import lombok.extern.slf4j.Slf4j; +import org.junit.After; +import org.junit.ClassRule; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import org.tron.api.WalletGrpc; +import org.tron.common.application.Application; +import org.tron.common.application.ApplicationFactory; +import org.tron.common.application.TronApplicationContext; +import org.tron.common.config.DbBackupConfig; +import org.tron.common.crypto.ECKey; +import org.tron.common.utils.FileUtil; +import org.tron.common.utils.PublicMethod; +import org.tron.common.utils.Utils; +import org.tron.core.config.DefaultConfig; +import org.tron.core.config.args.Args; +import picocli.CommandLine; + +@Slf4j +public class DbLiteTest { + + private TronApplicationContext context; + private WalletGrpc.WalletBlockingStub blockingStubFull = null; + private ManagedChannel channelFull; + private Application appTest; + private String databaseDir; + + @Rule + public final TemporaryFolder folder = new TemporaryFolder(); + + private String dbPath; + CommandLine cli = new CommandLine(new DbLite()); + + /** + * init logic. + */ + public void startApp() { + context = new TronApplicationContext(DefaultConfig.class); + appTest = ApplicationFactory.create(context); + appTest.startup(); + + String fullNode = String.format("%s:%d", "127.0.0.1", + Args.getInstance().getRpcPort()); + channelFull = ManagedChannelBuilder.forTarget(fullNode) + .usePlaintext() + .build(); + blockingStubFull = WalletGrpc.newBlockingStub(channelFull); + } + + /** + * shutdown the fullNode. + */ + public void shutdown() throws InterruptedException { + if (channelFull != null) { + channelFull.shutdown().awaitTermination(5, TimeUnit.SECONDS); + } + context.close(); + } + + public void init() throws IOException { + dbPath = folder.newFolder().toString(); + Args.setParam(new String[]{"-d", dbPath, "-w", "--p2p-disable", "true"}, + "config-localtest.conf"); + // allow account root + Args.getInstance().setAllowAccountStateRoot(1); + Args.getInstance().setRpcPort(PublicMethod.chooseRandomPort()); + Args.getInstance().setRpcEnable(true); + databaseDir = Args.getInstance().getStorage().getDbDirectory(); + // init dbBackupConfig to avoid NPE + Args.getInstance().dbBackupConfig = DbBackupConfig.getInstance(); + } + + @After + public void clear() { + Args.clearParam(); + } + + void testTools(String dbType, int checkpointVersion) + throws InterruptedException, IOException { + logger.info("dbType {}, checkpointVersion {}", dbType, checkpointVersion); + dbPath = String.format("%s_%s_%d", dbPath, dbType, System.currentTimeMillis()); + init(); + final String[] argsForSnapshot = + new String[]{"-o", "split", "-t", "snapshot", "--fn-data-path", + dbPath + File.separator + databaseDir, "--dataset-path", + dbPath}; + final String[] argsForHistory = + new String[]{"-o", "split", "-t", "history", "--fn-data-path", + dbPath + File.separator + databaseDir, "--dataset-path", + dbPath}; + final String[] argsForMerge = + new String[]{"-o", "merge", "--fn-data-path", dbPath + File.separator + databaseDir, + "--dataset-path", dbPath + File.separator + "history"}; + Args.getInstance().getStorage().setDbEngine(dbType); + Args.getInstance().getStorage().setCheckpointVersion(checkpointVersion); + DbLite.setRecentBlks(3); + // start fullNode + startApp(); + // produce transactions for 18 seconds + generateSomeTransactions(18); + // stop the node + shutdown(); + // delete tran-cache + FileUtil.deleteDir(Paths.get(dbPath, databaseDir, "trans-cache").toFile()); + // generate snapshot + cli.execute(argsForSnapshot); + // start fullNode + startApp(); + // produce transactions + generateSomeTransactions(checkpointVersion == 1 ? 6 : 18); + // stop the node + shutdown(); + // generate history + cli.execute(argsForHistory); + // backup original database to database_bak + File database = new File(Paths.get(dbPath, databaseDir).toString()); + if (!database.renameTo(new File(Paths.get(dbPath, databaseDir + "_bak").toString()))) { + throw new RuntimeException( + String.format("rename %s to %s failed", database.getPath(), + Paths.get(dbPath, databaseDir))); + } + // change snapshot to the new database + File snapshot = new File(Paths.get(dbPath, "snapshot").toString()); + if (!snapshot.renameTo(new File(Paths.get(dbPath, databaseDir).toString()))) { + throw new RuntimeException( + String.format("rename snapshot to %s failed", + Paths.get(dbPath, databaseDir))); + } + // start and validate the snapshot + startApp(); + generateSomeTransactions(checkpointVersion == 1 ? 18 : 6); + // stop the node + shutdown(); + // merge history + cli.execute(argsForMerge); + // start and validate + startApp(); + generateSomeTransactions(6); + shutdown(); + DbLite.reSetRecentBlks(); + } + + private void generateSomeTransactions(int during) { + during *= 1000; // ms + int runTime = 0; + int sleepOnce = 100; + while (true) { + ECKey ecKey2 = new ECKey(Utils.getRandom()); + byte[] address = ecKey2.getAddress(); + + String sunPri = getRandomPrivateKey(); + byte[] sunAddress = PublicMethod.getFinalAddress(sunPri); + PublicMethod.sendcoin(address, 1L, + sunAddress, sunPri, blockingStubFull); + try { + Thread.sleep(sleepOnce); + } catch (InterruptedException e) { + e.printStackTrace(); + } + if ((runTime += sleepOnce) > during) { + return; + } + } + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbMoveTest.java b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java new file mode 100644 index 00000000000..c1bc6b470fc --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbMoveTest.java @@ -0,0 +1,129 @@ +package org.tron.plugins; + +import static org.iq80.leveldb.impl.Iq80DBFactory.factory; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.nio.file.Paths; +import java.util.UUID; +import lombok.extern.slf4j.Slf4j; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.tron.plugins.utils.FileUtils; +import picocli.CommandLine; + +@Slf4j +public class DbMoveTest { + + private static final String OUTPUT_DIRECTORY = "output-directory-toolkit"; + private static final String OUTPUT_DIRECTORY_DATABASE = + Paths.get(OUTPUT_DIRECTORY,"ori","database").toString(); + private static final String ENGINE = "ENGINE"; + private static final String LEVELDB = "LEVELDB"; + private static final String ACCOUNT = "account"; + private static final String TRANS = "trans"; + private static final String MARKET = "market_pair_price_to_order"; + private static final String ENGINE_FILE = "engine.properties"; + + + @BeforeClass + public static void init() throws IOException { + File file = new File(OUTPUT_DIRECTORY_DATABASE, ACCOUNT); + factory.open(file, ArchiveManifest.newDefaultLevelDbOptions()).close(); + FileUtils.writeProperty(file + File.separator + ENGINE_FILE, ENGINE, LEVELDB); + + file = new File(OUTPUT_DIRECTORY_DATABASE, MARKET); + factory.open(file, ArchiveManifest.newDefaultLevelDbOptions()).close(); + FileUtils.writeProperty(file + File.separator + ENGINE_FILE, ENGINE, LEVELDB); + + file = new File(OUTPUT_DIRECTORY_DATABASE, TRANS); + factory.open(file, ArchiveManifest.newDefaultLevelDbOptions()).close(); + FileUtils.writeProperty(file + File.separator + ENGINE_FILE, ENGINE, LEVELDB); + + } + + @AfterClass + public static void destroy() { + deleteDir(new File(OUTPUT_DIRECTORY)); + } + + /** + * delete directory. + */ + private static boolean deleteDir(File dir) { + if (dir.isDirectory()) { + String[] children = dir.list(); + assert children != null; + for (String child : children) { + boolean success = deleteDir(new File(dir, child)); + if (!success) { + logger.warn("can't delete dir:" + dir); + return false; + } + } + } + return dir.delete(); + } + + private static String getConfig(String config) { + URL path = DbMoveTest.class.getClassLoader().getResource(config); + return path == null ? null : path.getPath(); + } + + @Test + public void testMv() { + String[] args = new String[] {"db", "mv", "-d", + Paths.get(OUTPUT_DIRECTORY,"ori").toString(), "-c", + getConfig("config.conf")}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + Assert.assertEquals(2, cli.execute(args)); + } + + @Test + public void testDuplicate() { + String[] args = new String[] {"db", "mv", "-d", + Paths.get(OUTPUT_DIRECTORY,"ori").toString(), "-c", + getConfig("config-duplicate.conf")}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(2, cli.execute(args)); + } + + @Test + public void testHelp() { + String[] args = new String[] {"db", "mv", "-h"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testDicNotExist() { + String[] args = new String[] {"db", "mv", "-d", "dicNotExist"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(2, cli.execute(args)); + } + + @Test + public void testConfNotExist() { + String[] args = new String[] {"db", "mv", "-d", + Paths.get(OUTPUT_DIRECTORY,"ori").toString(), "-c", + "config.conf"}; + CommandLine cli = new CommandLine(new Toolkit()); + Assert.assertEquals(2, cli.execute(args)); + } + + @Test + public void testEmpty() { + File file = new File(OUTPUT_DIRECTORY_DATABASE + File.separator + UUID.randomUUID()); + file.mkdirs(); + file.deleteOnExit(); + String[] args = new String[] {"db", "mv", "-d", file.toString(), "-c", + getConfig("config.conf")}; + CommandLine cli = new CommandLine(new Toolkit()); + + Assert.assertEquals(2, cli.execute(args)); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbRootTest.java b/plugins/src/test/java/org/tron/plugins/DbRootTest.java new file mode 100644 index 00000000000..b86688f77d5 --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbRootTest.java @@ -0,0 +1,82 @@ +package org.tron.plugins; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.rocksdb.RocksDBException; +import org.tron.plugins.utils.DBUtils; +import org.tron.plugins.utils.db.DBInterface; +import org.tron.plugins.utils.db.DbTool; +import org.tron.plugins.utils.db.LevelDBImpl; +import picocli.CommandLine; + +@Slf4j +public class DbRootTest { + + @Rule + public final TemporaryFolder folder = new TemporaryFolder(); + + CommandLine cli = new CommandLine(new Toolkit()); + + private static final String NORMAL_DB = "normal"; + private static final String EMPTY_DB = "empty"; + private static final String ERROR_DB = "error"; + + @Test + public void testRoot() throws IOException, RocksDBException { + + File file = folder.newFolder(); + + File database = Paths.get(file.getPath(),"database").toFile(); + Assert.assertTrue(database.mkdirs()); + + + try (DBInterface normal = DbTool.getDB(database.toString(), NORMAL_DB, DbTool.DbType.LevelDB); + DBInterface empty = DbTool.getDB(database.toString(), EMPTY_DB, DbTool.DbType.RocksDB)) { + for (int i = 0; i < 10; i++) { + normal.put(("" + i).getBytes(), (NORMAL_DB + "-" + i).getBytes()); + } + } + + String[] args = new String[] {"db", "root", database.toString(), + "--db", NORMAL_DB, "--db", EMPTY_DB}; + Assert.assertEquals(0, cli.execute(args)); + args = new String[] {"db", "root", database.toString(), + "--db", NORMAL_DB}; + Assert.assertEquals(0, cli.execute(args)); + args = new String[] {"db", "root", database.toString(), + "--db", EMPTY_DB}; + Assert.assertEquals(0, cli.execute(args)); + + try (DBInterface errorDb = new LevelDBImpl( + DBUtils.newLevelDb(Paths.get(database.toString(), ERROR_DB)), ERROR_DB)) { + for (int i = 0; i < 10; i++) { + errorDb.put(("" + i).getBytes(), (ERROR_DB + "-" + i).getBytes()); + } + args = new String[] {"db", "root", database.toString(), "--db", ERROR_DB}; + Assert.assertEquals(1, cli.execute(args)); + } + + } + + @Test + public void testHelp() { + String[] args = new String[] {"db", "root", "-h"}; + Assert.assertEquals(0, cli.execute(args)); + } + + @Test + public void testEmpty() throws IOException { + File file = folder.newFolder(); + File database = Paths.get(file.getPath(),"database").toFile(); + String[] args = new String[] {"db", "root", database.toString()}; + Assert.assertEquals(404, cli.execute(args)); + Assert.assertTrue(database.mkdirs()); + Assert.assertEquals(404, cli.execute(args)); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/DbTest.java b/plugins/src/test/java/org/tron/plugins/DbTest.java new file mode 100644 index 00000000000..8605fa18d50 --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/DbTest.java @@ -0,0 +1,99 @@ +package org.tron.plugins; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Paths; +import java.util.UUID; +import org.iq80.leveldb.DB; +import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import org.tron.plugins.utils.ByteArray; +import org.tron.plugins.utils.DBUtils; +import org.tron.plugins.utils.MarketUtils; +import picocli.CommandLine; + +public class DbTest { + + String INPUT_DIRECTORY; + private static final String ACCOUNT = "account"; + private static final String MARKET = DBUtils.MARKET_PAIR_PRICE_TO_ORDER; + CommandLine cli = new CommandLine(new Toolkit()); + String tmpDir = System.getProperty("java.io.tmpdir"); + + @Rule + public final TemporaryFolder temporaryFolder = new TemporaryFolder(); + + + @Before + public void init() throws IOException { + INPUT_DIRECTORY = temporaryFolder.newFolder().toString(); + initDB(new File(INPUT_DIRECTORY, ACCOUNT)); + initDB(new File(INPUT_DIRECTORY, MARKET)); + initDB(new File(INPUT_DIRECTORY, DBUtils.CHECKPOINT_DB_V2)); + } + + private static void initDB(File file) throws IOException { + if (DBUtils.CHECKPOINT_DB_V2.equalsIgnoreCase(file.getName())) { + File dbFile = new File(file, DBUtils.CHECKPOINT_DB_V2); + if (dbFile.mkdirs()) { + for (int i = 0; i < 3; i++) { + try (DB db = DBUtils.newLevelDb(Paths.get(dbFile.getPath(), + System.currentTimeMillis() + ""))) { + for (int j = 0; j < 100; j++) { + byte[] bytes = UUID.randomUUID().toString().getBytes(); + db.put(bytes, bytes); + } + } + } + } + return; + } + try (DB db = DBUtils.newLevelDb(file.toPath())) { + if (MARKET.equalsIgnoreCase(file.getName())) { + byte[] sellTokenID1 = ByteArray.fromString("100"); + byte[] buyTokenID1 = ByteArray.fromString("200"); + byte[] pairPriceKey1 = MarketUtils.createPairPriceKey( + sellTokenID1, + buyTokenID1, + 1000L, + 2001L + ); + byte[] pairPriceKey2 = MarketUtils.createPairPriceKey( + sellTokenID1, + buyTokenID1, + 1000L, + 2002L + ); + byte[] pairPriceKey3 = MarketUtils.createPairPriceKey( + sellTokenID1, + buyTokenID1, + 1000L, + 2003L + ); + + + //Use out-of-order insertion,key in store should be 1,2,3 + db.put(pairPriceKey1, "1".getBytes(StandardCharsets.UTF_8)); + db.put(pairPriceKey2, "2".getBytes(StandardCharsets.UTF_8)); + db.put(pairPriceKey3, "3".getBytes(StandardCharsets.UTF_8)); + } else { + for (int i = 0; i < 100; i++) { + byte[] bytes = UUID.randomUUID().toString().getBytes(); + db.put(bytes, bytes); + } + } + } + } + + /** + * Generate a not-exist temporary directory path. + * @return temporary path + */ + public String genarateTmpDir() { + File dir = Paths.get(tmpDir, UUID.randomUUID().toString()).toFile(); + dir.deleteOnExit(); + return dir.getPath(); + } +} diff --git a/plugins/src/test/java/org/tron/plugins/utils/ByteArrayTest.java b/plugins/src/test/java/org/tron/plugins/utils/ByteArrayTest.java new file mode 100644 index 00000000000..300c983db3a --- /dev/null +++ b/plugins/src/test/java/org/tron/plugins/utils/ByteArrayTest.java @@ -0,0 +1,44 @@ +package org.tron.plugins.utils; + +import lombok.extern.slf4j.Slf4j; +import org.junit.Assert; +import org.junit.Test; + +@Slf4j +public class ByteArrayTest { + + @Test + public void testToStrToInt() { + String test = "abc"; + byte[] testBytes = test.getBytes(); + Assert.assertEquals(test, ByteArray.toStr(testBytes)); + + int i = 5; + Assert.assertEquals(ByteArray.toInt(ByteArray.fromInt(i)), 5); + } + + @Test + public void testFromHexString() { + Assert.assertArrayEquals(ByteArray.EMPTY_BYTE_ARRAY, ByteArray.fromHexString(null)); + + Assert.assertArrayEquals(ByteArray.fromHexString("12"), ByteArray.fromHexString("0x12")); + + Assert.assertArrayEquals(ByteArray.fromHexString("0x2"), ByteArray.fromHexString("0x02")); + } + + @Test + public void testCompareUnsigned() { + byte[] a = new byte[] {1, 2}; + Assert.assertEquals(0, ByteArray.compareUnsigned(a, a)); + Assert.assertEquals(-1, ByteArray.compareUnsigned(null, a)); + Assert.assertEquals(1, ByteArray.compareUnsigned(a, null)); + + byte[] b = new byte[] {1, 3}; + Assert.assertEquals(-1, ByteArray.compareUnsigned(a, b)); + Assert.assertEquals(1, ByteArray.compareUnsigned(b, a)); + + byte[] c = new byte[] {1, 2, 3}; + Assert.assertEquals(-1, ByteArray.compareUnsigned(a, c)); + Assert.assertEquals(1, ByteArray.compareUnsigned(c, a)); + } +} diff --git a/plugins/src/test/resources/config-duplicate.conf b/plugins/src/test/resources/config-duplicate.conf new file mode 100644 index 00000000000..f2eb7fbf357 --- /dev/null +++ b/plugins/src/test/resources/config-duplicate.conf @@ -0,0 +1,21 @@ + +storage { + # Directory for storing persistent data + db.engine = "LEVELDB", + db.sync = false, + db.directory = "database", + index.directory = "index", + transHistory.switch = "on", + properties = [ + { + name = "trans", + path = "output-directory-toolkit/dest", + }, + { + name = "trans", + path = "output-directory-toolkit/dest2", + }, + ] +} + + diff --git a/plugins/src/test/resources/config.conf b/plugins/src/test/resources/config.conf new file mode 100644 index 00000000000..2bfca7dbdd7 --- /dev/null +++ b/plugins/src/test/resources/config.conf @@ -0,0 +1,21 @@ + +storage { + # Directory for storing persistent data + db.engine = "LEVELDB", + db.sync = false, + db.directory = "database", + index.directory = "index", + transHistory.switch = "on", + properties = [ + { + name = "account", + path = "output-directory-toolkit/dest", + }, + { + name = "market_pair_price_to_order", + path = "output-directory-toolkit/dest", + }, + ] +} + + diff --git a/protocol/build.gradle b/protocol/build.gradle index b818008515f..535fac43a65 100644 --- a/protocol/build.gradle +++ b/protocol/build.gradle @@ -1,18 +1,23 @@ apply plugin: 'com.google.protobuf' +def protobufVersion = '3.25.5' +def grpcVersion = '1.60.0' + dependencies { - compile group: 'com.google.protobuf', name: 'protobuf-java', version: '3.4.0' - compile group: 'com.google.protobuf', name: 'protobuf-java-util', version: '3.4.0' - compile group: 'net.jcip', name: 'jcip-annotations', version: '1.0' + api group: 'com.google.protobuf', name: 'protobuf-java', version: protobufVersion + api group: 'com.google.protobuf', name: 'protobuf-java-util', version: protobufVersion + api group: 'net.jcip', name: 'jcip-annotations', version: '1.0' // checkstyleConfig "com.puppycrawl.tools:checkstyle:${versions.checkstyle}" // google grpc - compile group: 'io.grpc', name: 'grpc-netty', version: '1.14.0' - compile group: 'io.grpc', name: 'grpc-protobuf', version: '1.14.0' - compile group: 'io.grpc', name: 'grpc-stub', version: '1.14.0' + api group: 'io.grpc', name: 'grpc-netty', version: grpcVersion + api group: 'io.grpc', name: 'grpc-protobuf', version: grpcVersion + api group: 'io.grpc', name: 'grpc-stub', version: grpcVersion + api group: 'io.grpc', name: 'grpc-services', version: grpcVersion + // end google grpc - compile group: 'com.google.api.grpc', name: 'googleapis-common-protos', version: '0.0.3' + api group: 'com.google.api.grpc', name: 'proto-google-common-protos', version: '2.15.0' } tasks.matching { it instanceof Test }.all { @@ -35,12 +40,12 @@ sourceSets { protobuf { generatedFilesBaseDir = "$projectDir/src/" protoc { - artifact = "com.google.protobuf:protoc:3.5.1-1" + artifact = "com.google.protobuf:protoc:${protobufVersion}" } plugins { grpc { - artifact = 'io.grpc:protoc-gen-grpc-java:1.9.0' + artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}" } } generateProtoTasks { @@ -61,3 +66,4 @@ clean.doFirst { delete "src/main/java" } +processResources.dependsOn(generateProto) // explicit_dependency diff --git a/protocol/gradle/wrapper/gradle-wrapper.jar b/protocol/gradle/wrapper/gradle-wrapper.jar deleted file mode 100644 index 28861d273a5..00000000000 Binary files a/protocol/gradle/wrapper/gradle-wrapper.jar and /dev/null differ diff --git a/protocol/gradle/wrapper/gradle-wrapper.properties b/protocol/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index 1b0ff046d00..00000000000 --- a/protocol/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,6 +0,0 @@ -#Thu Aug 01 15:17:43 CST 2019 -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-4.10-all.zip diff --git a/protocol/src/main/protos/.travis.yml b/protocol/src/main/protos/.travis.yml deleted file mode 100644 index 34fa71b3d15..00000000000 --- a/protocol/src/main/protos/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -language: ruby - -cache: - directories: - - $HOME/protobuf - -sudo: false - -before_install: - - bash install-protobuf.sh - - bash install-googleapis.sh - -# check what has been installed by listing contents of protobuf folder -before_script: - - ls -R $HOME/protobuf - -# let's use protobuf -script: - - $HOME/protobuf/bin/protoc --java_out=./ ./core/*.proto ./api/*.proto - - $HOME/protobuf/bin/protoc -I. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=./ ./core/*.proto - - $HOME/protobuf/bin/protoc -I. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --go_out=./ ./api/*.proto - - $HOME/protobuf/bin/protoc -I. -I$GOPATH/src/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis --grpc-gateway_out=logtostderr=true:./ ./api/*.proto - - - ls -l \ No newline at end of file diff --git a/protocol/src/main/protos/Chinese version of TRON Protocol document.md b/protocol/src/main/protos/Chinese version of TRON Protocol document.md index 283bd5fb8af..f393447e42e 100644 --- a/protocol/src/main/protos/Chinese version of TRON Protocol document.md +++ b/protocol/src/main/protos/Chinese version of TRON Protocol document.md @@ -442,7 +442,7 @@ `TOO_MANY_PEERS` `DUPLICATE_PEER` `INCOMPATIBLE_PROTOCOL` - `NULL_IDENTITY` + `RANDOM_ELIMINATION` `PEER_QUITING` `UNEXPECTED_IDENTITY` `LOCAL_IDENTITY` @@ -459,7 +459,7 @@ TOO_MANY_PEERS = 4; DUPLICATE_PEER = 5; INCOMPATIBLE_PROTOCOL = 6; - NULL_IDENTITY = 7; + RANDOM_ELIMINATION = 7; PEER_QUITING = 8; UNEXPECTED_IDENTITY = 9; LOCAL_IDENTITY = 10; diff --git a/protocol/src/main/protos/English version of TRON Protocol document.md b/protocol/src/main/protos/English version of TRON Protocol document.md index 87a61acd119..7d23f5c1f49 100644 --- a/protocol/src/main/protos/English version of TRON Protocol document.md +++ b/protocol/src/main/protos/English version of TRON Protocol document.md @@ -456,7 +456,7 @@ Input, transaction and head block all require signature. `TOO_MANY_PEERS` `DUPLICATE_PEER` `INCOMPATIBLE_PROTOCOL` - `NULL_IDENTITY` + `RANDOM_ELIMINATION` `PEER_QUITING` `UNEXPECTED_IDENTITY` `LOCAL_IDENTITY` @@ -473,7 +473,7 @@ Input, transaction and head block all require signature. TOO_MANY_PEERS = 4; DUPLICATE_PEER = 5; INCOMPATIBLE_PROTOCOL = 6; - NULL_IDENTITY = 7; + RANDOM_ELIMINATION = 7; PEER_QUITING = 8; UNEXPECTED_IDENTITY = 9; LOCAL_IDENTITY = 10; diff --git a/protocol/src/main/protos/README.md b/protocol/src/main/protos/README.md index 6a28119119a..0eaf7b30a80 100644 --- a/protocol/src/main/protos/README.md +++ b/protocol/src/main/protos/README.md @@ -6,6 +6,3 @@ java-tron, wallet-cli and grpc-gateway git subtree pull --prefix src/main/protos/ protocol master - -## Run the included *.sh files to initialize the dependencies - diff --git a/protocol/src/main/protos/api/api.proto b/protocol/src/main/protos/api/api.proto index 5f697026c10..2505fa48d6f 100644 --- a/protocol/src/main/protos/api/api.proto +++ b/protocol/src/main/protos/api/api.proto @@ -224,6 +224,10 @@ service Wallet { //Use this function instead of FreezeBalance. rpc FreezeBalance2 (FreezeBalanceContract) returns (TransactionExtention) { } + //Use this function when FreezeBalanceV2. + rpc FreezeBalanceV2 (FreezeBalanceV2Contract) returns (TransactionExtention) { + } + //Please use UnfreezeBalance2 instead of this function. rpc UnfreezeBalance (UnfreezeBalanceContract) returns (Transaction) { option (google.api.http) = { @@ -237,6 +241,10 @@ service Wallet { //Use this function instead of UnfreezeBalance. rpc UnfreezeBalance2 (UnfreezeBalanceContract) returns (TransactionExtention) { } + //Use this function when UnfreezeBalanceV2. + rpc UnfreezeBalanceV2 (UnfreezeBalanceV2Contract) returns (TransactionExtention) { + } + //Please use UnfreezeAsset2 instead of this function. rpc UnfreezeAsset (UnfreezeAssetContract) returns (Transaction) { option (google.api.http) = { @@ -263,6 +271,19 @@ service Wallet { //Use this function instead of WithdrawBalance. rpc WithdrawBalance2 (WithdrawBalanceContract) returns (TransactionExtention) { } + + rpc WithdrawExpireUnfreeze (WithdrawExpireUnfreezeContract) returns (TransactionExtention) { + } + + rpc DelegateResource (DelegateResourceContract) returns (TransactionExtention) { + } + + rpc UnDelegateResource (UnDelegateResourceContract) returns (TransactionExtention) { + } + + rpc CancelAllUnfreezeV2 (CancelAllUnfreezeV2Contract) returns (TransactionExtention) { + } + //Please use UpdateAsset2 instead of this function. rpc UpdateAsset (UpdateAssetContract) returns (Transaction) { option (google.api.http) = { @@ -462,6 +483,9 @@ service Wallet { rpc TriggerConstantContract (TriggerSmartContract) returns (TransactionExtention) { } + rpc EstimateEnergy (TriggerSmartContract) returns (EstimateEnergyMessage) { + } + rpc ClearContractABI (ClearABIContract) returns (TransactionExtention) { } @@ -479,9 +503,26 @@ service Wallet { rpc GetDelegatedResource (DelegatedResourceMessage) returns (DelegatedResourceList) { }; + rpc GetDelegatedResourceV2 (DelegatedResourceMessage) returns (DelegatedResourceList) { + }; + rpc GetDelegatedResourceAccountIndex (BytesMessage) returns (DelegatedResourceAccountIndex) { }; + rpc GetDelegatedResourceAccountIndexV2 (BytesMessage) returns (DelegatedResourceAccountIndex) { + }; + + rpc GetCanDelegatedMaxSize (CanDelegatedMaxSizeRequestMessage) returns (CanDelegatedMaxSizeResponseMessage) { + }; + + rpc GetAvailableUnfreezeCount (GetAvailableUnfreezeCountRequestMessage) + returns (GetAvailableUnfreezeCountResponseMessage) { + }; + + rpc GetCanWithdrawUnfreezeAmount (CanWithdrawUnfreezeAmountRequestMessage) + returns (CanWithdrawUnfreezeAmountResponseMessage) { + } + rpc ListProposals (EmptyMessage) returns (ProposalList) { option (google.api.http) = { post: "/wallet/listproposals" @@ -586,68 +627,6 @@ service Wallet { } }; } - //Warning: do not invoke this interface provided by others. - //Please use GetTransactionSign2 instead of this function. - rpc GetTransactionSign (TransactionSign) returns (Transaction) { - option (google.api.http) = { - post: "/wallet/gettransactionsign" - body: "*" - additional_bindings { - get: "/wallet/gettransactionsign" - } - }; - }; - //Warning: do not invoke this interface provided by others. - //Use this function instead of GetTransactionSign. - rpc GetTransactionSign2 (TransactionSign) returns (TransactionExtention) { - }; - //Warning: do not invoke this interface provided by others. - rpc CreateAddress (BytesMessage) returns (BytesMessage) { - option (google.api.http) = { - post: "/wallet/createaddress" - body: "*" - additional_bindings { - get: "/wallet/createaddress" - } - }; - }; - //Warning: do not invoke this interface provided by others. - rpc EasyTransferAsset (EasyTransferAssetMessage) returns (EasyTransferResponse) { - }; - //Warning: do not invoke this interface provided by others. - rpc EasyTransferAssetByPrivate (EasyTransferAssetByPrivateMessage) returns (EasyTransferResponse) { - }; - //Warning: do not invoke this interface provided by others. - rpc EasyTransfer (EasyTransferMessage) returns (EasyTransferResponse) { - option (google.api.http) = { - post: "/wallet/easytransfer" - body: "*" - additional_bindings { - get: "/wallet/easytransfer" - } - }; - }; - //Warning: do not invoke this interface provided by others. - rpc EasyTransferByPrivate (EasyTransferByPrivateMessage) returns (EasyTransferResponse) { - option (google.api.http) = { - post: "/wallet/easytransferbyprivate" - body: "*" - additional_bindings { - get: "/wallet/easytransferbyprivate" - } - }; - }; - //Warning: do not invoke this interface provided by others. - rpc GenerateAddress (EmptyMessage) returns (AddressPrKeyPairMessage) { - - option (google.api.http) = { - post: "/wallet/generateaddress" - body: "*" - additional_bindings { - get: "/wallet/generateaddress" - } - }; - } rpc GetTransactionInfoById (BytesMessage) returns (TransactionInfo) { option (google.api.http) = { @@ -669,10 +648,6 @@ service Wallet { }; } - rpc AddSign (TransactionSign) returns (TransactionExtention) { - - } - rpc GetTransactionSignWeight (Transaction) returns (TransactionSignWeight) { } @@ -789,6 +764,18 @@ service Wallet { rpc GetPendingSize (EmptyMessage) returns (NumberMessage) { } + + rpc GetBlock (BlockReq) returns (BlockExtention) { + } + + rpc GetBandwidthPrices (EmptyMessage) returns (PricesResponseMessage) { + } + + rpc GetEnergyPrices (EmptyMessage) returns (PricesResponseMessage) { + } + + rpc GetMemoFee (EmptyMessage) returns (PricesResponseMessage) { + } }; service WalletSolidity { @@ -880,9 +867,26 @@ service WalletSolidity { rpc GetDelegatedResource (DelegatedResourceMessage) returns (DelegatedResourceList) { }; + rpc GetDelegatedResourceV2 (DelegatedResourceMessage) returns (DelegatedResourceList) { + }; + rpc GetDelegatedResourceAccountIndex (BytesMessage) returns (DelegatedResourceAccountIndex) { }; + rpc GetDelegatedResourceAccountIndexV2 (BytesMessage) returns (DelegatedResourceAccountIndex) { + }; + + rpc GetCanDelegatedMaxSize (CanDelegatedMaxSizeRequestMessage) returns (CanDelegatedMaxSizeResponseMessage) { + }; + + rpc GetAvailableUnfreezeCount (GetAvailableUnfreezeCountRequestMessage) + returns (GetAvailableUnfreezeCountResponseMessage) { + }; + + rpc GetCanWithdrawUnfreezeAmount (CanWithdrawUnfreezeAmountRequestMessage) + returns (CanWithdrawUnfreezeAmountResponseMessage) { + } + rpc GetExchangeById (BytesMessage) returns (Exchange) { }; @@ -910,17 +914,6 @@ service WalletSolidity { }; } - //Warning: do not invoke this interface provided by others. - rpc GenerateAddress (EmptyMessage) returns (AddressPrKeyPairMessage) { - option (google.api.http) = { - post: "/walletsolidity/generateaddress" - body: "*" - additional_bindings { - get: "/walletsolidity/generateaddress" - } - }; - } - rpc GetMerkleTreeVoucherInfo (OutputPointInfo) returns (IncrementalMerkleVoucherInfo) { } @@ -954,6 +947,9 @@ service WalletSolidity { rpc TriggerConstantContract (TriggerSmartContract) returns (TransactionExtention) { } + rpc EstimateEnergy (TriggerSmartContract) returns (EstimateEnergyMessage) { + } + rpc GetTransactionInfoByBlockNum (NumberMessage) returns (TransactionInfoList) { } @@ -974,6 +970,13 @@ service WalletSolidity { rpc GetBurnTrx (EmptyMessage) returns (NumberMessage) { } + rpc GetBlock (BlockReq) returns (BlockExtention) { + } + rpc GetBandwidthPrices (EmptyMessage) returns (PricesResponseMessage) { + } + + rpc GetEnergyPrices (EmptyMessage) returns (PricesResponseMessage) { + } }; service WalletExtension { @@ -1048,6 +1051,8 @@ message Return { SERVER_BUSY = 9; NO_CONNECTION = 10; NOT_ENOUGH_EFFECTIVE_CONNECTION = 11; + BLOCK_UNSOLIDIFIED = 12; + OTHER_ERROR = 20; } @@ -1095,6 +1100,33 @@ message DelegatedResourceList { repeated DelegatedResource delegatedResource = 1; } +message GetAvailableUnfreezeCountRequestMessage { + bytes owner_address = 1; +} +message GetAvailableUnfreezeCountResponseMessage { + int64 count = 1; +} + +message CanDelegatedMaxSizeRequestMessage { + int32 type = 1; + bytes owner_address = 2; +} +message CanDelegatedMaxSizeResponseMessage { + int64 max_size = 1; +} + +message CanWithdrawUnfreezeAmountRequestMessage { + bytes owner_address = 1; + int64 timestamp = 2; +} +message CanWithdrawUnfreezeAmountResponseMessage { + int64 amount = 1; +} + +message PricesResponseMessage { + string prices = 1; +} + // Gossip node list message NodeList { repeated Node nodes = 1; @@ -1123,6 +1155,10 @@ message TimeMessage { int64 beginInMilliseconds = 1; int64 endInMilliseconds = 2; } +message BlockReq { + string id_or_num = 1; + bool detail = 2; +} message BlockLimit { int64 startNum = 1; int64 endNum = 2; @@ -1179,43 +1215,6 @@ message PaginatedMessage { int64 limit = 2; } -message EasyTransferMessage { - bytes passPhrase = 1; - bytes toAddress = 2; - int64 amount = 3; -} - -message EasyTransferAssetMessage { - bytes passPhrase = 1; - bytes toAddress = 2; - string assetId = 3; - int64 amount = 4; -} - -message EasyTransferByPrivateMessage { - bytes privateKey = 1; - bytes toAddress = 2; - int64 amount = 3; -} - -message EasyTransferAssetByPrivateMessage { - bytes privateKey = 1; - bytes toAddress = 2; - string assetId = 3; - int64 amount = 4; -} - -message EasyTransferResponse { - Transaction transaction = 1; - Return result = 2; - bytes txid = 3; //transaction id = sha256(transaction.rowdata) -} - -message AddressPrKeyPairMessage { - string address = 1; - string privateKey = 2; -} - message TransactionExtention { Transaction transaction = 1; bytes txid = 2; //transaction id = sha256(transaction.rowdata) @@ -1224,6 +1223,12 @@ message TransactionExtention { int64 energy_used = 5; repeated TransactionInfo.Log logs = 6; repeated InternalTransaction internal_transactions = 7; + int64 energy_penalty = 8; +} + +message EstimateEnergyMessage { + Return result = 1; + int64 energy_required = 2; } message BlockExtention { diff --git a/protocol/src/main/protos/core/Discover.proto b/protocol/src/main/protos/core/Discover.proto index 4cc0d83b02a..fadb819e92d 100644 --- a/protocol/src/main/protos/core/Discover.proto +++ b/protocol/src/main/protos/core/Discover.proto @@ -11,6 +11,7 @@ message Endpoint { bytes address = 1; int32 port = 2; bytes nodeId = 3; + bytes addressIpv6 = 4; } message PingMessage { diff --git a/protocol/src/main/protos/core/Tron.proto b/protocol/src/main/protos/core/Tron.proto index a4409923086..2ffefbf9f3e 100644 --- a/protocol/src/main/protos/core/Tron.proto +++ b/protocol/src/main/protos/core/Tron.proto @@ -2,6 +2,7 @@ syntax = "proto3"; import "google/protobuf/any.proto"; import "core/Discover.proto"; +import "core/contract/common.proto"; package protocol; @@ -161,6 +162,8 @@ message Account { int64 old_tron_power = 46; Frozen tron_power = 47; + bool asset_optimized = 60; + // this account create time int64 create_time = 0x09; // this last operation time, including transfer, voting and so on. //FIXME fix grammar @@ -189,6 +192,9 @@ message Account { // the identity of this account, case insensitive bytes account_id = 23; + int64 net_window_size = 24; + bool net_window_optimized = 25; + message AccountResource { // energy resource, get from frozen int64 energy_usage = 1; @@ -206,46 +212,34 @@ message Account { int64 storage_usage = 7; int64 latest_exchange_storage_time = 8; + int64 energy_window_size = 9; + + int64 delegated_frozenV2_balance_for_energy = 10; + int64 acquired_delegated_frozenV2_balance_for_energy = 11; + bool energy_window_optimized = 12; } AccountResource account_resource = 26; bytes codeHash = 30; Permission owner_permission = 31; Permission witness_permission = 32; repeated Permission active_permission = 33; -} - -/* AccountAsset */ -message AccountAsset { - /* frozen balance */ - message Frozen { - int64 frozen_balance = 1; // the frozen trx balance - int64 expire_time = 2; // the expire time + message FreezeV2 { + ResourceCode type = 1; + int64 amount = 2; } + message UnFreezeV2 { + ResourceCode type = 1; + int64 unfreeze_amount = 3; + int64 unfreeze_expire_time = 4; + } + repeated FreezeV2 frozenV2 = 34; + repeated UnFreezeV2 unfrozenV2 = 35; - // the create address - bytes address = 1; - - // the other asset owned by this account - map asset = 2; - - // the other asset owned by this account,key is assetId - map assetV2 = 3; - - bytes asset_issued_name = 4; - bytes asset_issued_ID = 5; - - map latest_asset_operation_time = 6; - map latest_asset_operation_timeV2 = 7; - - map free_asset_net_usage = 8; - map free_asset_net_usageV2 = 9; - - // frozen asset(for asset issuer) - repeated Frozen frozen_supply = 10; + int64 delegated_frozenV2_balance_for_bandwidth = 36; + int64 acquired_delegated_frozenV2_balance_for_bandwidth = 37; } - message Key { bytes address = 1; int64 weight = 2; @@ -329,6 +323,7 @@ message ResourceReceipt { int64 net_usage = 5; int64 net_fee = 6; Transaction.Result.contractResult result = 7; + int64 energy_penalty_total = 8; } message MarketOrderDetail { @@ -376,6 +371,12 @@ message Transaction { ShieldedTransferContract = 51; MarketSellAssetContract = 52; MarketCancelOrderContract = 53; + FreezeBalanceV2Contract = 54; + UnfreezeBalanceV2Contract = 55; + WithdrawExpireUnfreezeContract = 56; + DelegateResourceContract = 57; + UnDelegateResourceContract = 58; + CancelAllUnfreezeV2Contract = 59; } ContractType type = 1; google.protobuf.Any parameter = 2; @@ -406,6 +407,7 @@ message Transaction { UNKNOWN = 13; TRANSFER_FAILED = 14; INVALID_CODE = 15; + // please fill in the order according to the serial number } int64 fee = 1; code ret = 2; @@ -423,6 +425,8 @@ message Transaction { bytes orderId = 25; repeated MarketOrderDetail orderDetails = 26; + int64 withdraw_expire_amount = 27; + map cancel_unfreezeV2_amount = 28; } message raw { @@ -482,6 +486,8 @@ message TransactionInfo { repeated MarketOrderDetail orderDetails = 26; int64 packingFee = 27; + int64 withdraw_expire_amount = 28; + map cancel_unfreezeV2_amount = 29; } message TransactionRet { @@ -494,11 +500,6 @@ message Transactions { repeated Transaction transactions = 1; } -message TransactionSign { - Transaction transaction = 1; - bytes privateKey = 2; -} - message BlockHeader { message raw { int64 timestamp = 1; @@ -581,7 +582,7 @@ enum ReasonCode { TOO_MANY_PEERS = 0x04; DUPLICATE_PEER = 0x05; INCOMPATIBLE_PROTOCOL = 0x06; - NULL_IDENTITY = 0x07; + RANDOM_ELIMINATION = 0x07; PEER_QUITING = 0x08; UNEXPECTED_IDENTITY = 0x09; LOCAL_IDENTITY = 0x0A; @@ -599,6 +600,10 @@ enum ReasonCode { TIME_OUT = 0x20; CONNECT_FAIL = 0x21; TOO_MANY_PEERS_WITH_SAME_IP = 0x22; + LIGHT_NODE_SYNC_FAIL = 0x23; + BELOW_THAN_ME = 0X24; + NOT_WITNESS = 0x25; + NO_SUCH_MESSAGE = 0x26; UNKNOWN = 0xFF; } @@ -620,6 +625,9 @@ message HelloMessage { BlockId headBlockId = 6; bytes address = 7; bytes signature = 8; + int32 nodeType = 9; + int64 lowestBlockNum = 10; + bytes codeVersion = 11; } message InternalTransaction { @@ -646,6 +654,7 @@ message DelegatedResourceAccountIndex { bytes account = 1; repeated bytes fromAccounts = 2; repeated bytes toAccounts = 3; + int64 timestamp = 4; } message NodeInfo { diff --git a/protocol/src/main/protos/core/contract/balance_contract.proto b/protocol/src/main/protos/core/contract/balance_contract.proto index 293f62bed5b..ea1c96270d6 100644 --- a/protocol/src/main/protos/core/contract/balance_contract.proto +++ b/protocol/src/main/protos/core/contract/balance_contract.proto @@ -80,3 +80,39 @@ message AccountBalanceResponse { int64 balance = 1; BlockBalanceTrace.BlockIdentifier block_identifier = 2; } + +message FreezeBalanceV2Contract { + bytes owner_address = 1; + int64 frozen_balance = 2; + ResourceCode resource = 3; +} + +message UnfreezeBalanceV2Contract { + bytes owner_address = 1; + int64 unfreeze_balance = 2; + ResourceCode resource = 3; +} + +message WithdrawExpireUnfreezeContract { + bytes owner_address = 1; +} + +message DelegateResourceContract { + bytes owner_address = 1; + ResourceCode resource = 2; + int64 balance = 3; + bytes receiver_address = 4; + bool lock = 5; + int64 lock_period = 6; +} + +message UnDelegateResourceContract { + bytes owner_address = 1; + ResourceCode resource = 2; + int64 balance = 3; + bytes receiver_address = 4; +} + +message CancelAllUnfreezeV2Contract { + bytes owner_address = 1; +} \ No newline at end of file diff --git a/protocol/src/main/protos/core/contract/smart_contract.proto b/protocol/src/main/protos/core/contract/smart_contract.proto index ffbf399c38e..c913f7f7577 100644 --- a/protocol/src/main/protos/core/contract/smart_contract.proto +++ b/protocol/src/main/protos/core/contract/smart_contract.proto @@ -58,6 +58,12 @@ message SmartContract { int32 version = 11; } +message ContractState { + int64 energy_usage = 1; + int64 energy_factor = 2; + int64 update_cycle = 3; +} + message CreateSmartContract { bytes owner_address = 1; SmartContract new_contract = 2; @@ -94,4 +100,5 @@ message UpdateEnergyLimitContract { message SmartContractDataWrapper { SmartContract smart_contract = 1; bytes runtimecode = 2; + ContractState contract_state = 3; } \ No newline at end of file diff --git a/protocol/src/main/protos/install-googleapis.sh b/protocol/src/main/protos/install-googleapis.sh deleted file mode 100755 index e1c1df80124..00000000000 --- a/protocol/src/main/protos/install-googleapis.sh +++ /dev/null @@ -1,14 +0,0 @@ -#!/bin/sh -set -e - -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway -go get -u github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger -go get -u github.com/golang/protobuf/protoc-gen-go - -wget https://repo1.maven.org/maven2/com/google/api/grpc/googleapis-common-protos/0.0.3/googleapis-common-protos-0.0.3.jar -jar xvf googleapis-common-protos-0.0.3.jar -cp -r google/ $HOME/protobuf/include/ -ls -l - - - diff --git a/protocol/src/main/protos/install-protobuf.sh b/protocol/src/main/protos/install-protobuf.sh deleted file mode 100755 index b3a8cb5cbb2..00000000000 --- a/protocol/src/main/protos/install-protobuf.sh +++ /dev/null @@ -1,10 +0,0 @@ -#!/bin/sh -set -e -# check to see if protobuf folder is empty -if [ ! -d "$HOME/protobuf/lib" ]; then - wget https://github.com/google/protobuf/releases/download/v3.5.1/protobuf-all-3.5.1.tar.gz - tar -xzvf protobuf-all-3.5.1.tar.gz - cd protobuf-3.5.1 && ./configure --prefix=$HOME/protobuf && make && make install -else - echo "Using cached directory." -fi diff --git a/querySonar.sh b/querySonar.sh deleted file mode 100644 index 8c558634304..00000000000 --- a/querySonar.sh +++ /dev/null @@ -1,41 +0,0 @@ -echo "current branch is : "$BUILDKITE_BRANCH -if [ $BUILDKITE_PULL_REQUEST = "false" ]; then - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - echo "current branch sonarcloud status is : "$Status - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo "Sonar Check Failed" - echo "Please visit https://sonarcloud.io/dashboard?branch="$BUILDKITE_BRANCH"&id=java-tron for more details" - exit 1 - fi -else - echo "current PR number is : "$BUILDKITE_PULL_REQUEST - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - echo "current pullRequest sonarcloud status is : "$Status - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo "Sonar Check Failed" - echo "Please visit https://sonarcloud.io/dashboard?id=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST" for more details" - exit 1 - fi -fi \ No newline at end of file diff --git a/quickstart.md b/quickstart.md index 5359af00060..6eda855f1e9 100644 --- a/quickstart.md +++ b/quickstart.md @@ -28,8 +28,9 @@ cd java-tron #### Build the docker image -Use below command to start the build: +Use the command below to navigate to the docker directory and start the build: ``` +cd docker docker build -t tronprotocol/java-tron . ``` @@ -100,7 +101,6 @@ If everything goes well, your terminal console output will look like following :

Run Console Output - ``` [PM2] Spawning PM2 daemon with pm2_home=/root/.pm2 [PM2] PM2 Successfully daemonized @@ -166,25 +166,6 @@ If everything goes well, your terminal console output will look like following : (8) TYjQd4xrLZQGYMdLJqsTCuXVGapPqUp9ZX (10000 TRX) (9) THCw6hPZpFcLCWDcsZg3W77rXZ9rJQPncD (10000 TRX) - Private Keys - ================== - - (0) 2b2bddbeea87cecedcaf51eef55877b65725f709d2c0fcdfea0cb52d80acd52b - (1) f08759925316dc6344af538ebe3a619aeab836a0c254adca903cc764f87b0ee9 - (2) 1afc9f033cf9c6058db366b78a9f1b9c909b1b83397c9aed795afa05e9017511 - (3) f8f5bc70e91fc177eefea43b68c97b66536ac317a9300639e9d32a9db2f18a1f - (4) 031015272915917056c117d3cc2a03491a8f22ef450af83f6783efddf7064c59 - (5) 5eb25e2c1144f216aa99bbe2139d84bb6dedfb2c1ed72f3df6684a4c6d2cd96b - (6) f0b781da23992e6a3f536cb60917c3eb6a9c5434fcf441fcb8d7c58c01d6b70e - (7) 158f60a4379688a77d4a420e2f2a3e014ebf9ed0a1a093d7dc01ba23ebc5c970 - (8) e9342bb9108f46573804890a5301530c2834dce3703cd51ab77fba6161afec00 - (9) 2e9f0c507d2ea98dc4005a1afb1b743c629f7c145ccb55f38f75ae73cf8f605c - - HD Wallet - ================== - Mnemonic: border pulse twenty cruise grief shy need raw clean possible begin climb - Base HD Path: m/44'/60'/0'/0/{account_index} - ``` diff --git a/run.md b/run.md index 112478a4db5..c0ecbe4d91f 100644 --- a/run.md +++ b/run.md @@ -14,9 +14,9 @@ Use the [Testnet Config](https://github.com/tronprotocol/TronDeployment/blob/mas **Use the executable JAR(Recommended way):** ```bash -java -jar FullNode.jar -p your private key --witness -c your config.conf(Example:/data/java-tron/config.conf) +java -jar FullNode.jar -p --witness -c your config.conf(Example:/data/java-tron/config.conf) Example: -java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 --witness -c /data/java-tron/config.conf +java -jar FullNode.jar -p --witness -c /data/java-tron/config.conf ``` @@ -65,9 +65,9 @@ Then observe whether block synchronization success,If synchronization successf ```bash cd build/libs -java -jar FullNode.jar -p your private key --witness -c your config.conf (Example:/data/java-tron/config.conf) +java -jar FullNode.jar -p --witness -c your config.conf (Example:/data/java-tron/config.conf) Example: -java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812 --witness -c /data/java-tron/config.conf +java -jar FullNode.jar -p --witness -c /data/java-tron/config.conf ``` @@ -81,7 +81,7 @@ java -jar FullNode.jar -p 650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F Using TaskInputs.file() with something that doesn't resolve to a File object has been deprecated and is scheduled to be removed in Gradle 5.0. Use TaskInputs.files() instead. > Task :run -20:39:22.749 INFO [o.t.c.c.a.Args] private.key = 63e62a71ed39e30bac7223097a173924aad5855959de517ff2987b0e0ec89f1a +20:39:22.749 INFO [o.t.c.c.a.Args] private.key = 63e62a71ed3... 20:39:22.816 WARN [o.t.c.c.a.Args] localwitness size must be one, get the first one 20:39:22.832 INFO [o.t.p.FullNode] Here is the help message.output-directory/ 三月 22, 2018 8:39:23 下午 org.tron.core.services.RpcApiService start diff --git a/shell.md b/shell.md index df7d01e7cd9..700067a9aa3 100644 --- a/shell.md +++ b/shell.md @@ -20,7 +20,7 @@ The script is available in the java-tron project at [github](https://github.com/ sh start.sh --run ``` - Start the servive with options. + Start the service with options. ``` sh start.sh --run -j /data/FullNode.jar -c /data/config.conf -d /data/output-directory @@ -44,6 +44,10 @@ The script is available in the java-tron project at [github](https://github.com/ sh start.sh -cb --run ``` +* Select a supported network,default network `main`, optional network `test`,`private` + ``` + sh start.sh --net test + ``` ## Options @@ -73,6 +77,9 @@ The script is available in the java-tron project at [github](https://github.com/ * `-mem` Specify the maximum memory of the `FullNode.jar` service in`MB`, jvm's startup maximum memory will be adjusted according to this parameter. + +* `--net` + Select test and private networks. ### build project @@ -155,7 +162,7 @@ Get the latest released version. sh start.sh --release --run ``` -Following file structure will be generated after executed the above command and the `FullNode.jar` will be started. +Following file structure will be generated after executing the above command and the `FullNode.jar` will be started. ``` ├── ... @@ -226,4 +233,4 @@ sh start.sh --run -d /tmp/db/database -m 128 -b 64000 sh start.sh --release --run -d /tmp/db/database -m 128 -b 64000 ``` -For more design details, please refer to: [TIP298](https://github.com/tronprotocol/tips/issues/298) | [Leveldb Startup Optimization Plugins](https://github.com/tronprotocol/documentation-en/blob/master/docs/developers/archive-manifest.md) \ No newline at end of file +For more design details, please refer to: [TIP298](https://github.com/tronprotocol/tips/issues/298) | [Leveldb Startup Optimization Plugins](https://github.com/tronprotocol/documentation-en/blob/master/docs/developers/archive-manifest.md) diff --git a/sonar.sh b/sonar.sh deleted file mode 100644 index b3e2b5ccf28..00000000000 --- a/sonar.sh +++ /dev/null @@ -1,89 +0,0 @@ -echo "------------------------------ sonar check ------------------------------" -export SONAR_SCANNER_VERSION=4.2.0.1873 -export SONAR_SCANNER_HOME=/home/java-tron/sonar-scanner-4.1.0.1829-linux -export PATH=$SONAR_SCANNER_HOME/bin:$PATH -export SONAR_SCANNER_OPTS="-server" -#export PATH=$PATH:/home/java-tron/sonar-scanner-4.1.0.1829-linux/bin - -#BUILDKITE_BRANCH="MiraculousWang:develop" - -echo "current branch is : "$BUILDKITE_BRANCH -if [ $BUILDKITE_PULL_REQUEST = "false" ]; then - - sonar-scanner \ - -Dsonar.projectKey=java-tron \ - -Dsonar.organization=tron-zhaohong \ - -Dsonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src,./common/src,./crypto/src,./protocol/src \ - -Dsonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,./chainbase/build/classes,./common/build/classes,./crypto/build/classes,./protocol/build/classes \ - -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.links.homepage=https://github.com/tronprotocol/java-tron \ - -Dsonar.links.scm=https://github.com/tronprotocol/java-tron \ - -Dsoanr.links.issue=https://github.com/tronprotocol/java-tron/issues \ - -Dsonar.branch.name=$BUILDKITE_BRANCH \ - -Dsonar.coverage.jacoco.xmlReportPaths=./common/build/reports/jacoco/test/jacocoTestReport.xml,./consensus/build/reports/jacoco/test/jacocoTestReport.xml,./chainbase/build/reports/jacoco/test/jacocoTestReport.xml,./actuator/build/reports/jacoco/test/jacocoTestReport.xml,./framework/build/reports/jacoco/test/jacocoTestReport.xml \ - -Dsonar.login=1717c3c748ec2e0ea61e501b05458de243c4abcc > /data/checkStyle/sonar.log - - sleep 100 - - - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - echo "current branch sonarcloud status is : "$Status - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&branch="$BUILDKITE_BRANCH - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo ">>>>>>>>>>>>>>>>>>>>>>>>>> Sonar Check Failed <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<" - echo ">>>>>>>>>>>> Please visit https://sonarcloud.io/dashboard?branch="$BUILDKITE_BRANCH"&id=java-tron for more details <<<<<<<<<<<<<<<<<<" - touch checkFailTag - exit 0 - fi -else - echo "current PR number is : "$BUILDKITE_PULL_REQUEST - - sonar-scanner \ - -Dsonar.projectKey=java-tron \ - -Dsonar.organization=tron-zhaohong \ - -Dsonar.sources=./actuator/src,./framework/src/main,./consensus/src,./chainbase/src,./common/src,./crypto/src,./protocol/src \ - -Dsonar.java.binaries=./actuator/build/classes,./framework/build/classes,./consensus/build/classes,./chainbase/build/classes,./common/build/classes,./crypto/build/classes,./protocol/build/classes \ - -Dsonar.host.url=https://sonarcloud.io \ - -Dsonar.links.homepage=https://github.com/tronprotocol/java-tron \ - -Dsonar.links.scm=https://github.com/tronprotocol/java-tron \ - -Dsoanr.links.issue=https://github.com/tronprotocol/java-tron/issues \ - -Dsonar.pullrequest.key=$BUILDKITE_PULL_REQUEST \ - -Dsonar.pullrequest.branch=$BUILDKITE_BRANCH \ - -Dsonar.pullrequest.base=$BUILDKITE_PULL_REQUEST_BASE_BRANCH \ - -Dsonar.coverage.jacoco.xmlReportPaths=./common/build/reports/jacoco/test/jacocoTestReport.xml,./consensus/build/reports/jacoco/test/jacocoTestReport.xml,./chainbase/build/reports/jacoco/test/jacocoTestReport.xml,./actuator/build/reports/jacoco/test/jacocoTestReport.xml,./framework/build/reports/jacoco/test/jacocoTestReport.xml \ - -Dsonar.login=1717c3c748ec2e0ea61e501b05458de243c4abcc > /data/checkStyle/sonar.log - - sleep 100 - - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - if [ $Status = null ]; then - echo "wait for check finish, 5m ....." - sleep 300 - SonarStatus_Url="https://sonarcloud.io/api/qualitygates/project_status?projectKey=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST - Status=`curl -s $SonarStatus_Url | jq '.projectStatus.status'` - fi - - echo "current pullRequest sonarcloud status is : "$Status - if [ x"$Status" = x'"OK"' ];then - echo "Sonar Check Pass" - exit 0 - else - echo " -------------------------------- sonar check Failed ---------------------------------" - echo ">>>>>>>>>>>>>>> Please visit https://sonarcloud.io/dashboard?id=java-tron&pullRequest="$BUILDKITE_PULL_REQUEST" for more details <<<<<<<<<<<<<<<<<<" - echo "If this Sonar problem is not caused by your modification,Make sure you local branch is newest, And merge the newest tronprotocol/java-tron" - echo ">>>>>>>>>>>>>>>>>>>>>>>>>> Sonar Check Failed <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " - touch checkFailTag - exit 0 - fi -fi diff --git a/start.sh b/start.sh index 17c23012956..89f13cf25a7 100644 --- a/start.sh +++ b/start.sh @@ -19,11 +19,21 @@ # Build FullNode config FULL_NODE_DIR="FullNode" -FULL_NODE_CONFIG="main_net_config.conf" +FULL_NODE_CONFIG_DIR="config" +# config file +FULL_NODE_CONFIG_MAIN_NET="main_net_config.conf" +FULL_NODE_CONFIG_TEST_NET="test_net_config.conf" +FULL_NODE_CONFIG_PRIVATE_NET="private_net_config.conf" DEFAULT_FULL_NODE_CONFIG='config.conf' JAR_NAME="FullNode.jar" FULL_START_OPT='' + +# Github GITHUB_BRANCH='master' +GITHUB_CLONE_TYPE='HTTPS' +GITHUB_REPOSITORY='' +GITHUB_REPOSITORY_HTTPS_URL='https://github.com/tronprotocol/java-tron.git' +GITHUB_REPOSITORY_SSH_URL='git@github.com:tronprotocol/java-tron.git' # Shell option ALL_OPT_LENGTH=$# @@ -36,6 +46,7 @@ ALLOW_MIN_MEMORY=8192 MAX_DIRECT_MEMORY=1g JVM_MS=4g JVM_MX=4g +IS_BACKUP_GC_LOG=true SPECIFY_MEMORY=0 RUN=false @@ -53,6 +64,12 @@ RELEASE_URL='https://github.com/tronprotocol/java-tron/releases' QUICK_START=false CLONE_BUILD=false +if [[ $GITHUB_CLONE_TYPE == 'HTTPS' ]]; then + GITHUB_REPOSITORY=$GITHUB_REPOSITORY_HTTPS_URL +else + GITHUB_REPOSITORY=$GITHUB_REPOSITORY_SSH_URL +fi + # Determine the Java command to use to start the JVM. if [ -z "$JAVA_HOME" ]; then javaExecutable="`which javac`" @@ -97,9 +114,35 @@ if [ -z "$JAVA_HOME" ] ; then echo "Warning: JAVA_HOME environment variable is not set." fi +backupGCLog() { + local maxFile=5 + local gcLogDir=logs/gc_logs/ + if [ ! -d "$gcLogDir" ];then + mkdir -p 'logs/gc_logs' + fi + + if [ -f 'gc.log' ]; then + echo '[info] backup gc.log' + local dateformat=`date "+%Y-%m-%d_%H-%M-%S"` + tar -czvf gc.log_$dateformat'.tar.gz' gc.log + mv gc.log_$dateformat'.tar.gz' $gcLogDir + rm -rf gc.log + + # checking the number of backups + local currentDirCount=`ls -l $gcLogDir | grep "gc.log*" | wc -l` + if [ $currentDirCount -gt $maxFile ]; then + local oldFileSize=`expr $currentDirCount - $maxFile` + local oldGcLogFiles=(`ls -1 $gcLogDir |head -n $oldFileSize`) + fi + + for fileName in ${oldGcLogFiles[@]}; do + rm -rf $gcLogDir$fileName + done + fi +} getLatestReleaseVersion() { - full_node_version=`git ls-remote --tags git@github.com:tronprotocol/java-tron.git |grep GreatVoyage- | awk -F '/' 'END{print $3}'` + full_node_version=`git ls-remote --tags $GITHUB_REPOSITORY |grep GreatVoyage- | awk -F '/' 'END{print $3}'` if [[ -n $full_node_version ]]; then echo $full_node_version else @@ -166,8 +209,8 @@ quickStart() { mkdirFullNode echo "info: check latest version: $full_node_version" echo 'info: download config' - download https://raw.githubusercontent.com/tronprotocol/tron-deployment/$GITHUB_BRANCH/$FULL_NODE_CONFIG $FULL_NODE_CONFIG - mv $FULL_NODE_CONFIG 'config.conf' + download https://raw.githubusercontent.com/tronprotocol/tron-deployment/$GITHUB_BRANCH/$FULL_NODE_CONFIG_MAIN_NET $FULL_NODE_CONFIG_MAIN_NET + mv $FULL_NODE_CONFIG_MAIN_NET 'config.conf' echo "info: download $full_node_version" download $RELEASE_URL/download/$full_node_version/$JAR_NAME $JAR_NAME @@ -180,7 +223,7 @@ quickStart() { cloneCode() { if type git >/dev/null 2>&1; then - git_clone=$(git clone -b $GITHUB_BRANCH git@github.com:tronprotocol/java-tron.git) + git_clone=$(git clone -b $GITHUB_BRANCH $GITHUB_REPOSITORY) if [[ git_clone == 0 ]]; then echo 'info: git clone java-tron success' fi @@ -340,7 +383,8 @@ rebuildManifest() { $JAVACMD -jar $ARCHIVE_JAR -d $REBUILD_DIR -m $REBUILD_MANIFEST_SIZE -b $REBUILD_BATCH_SIZE else echo 'info: download the rebuild manifest plugin from the github' - download $RELEASE_URL/download/GreatVoyage-v4.3.0/$ARCHIVE_JAR $ARCHIVE_JAR + local latest=$(`echo getLatestReleaseVersion`) + download $RELEASE_URL/download/GreatVoyage-v"$latest"/$ARCHIVE_JAR $ARCHIVE_JAR if [[ $download == 0 ]]; then echo 'info: download success, rebuild manifest' $JAVACMD -jar $ARCHIVE_JAR $REBUILD_DIR -m $REBUILD_MANIFEST_SIZE -b $REBUILD_BATCH_SIZE @@ -353,6 +397,35 @@ rebuildManifest() { fi } +specifyConfig(){ + echo "info: specify the net: $1" + local netType=$1 + local configName; + if [[ "$netType" = 'test' ]]; then + configName=$FULL_NODE_CONFIG_TEST_NET + elif [[ "$netType" = 'private' ]]; then + configName=$FULL_NODE_CONFIG_PRIVATE_NET + else + echo "warn: no support config $nodeType" + exit + fi + + if [[ ! -d $FULL_NODE_CONFIG_DIR ]]; then + mkdir -p $FULL_NODE_CONFIG_DIR + fi + + if [[ -d $FULL_NODE_CONFIG_DIR/$configName ]]; then + DEFAULT_FULL_NODE_CONFIG=$FULL_NODE_CONFIG_DIR/$configName + break + fi + + if [[ ! -f $FULL_NODE_CONFIG_DIR/$configName ]]; then + download https://raw.githubusercontent.com/tronprotocol/tron-deployment/$GITHUB_BRANCH/$configName $configName + mv $configName $FULL_NODE_CONFIG_DIR/$configName + DEFAULT_FULL_NODE_CONFIG=$FULL_NODE_CONFIG_DIR/$configName + fi +} + checkSign() { echo 'info: verify signature' local latest_version=$(`echo getLatestReleaseVersion`) @@ -391,7 +464,6 @@ while [ -n "$1" ]; do case "$1" in -c) DEFAULT_FULL_NODE_CONFIG=$2 - FULL_START_OPT="$FULL_START_OPT $1 $2" shift 2 ;; -d) @@ -403,6 +475,22 @@ while [ -n "$1" ]; do JAR_NAME=$2 shift 2 ;; + -p) + FULL_START_OPT="$FULL_START_OPT $1 $2" + shift 2 + ;; + -w) + FULL_START_OPT="$FULL_START_OPT $1" + shift 1 + ;; + --witness) + FULL_START_OPT="$FULL_START_OPT $1" + shift 1 + ;; + --net) + specifyConfig $2 + shift 2 + ;; -m) REBUILD_MANIFEST_SIZE=$2 shift 2 @@ -454,14 +542,12 @@ while [ -n "$1" ]; do --run) if [[ $ALL_OPT_LENGTH -eq 1 ]]; then restart - exit fi RUN=true shift 1 ;; --stop) stopService - exit ;; FullNode) RUN=true @@ -487,12 +573,16 @@ while [ -n "$1" ]; do exit fi fi - echo "warn: option $1 does not exist" - exit + FULL_START_OPT="$FULL_START_OPT $@" + break ;; esac done +if [[ $IS_BACKUP_GC_LOG = true ]]; then + backupGCLog +fi + if [[ $CLONE_BUILD == true ]];then cloneBuild fi @@ -506,7 +596,6 @@ if [[ $QUICK_START == true ]]; then restart fi fi - exit fi if [[ $UPGRADE == true ]]; then @@ -523,13 +612,11 @@ if [[ $DOWNLOAD == true ]]; then fi fi -if [[ $ALL_OPT_LENGTH -eq 0 ]]; then +if [[ $ALL_OPT_LENGTH -eq 0 || $ALL_OPT_LENGTH -gt 0 ]]; then restart - exit fi if [[ $RUN == true ]]; then restart - exit fi diff --git a/work.sh b/work.sh deleted file mode 100755 index 91d7247ca57..00000000000 --- a/work.sh +++ /dev/null @@ -1,67 +0,0 @@ -#!/bin/bash - -# Function: to start, stop and restart java-tron. -# Usage: bash work.sh start|stop|restart. -# Note: modify the paths and private key to your own. - -# Auther: haoyouqiang -# Since: 2018/5/27 -# Version: 1.0 - -if [ $# -ne 1 ]; then - echo "Usage: bash work.sh start|stop|restart." - exit 1 -fi - -# Increase memory limit that JVM can use to avoid OOM error: -# 80% of your physical memory may be a proper ceiling that JVM can use. -# By default there, JVM initializes with 1g memory and can use 32g at most. -JVM_OPTIONS="-Xms1g -Xmx32g" - -JAR_FILE_PATH="./build/libs/java-tron.jar" -PID_FILE_PATH="java-tron.pid" -LOG_FILE_PATH="java-tron.log" - -CONF_FILE_PATH="./build/resources/main/config.conf" - -PRIVATE_KEY="650950B193DDDDB35B6E48912DD28F7AB0E7140C1BFDEFD493348F02295BD812" - -case "${1}" in - start) - # Already running - if [ -f ${PID_FILE_PATH} ]; then - pid=$(cat ${PID_FILE_PATH}) - if $(ps -p ${pid} > /dev/null); then - echo "Already running [PID: ${pid}], you can stop it and retry." - exit 1 - fi - fi - - nohup java ${JVM_OPTIONS} \ - -jar ${JAR_FILE_PATH} \ - -p ${PRIVATE_KEY} --witness \ - -c ${CONF_FILE_PATH} \ - > ${LOG_FILE_PATH} 2>&1 \ - & echo $! > ${PID_FILE_PATH} - - if [ $? -eq 0 ]; then - echo "Succeeded to start java-tron." - else - echo "Failed to start java-tron." - fi - ;; - stop) - kill $(cat ${PID_FILE_PATH}) - - if [ $? -eq 0 ]; then - rm ${PID_FILE_PATH} - echo "Succeeded to stop java-tron." - else - echo "Failed to stop java-tron." - fi - ;; - restart) - ${0} stop && sleep 1 && ${0} start - ;; -esac -